From 6ffcb1bb184b2cd2b49391969eecce423d41ccf6 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 12:32:33 +0100 Subject: [PATCH] WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .gitea/scripts/ambiente-prove.sh | 5 +- .gitea/scripts/riepilogo-prove.sh | 4 +- .gitea/workflows/verifica.yml | 4 +- docker/Dockerfile | 5 +- docs/decisioni.md | 1 + docs/docker.md | 5 +- docs/guida/Sicurezza-e-riservatezza.md | 4 +- docs/guida/Sviluppo.md | 2 +- docs/processo.md | 2 +- src/Febe.App/FebeApp.cs | 4 +- src/Febe.Core/Codecs/Containers/AviReader.cs | 385 ++++++++ .../Codecs/Containers/ContainerReader.cs | 70 ++ .../Codecs/Containers/IsoBmffReader.cs | 842 ++++++++++++++++++ .../Codecs/Containers/MatroskaReader.cs | 678 ++++++++++++++ .../Codecs/Containers/MediaContainer.cs | 122 +++ src/Febe.Core/Codecs/Containers/Mp4Writer.cs | 643 +++++++++++++ src/Febe.Core/Import/ContentAnalysis.cs | 5 +- src/Febe.Core/Import/ImportCopier.cs | 2 +- src/Febe.Core/Import/ImportEnvironment.cs | 9 +- src/Febe.Core/Import/LEGGIMI.md | 8 +- src/Febe.Core/Import/VideoMetadataProbe.cs | 193 +--- src/Febe.Core/Library/LibraryRebuilder.cs | 6 +- src/Febe.Core/Library/ThumbnailStore.cs | 2 +- src/Febe.Core/Library/VideoFrameDecoder.cs | 492 ++++++++++ src/Febe.Core/Library/VideoFrameExtractor.cs | 131 --- .../Security/ChildProcessEnvironment.cs | 2 +- src/Febe.Web/Import/ImportHub.cs | 4 +- src/Febe.Web/LEGGIMI.md | 2 +- src/Febe.Web/Library/DataFolderServices.cs | 2 +- .../Febe.Tests/Import/ImportAnalysisTests.cs | 32 +- tests/Febe.Tests/Import/MediaReaderTests.cs | 52 +- .../Import/Support/ImportTestFiles.cs | 33 +- .../Febe.Tests/Library/ThumbnailStoreTests.cs | 35 +- .../Media/Containers/ContainerTests.cs | 233 +++++ .../Febe.Tests/Media/Containers/TestVideos.cs | 461 ++++++++++ .../Containers/VideoFrameDecoderTests.cs | 145 +++ .../Media/H264/Conformita/LEGGIMI.md | 40 + tests/Febe.Tests/Packaging/PipelineTests.cs | 5 +- .../Server/SessionKeyOptionsTests.cs | 34 - 39 files changed, 4235 insertions(+), 469 deletions(-) create mode 100644 src/Febe.Core/Codecs/Containers/AviReader.cs create mode 100644 src/Febe.Core/Codecs/Containers/ContainerReader.cs create mode 100644 src/Febe.Core/Codecs/Containers/IsoBmffReader.cs create mode 100644 src/Febe.Core/Codecs/Containers/MatroskaReader.cs create mode 100644 src/Febe.Core/Codecs/Containers/MediaContainer.cs create mode 100644 src/Febe.Core/Codecs/Containers/Mp4Writer.cs create mode 100644 src/Febe.Core/Library/VideoFrameDecoder.cs delete mode 100644 src/Febe.Core/Library/VideoFrameExtractor.cs create mode 100644 tests/Febe.Tests/Media/Containers/ContainerTests.cs create mode 100644 tests/Febe.Tests/Media/Containers/TestVideos.cs create mode 100644 tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs create mode 100644 tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md diff --git a/.gitea/scripts/ambiente-prove.sh b/.gitea/scripts/ambiente-prove.sh index ece19fc..d7c0f47 100755 --- a/.gitea/scripts/ambiente-prove.sh +++ b/.gitea/scripts/ambiente-prove.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché # nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le -# sue lingue, Xvfb, ffmpeg e ffprobe, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi +# sue lingue, Xvfb, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi # caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody # (65534) vengono con Debian (prove dell'avvio del contenitore). # @@ -16,7 +16,6 @@ $sudo apt-get update -qq $sudo apt-get install -y -qq --no-install-recommends \ chromium chromium-l10n \ xvfb \ - ffmpeg \ nsis zip \ locales tzdata libicu76 ca-certificates \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ @@ -27,8 +26,6 @@ $sudo locale-gen > /dev/null echo "== Strumenti delle prove" chromium --version command -v Xvfb -ffmpeg -version | head -n 1 || true -ffprobe -version | head -n 1 || true echo "makensis $(makensis -VERSION)" echo "node $(node --version)" locale -a | grep -i '^it_IT\.utf8$' diff --git a/.gitea/scripts/riepilogo-prove.sh b/.gitea/scripts/riepilogo-prove.sh index a5ab3bd..79728f0 100755 --- a/.gitea/scripts/riepilogo-prove.sh +++ b/.gitea/scripts/riepilogo-prove.sh @@ -6,7 +6,7 @@ # .gitea/scripts/riepilogo-prove.sh [saltate ammesse] # # Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono -# Chromium, Xvfb, ffmpeg, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. +# Chromium, Xvfb, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. set -euo pipefail cartella="${1:?Indica la cartella con i file .trx.}" @@ -96,7 +96,7 @@ if (( fallite_totali > 0 )); then esito=1 fi if (( saltate_totali > ammesse )); then - echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 + echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 esito=1 fi diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 23cd7d6..1ef840f 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -4,7 +4,7 @@ # soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); # prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests # (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con -# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. +# Chromium, Xvfb, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. # Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di # questa esecuzione, scritto nel registro per rifare un errore; # installatore Febe-Setup--ci..exe e lo zip portabile, artefatti per 14 giorni; @@ -108,7 +108,7 @@ jobs: echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\"" - - name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana + - name: Chromium, Xvfb, NSIS e lingua italiana run: bash .gitea/scripts/ambiente-prove.sh - uses: actions/setup-dotnet@v4 diff --git a/docker/Dockerfile b/docker/Dockerfile index c416a2a..02ec824 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -14,7 +14,7 @@ # test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove # con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo); # publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET; -# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ffmpeg, ICU, caratteri +# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ICU, caratteri # (anche emoji), certificati, fusi orari, lingua italiana; tini come processo 1; setpriv per PUID/PGID. # # Vedi docs/docker.md per volumi, variabili, porte, sandbox, salute e aggiornamento. @@ -74,7 +74,7 @@ LABEL org.opencontainers.image.title="Febe" \ org.opencontainers.image.source="https://gitea.encke-hake.ts.net/Alby96/Febe" \ org.opencontainers.image.url="https://gitea.encke-hake.ts.net/Alby96/Febe" -# Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e +# Chromium della distribuzione con le sue lingue, il display virtuale, ICU e # le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua # italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID. # Prima gli aggiornamenti di sicurezza della distribuzione già pubblicati, anche quelli arrivati dopo l'immagine di @@ -85,7 +85,6 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends \ chromium chromium-l10n \ xvfb \ - ffmpeg \ libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ ca-certificates tzdata locales \ diff --git a/docs/decisioni.md b/docs/decisioni.md index bd24b83..5126fbc 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -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 | `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-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) | diff --git a/docs/docker.md b/docs/docker.md index c74528d..3d560da 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -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. - 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. - `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. @@ -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` | 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 diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 5bd361e..7705e05 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -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. - Se cambi la chiave, o il file si rovina, Febe la tratta come assente e lo scrive nel registro: basta rifare l'accesso. «Scollega» la cancella. -- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb, - ffmpeg): il browser esegue il codice del sito, e non deve poterle leggere. +- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser e + Xvfb): il browser esegue il codice del sito, e non deve poterle leggere. ## Docker: l'interfaccia non va esposta su Internet diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 9dd2176..8c6225f 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -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 tutta la storia (gitleaks); - `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - un contenitore Debian con Chromium, 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--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie diff --git a/docs/processo.md b/docs/processo.md index 5a42f53..6cc0727 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -87,7 +87,7 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget | Lavoro | Quando | Che cosa garantisce | |---|---|---| | `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) | -| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) 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--ci..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-` | diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index 81034e2..a4095ab 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -250,8 +250,8 @@ public sealed class FebeApp : IAsyncDisposable Clock = Clock, Thumbnails = thumbnails, HashIndex = hashes, - Frames = VideoFrameExtractor.TryCreate(), - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), + Frames = VideoFrameDecoder.Instance, + VideoProbe = new ContainerVideoMetadataProbe(Clock), SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), DataFolder = data.Root, diff --git a/src/Febe.Core/Codecs/Containers/AviReader.cs b/src/Febe.Core/Codecs/Containers/AviReader.cs new file mode 100644 index 0000000..6689501 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/AviReader.cs @@ -0,0 +1,385 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF AVIX parts), +/// written from the format description: the main header, the first video and audio streams and the chunks of the +/// movi lists in file order. Key frames come from the idx1 index when there is one. +/// +public static class AviReader +{ + private const int MaxSamples = 20_000_000; + private const int MaxHeaderBytes = 16 * 1024 * 1024; + + /// True when the stream starts like an AVI file. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8); + + /// Reads a seekable stream from its start. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true) + { + ArgumentNullException.ThrowIfNull(stream); + var state = new State(); + long position = 0; + var length = stream.Length; + Span header = stackalloc byte[12]; + var first = true; + while (position + 12 <= length) + { + stream.Position = position; + stream.ReadExactly(header); + if (!header[..4].SequenceEqual("RIFF"u8)) + { + break; + } + + var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]); + var form = header.Slice(8, 4); + if (first && !form.SequenceEqual("AVI "u8)) + { + throw new ContainerException("Non è un file AVI."); + } + + var end = Math.Min(length, position + 8 + size); + ParseList(stream, position + 12, end, state, samples, now, depth: 0); + if (!samples) + { + break; + } + + first = false; + position = position + 8 + size + (size & 1); + } + + if (!state.HaveHeader) + { + throw new ContainerException("Manca l'intestazione AVI."); + } + + return state.Build(); + } + + private static void ParseList(Stream stream, long start, long end, State state, bool samples, DateTimeOffset now, int depth) + { + Span header = stackalloc byte[12]; + var position = start; + while (position + 8 <= end) + { + stream.Position = position; + stream.ReadExactly(header[..8]); + var 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)); + } + } + + /// The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021». + 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(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(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 }; + } + + /// Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index. + private HashSet? KeyFrames() + { + if (Index is null || VideoStream < 0) + { + return null; + } + + var keys = new HashSet(); + var n = 0; + for (var p = 0; p + 16 <= Index.Length; p += 16) + { + var id = Index.AsSpan(p, 4); + if (!char.IsAsciiDigit((char)id[0]) || (id[0] - '0') * 10 + (id[1] - '0') != VideoStream || id[2] != 'd') + { + continue; + } + + if ((BinaryPrimitives.ReadUInt32LittleEndian(Index.AsSpan(p + 4)) & 0x10) != 0) + { + keys.Add(n); + } + + n++; + } + + return n == Chunks.Count ? keys : null; // an index that does not match the chunks is ignored + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs new file mode 100644 index 0000000..0cd10a2 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -0,0 +1,70 @@ +namespace Febe.Core.Codecs.Containers; + +/// Recognises the container of a video by its first bytes and reads it with the matching reader. +public static class ContainerReader +{ + /// The format of a file from its first bytes; null when it is none of those read here. + public static ContainerFormat? Detect(ReadOnlySpan start) + { + if (MatroskaReader.Looks(start)) + { + return ContainerFormat.Matroska; + } + + if (AviReader.Looks(start)) + { + return ContainerFormat.Avi; + } + + return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null; + } + + /// + /// Reads a seekable stream; null when its format is not recognised. Damaged files raise + /// (or when truncated). + /// + public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true) + { + ArgumentNullException.ThrowIfNull(stream); + Span start = stackalloc byte[16]; + stream.Position = 0; + var read = stream.ReadAtLeast(start, start.Length, throwOnEndOfStream: false); + stream.Position = 0; + return Detect(start[..read]) switch + { + ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples), + ContainerFormat.Avi => AviReader.Read(stream, now, samples), + ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples), + _ => null, + }; + } + + /// Reads a file (read-only, shared); null when its format is not recognised. + public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true) + { + using var stream = OpenRead(path); + return Read(stream, now, samples); + } + + /// Opens a file for reading without blocking other readers or writers. + public static FileStream OpenRead(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess); + + /// The bytes of a sample, read into (grown when needed). + public static ReadOnlySpan ReadSample(Stream stream, in MediaSample sample, ref byte[] buffer) + { + if (sample.Size < 0 || sample.Offset < 0 || sample.Offset + sample.Size > stream.Length) + { + throw new ContainerException("Campione fuori dal file."); + } + + if (buffer.Length < sample.Size) + { + buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)]; + } + + stream.Position = sample.Offset; + stream.ReadExactly(buffer, 0, sample.Size); + return buffer.AsSpan(0, sample.Size); + } +} diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs new file mode 100644 index 0000000..ce7c8c9 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -0,0 +1,842 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of the ISO base media file format (ISO/IEC 14496-12: MP4, MOV, 3GP), written from the standard: the movie +/// header, the first video and audio tracks with their sample tables, and the fragments (moof) of fragmented +/// files. Only boxes are read into memory; media data is never loaded here. +/// +public static class IsoBmffReader +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private const long MaxBoxInMemory = 128L * 1024 * 1024; + private const int MaxTopLevelBoxes = 1_000_000; + private const int MaxSamples = 20_000_000; + + /// True when the stream starts like an ISO media file (an ftyp, moov, mdat... box). + public static bool Looks(ReadOnlySpan start) => + start.Length >= 8 && (start.Slice(4, 4).SequenceEqual("ftyp"u8) || start.Slice(4, 4).SequenceEqual("moov"u8) + || start.Slice(4, 4).SequenceEqual("mdat"u8) || start.Slice(4, 4).SequenceEqual("wide"u8) + || start.Slice(4, 4).SequenceEqual("free"u8) || start.Slice(4, 4).SequenceEqual("skip"u8)); + + /// Reads a seekable stream from its start. + /// The file. + /// Current time: later creation times are ignored. + /// False to stop at the metadata (no sample tables, no fragments). + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true) + { + ArgumentNullException.ThrowIfNull(stream); + var length = stream.Length; + long position = 0; + Span 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; + } + + /// Child boxes of the box body data[start..start+count]: type, body start and body length. + internal static List<(string Type, int Start, int Length)> Children(byte[] data, int start, int count) + { + var list = new List<(string, int, int)>(); + var offset = start; + var end = start + count; + while (offset + 8 <= end && list.Count < 100_000) + { + long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(offset)); + var type = System.Text.Encoding.Latin1.GetString(data, offset + 4, 4); + var headerSize = 8; + if (size == 1) + { + if (offset + 16 > end) + { + break; + } + + size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(offset + 8)); + headerSize = 16; + } + else if (size == 0) + { + size = end - offset; + } + + if (size < headerSize || size > end - offset) + { + break; + } + + list.Add((type, offset + headerSize, (int)size - headerSize)); + offset += (int)size; + } + + return list; + } + + private static int Rotation(ReadOnlySpan matrix) + { + var a = BinaryPrimitives.ReadInt32BigEndian(matrix); + var b = BinaryPrimitives.ReadInt32BigEndian(matrix[4..]); + var c = BinaryPrimitives.ReadInt32BigEndian(matrix[12..]); + var d = BinaryPrimitives.ReadInt32BigEndian(matrix[16..]); + const int One = 0x10000; + if (a == 0 && d == 0 && b == One && c == -One) + { + return 90; + } + + if (a == -One && d == -One && b == 0 && c == 0) + { + return 180; + } + + if (a == 0 && d == 0 && b == -One && c == One) + { + return 270; + } + + return 0; + } + + private sealed class Track + { + internal uint Id; + internal string Handler = string.Empty; + internal long Timescale; + internal long Duration; + internal int Rotation; + internal int TkhdWidth; + internal int TkhdHeight; + internal string Format = string.Empty; + internal int Width; + internal int Height; + internal int Channels; + internal int SampleRate; + internal byte[]? Avcc; + internal byte[]? Asc; + internal long EditOffset; + internal List Samples = []; + internal long FragmentTime = -1; + } + + private sealed class Movie(bool samples) + { + internal readonly Dictionary TrackDefaults = []; + private readonly List tracks = []; + private DateTimeOffset? created; + private long timescale; + private long duration; + + internal void ParseMvhd(ReadOnlySpan body, DateTimeOffset now) + { + ulong creation; + if (body[0] == 1) + { + creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); + duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); + } + else + { + creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); + duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); + if (duration == uint.MaxValue) + { + duration = 0; + } + } + + if (creation > 0 && creation < 400UL * 366 * 86400) + { + var instant = Epoch1904.AddSeconds(creation); + if (instant >= Earliest && instant <= now.AddDays(1)) + { + created = instant; + } + } + } + + internal void ParseTrak(byte[] data, int start, int count) + { + var track = new Track(); + foreach (var (type, s, c) in Children(data, start, count)) + { + var body = data.AsSpan(s, c); + switch (type) + { + case "tkhd": + { + var v1 = body[0] == 1; + track.Id = BinaryPrimitives.ReadUInt32BigEndian(body[(v1 ? 20 : 12)..]); + var offset = (v1 ? 36 : 24) + 16; + track.Rotation = Rotation(body.Slice(offset, 36)); + track.TkhdWidth = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 36)..]) >> 16); + track.TkhdHeight = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 40)..]) >> 16); + break; + } + + case "edts": + foreach (var (t, es, ec) in Children(data, s, c)) + { + if (t == "elst") + { + ParseElst(data.AsSpan(es, ec), track); + } + } + + break; + case "mdia": + ParseMdia(data, s, c, track); + break; + } + } + + tracks.Add(track); + } + + private static void ParseElst(ReadOnlySpan body, Track track) + { + var v1 = body[0] == 1; + var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + var offset = 8; + for (var i = 0; i < entries && i < 16; i++) + { + long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]); + offset += v1 ? 20 : 12; + if (mediaTime >= 0) + { + track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero + return; + } + } + } + + private void ParseMdia(byte[] data, int start, int count, Track track) + { + foreach (var (type, s, c) in Children(data, start, count)) + { + var body = data.AsSpan(s, c); + switch (type) + { + case "mdhd": + if (body[0] == 1) + { + track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); + track.Duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); + } + else + { + track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); + var d = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); + track.Duration = d == uint.MaxValue ? 0 : d; + } + + break; + case "hdlr": + track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4)); + break; + case "minf": + foreach (var (t, ms, mc) in Children(data, s, c)) + { + if (t == "stbl") + { + ParseStbl(data, ms, mc, track); + } + } + + break; + } + } + } + + private void ParseStbl(byte[] data, int start, int count, Track track) + { + byte[]? stts = null, ctts = null, stsc = null, stsz = null, stco = null, stss = null; + var co64 = false; + var stz2 = false; + foreach (var (type, s, c) in Children(data, start, count)) + { + 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)); + } + } + } + } + } + + /// The DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 descriptors). + private static byte[]? EsdsConfig(ReadOnlySpan body) + { + var p = 4; // version and flags + while (p + 2 <= body.Length) + { + var tag = body[p++]; + var length = 0; + for (var i = 0; i < 4 && p < body.Length; i++) + { + var b = body[p++]; + length = (length << 7) | (b & 0x7F); + if ((b & 0x80) == 0) + { + break; + } + } + + switch (tag) + { + case 0x03: // ES_Descriptor + { + 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(); + 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(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; + } + + /// Adds the samples of one movie fragment (ISO/IEC 14496-12 §8.8). + internal void AddFragment(long moofStart, byte[] moof) + { + try + { + foreach (var (type, s, c) in Children(moof, 0, moof.Length)) + { + if (type == "traf") + { + AddTrackFragment(moofStart, moof, s, c); + } + } + } + catch (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; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs new file mode 100644 index 0000000..1f7a0a7 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -0,0 +1,678 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of Matroska and WebM (EBML, RFC 8794, and the Matroska specification, RFC 9559), written from the +/// specifications: segment information, the first video and audio tracks and, when asked, the blocks of the clusters. +/// Elements are read one by one from the stream; the frames are never loaded here. +/// +public static class MatroskaReader +{ + private static readonly DateTimeOffset Epoch2001 = new(2001, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private const uint EbmlId = 0x1A45DFA3; + private const uint SegmentId = 0x18538067; + private const uint InfoId = 0x1549A966; + private const uint TracksId = 0x1654AE6B; + private const uint ClusterId = 0x1F43B675; + private const uint CuesId = 0x1C53BB6B; + private const uint TagsId = 0x1254C367; + private const uint AttachmentsId = 0x1941A469; + private const uint ChaptersId = 0x1043A770; + private const uint SeekHeadId = 0x114D9B74; + private const long UnknownSize = -1; + private const int MaxSamples = 20_000_000; + private const long MaxElementInMemory = 64L * 1024 * 1024; + + /// True when the stream starts with an EBML header. + public static bool Looks(ReadOnlySpan start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId; + + /// Reads a seekable stream from its start. + /// The file. + /// Current time: later creation times are ignored. + /// False to stop before the first cluster. + 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 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 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 }; + } + } + + /// EBML primitives over the stream. + private sealed class Reader(Stream stream) + { + internal Stream Stream => stream; + + internal (uint Id, long Size) Header() + { + var first = stream.ReadByte(); + if (first <= 0) + { + throw new ContainerException("Elemento EBML non valido."); + } + + var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24); + if (length > 4) + { + throw new ContainerException("Identificatore EBML non valido."); + } + + var id = (uint)first; + for (var i = 1; i < length; i++) + { + id = (id << 8) | (uint)ReadByteOrThrow(); + } + + var (raw, sizeLength) = VintRaw(); + var allOnes = (1UL << (7 * sizeLength)) - 1; + return (id, raw == allOnes ? UnknownSize : (long)raw); + } + + internal (ulong Raw, int Length) VintRaw() + { + var first = ReadByteOrThrow(); + if (first == 0) + { + throw new ContainerException("Intero EBML non valido."); + } + + var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24); + ulong value = (ulong)(first & (0xFF >> length)); + for (var i = 1; i < length; i++) + { + value = (value << 8) | (uint)ReadByteOrThrow(); + } + + return (value, length); + } + + internal ulong VintValue() => VintRaw().Raw; + + internal ulong Unsigned(long size) + { + if (size is < 0 or > 8) + { + throw new ContainerException("Intero EBML troppo lungo."); + } + + ulong value = 0; + for (var i = 0; i < size; i++) + { + value = (value << 8) | (uint)ReadByteOrThrow(); + } + + return value; + } + + internal long Signed(long size) + { + var value = Unsigned(size); + if (size is > 0 and < 8 && (value & (1UL << (int)((size * 8) - 1))) != 0) + { + value |= ulong.MaxValue << (int)(size * 8); + } + + return (long)value; + } + + internal double Float(long size) + { + Span buffer = stackalloc byte[8]; + if (size == 4) + { + stream.ReadExactly(buffer[..4]); + return BinaryPrimitives.ReadSingleBigEndian(buffer); + } + + if (size == 8) + { + stream.ReadExactly(buffer); + return BinaryPrimitives.ReadDoubleBigEndian(buffer); + } + + Skip(size); + return 0; + } + + internal string String(long size) => Encoding.UTF8.GetString(Bytes(size)).TrimEnd('\0'); + + internal byte[] Bytes(long size) + { + if (size < 0 || size > MaxElementInMemory) + { + throw new ContainerException("Elemento Matroska troppo grande."); + } + + 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; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs new file mode 100644 index 0000000..79b98a6 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -0,0 +1,122 @@ +namespace Febe.Core.Codecs.Containers; + +/// The container formats Febe reads without external programs. +public enum ContainerFormat +{ + /// ISO base media file format: MP4, MOV, 3GP, M4V (also fragmented). + IsoBmff, + + /// Matroska and WebM. + Matroska, + + /// RIFF AVI (also OpenDML). + Avi, +} + +/// Video codecs recognised in a container; only can be decoded. +public enum VideoCodec +{ + Unknown, + H264, + Hevc, + Vp8, + Vp9, + Av1, + Mpeg4Part2, + Mjpeg, +} + +/// Audio codecs recognised in a container. +public enum AudioCodec +{ + Unknown, + Aac, + Mp3, + Opus, + Vorbis, + Pcm, +} + +/// +/// One sample (an access unit) of a track: where its bytes are in the file and when it is decoded and shown, in units of +/// the track's . Samples are listed in decoding order. +/// +public readonly record struct MediaSample(long Offset, int Size, long DecodeTime, long PresentationTime, bool Key); + +/// A track of a container. +public abstract class MediaTrack +{ + /// Ticks per second of the sample times. + public long Timescale { get; init; } = 1000; + + /// Duration of the track in units; 0 when unknown. + public long Duration { get; init; } + + /// Samples in decoding order (empty when the container was read for its metadata only). + public IReadOnlyList Samples { get; init; } = []; + + /// The four-character code or codec identifier of the container, for messages. + public string CodecTag { get; init; } = string.Empty; + + /// Time in seconds of a value in track units. + public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0; +} + +/// The video track of a container. +public sealed class VideoTrack : MediaTrack +{ + public VideoCodec Codec { get; init; } + + /// Coded width in pixels (before rotation). + public int Width { get; init; } + + /// Coded height in pixels (before rotation). + public int Height { get; init; } + + /// Clockwise rotation to apply when showing the frames: 0, 90, 180 or 270. + public int Rotation { get; init; } + + /// The AVCDecoderConfigurationRecord (avcC) of an H.264 track stored with length prefixes. + public byte[]? AvcConfiguration { get; init; } + + /// True when the samples are an Annex B byte stream (start codes), as in AVI. + public bool AnnexB { get; init; } + + /// Width as shown (rotation applied). + public int DisplayWidth => Rotation % 180 == 0 ? Width : Height; + + /// Height as shown (rotation applied). + public int DisplayHeight => Rotation % 180 == 0 ? Height : Width; +} + +/// The audio track of a container. +public sealed class AudioTrack : MediaTrack +{ + public AudioCodec Codec { get; init; } + + public int SampleRate { get; init; } + + public int Channels { get; init; } + + /// The AudioSpecificConfig of an AAC track. + public byte[]? AacConfiguration { get; init; } +} + +/// What a container says: its creation time, duration and first video and audio tracks. +public sealed class MediaContainer +{ + public ContainerFormat Format { get; init; } + + /// Creation time written in the container, when plausible. + public DateTimeOffset? CreatedAt { get; init; } + + /// Duration of the whole presentation. + public TimeSpan? Duration { get; init; } + + public VideoTrack? Video { get; init; } + + public AudioTrack? Audio { get; init; } +} + +/// A container that cannot be read: damaged, truncated or of a shape Febe does not handle. +public sealed class ContainerException(string message) : Exception(message); diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs new file mode 100644 index 0000000..07571e2 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -0,0 +1,643 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// A sample to write: its size, its times in track units, whether it is a sync sample. +public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key); + +/// A track to write: H.264 video (with its avcC) or AAC audio (with its AudioSpecificConfig). +public sealed class Mp4OutputTrack +{ + public required bool IsVideo { get; init; } + + public required long Timescale { get; init; } + + public required IReadOnlyList Samples { get; init; } + + /// Writes the bytes of sample i (exactly its ) into the stream. + public required Action WriteSample { get; init; } + + public int Width { get; init; } + + public int Height { get; init; } + + /// Clockwise rotation written in the track matrix: 0, 90, 180 or 270. + public int Rotation { get; init; } + + public byte[]? AvcConfiguration { get; init; } + + public byte[]? AacConfiguration { get; init; } + + public int SampleRate { get; init; } + + public int Channels { get; init; } + + /// Duration of the last sample, when the times cannot tell it (0: as the one before it). + public long LastSampleDuration { get; init; } +} + +/// +/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: ftyp, then the +/// moov box (so the file plays while it downloads), then one mdat with the tracks interleaved about every +/// half second. +/// +public static class Mp4Writer +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + private const int MovieTimescale = 1000; + + /// Writes the tracks into (from its current position). + public static void Write(Stream output, IReadOnlyList tracks, DateTimeOffset? created = null) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(tracks); + if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0)) + { + throw new ArgumentException("Servono tracce con campioni.", nameof(tracks)); + } + + foreach (var track in tracks) + { + if (track.IsVideo ? track.AvcConfiguration is null : track.AacConfiguration is null) + { + throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks)); + } + } + + var timing = tracks.Select(Timing.Of).ToArray(); + var chunks = Interleave(tracks); + long payload = 0; + foreach (var track in tracks) + { + foreach (var s in track.Samples) + { + payload += s.Size; + } + } + + var wideMdat = payload + 8 > uint.MaxValue; + var ftyp = Ftyp(); + var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL; + + // The moov box has the same size whatever the chunk offsets: build it once to know where the data starts. + var co64 = false; + var moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time); + var dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8); + if (dataStart + payload > uint.MaxValue) + { + co64 = true; + moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time); + dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8); + } + + var offsets = new long[chunks.Count]; + var position = (long)dataStart; + for (var i = 0; i < chunks.Count; i++) + { + offsets[i] = position; + var (track, first, count) = chunks[i]; + for (var k = first; k < first + count; k++) + { + position += tracks[track].Samples[k].Size; + } + } + + moov = Moov(tracks, timing, chunks, offsets, co64, time); + output.Write(ftyp); + output.Write(moov); + Span header = stackalloc byte[16]; + if (wideMdat) + { + BinaryPrimitives.WriteUInt32BigEndian(header, 1); + "mdat"u8.CopyTo(header[4..]); + BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16)); + output.Write(header); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8)); + "mdat"u8.CopyTo(header[4..]); + output.Write(header[..8]); + } + + foreach (var (track, first, count) in chunks) + { + for (var k = first; k < first + count; k++) + { + var before = output.CanSeek ? output.Position : -1; + tracks[track].WriteSample(k, output); + if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size) + { + throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata."); + } + } + } + } + + /// Times of a track as the boxes need them. + private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey) + { + internal static Timing Of(Mp4OutputTrack track) + { + var samples = track.Samples; + var n = samples.Count; + var durations = new long[n]; + for (var i = 0; i < n - 1; i++) + { + durations[i] = Math.Max(0, samples[i + 1].DecodeTime - samples[i].DecodeTime); + } + + durations[n - 1] = track.LastSampleDuration > 0 ? track.LastSampleDuration : n > 1 ? durations[n - 2] : 1; + + // Decoding must not come after presentation: delay the decoding times when it would. + long shift = 0; + var minPts = long.MaxValue; + foreach (var s in samples) + { + shift = Math.Max(shift, s.DecodeTime - s.PresentationTime); + minPts = Math.Min(minPts, s.PresentationTime); + } + + var first = samples[0].DecodeTime; + var offsets = new int[n]; + var allKey = true; + for (var i = 0; i < n; i++) + { + offsets[i] = (int)Math.Clamp(samples[i].PresentationTime - samples[i].DecodeTime + shift, 0, int.MaxValue); + allKey &= samples[i].Key; + } + + long total = 0; + foreach (var d in durations) + { + total += d; + } + + // The edit list starts the presentation at the first shown sample. + var editTime = minPts - first + shift; + return new Timing(durations, offsets, total, editTime, allKey); + } + } + + private static List<(int Track, int First, int Count)> Interleave(IReadOnlyList tracks) + { + var list = new List<(int Track, int First, int Count, double Start)>(); + for (var t = 0; t < tracks.Count; t++) + { + var track = tracks[t]; + var samples = track.Samples; + var first = 0; + var limit = track.Timescale / 2; + 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 tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + { + long movieDuration = 0; + for (var t = 0; t < tracks.Count; t++) + { + movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale)); + } + + var moov = new Box("moov"); + var mvhd = new Box("mvhd"); + var wide = movieDuration > uint.MaxValue || time > uint.MaxValue; + mvhd.U32(wide ? 0x01000000u : 0); + Times(mvhd, wide, time, MovieTimescale, movieDuration); + mvhd.U32(0x00010000); + mvhd.U16(0x0100); + mvhd.Zero(10); + Matrix(mvhd, 0, 0, 0); + mvhd.Zero(24); + mvhd.U32((uint)tracks.Count + 1); + moov.Child(mvhd); + + for (var t = 0; t < tracks.Count; t++) + { + moov.Child(Trak(tracks[t], timing[t], t, chunks, offsets, co64, time)); + } + + return moov.ToArray(); + } + + private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale); + + private static void Times(Box box, bool wide, ulong time, long timescale, long duration) + { + if (wide) + { + box.U64(time); + box.U64(time); + box.U32((uint)timescale); + box.U64((ulong)duration); + } + else + { + box.U32((uint)time); + box.U32((uint)time); + box.U32((uint)timescale); + box.U32((uint)duration); + } + } + + private static void Matrix(Box box, int rotation, int width, int height) + { + int a = 0x10000, b = 0, c = 0, d = 0x10000, x = 0, y = 0; + switch (rotation) + { + case 90: + (a, b, c, d, x) = (0, 0x10000, -0x10000, 0, height << 16); + break; + case 180: + (a, d, x, y) = (-0x10000, -0x10000, width << 16, height << 16); + break; + case 270: + (a, b, c, d, y) = (0, -0x10000, 0x10000, 0, width << 16); + break; + } + + foreach (var v in new[] { a, b, 0, c, d, 0, x, y, 0x40000000 }) + { + box.U32((uint)v); + } + } + + private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + { + var trak = new Box("trak"); + var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale); + var wide = duration > uint.MaxValue || time > uint.MaxValue; + var tkhd = new Box("tkhd"); + tkhd.U32((wide ? 0x01000000u : 0) | 3); + if (wide) + { + tkhd.U64(time); + tkhd.U64(time); + tkhd.U32((uint)index + 1); + tkhd.U32(0); + tkhd.U64((ulong)duration); + } + else + { + tkhd.U32((uint)time); + tkhd.U32((uint)time); + tkhd.U32((uint)index + 1); + tkhd.U32(0); + tkhd.U32((uint)duration); + } + + tkhd.Zero(8); + tkhd.U16(0); + tkhd.U16(0); + tkhd.U16(track.IsVideo ? (ushort)0 : (ushort)0x0100); + tkhd.U16(0); + Matrix(tkhd, track.IsVideo ? track.Rotation : 0, track.Width, track.Height); + tkhd.U32(track.IsVideo ? (uint)track.Width << 16 : 0); + tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0); + trak.Child(tkhd); + + if (timing.EditMediaTime != 0) + { + var edts = new Box("edts"); + var elst = new Box("elst"); + elst.U32(0x01000000); + elst.U32(1); + elst.U64((ulong)duration); + elst.U64((ulong)timing.EditMediaTime); + elst.U16(1); + elst.U16(0); + edts.Child(elst); + trak.Child(edts); + } + + var mdia = new Box("mdia"); + var mdhd = new Box("mdhd"); + var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue; + mdhd.U32(mediaWide ? 0x01000000u : 0); + Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration); + mdhd.U16(0x55C4); // «und» + mdhd.U16(0); + mdia.Child(mdhd); + + var hdlr = new Box("hdlr"); + hdlr.U32(0); + hdlr.U32(0); + hdlr.Bytes(track.IsVideo ? "vide"u8 : "soun"u8); + hdlr.Zero(12); + hdlr.Bytes(track.IsVideo ? "VideoHandler\0"u8 : "SoundHandler\0"u8); + mdia.Child(hdlr); + + var minf = new Box("minf"); + if (track.IsVideo) + { + var vmhd = new Box("vmhd"); + vmhd.U32(1); + vmhd.Zero(8); + minf.Child(vmhd); + } + else + { + var smhd = new Box("smhd"); + smhd.U32(0); + smhd.Zero(4); + minf.Child(smhd); + } + + var dinf = new Box("dinf"); + var dref = new Box("dref"); + dref.U32(0); + dref.U32(1); + var url = new Box("url "); + url.U32(1); + dref.Child(url); + dinf.Child(dref); + minf.Child(dinf); + minf.Child(Stbl(track, timing, index, chunks, offsets, co64)); + mdia.Child(minf); + trak.Child(mdia); + return trak; + } + + private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64) + { + var stbl = new Box("stbl"); + var stsd = new Box("stsd"); + stsd.U32(0); + stsd.U32(1); + stsd.Child(track.IsVideo ? Avc1(track) : Mp4a(track)); + stbl.Child(stsd); + + // stts: runs of equal durations. + var stts = new Box("stts"); + var runs = new List<(int Count, long Delta)>(); + foreach (var d in timing.Durations) + { + if (runs.Count > 0 && runs[^1].Delta == d) + { + runs[^1] = (runs[^1].Count + 1, d); + } + else + { + runs.Add((1, d)); + } + } + + stts.U32(0); + stts.U32((uint)runs.Count); + foreach (var (count, delta) in runs) + { + stts.U32((uint)count); + stts.U32((uint)delta); + } + + stbl.Child(stts); + + var anyOffset = false; + foreach (var o in timing.CompositionOffsets) + { + anyOffset |= o != 0; + } + + if (anyOffset) + { + var ctts = new Box("ctts"); + var cruns = new List<(int Count, int Offset)>(); + foreach (var o in timing.CompositionOffsets) + { + if (cruns.Count > 0 && cruns[^1].Offset == o) + { + cruns[^1] = (cruns[^1].Count + 1, o); + } + else + { + cruns.Add((1, o)); + } + } + + ctts.U32(0); + ctts.U32((uint)cruns.Count); + foreach (var (count, offset) in cruns) + { + ctts.U32((uint)count); + ctts.U32((uint)offset); + } + + stbl.Child(ctts); + } + + if (track.IsVideo && !timing.AllKey) + { + var stss = new Box("stss"); + var keys = new List(); + for (var i = 0; i < track.Samples.Count; i++) + { + if (track.Samples[i].Key) + { + keys.Add(i + 1); + } + } + + stss.U32(0); + stss.U32((uint)keys.Count); + foreach (var k in keys) + { + stss.U32((uint)k); + } + + stbl.Child(stss); + } + + // stsc and the chunk offsets of this track, in file order. + var stsc = new Box("stsc"); + var entries = new List<(int FirstChunk, int PerChunk)>(); + var mine = new List(); + for (var c = 0; c < chunks.Count; c++) + { + if (chunks[c].Track != index) + { + continue; + } + + mine.Add(offsets[c]); + if (entries.Count == 0 || entries[^1].PerChunk != chunks[c].Count) + { + entries.Add((mine.Count, chunks[c].Count)); + } + } + + stsc.U32(0); + stsc.U32((uint)entries.Count); + foreach (var (firstChunk, perChunk) in entries) + { + stsc.U32((uint)firstChunk); + stsc.U32((uint)perChunk); + stsc.U32(1); + } + + stbl.Child(stsc); + + var stsz = new Box("stsz"); + stsz.U32(0); + stsz.U32(0); + stsz.U32((uint)track.Samples.Count); + foreach (var s in track.Samples) + { + stsz.U32((uint)s.Size); + } + + stbl.Child(stsz); + + var stco = new Box(co64 ? "co64" : "stco"); + stco.U32(0); + stco.U32((uint)mine.Count); + foreach (var o in mine) + { + if (co64) + { + stco.U64((ulong)o); + } + else + { + stco.U32((uint)o); + } + } + + stbl.Child(stco); + return stbl; + } + + private static Box Avc1(Mp4OutputTrack track) + { + var entry = new Box("avc1"); + entry.Zero(6); + entry.U16(1); + entry.Zero(16); + entry.U16((ushort)track.Width); + entry.U16((ushort)track.Height); + entry.U32(0x00480000); + entry.U32(0x00480000); + entry.U32(0); + entry.U16(1); + entry.Zero(32); + entry.U16(0x0018); + entry.U16(0xFFFF); + var avcC = new Box("avcC"); + avcC.Bytes(track.AvcConfiguration); + entry.Child(avcC); + return entry; + } + + private static Box Mp4a(Mp4OutputTrack track) + { + var entry = new Box("mp4a"); + entry.Zero(6); + entry.U16(1); + entry.Zero(8); + entry.U16((ushort)Math.Max(1, track.Channels)); + entry.U16(16); + entry.U16(0); + entry.U16(0); + entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16); + + var asc = track.AacConfiguration!; + var decoderSpecific = Descriptor(0x05, asc); + var config = new byte[13 + decoderSpecific.Length]; + config[0] = 0x40; // MPEG-4 audio + config[1] = 0x15; // audio stream + decoderSpecific.CopyTo(config, 13); + byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])]; + var esds = new Box("esds"); + esds.U32(0); + esds.Bytes(Descriptor(0x03, es)); + entry.Child(esds); + return entry; + } + + private static byte[] Descriptor(byte tag, ReadOnlySpan body) + { + var data = new byte[5 + body.Length]; + data[0] = tag; + var length = body.Length; + data[1] = (byte)(0x80 | ((length >> 21) & 0x7F)); + data[2] = (byte)(0x80 | ((length >> 14) & 0x7F)); + data[3] = (byte)(0x80 | ((length >> 7) & 0x7F)); + data[4] = (byte)(length & 0x7F); + body.CopyTo(data.AsSpan(5)); + return data; + } + + /// A box being built in memory. + private sealed class Box + { + private readonly MemoryStream body = new(); + + internal Box(string type) => Type = type; + + internal string Type { get; } + + internal void U16(ushort v) + { + Span b = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(b, v); + body.Write(b); + } + + internal void U32(uint v) + { + Span b = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(b, v); + body.Write(b); + } + + internal void U64(ulong v) + { + Span b = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(b, v); + body.Write(b); + } + + internal void Zero(int count) + { + for (var i = 0; i < count; i++) + { + body.WriteByte(0); + } + } + + internal void Bytes(ReadOnlySpan data) => body.Write(data); + + internal void Child(Box child) => body.Write(child.ToArray()); + + internal byte[] ToArray() + { + var size = body.Length + 8; + var result = new byte[size]; + BinaryPrimitives.WriteUInt32BigEndian(result, (uint)size); + Encoding.Latin1.GetBytes(Type, result.AsSpan(4, 4)); + body.Position = 0; + body.ReadExactly(result, 8, (int)body.Length); + return result; + } + } +} diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index d250a4b..eb9745c 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -18,7 +18,7 @@ internal sealed record ContentFacts( /// /// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for -/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, ffprobe as an extra for the rest). +/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, the in-house container readers for WebM, Matroska and AVI). /// 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); if (extra is not null) { diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 0bae0c3..61c7f49 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -688,7 +688,7 @@ public sealed class ImportCopier(ImportEnvironment env) return null; } - var frame = await env.Frames.ExtractJpegAsync(videoPath, ct).ConfigureAwait(false); + var frame = await env.Frames.ExtractImageAsync(videoPath, ct).ConfigureAwait(false); return frame is null ? null : new MemoryStream(frame, writable: false); } diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs index e1d4cc1..ca0a337 100644 --- a/src/Febe.Core/Import/ImportEnvironment.cs +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -33,10 +33,13 @@ public sealed record ImportEnvironment /// public PerceptualHashIndex? HashIndex { get; init; } - /// ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile. - public VideoFrameExtractor? Frames { get; init; } + /// The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile. + public VideoFrameDecoder? Frames { get; init; } - /// ffprobe, an optional extra for videos the hand-written reader does not cover. + /// + /// Reader of the metadata of videos the MP4 header reader does not cover (WebM, Matroska, AVI). Null: the in-house + /// on the clock of this environment. + /// public IVideoMetadataProbe? VideoProbe { get; init; } /// «Imposta la data del file a quella di pubblicazione» (library setting). diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index 3ed596b..553c94f 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -21,8 +21,8 @@ var import = new ImportService(new ImportEnvironment Clock = clock, Thumbnails = new ThumbnailStore(data.Thumbnails), HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta - Frames = VideoFrameExtractor.TryCreate(), // miniature dei video importati, se c'è ffmpeg - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), // facoltativo + Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa + VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita) SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, 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. - **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF - `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; ffprobe - solo come aggiunta per gli altri video), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora + `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di + contenitori scritti in casa per WebM, Matroska 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`). - **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 diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index 2a8bfce..c465b63 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -1,192 +1,53 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text.Json; -using Febe.Core.Security; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.Containers; namespace Febe.Core.Import; -/// Metadata of a video read by an external tool. +/// Metadata of a video read from its container. public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); -/// -/// Reads creation time, duration and size of videos the hand-written reader does not cover (WebM, Matroska, AVI, ...). -/// Optional: the analysis works without it (spec §9.2: «oppure si usa ffprobe dove è presente»). -/// +/// Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI). public interface IVideoMetadataProbe { - /// Metadata of a video file, read-only; null when the tool cannot read it. + /// Metadata of a video file, read-only; null when it cannot be read. Task ProbeAsync(string path, CancellationToken ct = default); } /// -/// with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is -/// parsed with ; error output is never logged (it may contain paths). +/// written in house on the container readers of : no +/// external program. Only the headers are read (no sample tables), so it is quick also on long videos. /// -public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe +public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMetadataProbe { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); + private readonly IClock _clock = clock ?? new SystemClock(); - private FfprobeVideoMetadataProbe(string executable) => Executable = executable; - - /// Full path of ffprobe. - public string Executable { get; } - - /// Finds ffprobe on the PATH (or at ); null when it is not available. - public static FfprobeVideoMetadataProbe? TryCreate(string? explicitPath = null) - { - if (!string.IsNullOrWhiteSpace(explicitPath)) - { - return File.Exists(explicitPath) ? new FfprobeVideoMetadataProbe(Path.GetFullPath(explicitPath)) : null; - } - - var name = OperatingSystem.IsWindows() ? "ffprobe.exe" : "ffprobe"; - foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) - { - try - { - var candidate = Path.Combine(folder.Trim('"'), name); - if (File.Exists(candidate)) - { - return new FfprobeVideoMetadataProbe(candidate); - } - } - catch (ArgumentException) - { - // A malformed PATH entry: skip it. - } - } - - return null; - } - - /// - /// The start of ffprobe for : its arguments, and the environment of Febe without - /// FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last (spec §13.2). - /// - internal ProcessStartInfo BuildStartInfo(string path) - { - var start = new ProcessStartInfo(Executable) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - }; - foreach (var argument in new[] - { - "-hide_banner", "-v", "error", "-print_format", "json", - "-show_entries", "format=duration:format_tags=creation_time:stream=codec_type,width,height:stream_tags=rotate,creation_time", - "-i", path, - }) - { - start.ArgumentList.Add(argument); - } - - return start.WithoutSecrets(); - } - - public async Task ProbeAsync(string path, CancellationToken ct = default) + public Task ProbeAsync(string path, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(path); - using var process = new Process { StartInfo = BuildStartInfo(path) }; + ct.ThrowIfCancellationRequested(); + return Task.FromResult(Probe(path, _clock.Now)); + } + + /// The metadata of ; null when the file is unreadable or of another format. + public static VideoMetadata? Probe(string path, DateTimeOffset now) + { try { - if (!process.Start()) + if (ContainerReader.ReadFile(path, now, samples: false) is not { } container) { return null; } + + var video = container.Video; + int? width = video is { DisplayWidth: > 0 } ? video.DisplayWidth : null; + int? height = video is { DisplayHeight: > 0 } ? video.DisplayHeight : null; + var duration = container.Duration is { } d && d > TimeSpan.Zero ? d : (TimeSpan?)null; + return new VideoMetadata(container.CreatedAt, duration, width, height); } - catch (System.ComponentModel.Win32Exception) + catch (Exception ex) when (ex is ContainerException or IOException or EndOfStreamException or UnauthorizedAccessException + or ArgumentException or OverflowException or InvalidDataException) { - return null; + return null; // a damaged or unreadable file: as if the container had nothing to say } - - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(Timeout); - string output; - try - { - var read = process.StandardOutput.ReadToEndAsync(timeout.Token); - var drain = process.StandardError.ReadToEndAsync(timeout.Token); - await Task.WhenAll(read, drain).ConfigureAwait(false); - await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); - output = read.Result; - } - catch (OperationCanceledException) - { - try - { - process.Kill(entireProcessTree: true); - } - catch (InvalidOperationException) - { - } - - ct.ThrowIfCancellationRequested(); - return null; - } - - return process.ExitCode == 0 ? Parse(output) : null; - } - - /// Parses the JSON printed by ffprobe. - internal static VideoMetadata? Parse(string json) - { - try - { - using var document = JsonDocument.Parse(json); - var root = document.RootElement; - DateTimeOffset? created = null; - TimeSpan? duration = null; - int? width = null, height = null; - if (root.TryGetProperty("format", out var format)) - { - if (format.TryGetProperty("duration", out var d) && d.ValueKind == JsonValueKind.String - && double.TryParse(d.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0) - { - duration = TimeSpan.FromSeconds(seconds); - } - - created = CreationTime(format); - } - - if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array) - { - foreach (var stream in streams.EnumerateArray()) - { - if (stream.TryGetProperty("codec_type", out var type) && type.ValueKind == JsonValueKind.String && type.GetString() == "video" - && stream.TryGetProperty("width", out var w) && w.TryGetInt32(out var wv) && wv > 0 - && stream.TryGetProperty("height", out var h) && h.TryGetInt32(out var hv) && hv > 0) - { - var rotate = stream.TryGetProperty("tags", out var tags) && tags.TryGetProperty("rotate", out var r) - && int.TryParse(r.ValueKind == JsonValueKind.String ? r.GetString() : r.GetRawText(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees) - ? Math.Abs(degrees) % 180 - : 0; - (width, height) = rotate == 90 ? (hv, wv) : (wv, hv); - created ??= CreationTime(stream); - break; - } - } - } - - return new VideoMetadata(created, duration, width, height); - } - catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException) - { - return null; // an unexpected shape: as if ffprobe had nothing to say - } - } - - private static DateTimeOffset? CreationTime(JsonElement element) - { - if (element.TryGetProperty("tags", out var tags) && tags.ValueKind == JsonValueKind.Object - && tags.TryGetProperty("creation_time", out var value) && value.ValueKind == JsonValueKind.String - && DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant) - && instant.Year >= 1995) - { - return instant.ToUniversalTime(); - } - - return null; } } diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 1b59398..6554f4d 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -14,7 +14,7 @@ public sealed record RebuildOptions /// public IReadOnlyList ExtraAccountFolders { get; init; } = []; - /// Create missing thumbnails (photos; videos with ffmpeg when available). + /// Create missing thumbnails (photos; H.264 videos with the in-house frame decoder). public bool CreateThumbnails { get; init; } = true; /// Files hashed in parallel. @@ -80,7 +80,7 @@ public sealed class LibraryRebuilder( LibraryLayout layout, IClock clock, ThumbnailStore? thumbnails = null, - VideoFrameExtractor? frames = null, + VideoFrameDecoder? frames = null, PerceptualHashIndex? hashIndex = null) { private const int BatchSize = 200; @@ -468,7 +468,7 @@ public sealed class LibraryRebuilder( } else if (isVideo && createThumbnails && thumbnails is not null && !thumbnail && frames is not null) { - var frame = await frames.ExtractJpegAsync(path, ct).ConfigureAwait(false); + var frame = await frames.ExtractImageAsync(path, ct).ConfigureAwait(false); if (frame is not null) { using var stream = new MemoryStream(frame); diff --git a/src/Febe.Core/Library/ThumbnailStore.cs b/src/Febe.Core/Library/ThumbnailStore.cs index 7dceb90..1c7bd2f 100644 --- a/src/Febe.Core/Library/ThumbnailStore.cs +++ b/src/Febe.Core/Library/ThumbnailStore.cs @@ -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 /// Dati/miniature, in 256 shard folders named after the first two hex digits of the key. The key is the /// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a -/// frame (); without either, the interface shows the neutral tile +/// frame (); without either, the interface shows the neutral tile /// (). /// public sealed class ThumbnailStore diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs new file mode 100644 index 0000000..420ef98 --- /dev/null +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -0,0 +1,492 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Library; + +/// A decoded video frame in 8-bit RGB, rows top to bottom, three bytes per pixel (red, green, blue). +public sealed record VideoImage(int Width, int Height, byte[] Rgb) +{ + /// The image as an uncompressed 24-bit BMP file (Windows bitmap, rows bottom to top). + public byte[] ToBmp() + { + var stride = ((Width * 3) + 3) & ~3; + var size = 54 + (stride * Height); + var bmp = new byte[size]; + var span = bmp.AsSpan(); + span[0] = (byte)'B'; + span[1] = (byte)'M'; + BinaryPrimitives.WriteInt32LittleEndian(span[2..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54); + BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40); + BinaryPrimitives.WriteInt32LittleEndian(span[18..], Width); + BinaryPrimitives.WriteInt32LittleEndian(span[22..], Height); + BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1); + BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24); + BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * Height); + BinaryPrimitives.WriteInt32LittleEndian(span[38..], 2835); // 72 dpi + BinaryPrimitives.WriteInt32LittleEndian(span[42..], 2835); + for (var y = 0; y < Height; y++) + { + var source = Rgb.AsSpan(y * Width * 3, Width * 3); + var target = span.Slice(54 + ((Height - 1 - y) * stride), Width * 3); + for (var x = 0; x < source.Length; x += 3) + { + target[x] = source[x + 2]; + target[x + 1] = source[x + 1]; + target[x + 2] = source[x]; + } + } + + return bmp; + } +} + +/// +/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole +/// video. is the largest mean difference, on a 0–255 scale, between the first sampled frame and +/// the others, measured on a coarse grid so that the noise of the compression does not count. +/// +public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference); + +/// +/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover): +/// the container readers of and the H.264 decoder written in house +/// (). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the +/// neutral tile. +/// +public sealed class VideoFrameDecoder +{ + /// Differences up to this value (0–255) count as compression noise of a still picture. + public const double StillThreshold = 3.0; + + 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); + + /// The shared instance: it keeps no state between calls. + public static VideoFrameDecoder Instance { get; } = new(); + + /// + /// A frame of the video as a BMP image, taken one second in (or the first frame of shorter videos), rotated as the + /// video is shown; null when the file cannot be read or decoded. + /// + public Task ExtractImageAsync(string videoPath, CancellationToken ct = default) => + ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 0, ct); + + /// + /// A frame of the video at (the first frame when the video is shorter), as a BMP image whose + /// long side is at most pixels (0: full size); null when it cannot be decoded. + /// + public async Task ExtractImageAsync(string videoPath, TimeSpan at, int maxLongSide, CancellationToken ct = default) + { + var image = await DecodeFrameAsync(videoPath, at, maxLongSide, ct).ConfigureAwait(false); + return image?.ToBmp(); + } + + /// A frame of the video at in RGB; null when it cannot be decoded. + public Task DecodeFrameAsync(string videoPath, TimeSpan at, int maxLongSide = 0, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); + return Task.Run(() => DecodeFrame(videoPath, at, maxLongSide, ct), ct); + } + + /// + /// Whether the video shows a still picture, from frames spread over its whole length; null when it cannot be told + /// (unreadable file, codec not decoded, or one long run without key frames in a long video). + /// + public Task AnalyseStillnessAsync(string videoPath, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); + return Task.Run(() => 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(); + 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; + + /// The H.264 video track of a container with its samples; null for other codecs or without video. + private static VideoTrack? Open(Stream stream) + { + // The creation time does not matter here: any date is accepted (the readers add a day to «now»). + var container = ContainerReader.Read(stream, AnyDate, samples: true); + return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video + && (video.AnnexB || video.AvcConfiguration is not null) + ? video + : null; + } + + /// The sample shown at from the start; the first shown one when the video is shorter. + private static int SampleAt(VideoTrack video, TimeSpan at) + { + var samples = video.Samples; + long first = long.MaxValue, last = long.MinValue; + foreach (var s in samples) + { + first = Math.Min(first, s.PresentationTime); + last = Math.Max(last, s.PresentationTime); + } + + var wanted = first + (long)(at.TotalSeconds * video.Timescale); + return Closest(samples, wanted > last ? first : wanted); + } + + private static int Closest(IReadOnlyList samples, long time) + { + var best = 0; + var distance = long.MaxValue; + for (var i = 0; i < samples.Count; i++) + { + var d = Math.Abs(samples[i].PresentationTime - time); + if (d < distance) + { + (best, distance) = (i, d); + } + } + + return best; + } + + private static int[] KeyIndices(VideoTrack video) + { + var keys = new List(); + for (var i = 0; i < video.Samples.Count; i++) + { + if (video.Samples[i].Key) + { + keys.Add(i); + } + } + + return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys]; + } + + 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)]; + } + + /// Decodes chosen samples, each from the key frame before it, reusing a run when the targets share it. + private sealed class Decoding(Stream stream, VideoTrack video) + { + private readonly Dictionary found = []; + private readonly HashSet wanted = []; + private byte[] buffer = new byte[64 * 1024]; + + internal Dictionary 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; + } + } + + /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise. + 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; + } + + /// + /// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited + /// or full range, reduced by an integer factor to fit , then rotated clockwise. + /// + internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) + { + 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); + } +} diff --git a/src/Febe.Core/Library/VideoFrameExtractor.cs b/src/Febe.Core/Library/VideoFrameExtractor.cs deleted file mode 100644 index a4ed64f..0000000 --- a/src/Febe.Core/Library/VideoFrameExtractor.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Diagnostics; -using Febe.Core.Security; - -namespace Febe.Core.Library; - -/// -/// Extracts a frame from a video with ffmpeg, when ffmpeg is installed (spec §8.4: thumbnails of imported videos and of -/// videos without a cover). In Docker ffmpeg is part of the image (§11); on Windows it is optional. -/// -public sealed class VideoFrameExtractor -{ - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); - - private VideoFrameExtractor(string executable) => Executable = executable; - - /// Full path of ffmpeg. - public string Executable { get; } - - /// Finds ffmpeg on the PATH (or at ); null when it is not available. - public static VideoFrameExtractor? TryCreate(string? explicitPath = null) - { - if (!string.IsNullOrWhiteSpace(explicitPath)) - { - return File.Exists(explicitPath) ? new VideoFrameExtractor(Path.GetFullPath(explicitPath)) : null; - } - - var name = OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"; - var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; - foreach (var folder in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) - { - try - { - var candidate = Path.Combine(folder.Trim('"'), name); - if (File.Exists(candidate)) - { - return new VideoFrameExtractor(candidate); - } - } - catch (ArgumentException) - { - // A malformed PATH entry: skip it. - } - } - - return null; - } - - /// - /// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot - /// read the file. - /// - public async Task ExtractJpegAsync(string videoPath, CancellationToken ct = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); - foreach (var seek in new[] { "1", "0" }) - { - var frame = await RunAsync(videoPath, seek, ct).ConfigureAwait(false); - if (frame is { Length: > 0 }) - { - return frame; - } - } - - return null; - } - - /// - /// The start of ffmpeg for one frame of at seconds: its - /// arguments, and the environment of Febe without FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last - /// (spec §13.2). - /// - internal ProcessStartInfo BuildStartInfo(string videoPath, string seek) - { - var start = new ProcessStartInfo(Executable) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - RedirectStandardInput = false, - UseShellExecute = false, - CreateNoWindow = true, - }; - foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-ss", seek, "-i", videoPath, "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-q:v", "3", "-" }) - { - start.ArgumentList.Add(argument); - } - - return start.WithoutSecrets(); - } - - private async Task RunAsync(string videoPath, string seek, CancellationToken ct) - { - using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) }; - try - { - if (!process.Start()) - { - return null; - } - } - catch (System.ComponentModel.Win32Exception) - { - return null; - } - - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(Timeout); - using var output = new MemoryStream(); - try - { - var copy = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); - var drainErrors = process.StandardError.ReadToEndAsync(timeout.Token); // never logged: may contain paths - await Task.WhenAll(copy, drainErrors).ConfigureAwait(false); - await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - try - { - process.Kill(entireProcessTree: true); - } - catch (InvalidOperationException) - { - } - - ct.ThrowIfCancellationRequested(); - return null; - } - - return process.ExitCode == 0 && output.Length > 0 ? output.ToArray() : null; - } -} diff --git a/src/Febe.Core/Security/ChildProcessEnvironment.cs b/src/Febe.Core/Security/ChildProcessEnvironment.cs index cb2b501..2b18ecd 100644 --- a/src/Febe.Core/Security/ChildProcessEnvironment.cs +++ b/src/Febe.Core/Security/ChildProcessEnvironment.cs @@ -3,7 +3,7 @@ using System.Diagnostics; namespace Febe.Core.Security; /// -/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36, +/// What a process Febe starts (Chromium, Edge, Xvfb, Explorer) must not inherit from Febe (issue #36, /// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its /// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site. /// diff --git a/src/Febe.Web/Import/ImportHub.cs b/src/Febe.Web/Import/ImportHub.cs index 55fe82b..ec1fab2 100644 --- a/src/Febe.Web/Import/ImportHub.cs +++ b/src/Febe.Web/Import/ImportHub.cs @@ -122,8 +122,8 @@ public sealed class ImportHub : IAsyncDisposable Clock = _clock, Thumbnails = library.Thumbnails, HashIndex = library.HashIndex, - Frames = VideoFrameExtractor.TryCreate(), - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), + Frames = VideoFrameDecoder.Instance, + VideoProbe = new ContainerVideoMetadataProbe(_clock), SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, DataFolder = library.Data.Root, diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index a09b4d6..69050f6 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -71,7 +71,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | `IDiagnosticSource` (`Engine/DiagnosticSource.cs`) | `NoDiagnosticSource`: niente registrato, il rapporto ha gli elenchi vuoti (prove, avvio con un problema di configurazione) | `Febe.App`: `RecordedDiagnosticSource` sul registratore `CollectionDiagnostics` (registro in `Dati/diagnostica`, 14 giorni, e sessioni in corso); dimostrazione: `DemoDiagnosticSource`, secondo la scena | | `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` | | `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) | -| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) | +| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (decodificatore dei fotogrammi, cartella sorgente) | - `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già `PUT /api/settings/general`); a copia finita pubblica `LibraryChange` con motivo `import`. diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs index 7e27485..c824448 100644 --- a/src/Febe.Web/Library/DataFolderServices.cs +++ b/src/Febe.Web/Library/DataFolderServices.cs @@ -200,7 +200,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock var progress = new SyncProgress(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked }); try { - var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameExtractor.TryCreate(), library.HashIndex); + var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameDecoder.Instance, library.HashIndex); var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false); State = State with { Running = false, Report = report, FinishedAt = clock.Now }; changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); diff --git a/tests/Febe.Tests/Import/ImportAnalysisTests.cs b/tests/Febe.Tests/Import/ImportAnalysisTests.cs index cd16f2d..278fa77 100644 --- a/tests/Febe.Tests/Import/ImportAnalysisTests.cs +++ b/tests/Febe.Tests/Import/ImportAnalysisTests.cs @@ -23,8 +23,8 @@ public sealed class ImportAnalysisTests bed.Write("marta.demo/travestita.png", ImportTestFiles.Photo(4, 320, 240)); bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5)); bed.Write("marta.demo/Thumbs.db", [1, 2, 3]); - var realVideo = Path.Combine(bed.Source, "marta.demo", "storie", "ffmpeg.mp4"); - var withFfmpeg = ImportTestFiles.TryMakeMp4WithFfmpeg(realVideo, new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero)); + bed.Write("marta.demo/storie/vero.mp4", ImportTestFiles.RealMp4(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero))); + bed.Write("marta.demo/storie/vero.webm", ImportTestFiles.RealWebm(new DateTimeOffset(2021, 4, 5, 6, 7, 8, TimeSpan.Zero))); var before = bed.Fingerprint(); var run = await bed.AnalyzeAsync(); @@ -32,16 +32,18 @@ public sealed class ImportAnalysisTests Assert.AreEqual(ImportRunState.Reviewing, run.State); Assert.IsNotNull(run.AnalyzedAt); CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "L'analisi è in sola lettura: nessun file della sorgente cambia."); - var files = (await bed.FilesAsync(run.Id)).Where(f => !f.RelativePath.EndsWith("ffmpeg.mp4", StringComparison.Ordinal)).ToList(); - Assert.HasCount(7, files, "Thumbs.db non è un contenuto e non si elenca."); - if (withFfmpeg) - { - var real = await bed.FileAsync(run.Id, "marta.demo/storie/ffmpeg.mp4"); - Assert.AreEqual("video/mp4", real.ContentType); - Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); - Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); - Assert.AreEqual((64, 48), (real.Width, real.Height)); - } + var files = await bed.FilesAsync(run.Id); + Assert.HasCount(9, files, "Thumbs.db non è un contenuto e non si elenca."); + var real = await bed.FileAsync(run.Id, "marta.demo/storie/vero.mp4"); + Assert.AreEqual("video/mp4", real.ContentType); + Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); + Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (real.Width!.Value, real.Height!.Value)); + var webm = await bed.FileAsync(run.Id, "marta.demo/storie/vero.webm"); + Assert.AreEqual("video/webm", webm.ContentType); + Assert.AreEqual(new DateTimeOffset(2021, 4, 5, 6, 7, 8, TimeSpan.Zero), webm.TakenAt, "Data di creazione dal lettore Matroska scritto in casa."); + Assert.AreEqual(ImportDateSource.Metadata, webm.DateSource); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (webm.Width!.Value, webm.Height!.Value)); Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed)); @@ -84,15 +86,15 @@ public sealed class ImportAnalysisTests Assert.IsNull(loose.ProbableAccount, "«Foto sparse» non può essere un nome utente."); var summary = await bed.Review.GetSummaryAsync(run.Id); - Assert.AreEqual(withFfmpeg ? 8 : 7, summary.Files); - Assert.AreEqual(withFfmpeg ? 7 : 6, summary.ByOutcome[ImportOutcome.New]); + Assert.AreEqual(9, summary.Files); + Assert.AreEqual(8, summary.ByOutcome[ImportOutcome.New]); Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]); var marta = summary.Folders.Single(f => f.Folder == "marta.demo"); Assert.AreEqual(FolderTargetKind.NewArchiveAccount, marta.Target.Kind, "Un nome valido senza account: nuovo account, solo archivio."); Assert.AreEqual("marta.demo", marta.Target.Username); Assert.AreEqual(FolderTargetKind.None, summary.Folders.Single(f => f.Folder == "Foto sparse").Target.Kind, "Nessun nome riconosciuto: nessuna scelta fatta."); Assert.IsTrue(summary.CanMove); - StringAssert.StartsWith(summary.Headline, withFfmpeg ? "8 file, " : "7 file, "); + StringAssert.StartsWith(summary.Headline, "9 file, "); StringAssert.EndsWith(summary.Headline, "Nessun file è stato ancora copiato."); } diff --git a/tests/Febe.Tests/Import/MediaReaderTests.cs b/tests/Febe.Tests/Import/MediaReaderTests.cs index d2996b3..a291ddc 100644 --- a/tests/Febe.Tests/Import/MediaReaderTests.cs +++ b/tests/Febe.Tests/Import/MediaReaderTests.cs @@ -121,55 +121,41 @@ public sealed class MediaReaderTests } [TestMethod] - public void AnMp4MadeByFfmpegCarriesItsCreationTime() + public void ARealMp4CarriesItsCreationTime() { using var temp = new TempFolder("mp4"); var path = temp.Combine("prova.mp4"); var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); - if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) - { - Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore."); - } + File.WriteAllBytes(path, ImportTestFiles.RealMp4(created)); Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType); var info = Mp4Reader.ReadFile(path, Now); Assert.AreEqual(created, info?.CreatedAt); - Assert.AreEqual(64, info?.Width); - Assert.AreEqual(48, info?.Height); - Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500)); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (info!.Width!.Value, info.Height!.Value)); + Assert.IsTrue(info.Duration > TimeSpan.FromMilliseconds(500)); } [TestMethod] - public async Task FfprobeIsAnOptionalExtra() + public async Task TheContainerProbeReadsWhatTheMp4ReaderDoesNot() { - var parsed = FfprobeVideoMetadataProbe.Parse(""" - {"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}], - "format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}} - """); - Assert.AreEqual(new DateTimeOffset(2020, 8, 9, 10, 11, 12, TimeSpan.Zero), parsed?.CreatedAt); - Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration); - Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height)); - Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json")); - Assert.AreEqual(640, FfprobeVideoMetadataProbe.Parse("""{"streams":[{"codec_type":"video","width":640,"height":480,"tags":{"rotate":0}}],"format":{"tags":{"creation_time":5}}}""")?.Width, "Valori di tipo inatteso non fanno fallire la lettura."); - - var probe = FfprobeVideoMetadataProbe.TryCreate(); - if (probe is null) - { - Assert.Inconclusive("ffprobe non è installato."); - return; - } - - using var temp = new TempFolder("ffprobe"); - var path = temp.Combine("prova.mp4"); + using var temp = new TempFolder("sonda"); + var webm = temp.Combine("prova.webm"); + var mp4 = temp.Combine("prova.mp4"); var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); - if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) + File.WriteAllBytes(webm, ImportTestFiles.RealWebm(created)); + File.WriteAllBytes(mp4, ImportTestFiles.RealMp4(created)); + Assert.AreEqual("video/webm", MediaSniffer.DetectFile(webm)?.ContentType); + + var probe = new ContainerVideoMetadataProbe(); + foreach (var path in new[] { webm, mp4 }) { - Assert.Inconclusive("ffmpeg non è installato."); + var metadata = await probe.ProbeAsync(path); + Assert.AreEqual(created, metadata?.CreatedAt, path); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (metadata!.Width!.Value, metadata.Height!.Value), path); + Assert.IsTrue(metadata.Duration > TimeSpan.FromMilliseconds(500), path); } - var metadata = await probe.ProbeAsync(path); - Assert.AreEqual(created, metadata?.CreatedAt); - Assert.AreEqual(64, metadata?.Width); + Assert.IsNull(await probe.ProbeAsync(temp.Combine("non-esiste.webm"))); } [TestMethod] diff --git a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs index d6ad1de..e6c85fa 100644 --- a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs +++ b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs @@ -1,6 +1,6 @@ using System.Buffers.Binary; -using System.Diagnostics; using System.Text; +using Febe.Tests.Codecs.Containers; using Febe.Tests.Support; using SkiaSharp; @@ -199,31 +199,16 @@ internal static class ImportTestFiles return output.ToArray(); } - /// Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing. - public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt) - { - var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists); - if (ffmpeg is null) - { - return false; - } + /// + /// A real H.264 MP4 (a conformance stream, 176×144, muxed by the in-house writer) with the given creation time. + /// + public static byte[] RealMp4(DateTimeOffset createdAt) => TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"), createdAt); - var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; - foreach (var argument in new[] - { - "-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x3366aa:s=64x48:d=1:r=10", - "-metadata", "creation_time=" + createdAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "Z", - "-c:v", "mpeg4", "-f", "mp4", path, - }) - { - start.ArgumentList.Add(argument); - } + /// A real H.264 WebM-style Matroska file (the same stream) with the given creation time. + public static byte[] RealWebm(DateTimeOffset createdAt) => TestVideos.Matroska(ElementaryStream.Load("BA1_Sony_D"), createdAt, webm: true); - using var process = Process.Start(start)!; - process.StandardError.ReadToEnd(); - process.WaitForExit(30_000); - return process.ExitCode == 0 && File.Exists(path); - } + /// Width and height of and . + public static (int Width, int Height) RealVideoSize => (176, 144); /// The PNG encoding of a generated scene. public static byte[] Png(int scene, int width = 400, int height = 300) diff --git a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs index b07a2f4..de3e82c 100644 --- a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs +++ b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs @@ -1,4 +1,5 @@ using Febe.Core.Library; +using Febe.Tests.Codecs.Containers; using Febe.Tests.Support; using SkiaSharp; @@ -105,39 +106,19 @@ public sealed class ThumbnailStoreTests } [TestMethod] - public async Task VideoFramesComeFromFfmpegWhenAvailable() + public async Task VideoFramesComeFromTheInHouseDecoder() { - var ffmpeg = VideoFrameExtractor.TryCreate(); - if (ffmpeg is null) - { - Assert.Inconclusive("ffmpeg non è installato: le miniature dei video senza copertina usano la tessera neutra."); - } - using var temp = new TempFolder(); - var video = temp.Combine("prova.mp4"); - var start = new System.Diagnostics.ProcessStartInfo(ffmpeg.Executable) - { - RedirectStandardError = true, - RedirectStandardOutput = true, - UseShellExecute = false, - }; - foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=2:size=640x360:rate=10", "-pix_fmt", "yuv420p", video }) - { - start.ArgumentList.Add(argument); - } + var es = ElementaryStream.Load("CABA3_SVA_B"); + var video = TestVideos.Write(temp, "prova.mp4", TestVideos.Mp4(es)); - using (var process = System.Diagnostics.Process.Start(start)!) - { - await process.WaitForExitAsync(); - Assert.AreEqual(0, process.ExitCode, "ffmpeg non ha creato il video di prova."); - } - - var frame = await ffmpeg.ExtractJpegAsync(video); + var frame = await VideoFrameDecoder.Instance.ExtractImageAsync(video); Assert.IsNotNull(frame); var store = new ThumbnailStore(temp.Combine("miniature")); Assert.IsTrue(store.Create(Make.Sha(6), new MemoryStream(frame))); - Assert.AreEqual(480, InfoOf(store.PathFor(Make.Sha(6))).Width); + var info = InfoOf(store.PathFor(Make.Sha(6))); + Assert.AreEqual((es.Width, es.Height), (info.Width, info.Height)); - Assert.IsNull(await ffmpeg.ExtractJpegAsync(temp.Combine("non-esiste.mp4"))); + Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mp4"))); } } diff --git a/tests/Febe.Tests/Media/Containers/ContainerTests.cs b/tests/Febe.Tests/Media/Containers/ContainerTests.cs new file mode 100644 index 0000000..6254145 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/ContainerTests.cs @@ -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; + +/// +/// The container readers and the MP4 writer on videos built from the H.264 conformance streams: every decoded frame must +/// still have its official MD5 after a trip through MP4 (also fragmented), Matroska and AVI. +/// +[TestClass] +public sealed class ContainerTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + [TestMethod] + [DataRow("BA1_Sony_D")] + [DataRow("CABA3_SVA_B")] + [DataRow("CANL1_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("HCAFR1_HHI_C")] + public void AnMp4WrittenHereDecodesToTheReferenceFrames(string name) + { + var es = ElementaryStream.Load(name); + var container = Read(TestVideos.Mp4(es)); + Assert.AreEqual(ContainerFormat.IsoBmff, container.Format); + AssertTrack(es, container.Video!); + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(TestVideos.Mp4(es), container.Video!)); + } + + [TestMethod] + [DataRow("CABA3_SVA_B")] + [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(); + 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 DecodeAll(byte[] file, VideoTrack video) + { + using var stream = new MemoryStream(file); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + var lengthSize = video.AnnexB ? 0 : decoder.ConfigureAvcC(video.AvcConfiguration); + var buffer = Array.Empty(); + foreach (var sample in video.Samples) + { + var bytes = ContainerReader.ReadSample(stream, sample, ref buffer); + if (video.AnnexB) + { + decoder.DecodeAccessUnitAnnexB(bytes); + } + else + { + decoder.DecodeSample(bytes, lengthSize); + } + } + + decoder.Flush(); + return ElementaryStream.Md5InOutputOrder(frames); + } + + private sealed class FixedClock(DateTimeOffset now) : Febe.Core.Abstractions.IClock + { + public DateTimeOffset Now { get; } = now; + + public TimeZoneInfo LocalZone => TimeZoneInfo.Utc; + + public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask; + } +} diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs new file mode 100644 index 0000000..050b10a --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -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; + +/// +/// An H.264 conformance stream cut into access units, with what a container needs: key frames, presentation order, +/// parameter sets. The test videos are built from these streams, so every frame has an official MD5. +/// +internal sealed class ElementaryStream +{ + private ElementaryStream(string name, List> units, int[] rank, bool[] key, byte[] avcC, int width, int height) + { + Name = name; + Units = units; + Rank = rank; + Key = key; + AvcC = avcC; + Width = width; + Height = height; + } + + public string Name { get; } + + /// The NAL units (without start codes) of each access unit, in decoding order. + public List> Units { get; } + + /// Position of each access unit in presentation order. + public int[] Rank { get; } + + /// True for access units with an IDR picture. + public bool[] Key { get; } + + public byte[] AvcC { get; } + + public int Width { get; } + + public int Height { get; } + + public int Count => Units.Count; + + public static string Folder(string name) => Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); + + public static byte[] AnnexB(string name) => + File.ReadAllBytes(Directory.EnumerateFiles(Folder(name)).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc")); + + /// The official per-frame MD5 values, in output order. + public static List Reference(string name) => + File.ReadAllLines(Path.Combine(Folder(name), "riferimento.md5")) + .Select(l => l.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + .Where(p => p.Length == 2 && int.TryParse(p[0], out _)) + .Select(p => p[1]) + .ToList(); + + /// MD5 values of frames in output order. + public static List Md5InOutputOrder(IEnumerable frames) => + frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex) + .Select(f => Convert.ToHexStringLower(MD5.HashData(f.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? current = null; + var hasSlice = false; + foreach (var nal in SplitAnnexB(annexB)) + { + var type = nal[0] & 0x1F; + var startsPicture = type is 1 or 5 && nal.Length > 1 && (nal[1] & 0x80) != 0; // first_mb_in_slice == 0 + var beforePicture = type is 6 or 7 or 8 or 9 or (>= 14 and <= 18); + if (current is null || (hasSlice && (startsPicture || beforePicture))) + { + current = []; + units.Add(current); + hasSlice = false; + } + + current.Add(nal); + hasSlice |= type is 1 or 5; + } + + var key = units.Select(u => u.Any(n => (n[0] & 0x1F) == 5)).ToArray(); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(annexB); + Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi"); + var order = frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList(); + var rank = new int[frames.Count]; + for (var i = 0; i < order.Count; i++) + { + rank[order[i].DecodeIndex] = i; + } + + var sps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 7).DistinctBy(Convert.ToBase64String).ToList(); + var pps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 8).DistinctBy(Convert.ToBase64String).ToList(); + var avcC = new List { 1, sps[0][1], sps[0][2], sps[0][3], 0xFF, (byte)(0xE0 | sps.Count) }; + foreach (var s in sps) + { + avcC.Add((byte)(s.Length >> 8)); + avcC.Add((byte)s.Length); + avcC.AddRange(s); + } + + avcC.Add((byte)pps.Count); + foreach (var p in pps) + { + avcC.Add((byte)(p.Length >> 8)); + avcC.Add((byte)p.Length); + avcC.AddRange(p); + } + + return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height); + } + + /// The same stream with only its first access unit, repeated: a video of a still picture. + public ElementaryStream FirstPictureRepeated(int times) + { + var units = Enumerable.Repeat(Units[0], times).ToList(); + return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height); + } + + /// An access unit with 4-byte length prefixes (MP4, Matroska). + public byte[] LengthPrefixed(int index) + { + using var output = new MemoryStream(); + Span length = stackalloc byte[4]; + foreach (var nal in Units[index]) + { + BinaryPrimitives.WriteInt32BigEndian(length, nal.Length); + output.Write(length); + output.Write(nal); + } + + return output.ToArray(); + } + + /// An access unit with start codes (AVI). + public byte[] WithStartCodes(int index) + { + using var output = new MemoryStream(); + foreach (var nal in Units[index]) + { + output.Write([0, 0, 0, 1]); + output.Write(nal); + } + + return output.ToArray(); + } + + private static List SplitAnnexB(byte[] data) + { + var starts = new List<(int Payload, int Code)>(); + for (var i = 0; i + 2 < data.Length; i++) + { + if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) + { + var code = i > 0 && data[i - 1] == 0 ? i - 1 : i; + starts.Add((i + 3, code)); + i += 2; + } + } + + var nals = new List(); + for (var k = 0; k < starts.Count; k++) + { + var end = k + 1 < starts.Count ? starts[k + 1].Code : data.Length; + while (end > starts[k].Payload && data[end - 1] == 0) + { + end--; // trailing zero bytes belong to no NAL unit + } + + if (end > starts[k].Payload) + { + nals.Add(data[starts[k].Payload..end]); + } + } + + return nals; + } +} + +/// Builders of test videos in the three containers, from an . +internal static class TestVideos +{ + /// Ticks per frame at timescale 30000: 30 frames per second. + public const int FrameTicks = 1000; + public const int Timescale = 30000; + + /// An MP4 written with ; with , also an AAC track of silence-shaped samples. + public static byte[] Mp4(ElementaryStream es, DateTimeOffset? created = null, int rotation = 0, bool audio = false) + { + var samples = new List(); + var data = new List(); + for (var i = 0; i < es.Count; i++) + { + var bytes = es.LengthPrefixed(i); + data.Add(bytes); + samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i])); + } + + var tracks = new List + { + new() + { + IsVideo = true, + Timescale = Timescale, + Samples = samples, + WriteSample = (i, s) => s.Write(data[i]), + Width = es.Width, + Height = es.Height, + Rotation = rotation, + AvcConfiguration = es.AvcC, + }, + }; + if (audio) + { + var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024); + var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C }; + tracks.Add(new Mp4OutputTrack + { + IsVideo = false, + Timescale = 44100, + Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))], + WriteSample = (_, s) => s.Write(payload), + AacConfiguration = [0x12, 0x10], // AAC LC, 44.1 kHz, stereo + SampleRate = 44100, + Channels = 2, + }); + } + + using var output = new MemoryStream(); + Mp4Writer.Write(output, tracks, created); + return output.ToArray(); + } + + /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). + 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(); + 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(); + } + + /// A Matroska file with one video track of SimpleBlocks (times in milliseconds). + 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 { 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 { 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]; + } + + /// An AVI file with one H.264 stream in Annex B form, an idx1 index and, when given, an IDIT date. + public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true) + { + var avih = new List(); + foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 }) + { + avih.AddRange(Le32(v)); + } + + var strh = new List(); + strh.AddRange("vidsH264"u8.ToArray()); + foreach (var v in new uint[] { 0, 0, 0, 1, 30, 0, (uint)es.Count, 0, 0xFFFFFFFF, 0 }) + { + strh.AddRange(Le32(v)); + } + + strh.AddRange(new byte[8]); + var strf = new List(); + foreach (var v in new uint[] { 40, (uint)es.Width, (uint)es.Height }) + { + strf.AddRange(Le32(v)); + } + + strf.AddRange([1, 0, 24, 0]); + strf.AddRange("H264"u8.ToArray()); + strf.AddRange(new byte[20]); + var hdrl = new List { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) }; + if (idit is not null) + { + hdrl.Add(Chunk("IDIT", [.. Encoding.ASCII.GetBytes(idit), (byte)'\n', 0])); + } + + var chunks = new List(); + var idx = new List(); + var offset = 4u; // from the «movi» code + for (var i = 0; i < es.Count; i++) + { + var chunk = Chunk("00dc", es.WithStartCodes(i)); + chunks.Add(chunk); + idx.AddRange("00dc"u8.ToArray()); + idx.AddRange(Le32(es.Key[i] ? 0x10u : 0)); + idx.AddRange(Le32(offset)); + idx.AddRange(Le32((uint)es.WithStartCodes(i).Length)); + offset += (uint)chunk.Length; + } + + var body = new List { List("hdrl", [.. hdrl]), List("movi", [.. chunks]) }; + if (index) + { + body.Add(Chunk("idx1", [.. idx])); + } + + var content = body.SelectMany(b => b).ToArray(); + return [.. "RIFF"u8, .. Le32((uint)(content.Length + 4)), .. "AVI "u8, .. content]; + } + + public static string Write(TempFolder folder, string name, byte[] data) + { + var path = folder.Combine(name); + File.WriteAllBytes(path, data); + return path; + } + + private static byte[] Avc1(ElementaryStream es) => Box("avc1", + [.. new byte[6], 0, 1, .. new byte[16], .. U16((ushort)es.Width), .. U16((ushort)es.Height), .. U32(0x00480000), .. U32(0x00480000), + .. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box("avcC", es.AvcC)]); + + private static byte[] Box(string type, params byte[][] children) + { + var body = children.SelectMany(c => c).ToArray(); + return [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body]; + } + + private static byte[] Box(string type, byte[] body) => [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body]; + + private static byte[] FullBox(string type, uint flags, byte[] body) => Box(type, [.. U32(flags & 0xFFFFFF), .. body]); + + private static byte[] Element(uint id, params byte[][] children) => Element(id, children.SelectMany(c => c).ToArray()); + + private static byte[] Element(uint id, byte[] body) + { + var idBytes = id > 0xFFFFFF ? U32(id) : id > 0xFFFF ? U32(id)[1..] : id > 0xFF ? U16((ushort)id) : [(byte)id]; + return [.. idBytes, 0x01, .. BitConverter.GetBytes((ulong)body.Length).Reverse().Skip(1), .. body]; + } + + private static byte[] Chunk(string id, byte[] body) => + [.. Encoding.ASCII.GetBytes(id), .. Le32((uint)body.Length), .. body, .. (body.Length % 2 == 1 ? new byte[] { 0 } : [])]; + + private static byte[] List(string type, params byte[][] children) + { + var body = children.SelectMany(c => c).ToArray(); + return [.. "LIST"u8, .. Le32((uint)(body.Length + 4)), .. Encoding.ASCII.GetBytes(type), .. body]; + } + + private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v]; + + private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v]; + + private static byte[] I64(long v) + { + var b = new byte[8]; + BinaryPrimitives.WriteInt64BigEndian(b, v); + return b; + } + + private static byte[] F64(double v) + { + var b = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(b, v); + return b; + } + + private static byte[] Le32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, v); + return b; + } +} diff --git a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs new file mode 100644 index 0000000..49a011a --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs @@ -0,0 +1,145 @@ +using Febe.Core.Codecs.H264; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture. +[TestClass] +public sealed class VideoFrameDecoderTests +{ + [TestMethod] + [DataRow("mp4")] + [DataRow("mkv")] + [DataRow("avi")] + [DataRow("frammentato.mp4")] + 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"))); + } + + /// The frame decoded at position , straight from the stream. + private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]); + + /// The frame shown at position , decoded straight from the stream. + private static H264Frame ShownFrame(ElementaryStream es, int rank) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name)); + var index = Array.IndexOf(es.Rank, rank); + return frames.Single(f => f.DecodeIndex == index); + } +} diff --git a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md new file mode 100644 index 0000000..0c26892 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md @@ -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. diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index e4e4b87..170b799 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -69,11 +69,14 @@ public sealed partial class PipelineTests StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\""); var environment = Script("ambiente-prove.sh"); - foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" }) + foreach (var package in new[] { "chromium", "xvfb", "nsis", "locales" }) { StringAssert.Contains(environment, package); } + // Videos are read and decoded in house: no ffmpeg in the CI, nor in the image (Alberto, 18 November 2026). + 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. foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) { diff --git a/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs b/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs index 94132c9..7551a61 100644 --- a/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs +++ b/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs @@ -225,40 +225,6 @@ public sealed class SessionKeyOptionsTests Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret)); } - [TestMethod] - [DoNotParallelize] - public void FfmpegAndFfprobeStartWithoutThePasswordOrTheKeyOfFebesEnvironment() - { - // Febe's own environment holds both (as in Docker): ffprobe and ffmpeg must not inherit them (spec §13.2). - using var folder = new TempFolder("figli"); - var tool = folder.Combine("strumento-di-prova"); - File.WriteAllText(tool, string.Empty); - var before = ChildProcessEnvironment.SecretVariables.Select(n => (Name: n, Value: Environment.GetEnvironmentVariable(n))).ToList(); - try - { - foreach (var name in ChildProcessEnvironment.SecretVariables) - { - Environment.SetEnvironmentVariable(name, "valore-di-prova"); - } - - Assert.IsTrue(new System.Diagnostics.ProcessStartInfo("x").Environment.Keys.Any(ChildProcessEnvironment.IsSecret), "The parent holds them."); - var probe = Febe.Core.Import.FfprobeVideoMetadataProbe.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4"); - var frame = VideoFrameExtractor.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4", "1"); - foreach (var info in new[] { probe, frame }) - { - Assert.IsFalse(info.Environment.Keys.Any(ChildProcessEnvironment.IsSecret), info.FileName); - CollectionAssert.Contains(info.ArgumentList.ToArray(), "video-di-prova.mp4"); - } - } - finally - { - foreach (var (name, value) in before) - { - Environment.SetEnvironmentVariable(name, value); - } - } - } - private static Func Env(params (string Name, string Value)[] values) { var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);