From b23632fc960f75a09560dd4256d159364e70c253 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 14:13:45 +0100 Subject: [PATCH] =?UTF-8?q?Fotogrammi=20e=20contenitori=20pi=C3=B9=20robus?= =?UTF-8?q?ti=20dopo=20la=20revisione:=20punto=20di=20partenza=20vero,=20l?= =?UTF-8?q?imiti=20di=20tempo=20e=20di=20riferimenti,=20file=20rovinati=20?= =?UTF-8?q?tollerati=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori di contenitori. - Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni), altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come l'estrattore con ffmpeg che sostituisce. - H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num; immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica. - Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano; scala dei tempi esatta per ogni TimecodeScale. - MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né campioni dei frammenti. - AVI: durata impossibile ignota senza perdere la data. - Sonda dei metadati davvero asincrona, annullabile fra i frammenti. - Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice), AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI, TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile. Provate contro il codice senza le correzioni: falliscono tutte. - decisioni.md: quattro righe del 18 novembre. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 4 + src/Febe.Core/Codecs/Containers/AviReader.cs | 12 +- .../Codecs/Containers/ContainerReader.cs | 15 +- .../Codecs/Containers/IsoBmffReader.cs | 66 +++++- .../Codecs/Containers/MatroskaReader.cs | 125 +++++++--- src/Febe.Core/Codecs/H264/CabacEngine.cs | 74 +++++- .../Codecs/H264/H264Decoder.Motion.cs | 3 +- src/Febe.Core/Codecs/H264/H264Decoder.cs | 192 +++++++++++++--- src/Febe.Core/Codecs/H264/ParameterSets.cs | 10 + src/Febe.Core/Codecs/H264/RbspReader.cs | 187 +++++++++------ src/Febe.Core/Codecs/H264/SliceHeader.cs | 6 +- src/Febe.Core/Import/VideoMetadataProbe.cs | 12 +- src/Febe.Core/Library/VideoFrameDecoder.cs | 165 +++++++++++-- .../Media/Containers/ContainerTests.cs | 17 ++ .../Media/Containers/MalformedInputTests.cs | 83 ++++++- .../Febe.Tests/Media/Containers/TestVideos.cs | 35 ++- .../Containers/VideoFrameDecoderTests.cs | 79 ++++++- .../Media/H264/H264ConformanceTests.cs | 37 ++- .../Media/H264/H264RobustnessTests.cs | 104 ++------- .../Media/H264/H264SyntheticStreamTests.cs | 106 +++++++++ .../Febe.Tests/Media/H264/SyntheticStreams.cs | 216 ++++++++++++++++++ tests/Febe.Tests/Packaging/PipelineTests.cs | 7 +- 22 files changed, 1273 insertions(+), 282 deletions(-) create mode 100644 tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs create mode 100644 tests/Febe.Tests/Media/H264/SyntheticStreams.cs diff --git a/docs/decisioni.md b/docs/decisioni.md index 4ddcec5..81dc2d7 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -423,3 +423,7 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Video senza programmi esterni: ffmpeg e ffprobe tolti dall'immagine Docker, dalla CI e dal codice. I metadati vengono dai lettori di contenitori scritti in casa (`Febe.Core.Codecs.Containers`: ISO BMFF anche frammentato, Matroska/WebM, AVI; `ContainerVideoMetadataProbe` è la sonda predefinita), i fotogrammi delle miniature dal decodificatore H.264 scritto in casa (`Febe.Core.Codecs.H264`, `VideoFrameDecoder`, BMP ruotato come il video), che dice anche se un video mostra solo un'immagine ferma; c'è uno scrittore MP4 (moov in testa) per rimpacchettare. Le tabelle CABAC sono trascritte dal testo della Raccomandazione ITU-T H.264, non a memoria; il decodificatore è provato fotogramma per fotogramma sugli MD5 dei flussi di conformità ITU-T H.264.1 | Decisione di Alberto del 18 novembre 2026 (niente componenti esterni, tutto il codice in casa). Limiti: si decodifica solo H.264 a immagini intere, 4:2:0, 8 bit; HEVC, VP9 e AV1 si leggono nei contenitori ma restano senza fotogramma (tessera neutra) | | 2026-11-18 | Limiti dei lettori di contenitori e del decodificatore H.264 contro i file danneggiati: al più 2.000.000 di campioni per traccia, un campione al più di 64 MB, ogni tabella o elemento controllato contro la lunghezza del file prima di allocare, un SPS oltre il MaxFS del livello 6.2 (139.264 macroblocchi) o con un ritaglio che non lascia immagine rifiutato, mai più riferimenti di Max(max_num_ref_frames, 1) nel buffer. Una traccia MP4 con tabelle danneggiate o oltre il limite resta senza campioni e le altre si leggono lo stesso | I lettori leggono ogni file della libreria e delle importazioni: prima un `stsz` di pochi byte poteva chiedere 800 MB, un SPS danneggiato immagini da 16384×16384, un `trex` letto con i campi scambiati dava durate sbagliate ai video frammentati. L'audio PCM di QuickTime conta ogni campione e supera il limite: perderne i campioni non toglie i metadati né il video | | 2026-11-18 | Il fotogramma per la miniatura di un video si riduce a 960 pixel sul lato lungo (fattore intero) prima di diventare BMP; la durata di un MP4 frammentato viene da `mehd` o, se manca, dai frammenti, anche nella sola lettura dei metadati | Un fotogramma 4K intero è un BMP da 24 MB per una miniatura di 480 pixel; senza i frammenti la sonda dava a un MP4 frammentato una durata ignota, che ffprobe sapeva dire | +| 2026-11-18 | Il fotogramma di un video parte sempre da un punto da cui si può decodificare: dei campioni segnati come chiave si guarda il contenuto, dal più vicino all'indietro, e si prende un'immagine IDR entro 300 campioni, altrimenti un'immagine di sole slice I, altrimenti il primo campione. Più lontano di 300 campioni (una tabella dei tempi danneggiata, una sola chiave in un video lungo) vale il fotogramma del punto di partenza. Ogni fotogramma o analisi ha al più 30 secondi, poi dà niente come un file illeggibile; l'annullamento di chi chiama resta un annullamento. Il decodificatore H.264 rifiuta una slice P o B senza immagini di riferimento invece di predirla da sé stessa | Un AVI senza `idx1` (registrazione interrotta) o OpenDML oltre il primo gigabyte segna ogni campione come chiave: si partiva dal fotogramma P cercato, e con i parametri ripetuti in ogni campione usciva una miniatura rovinata data per buona. L'estrattore con ffmpeg veniva fermato dopo 30 secondi; senza limite un file danneggiato poteva tenere ferma un'importazione per ore | +| 2026-11-18 | Il decodificatore H.264 non ricostruisce le immagini che nessuno usa come riferimento e che non sono chieste (ne legge solo l'intestazione), salta le immagini ridondanti (`redundant_pic_cnt` > 0), riconosce l'inizio di un'immagine con le condizioni di §7.4.1.2.4, rifiuta un SPS i cui riferimenti non stanno nel buffer più grande di ogni livello (MaxDpbMbs del livello 6.2, 696.320 macroblocchi), dà ai fotogrammi mancanti di un salto di `frame_num` il loro FrameNumOffset; CABAC legge i bit da una finestra di 64 bit e rinormalizza in un passo; le unità NAL si leggono una per volta in un solo buffer | Prestazioni della miniatura a 1 s (le B non di riferimento fra la chiave e il fotogramma) e difetti trovati in revisione: un SPS di pochi byte poteva chiedere 1,4 GB, un salto di `frame_num` a cavallo del giro perdeva il giro nel POC (tipi 1 e 2), un'immagine ridondante usciva come fotogramma in più. Le parti verificate con MD5 ufficiali sono solo quelle dei 12 flussi di conformità: predizione pesata, operazioni di gestione della memoria, riferimenti a lungo termine, POC di tipo 1, I_PCM e CABAC con più slice per immagine non hanno un riferimento ufficiale (i flussi di prova ITU-T in più sono dati di terzi: decide Alberto) | +| 2026-11-18 | Lettori di contenitori più tolleranti: un blocco Matroska danneggiato o troncato, o oltre il limite dei campioni, ferma la lettura e i blocchi letti restano; una traccia MP4 con `tkhd`, `elst`, `mdhd`, `hdlr` o `esds` danneggiati si scarta e le altre restano; la durata AVI oltre 10⁹ secondi è ignota senza perdere la data; i tempi Matroska usano come unità il massimo comun divisore fra TimecodeScale e un secondo, così la scala dei tempi è esatta per ogni TimecodeScale; la sonda dei metadati legge su un thread del pool e controlla l'annullamento fra i frammenti, e senza campioni non copia le tabelle né conserva i campioni dei frammenti | Come per il lettore ISO già prima: un file con un solo punto rovinato dopo il primo secondo non deve restare senza miniatura né perdere la data. La divisione intera 10⁹ / TimecodeScale spostava i tempi dello 0,1% con 3 ms e sbagliava fotogramma oltre il secondo | +| 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma | diff --git a/src/Febe.Core/Codecs/Containers/AviReader.cs b/src/Febe.Core/Codecs/Containers/AviReader.cs index aeb3c2e..f4d2fb5 100644 --- a/src/Febe.Core/Codecs/Containers/AviReader.cs +++ b/src/Febe.Core/Codecs/Containers/AviReader.cs @@ -19,7 +19,7 @@ public static class AviReader 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) + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); var state = new State(); @@ -29,6 +29,7 @@ public static class AviReader var first = true; while (position + 12 <= length) { + ct.ThrowIfCancellationRequested(); stream.Position = position; stream.ReadExactly(header); if (!header[..4].SequenceEqual("RIFF"u8)) @@ -307,6 +308,9 @@ public static class AviReader var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant(); var frames = VideoLength > 0 ? VideoLength : TotalFrames; + + // Header values are taken as stored: a damaged one never gives an overflowing or negative duration. + var trackDuration = frames <= long.MaxValue / frameTicks ? frames * frameTicks : 0; var video = VideoStream < 0 ? null : new VideoTrack { Codec = tag switch @@ -322,7 +326,7 @@ public static class AviReader Height = VideoHeight > 0 ? VideoHeight : Height, AnnexB = true, Timescale = timescale, - Duration = frames * frameTicks, + Duration = trackDuration, Samples = samples, }; @@ -353,7 +357,9 @@ public static class AviReader }; } - TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null; + // As the other readers: beyond what a video can last (a damaged header) there is no duration, and the rest stands. + var seconds = video is { Duration: > 0 } ? video.Seconds(video.Duration) : 0; + TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; } diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs index 6faf12d..c24e805 100644 --- a/src/Febe.Core/Codecs/Containers/ContainerReader.cs +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -24,9 +24,10 @@ public static class ContainerReader /// /// Reads a seekable stream; null when its format is not recognised. Damaged files raise - /// (or when truncated). + /// (or when truncated); is + /// checked between the top-level boxes, elements and fragments. /// - public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true) + public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); Span start = stackalloc byte[16]; @@ -35,18 +36,18 @@ public static class ContainerReader 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), + ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct), + ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct), + ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct), _ => null, }; } /// Reads a file (read-only, shared); null when its format is not recognised. - public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true) + public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { using var stream = OpenRead(path); - return Read(stream, now, samples); + return Read(stream, now, samples, ct); } /// Opens a file for reading without blocking other readers or writers. diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs index 59abb64..79ad9f7 100644 --- a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -27,8 +27,12 @@ public static class IsoBmffReader /// 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) + /// + /// False to stop at the metadata: no sample tables, and fragments only when they alone tell the duration (then only + /// their durations are added up). + /// + /// Checked between the top-level boxes (each fragment of a fragmented file). + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); var length = stream.Length; @@ -38,6 +42,7 @@ public static class IsoBmffReader var pending = new List<(long Start, byte[] Body)>(); for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) { + ct.ThrowIfCancellationRequested(); stream.Position = position; stream.ReadExactly(header[..8]); long size = BinaryPrimitives.ReadUInt32BigEndian(header); @@ -137,7 +142,17 @@ public static class IsoBmffReader movie.ParseMvhd(body, now); break; case "trak": - movie.ParseTrak(moov, start, count); + try + { + movie.ParseTrak(moov, start, count); + } + catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException + or ContainerException) + { + // A damaged track header, edit list or description (often of the audio track): that track is + // dropped, the others are still read. + } + break; case "mvex": movie.Fragmented = true; @@ -406,6 +421,11 @@ public static class IsoBmffReader var stz2 = false; foreach (var (type, s, c) in Children(data, start, count)) { + if (!samples && type != "stsd") + { + continue; // metadata only: the tables are not even copied + } + switch (type) { case "stsd": @@ -528,6 +548,11 @@ public static class IsoBmffReader { case 0x03: // ES_Descriptor { + if (p + 3 > body.Length) + { + return null; + } + var flags = body[p + 2]; p += 3; if ((flags & 0x80) != 0) @@ -537,6 +562,11 @@ public static class IsoBmffReader if ((flags & 0x40) != 0) { + if (p >= body.Length) + { + return null; + } + p += 1 + body[p]; } @@ -789,12 +819,22 @@ public static class IsoBmffReader var bounded = perSample > 0 ? (long)n * perSample <= body.Length - p : (long)n * Math.Max(1u, defSize) <= fileLength; - if (n < 0 || !bounded || track.Samples.Count + n > MaxSamples) + if (n < 0 || !bounded || (samples && track.Samples.Count + n > MaxSamples)) { throw new ContainerException("Troppi campioni."); } var dts = decodeTime ?? Math.Max(0, track.FragmentTime); + if (!samples) + { + // Metadata only: the fragments are read for the duration, so only durations add up. + var run = RunDuration(body[p..], flags, n, defDuration); + dts = run > (long.MaxValue / 2) - dts ? long.MaxValue / 2 : dts + run; + track.FragmentTime = dts; + decodeTime = dts; + break; + } + for (var i = 0; i < n; i++) { var duration = defDuration; @@ -840,6 +880,24 @@ public static class IsoBmffReader } } + /// The total duration of the samples of a trun, from their fields after the header. + private static long RunDuration(ReadOnlySpan fields, uint flags, int count, uint defaultDuration) + { + if ((flags & 0x100) == 0) + { + return (long)count * defaultDuration; + } + + var stride = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1)); + long total = 0; + for (var i = 0; i < count; i++) + { + total += BinaryPrimitives.ReadUInt32BigEndian(fields[(i * stride)..]); // the duration comes first + } + + return total; + } + internal MediaContainer Build() { var video = tracks.Find(t => t.Handler == "vide"); diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs index 8c98c98..f04168e 100644 --- a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -34,7 +34,8 @@ public static class MatroskaReader /// 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) + /// Checked between the top-level elements. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); var reader = new Reader(stream); @@ -82,45 +83,55 @@ public static class MatroskaReader var state = new State(); while (stream.Position < segmentEnd) { + ct.ThrowIfCancellationRequested(); var elementStart = stream.Position; if (segmentEnd - elementStart < 2) { break; } - (id, size) = reader.Header(); - var bodyEnd = size < 0 ? segmentEnd : stream.Position + size; - if (bodyEnd > segmentEnd) + try { - bodyEnd = segmentEnd; // truncated file - } + (id, size) = reader.Header(); + var bodyEnd = size < 0 ? segmentEnd : stream.Position + size; + if (bodyEnd > segmentEnd) + { + bodyEnd = segmentEnd; // truncated file + } - switch (id) + switch (id) + { + case InfoId: + ParseInfo(reader, bodyEnd, state, now); + break; + case TracksId: + ParseTracks(reader, bodyEnd, state); + break; + case ClusterId: + if (!samples) + { + return state.Build(); + } + + ParseCluster(reader, bodyEnd, size < 0, state); + continue; // the position is already past the cluster + default: + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + + break; + } + + stream.Position = bodyEnd; + } + catch (Exception ex) when ((ex is ContainerException or EndOfStreamException) && state.HasSamples) { - 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; + // A damaged or truncated block after the first ones, or more samples than the limit: what was read + // stands, as in the ISO reader. + break; } - - stream.Position = bodyEnd; } return state.Build(); @@ -377,7 +388,7 @@ public static class MatroskaReader throw new ContainerException("Troppi campioni."); } - var time = clusterTime + relative; + var time = state.ToUnits(clusterTime + relative); var lacing = (flags >> 1) & 3; var dataStart = stream.Position; if (lacing == 0) @@ -456,7 +467,7 @@ public static class MatroskaReader } var offset = dataBegin; - var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0; + var frameDuration = target.DefaultDuration > 0 ? target.DefaultDuration / state.UnitNanoseconds : 0; for (var i = 0; i < frames; i++) { if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end) @@ -498,9 +509,53 @@ public static class MatroskaReader internal TrackEntry? Video; internal TrackEntry? Audio; + /// Nanoseconds of one unit of the sample times; fixed by the first block, 0 before. + private long unit; + + internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0; + + /// + /// Nanoseconds of one unit of the sample times: the greatest common divisor of TimecodeScale and a second, so + /// that the timescale of the tracks (a second in units) is exact for any TimecodeScale (3 ms gives units of + /// 1 ms, 2 s units of 1 s) and the block times are whole units. + /// + internal long UnitNanoseconds + { + get + { + if (unit == 0) + { + long a = Scale, b = 1_000_000_000; + while (b != 0) + { + (a, b) = (b, a % b); + } + + unit = a; + } + + return unit; + } + } + + /// TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value. + private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000; + + /// Units of in a tick (at least 1, should Info come after the first block). + private long Factor => Math.Max(1, Scale / UnitNanoseconds); + + /// A time in TimecodeScale ticks as a time in units of . + internal long ToUnits(long ticks) + { + var limit = long.MaxValue / 4 / Factor; + return Math.Clamp(ticks, -limit, limit) * Factor; // a damaged cluster time stays a (wrong) number + } + internal MediaContainer Build() { - var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale)); + var timescale = 1_000_000_000L / UnitNanoseconds; + var trackDuration = DurationTicks * Factor; + var trackUnits = trackDuration is > 0 and < long.MaxValue / 2 ? (long)trackDuration : 0; VideoTrack? video = null; if (Video is { } v) { @@ -541,7 +596,7 @@ public static class MatroskaReader Rotation = roll is 90 or 180 or 270 ? roll : 0, AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null, Timescale = timescale, - Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0, + Duration = trackUnits, Samples = samples, }; } @@ -565,7 +620,7 @@ public static class MatroskaReader Channels = a.Channels, AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, Timescale = timescale, - Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0, + Duration = trackUnits, Samples = a.Samples, }; } diff --git a/src/Febe.Core/Codecs/H264/CabacEngine.cs b/src/Febe.Core/Codecs/H264/CabacEngine.cs index 26985ba..645db82 100644 --- a/src/Febe.Core/Codecs/H264/CabacEngine.cs +++ b/src/Febe.Core/Codecs/H264/CabacEngine.cs @@ -1,17 +1,31 @@ +using System.Buffers.Binary; +using System.Numerics; + namespace Febe.Core.Codecs.H264; /// -/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), reading the slice data bit by bit, with the -/// context variables of the slice. +/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), with the context variables of the slice. The slice +/// data is read through a 64-bit window refilled four bytes at a time, and renormalisation shifts all its bits at once +/// (the count of leading zeros of the range): the arithmetic is the one of the standard, bit for bit. /// internal sealed class CabacEngine { private readonly byte[] state = new byte[CabacTables.ContextCount]; private readonly byte[] mps = new byte[CabacTables.ContextCount]; private RbspReader reader = null!; + private byte[] data = []; private int range; private int offset; + /// The next bits of the slice data, from the most significant bit. + private ulong window; + + /// Valid bits at the top of . + private int bits; + + /// The next byte of to load into the window. + private int next; + /// Initialises the context variables (§9.3.1.1). internal void InitContexts(SliceHeader header, int sliceQp) { @@ -38,8 +52,18 @@ internal sealed class CabacEngine internal void Start(RbspReader source) { reader = source; + data = source.Data; + var position = source.Position; + next = position >> 3; + window = 0; + bits = 0; + Refill(); + var skip = position & 7; + window <<= skip; + bits -= skip; + range = 510; - offset = (int)source.Read(9); + offset = Take(9); if (offset >= range) { throw new H264Exception("Dati CABAC non validi."); @@ -73,10 +97,12 @@ internal sealed class CabacEngine } } - while (range < 256) + if (range < 256) { - range <<= 1; - offset = (offset << 1) | reader.ReadBit(); + // RenormD (§9.3.3.2.2): as many single-bit steps as the range has leading zeros below bit 8. + var shift = BitOperations.LeadingZeroCount((uint)range) - 23; + range <<= shift; + offset = (offset << shift) | Take(shift); } return bin; @@ -84,7 +110,7 @@ internal sealed class CabacEngine internal int Bypass() { - offset = (offset << 1) | reader.ReadBit(); + offset = (offset << 1) | Take(1); if (offset >= range) { offset -= range; @@ -99,15 +125,45 @@ internal sealed class CabacEngine range -= 2; if (offset >= range) { + // The end of the slice or an I_PCM macroblock: the reader goes on exactly after the bits read here. + reader.Position = (next * 8) - bits; return 1; } - while (range < 256) + if (range < 256) { range <<= 1; - offset = (offset << 1) | reader.ReadBit(); + offset = (offset << 1) | Take(1); } return 0; } + + /// The next bits (1 to 32) of the slice data. + private int Take(int count) + { + if (bits < count) + { + Refill(); + } + + var value = (int)(window >> (64 - count)); + window <<= count; + bits -= count; + return value; + } + + /// + /// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see + /// ); a damaged slice that reads beyond the padding fails as the bit reader would. + /// + private void Refill() + { + while (bits <= 32) + { + window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits); + next += 4; + bits += 32; + } + } } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs index 0178ed7..aaf05c2 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs @@ -371,7 +371,8 @@ public sealed partial class H264Decoder } } - return cur!; + // Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged. + throw new H264Exception("Slice P o B senza immagini di riferimento."); } private void PrepareWeights() diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index 27d595d..963f428 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -1,11 +1,26 @@ namespace Febe.Core.Codecs.H264; +/// What an access unit offers to start decoding from (see ). +public enum H264AccessPoint +{ + /// A P or B picture, or no picture: decoding cannot start here. + None, + + /// A picture of I slices that is not IDR: the pictures after it may still refer to earlier ones. + IntraPicture, + + /// An IDR picture: nothing after it refers to anything before. + Idr, +} + /// /// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles for /// progressive frames in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling -/// matrices, explicit and implicit weighted prediction, spatial and temporal direct prediction, multiple reference frames -/// with list modification and memory management, deblocking. Not handled (an ): interlaced -/// pictures (fields and MBAFF), slice groups, SP/SI slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits. +/// matrices, spatial and temporal direct prediction, list modification, deblocking. Written from the standard but not +/// yet checked against a conformance stream: explicit and implicit weighted prediction, memory management operations +/// and long-term references, gaps in frame_num, picture order count type 1, I_PCM and CABAC pictures of several +/// slices. Not handled (an ): interlaced pictures (fields and MBAFF), slice groups, SP/SI +/// slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped. /// public sealed partial class H264Decoder { @@ -20,8 +35,12 @@ public sealed partial class H264Decoder private int picNalType; private int picRefIdc; private bool picMmco5; + private bool picSkipped; private int sliceCounter; + /// The RBSP of the NAL unit being decoded: one buffer for the whole stream. + private byte[]? rbsp; + private int prevPocMsb; private int prevPocLsb; private int prevFrameNumOffset; @@ -34,7 +53,10 @@ public sealed partial class H264Decoder private int period; private long decodeCounter; - /// Which frames to hand out, by decoding index; null hands out all of them. + /// + /// Which frames to hand out, by decoding index; null hands out all of them. A picture that is not used for reference + /// and is not wanted is not reconstructed at all: only its header counts. + /// public Func? Wanted { get; set; } /// Raised for each decoded frame that accepts, in decoding order. @@ -46,11 +68,7 @@ public sealed partial class H264Decoder /// Decodes a whole Annex B byte stream (start codes), then flushes the last picture. public void DecodeAnnexB(ReadOnlySpan stream) { - foreach (var nal in NalUnits.SplitAnnexB(stream)) - { - Decode(nal); - } - + DecodeUnitsAnnexB(stream); Flush(); } @@ -85,7 +103,7 @@ public sealed partial class H264Decoder throw new H264Exception("Configurazione avcC troncata."); } - Decode(NalUnits.Parse(avcC.Slice(offset, size))); + Decode(NalUnits.Unescape(avcC.Slice(offset, size), ref rbsp)); offset += size; } } @@ -96,9 +114,10 @@ public sealed partial class H264Decoder /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. public void DecodeSample(ReadOnlySpan sample, int lengthSize) { - foreach (var nal in NalUnits.SplitLengthPrefixed(sample, lengthSize)) + var position = 0; + while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit)) { - Decode(nal); + Decode(NalUnits.Unescape(sample[unit], ref rbsp)); } FinishPicture(); @@ -107,14 +126,59 @@ public sealed partial class H264Decoder /// Decodes one access unit in Annex B form and finishes its picture. public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit) { - foreach (var nal in NalUnits.SplitAnnexB(accessUnit)) - { - Decode(nal); - } - + DecodeUnitsAnnexB(accessUnit); FinishPicture(); } + /// + /// Whether decoding can start at this access unit: exactly at an IDR picture; only approximately at a picture whose + /// first slice is an I slice, since the pictures after it may still refer to earlier ones. + /// is the size of the NAL length fields, 0 for Annex B. + /// + public static H264AccessPoint AccessPoint(ReadOnlySpan accessUnit, int lengthSize) + { + var position = 0; + while (true) + { + Range unit; + var more = lengthSize == 0 + ? NalUnits.NextAnnexB(accessUnit, ref position, out unit) + : NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit); + if (!more) + { + return H264AccessPoint.None; + } + + var nal = accessUnit[unit]; + switch (nal[0] & 0x1F) + { + case 5: + return H264AccessPoint.Idr; + case 1: + try + { + // first_mb_in_slice and slice_type: a few bytes of the header are enough. + var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader(); + _ = reader.ReadUe(); + return reader.ReadUe(9) % 5 == (int)SliceType.I ? H264AccessPoint.IntraPicture : H264AccessPoint.None; + } + catch (H264Exception) + { + return H264AccessPoint.None; + } + } + } + } + + private void DecodeUnitsAnnexB(ReadOnlySpan stream) + { + var position = 0; + while (NalUnits.NextAnnexB(stream, ref position, out var unit)) + { + Decode(NalUnits.Unescape(stream[unit], ref rbsp)); + } + } + /// Finishes the picture being decoded, if any. public void Flush() => FinishPicture(); @@ -194,15 +258,64 @@ public sealed partial class H264Decoder throw new H264Exception("La codifica senza perdita non è gestita."); } - if (header.FirstMb == 0 || cur is null) + // A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped. + if (header.RedundantPicCnt > 0) + { + return; + } + + if (cur is null || picHeader is null || StartsNewPicture(header, nal) || (header.FirstMb == 0 && mbSlice[0] >= 0)) { FinishPicture(); StartPicture(nal, header, sps); } + if (picSkipped) + { + return; + } + + if (!header.IsIntra && !HasReference()) + { + // A P or B slice without any picture to predict from: decoding started away from a random access point + // (a missing index, a damaged stream). Predicting from nothing would give a corrupt frame. + throw new H264Exception("Slice P o B senza immagini di riferimento."); + } + DecodeSliceData(reader, nal, header, sps, pps); } + /// The first slice of a new primary picture (§7.4.1.2.4), compared with the first slice of the current one. + private bool StartsNewPicture(SliceHeader h, NalUnit nal) + { + var p = picHeader!; + if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || (nal.RefIdc == 0) != (picRefIdc == 0) + || (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId)) + { + return true; + } + + return activeSps!.PocType switch + { + 0 => h.PocLsb != p.PocLsb || h.DeltaPocBottom != p.DeltaPocBottom, + 1 => h.DeltaPoc0 != p.DeltaPoc0 || h.DeltaPoc1 != p.DeltaPoc1, + _ => false, + }; + } + + private bool HasReference() + { + foreach (var p in dpb) + { + if (p.IsReference && !ReferenceEquals(p, cur)) + { + return true; + } + } + + return false; + } + private void StartPicture(NalUnit nal, SliceHeader header, Sps sps) { if (activeSps is null || !ReferenceEquals(activeSps, sps)) @@ -239,6 +352,9 @@ public sealed partial class H264Decoder sliceCounter = 0; sliceFilters.Clear(); Array.Fill(mbSlice, -1); + + // A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded. + picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(cur.DecodeIndex); } private Picture NewPicture(Sps sps) @@ -355,13 +471,16 @@ public sealed partial class H264Decoder } } - /// Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters. + /// + /// Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters, and their frame number offset + /// (§8.2.1), which carries the wraps of frame_num to the pictures after the gap. Of a gap longer than the buffer only + /// the last frames can stay references: the earlier ones are counted, never allocated. + /// private void FillFrameNumGap(int frameNum, Sps sps) { var max = sps.MaxFrameNum; var missing = ((frameNum - prevRefFrameNum - 1) % max + max) % max; var keep = Math.Max(1, sps.MaxNumRefFrames); - var first = missing > keep ? (frameNum - keep + max) % max : (prevRefFrameNum + 1) % max; if (missing > keep) { foreach (var p in dpb) @@ -370,8 +489,24 @@ public sealed partial class H264Decoder } } - for (var n = first; n != frameNum; n = (n + 1) % max) + var skipped = missing - keep; + var i = 0; + for (var n = (prevRefFrameNum + 1) % max; n != frameNum; n = (n + 1) % max, i++) { + if (sps.PocType != 0) + { + // UpdateFrameNumOffset for the inferred frame n (never an IDR picture). + frameNumOffset = prevFrameNum > n ? prevFrameNumOffset + max : prevFrameNumOffset; + prevFrameNumOffset = frameNumOffset; + } + + prevRefFrameNum = n; + prevFrameNum = n; + if (i < skipped) + { + continue; + } + var gap = NewPicture(sps); gap.FrameNum = n; gap.NonExisting = true; @@ -381,12 +516,6 @@ public sealed partial class H264Decoder SlidingWindow(sps, n); gap.ShortTerm = true; dpb.Add(gap); - prevRefFrameNum = n; - prevFrameNum = n; - if (sps.PocType != 0) - { - prevFrameNumOffset = frameNumOffset; - } } PruneDpb(); @@ -401,7 +530,12 @@ public sealed partial class H264Decoder var sps = activeSps; var picture = cur; - Deblock(picture); + var skipped = picSkipped; + picSkipped = false; + if (!skipped) + { + Deblock(picture); + } if (picRefIdc != 0) { @@ -437,7 +571,7 @@ public sealed partial class H264Decoder haveReference = true; } - if (Wanted?.Invoke(picture.DecodeIndex) ?? true) + if (!skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true)) { FrameDecoded?.Invoke(Crop(picture, sps)); } diff --git a/src/Febe.Core/Codecs/H264/ParameterSets.cs b/src/Febe.Core/Codecs/H264/ParameterSets.cs index 9b9b5c9..0b529dc 100644 --- a/src/Febe.Core/Codecs/H264/ParameterSets.cs +++ b/src/Febe.Core/Codecs/H264/ParameterSets.cs @@ -6,6 +6,9 @@ internal sealed class Sps /// MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits. internal const int MaxFrameMbs = 139_264; + /// MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks. + internal const int MaxDpbMbs = 696_320; + internal int ProfileIdc; internal int LevelIdc; internal int Id; @@ -105,6 +108,13 @@ internal sealed class Sps throw new H264Exception("Immagine più grande di ogni livello H.264."); } + // The reference frames must fit in the largest buffer of any level (MaxDpbMbs of level 6.2, table A-1; A.3.1 + // and A.3.2 bound max_num_ref_frames by it): sixteen frames of the largest size would be 1.4 GB. + if ((long)s.MaxNumRefFrames * s.WidthInMbs * s.HeightInMbs > MaxDpbMbs) + { + throw new H264Exception("Troppe immagini di riferimento per ogni livello H.264."); + } + s.Direct8x8Inference = r.ReadFlag(); if (r.ReadFlag()) { diff --git a/src/Febe.Core/Codecs/H264/RbspReader.cs b/src/Febe.Core/Codecs/H264/RbspReader.cs index e7aee38..50d8a05 100644 --- a/src/Febe.Core/Codecs/H264/RbspReader.cs +++ b/src/Febe.Core/Codecs/H264/RbspReader.cs @@ -129,105 +129,154 @@ internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int L internal RbspReader Reader() => new(Rbsp, Length, 1); } -/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units. +/// +/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units, one at a time, and +/// removal of their emulation prevention bytes into a buffer the caller keeps: decoding a sample allocates nothing. +/// internal static class NalUnits { - /// Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1). + /// Bytes of zero padding a buffer keeps past the payload (see ). + internal const int Padding = 16; + + /// Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer. internal static NalUnit Parse(ReadOnlySpan nal) + { + byte[]? buffer = null; + return Unescape(nal, ref buffer); + } + + /// + /// Removes the emulation prevention bytes of one NAL unit into , grown when needed; the + /// unit is valid until the buffer is used again. + /// + internal static NalUnit Unescape(ReadOnlySpan nal, ref byte[]? buffer) { if (nal.Length < 1) { throw new H264Exception("Unità NAL vuota."); } - var buffer = new byte[nal.Length + 16]; - var count = 0; - var zeros = 0; - for (var i = 0; i < nal.Length; i++) + if (buffer is null || buffer.Length < nal.Length + Padding) { - var b = nal[i]; - if (zeros >= 2 && b == 3) - { - zeros = 0; - continue; - } - - buffer[count++] = b; - zeros = b == 0 ? zeros + 1 : 0; + buffer = new byte[Math.Max(nal.Length + Padding, (buffer?.Length ?? 0) * 2)]; } + // Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1. + ReadOnlySpan pattern = [0, 0, 3]; + var target = buffer.AsSpan(); + var count = 0; + var rest = nal; + while (true) + { + var i = rest.IndexOf(pattern); + if (i < 0) + { + rest.CopyTo(target[count..]); + count += rest.Length; + break; + } + + rest[..(i + 2)].CopyTo(target[count..]); + count += i + 2; + rest = rest[(i + 3)..]; + } + + target.Slice(count, Padding).Clear(); return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count); } - /// The NAL units of an Annex B byte stream (start codes 0x000001 or 0x00000001). + /// + /// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from , + /// which moves past it; false when there is none left. + /// + internal static bool NextAnnexB(ReadOnlySpan stream, ref int position, out Range unit) + { + ReadOnlySpan startCode = [0, 0, 1]; + while (position < stream.Length) + { + var found = stream[position..].IndexOf(startCode); + if (found < 0) + { + break; + } + + var start = position + found + 3; + var next = start < stream.Length ? stream[start..].IndexOf(startCode) : -1; + var end = next < 0 ? stream.Length : start + next; + position = end; + + // Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits). + var trimmed = end; + while (trimmed > start && stream[trimmed - 1] == 0) + { + trimmed--; + } + + if (trimmed > start) + { + unit = start..trimmed; + return true; + } + } + + position = stream.Length; + unit = default; + return false; + } + + /// + /// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from + /// ; false at the end or at a damaged length (what was read stands). + /// + internal static bool NextLengthPrefixed(ReadOnlySpan sample, int lengthSize, ref int position, out Range unit) + { + unit = default; + if (position + lengthSize > sample.Length) + { + return false; + } + + var size = 0; + for (var k = 0; k < lengthSize; k++) + { + size = (size << 8) | sample[position + k]; + } + + position += lengthSize; + if (size <= 0 || size > sample.Length - position) + { + position = sample.Length; + return false; + } + + unit = position..(position + size); + position += size; + return true; + } + + /// The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests). internal static List SplitAnnexB(ReadOnlySpan stream) { var units = new List(); - var start = -1; - var i = 0; - while (i + 2 < stream.Length) + var position = 0; + while (NextAnnexB(stream, ref position, out var unit)) { - if (stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1) - { - if (start >= 0) - { - AddTrimmed(units, stream[start..i]); - } - - i += 3; - start = i; - continue; - } - - i++; - } - - if (start >= 0 && start < stream.Length) - { - AddTrimmed(units, stream[start..]); + units.Add(Parse(stream[unit])); } return units; } - /// The NAL units of a sample whose units are each prefixed by a big-endian length. + /// The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests). internal static List SplitLengthPrefixed(ReadOnlySpan sample, int lengthSize) { var units = new List(); - var offset = 0; - while (offset + lengthSize <= sample.Length) + var position = 0; + while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit)) { - var size = 0; - for (var k = 0; k < lengthSize; k++) - { - size = (size << 8) | sample[offset + k]; - } - - offset += lengthSize; - if (size <= 0 || size > sample.Length - offset) - { - break; // damaged: keep what was read - } - - units.Add(Parse(sample.Slice(offset, size))); - offset += size; + units.Add(Parse(sample[unit])); } return units; } - - private static void AddTrimmed(List units, ReadOnlySpan nal) - { - // Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits). - var end = nal.Length; - while (end > 0 && nal[end - 1] == 0) - { - end--; - } - - if (end > 0) - { - units.Add(Parse(nal[..end])); - } - } } diff --git a/src/Febe.Core/Codecs/H264/SliceHeader.cs b/src/Febe.Core/Codecs/H264/SliceHeader.cs index c75bc7b..9301d85 100644 --- a/src/Febe.Core/Codecs/H264/SliceHeader.cs +++ b/src/Febe.Core/Codecs/H264/SliceHeader.cs @@ -23,6 +23,10 @@ internal sealed class SliceHeader internal int DeltaPocBottom; internal int DeltaPoc0; internal int DeltaPoc1; + + /// redundant_pic_cnt: 0 for the primary coded picture, above 0 for a redundant one. + internal int RedundantPicCnt; + internal bool DirectSpatialMvPred; internal int NumRefIdxActiveL0; internal int NumRefIdxActiveL1; @@ -105,7 +109,7 @@ internal sealed class SliceHeader if (pps.RedundantPicCntPresent) { - r.ReadUe(); // redundant_pic_cnt + h.RedundantPicCnt = r.ReadUe(127); } if (h.IsB) diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index 98fbd02..b14c631 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -21,19 +21,23 @@ public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMe { private readonly IClock _clock = clock ?? new SystemClock(); + /// + /// Reads on a thread of the pool, not on the caller's: a fragmented MP4 without a declared duration is read through + /// all its fragments, and the token is checked between them. + /// public Task ProbeAsync(string path, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(path); - ct.ThrowIfCancellationRequested(); - return Task.FromResult(Probe(path, _clock.Now)); + var now = _clock.Now; + return Task.Run(() => Probe(path, now, ct), ct); } /// The metadata of ; null when the file is unreadable or of another format. - public static VideoMetadata? Probe(string path, DateTimeOffset now) + public static VideoMetadata? Probe(string path, DateTimeOffset now, CancellationToken ct = default) { try { - if (ContainerReader.ReadFile(path, now, samples: false) is not { } container) + if (ContainerReader.ReadFile(path, now, samples: false, ct) is not { } container) { return null; } diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 1722de5..c86c632 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -60,13 +60,42 @@ public sealed class VideoFrameDecoder /// Differences up to this value (0–255) count as compression noise of a still picture. public const double StillThreshold = 3.0; + /// + /// The longest a frame or a stillness analysis may take: what the ffmpeg extractor it replaces was given. A damaged + /// file never holds an import or a rebuild for longer. + /// + public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30); + private const int GridSize = 32; private const int SampledPositions = 6; private const int MaxSequentialSamples = 2000; - private const int MaxRunPerTarget = 300; + private const int DefaultMaxRun = 300; + + /// How far back from a sample flagged as key the decoder looks for one it can really start from. + private const int MaxRunStartSearch = 2000; private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero); + private readonly TimeSpan budget; + private readonly int maxRun; + + /// A decoder with the default budget and run length. + public VideoFrameDecoder() + : this(DefaultBudget, DefaultMaxRun) + { + } + + /// The longest one call may take (zero: no time at all). + /// + /// Samples decoded at most from a random access point to the frame asked for; a frame further away (a damaged time + /// table, a track with a single key frame) gives way to the frame of the random access point itself. + /// + internal VideoFrameDecoder(TimeSpan budget, int maxRun) + { + this.budget = budget; + this.maxRun = maxRun; + } + /// The shared instance: it keeps no state between calls. public static VideoFrameDecoder Instance { get; } = new(); @@ -92,7 +121,7 @@ public sealed class VideoFrameDecoder 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); + return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct); } /// @@ -102,24 +131,58 @@ public sealed class VideoFrameDecoder public Task AnalyseStillnessAsync(string videoPath, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); - return Task.Run(() => AnalyseStillness(videoPath, ct), ct); + return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct); } - private static VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct) + /// Runs for at most the budget: past it the result is null, as for an unreadable file. + private T? WithinBudget(Func work, CancellationToken ct) + where T : class + { + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + if (budget <= TimeSpan.Zero) + { + limit.Cancel(); + } + else + { + limit.CancelAfter(budget); + } + + try + { + return work(limit.Token); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return null; + } + } + + private VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct) { try { + ct.ThrowIfCancellationRequested(); using var stream = ContainerReader.OpenRead(path); if (Open(stream) is not { } video) { return null; } + var decoding = new Decoding(stream, video, maxRun); var target = SampleAt(video, at); - var frames = new Decoding(stream, video).Decode([target], ct); + + // Too far from where decoding can start: the frame there stands for it, so the work stays bounded. + var start = decoding.RunStart(target); + if (target - start > maxRun) + { + target = start; + } + + var frames = decoding.Decode([target], ct); if (!frames.TryGetValue(target, out var frame) && target != 0) { - frames = new Decoding(stream, video).Decode([0], ct); + frames = new Decoding(stream, video, maxRun).Decode([0], ct); frames.TryGetValue(0, out frame); } @@ -131,10 +194,11 @@ public sealed class VideoFrameDecoder } } - private static VideoStillness? AnalyseStillness(string path, CancellationToken ct) + private VideoStillness? AnalyseStillness(string path, CancellationToken ct) { try { + ct.ThrowIfCancellationRequested(); using var stream = ContainerReader.OpenRead(path); if (Open(stream) is not { } video) { @@ -155,18 +219,20 @@ public sealed class VideoFrameDecoder last = Math.Max(last, s.PresentationTime); } - var keys = KeyIndices(video); + var decoding = new Decoding(stream, video, maxRun); var targets = new SortedSet(); for (var i = 0; i < SampledPositions; i++) { + ct.ThrowIfCancellationRequested(); var time = first + ((last - first) * i / (SampledPositions - 1)); var index = Closest(samples, time); - // Far from 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) + // Far from where decoding can start in a long video: the frame there stands for it, so the work stays + // bounded. + var start = decoding.RunStart(index); + if (index - start > maxRun && samples.Count > MaxSequentialSamples) { - index = key; + index = start; } targets.Add(index); @@ -177,7 +243,7 @@ public sealed class VideoFrameDecoder return null; } - var frames = new Decoding(stream, video).Decode([.. targets], ct); + var frames = decoding.Decode([.. targets], ct); if (frames.Count < 2) { return null; @@ -276,22 +342,76 @@ public sealed class VideoFrameDecoder 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) + /// + /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. + /// + private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) { private readonly Dictionary found = []; private readonly HashSet wanted = []; + private readonly int[] keys = KeyIndices(video); + private readonly Dictionary accessPoints = []; private byte[] buffer = new byte[64 * 1024]; /// The sample being decoded: the picture it finishes is that sample's frame. private int current; + /// + /// The sample where decoding for starts. A container without an index (an AVI cut short, + /// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give + /// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest + /// IDR picture is taken when it is within the run limit (the frame comes out exact); otherwise the nearest + /// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture + /// further back, or the first sample. + /// + internal int RunStart(int index) + { + var position = Array.BinarySearch(keys, index); + position = position >= 0 ? position : Math.Max(0, ~position - 1); + var intra = -1; + for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++) + { + var candidate = keys[position]; + if (!accessPoints.TryGetValue(candidate, out var point)) + { + point = AccessPointOf(candidate); + accessPoints[candidate] = point; + } + + if (point == H264AccessPoint.Idr) + { + return index - candidate <= maxRun || intra < 0 ? candidate : intra; + } + + if (point == H264AccessPoint.IntraPicture && intra < 0) + { + intra = candidate; + } + + if (index - candidate > maxRun && intra >= 0) + { + return intra; // no IDR picture within reach: the nearest picture of I slices + } + } + + // The first sample, where every stream starts (or the end of the search): it counts as an IDR picture. + return index <= maxRun || intra < 0 ? 0 : intra; + } + + private H264AccessPoint AccessPointOf(int index) + { + try + { + var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer); + var lengthSize = video.AnnexB ? 0 : video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4; + return H264Decoder.AccessPoint(sample, lengthSize); + } + catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException) + { + return H264AccessPoint.None; + } + } + internal Dictionary Decode(int[] targets, CancellationToken ct) { foreach (var t in targets) @@ -299,13 +419,12 @@ public sealed class VideoFrameDecoder 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); + var key = RunStart(target); if (decoder is null || next > target || key >= next) { // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a diff --git a/tests/Febe.Tests/Media/Containers/ContainerTests.cs b/tests/Febe.Tests/Media/Containers/ContainerTests.cs index 34da89a..661b70b 100644 --- a/tests/Febe.Tests/Media/Containers/ContainerTests.cs +++ b/tests/Febe.Tests/Media/Containers/ContainerTests.cs @@ -230,6 +230,23 @@ public sealed class ContainerTests Assert.AreEqual(2020, meta!.CreatedAt!.Value.Year); } + [TestMethod] + [DataRow(3_000_000u)] + [DataRow(1_000_000u)] + [DataRow(2_500_000u)] + public void MatroskaTimesStayExactWithAnyTimecodeScale(uint timecodeScale) + { + // A TimecodeScale that does not divide a second (3 ms): the timescale of the track must not be rounded down + // (333 ticks a second instead of 333.3), or every time drifts by 0.1% and disagrees with the duration. + var es = ElementaryStream.Load("CI_MW_D"); + var container = Read(TestVideos.Matroska(es, timecodeScale: timecodeScale)); + var video = container.Video!; + var tick = timecodeScale / 1e9; + Assert.AreEqual(container.Duration!.Value.TotalSeconds, video.Seconds(video.Duration), 1.0 / video.Timescale, "durata della traccia e del file"); + var span = video.Samples.Max(s => s.PresentationTime) - video.Samples.Min(s => s.PresentationTime); + Assert.AreEqual((es.Count - 1) / 30.0, video.Seconds(span), tick, "dal primo all'ultimo fotogramma"); + } + private static MediaContainer Read(byte[] file) { using var stream = new MemoryStream(file); diff --git a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs index ac39c87..40c46e9 100644 --- a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs +++ b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs @@ -85,14 +85,91 @@ public sealed class MalformedInputTests Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); Assert.IsEmpty(container!.Video!.Samples, "una tabella impossibile non dà campioni"); - // A trun of two billion samples without per-sample fields. + // A trun of almost two million samples without per-sample fields: under the sample limit, but far more than the + // file can hold (the trex default size is 0, so each would take at least a byte). That fragment gives nothing, + // the others give their samples. var fragmented = TestVideos.FragmentedMp4(es, perFragment: 5); var trun = IndexOf(fragmented, "trun"u8); BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 4), 0x000001); // only data_offset - BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), int.MaxValue); + BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), 1_999_999); container = ReadMeasured(fragmented, out allocated); Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); - Assert.IsNotNull(container); + Assert.HasCount(es.Count - 5, container!.Video!.Samples, "nessun campione inventato"); + } + + [TestMethod] + public async Task AMatroskaFileWithADamagedOrTruncatedBlockKeepsTheBlocksBefore() + { + var es = ElementaryStream.Load("CI_MW_D"); + var file = TestVideos.Matroska(es); + using var temp = new TempFolder("matroska-rovinato"); + var intact = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "intero.mkv", file), TimeSpan.FromSeconds(1)); + Assert.IsNotNull(intact); + + // The blocks close the file: each is the ID, an eight-byte size, track, time, flags and the sample. + int StartOf(int block) => file.Length - Enumerable.Range(block, es.Count - block).Sum(i => 1 + 8 + 4 + es.LengthPrefixed(i).Length); + + // Cut inside the fixed part of the last block. + var truncated = file[..(StartOf(es.Count - 1) + 1 + 8 + 2)]; + Assert.HasCount(es.Count - 1, ReadMeasured(truncated, out _)!.Video!.Samples); + + // Block 50 says it holds nothing but its own header: the blocks before it stand, the frame at one second too. + var damaged = (byte[])file.Clone(); + var block = StartOf(50); + Assert.AreEqual(0xA3, damaged[block]); + damaged.AsSpan(block + 2, 7).Clear(); + damaged[block + 8] = 4; + Assert.HasCount(50, ReadMeasured(damaged, out _)!.Video!.Samples); + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "rovinato.mkv", damaged), TimeSpan.FromSeconds(1)); + CollectionAssert.AreEqual(intact.Rgb, image!.Rgb); + } + + [TestMethod] + public void ADamagedAudioTrackDoesNotCostTheVideo() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + + // The descriptors of the audio esds run to its very end: the ES_Descriptor starts at its last two bytes. + var file = TestVideos.Mp4(es, audio: true); + var esds = IndexOf(file, "esds"u8); + var length = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(esds - 4)) - 8; + var body = file.AsSpan(esds + 4, length); + body[4..].Clear(); + body[4] = 0x7F; // an unknown descriptor that covers the body... + body[5] = (byte)(length - 8); + body[length - 2] = 0x03; // ...up to an ES_Descriptor with no room for its fields + var container = ReadMeasured(file, out _)!; + Assert.HasCount(es.Count, container.Video!.Samples); + Assert.IsNotNull(container.Audio); + Assert.IsNull(container.Audio.AacConfiguration); + + // The audio track header claims version 1, whose fields lie past the end of the box: that track is dropped. + file = TestVideos.Mp4(es, audio: true); + var audioTkhd = file.AsSpan(IndexOf(file, "tkhd"u8) + 4).IndexOf("tkhd"u8) + IndexOf(file, "tkhd"u8) + 4; + file[audioTkhd + 4] = 1; + container = ReadMeasured(file, out _)!; + Assert.HasCount(es.Count, container.Video!.Samples); + Assert.IsNull(container.Audio); + using var temp = new TempFolder("audio-rovinato"); + var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mp4", file), Now); + Assert.AreEqual((es.Width, es.Height), (metadata!.Width, metadata.Height)); + } + + [TestMethod] + public void AnAviWithAnImpossibleDurationKeepsItsDate() + { + // One frame per million seconds for a million frames: 10¹² seconds, beyond what a TimeSpan holds. + var es = ElementaryStream.Load("BA1_Sony_D"); + var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021", scale: 1_000_000, rate: 1, length: 1_000_000); + var container = ReadMeasured(file, out _)!; + Assert.IsNull(container.Duration); + Assert.AreEqual(2021, container.CreatedAt!.Value.Year); + + using var temp = new TempFolder("avi-durata"); + var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.avi", file), Now); + Assert.IsNotNull(metadata, "la data scritta nel file non va persa"); + Assert.AreEqual(2021, metadata.CreatedAt!.Value.Year); + Assert.IsNull(metadata.Duration); } [TestMethod] diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index 62a3205..3dea09d 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -126,6 +126,17 @@ internal sealed class ElementaryStream return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height); } + /// + /// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a + /// decoder started at any of its P or B frames finds its parameter sets. + /// + public ElementaryStream WithParameterSetsEverywhere() + { + var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList(); + var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList(); + return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height); + } + /// An access unit with 4-byte length prefixes (MP4, Matroska). public byte[] LengthPrefixed(int index) { @@ -328,8 +339,11 @@ internal static class TestVideos 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) + /// + /// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of + /// nanoseconds (milliseconds by default). + /// + public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000) { var shift = 0; for (var i = 0; i < es.Count; i++) @@ -340,8 +354,9 @@ internal static class TestVideos 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()) }; + var tickMs = timecodeScale / 1e6; + var durationTicks = es.Count * 1000.0 / 30 / tickMs; + var info = new List { Element(0x2AD7B1, U32(timecodeScale)), Element(0x4489, F64(durationTicks)), Element(0x4D80, "febe-prove"u8.ToArray()) }; if (created is { } c) { var ns = (c - new DateTimeOffset(2001, 1, 1, 0, 0, 0, TimeSpan.Zero)).Ticks * 100; @@ -354,7 +369,7 @@ internal static class TestVideos 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 pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30 / tickMs); var payload = es.LengthPrefixed(i); blocks.Add(Element(0xA3, [0x81, (byte)(pts >> 8), (byte)pts, es.Key[i] ? (byte)0x80 : (byte)0, .. payload])); } @@ -363,8 +378,12 @@ internal static class TestVideos 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) + /// + /// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless is false, as in a + /// recording cut short) and, when given, an IDIT date. The stream header says / + /// frames per second and frames (default: the stream's). + /// + public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true, uint scale = 1, uint rate = 30, uint? length = null) { var avih = new List(); foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 }) @@ -374,7 +393,7 @@ internal static class TestVideos 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 }) + foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 }) { strh.AddRange(Le32(v)); } diff --git a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs index 49a011a..cbc7a5f 100644 --- a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs +++ b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs @@ -1,5 +1,8 @@ +using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.H264; +using Febe.Core.Import; using Febe.Core.Library; +using Febe.Tests.Desktop.Support; using Febe.Tests.Support; namespace Febe.Tests.Codecs.Containers; @@ -13,14 +16,22 @@ public sealed class VideoFrameDecoderTests [DataRow("mkv")] [DataRow("avi")] [DataRow("frammentato.mp4")] + [DataRow("senza-indice.avi")] + [DataRow("senza-indice-con-parametri.avi")] public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind) { var es = ElementaryStream.Load("CABA3_SVA_B"); using var temp = new TempFolder("fotogramma"); + + // Without idx1 (a recording cut short) every chunk counts as a key frame: decoding must still start from the + // IDR picture, also when every chunk carries its own parameter sets (then a decoder started at the P frame itself + // would give a corrupt picture rather than none). var data = kind switch { "mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), "avi" => TestVideos.Avi(es), + "senza-indice.avi" => TestVideos.Avi(es, index: false), + "senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false), "frammentato.mp4" => TestVideos.FragmentedMp4(es), _ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone }; @@ -32,7 +43,7 @@ public sealed class VideoFrameDecoderTests // 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 expected = kind.EndsWith("avi", StringComparison.Ordinal) ? DecodedFrame(es, position) : ShownFrame(es, position); var reference = VideoFrameDecoder.ToImage(expected, 0, 0); Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height)); CollectionAssert.AreEqual(reference.Rgb, image.Rgb); @@ -119,6 +130,72 @@ public sealed class VideoFrameDecoderTests Assert.IsFalse(result.IsStill, $"differenza {result.Difference}"); } + [TestMethod] + public async Task AFrameFarFromWhereDecodingCanStartGivesWayToTheFrameThere() + { + // At most five samples from the random access point: the frame at one second (sample 30, one IDR at sample 0) + // is too far, the IDR picture stands for it instead of decoding the whole run (a damaged time table can put the + // frame asked for two million samples after the only key frame). + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("fotogramma-lontano"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var decoder = new VideoFrameDecoder(VideoFrameDecoder.DefaultBudget, maxRun: 5); + var image = await decoder.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + CollectionAssert.AreEqual(VideoFrameDecoder.ToImage(DecodedFrame(es, 0), 0, 0).Rgb, image!.Rgb); + Assert.IsNotNull(await decoder.AnalyseStillnessAsync(path), "anche l'analisi resta limitata e risponde"); + } + + [TestMethod] + public async Task PastItsBudgetTheDecoderGivesNothingButTheCallerCanStillCancel() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("fotogramma-tempo"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var late = new VideoFrameDecoder(TimeSpan.Zero, maxRun: 300); + Assert.IsNull(await late.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)), "oltre il tempo concesso: nessun fotogramma"); + Assert.IsNull(await late.AnalyseStillnessAsync(path)); + + // A cancellation asked by the caller is not a missing frame: it stays a cancellation. + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Assert.ThrowsAsync(() => VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1), 0, cancelled.Token)); + } + + [TestMethod] + [DataRow("filmato-muto.mp4", false)] + [DataRow("filmato-con-audio.mp4", true)] + public async Task TheVideosOfARealEncoderAreReadAndDecoded(string name, bool audio) + { + // The two small MP4s of the test site come from a real muxer and encoder (libavformat, x264 High profile: the + // shape of the videos Instagram serves); no official MD5 exists for them, so the frame is checked coarsely. + var path = Repository.PathOf("tools", "Febe.SitoDiProva", "Risorse", name); + var now = new DateTimeOffset(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + var metadata = ContainerVideoMetadataProbe.Probe(path, now); + Assert.IsNotNull(metadata); + Assert.IsTrue(metadata.Width > 0 && metadata.Height > 0, $"{metadata.Width}×{metadata.Height}"); + Assert.IsTrue(metadata.Duration > TimeSpan.Zero && metadata.Duration < TimeSpan.FromMinutes(1), $"{metadata.Duration}"); + + var container = ContainerReader.ReadFile(path, now); + Assert.AreEqual(VideoCodec.H264, container!.Video!.Codec); + Assert.AreEqual(audio, container.Audio is not null); + + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + Assert.IsNotNull(image, "nessun fotogramma da un video di un codificatore vero"); + Assert.AreEqual((metadata.Width, metadata.Height), (image.Width, image.Height)); + + // A real picture: not a flat field of one value, not out of range. + var luma = new double[image.Width * image.Height]; + for (var i = 0; i < luma.Length; i++) + { + luma[i] = (0.299 * image.Rgb[i * 3]) + (0.587 * image.Rgb[(i * 3) + 1]) + (0.114 * image.Rgb[(i * 3) + 2]); + } + + var mean = luma.Average(); + Assert.IsTrue(mean is > 2 and < 253, $"luminanza media {mean:F1}"); + var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path); + Assert.IsNotNull(bmp); + } + [TestMethod] public async Task UnreadableFilesGiveNothing() { diff --git a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs index fbdc811..e947dfe 100644 --- a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs +++ b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs @@ -5,7 +5,10 @@ namespace Febe.Tests.Codecs.H264; /// /// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the -/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). +/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). None of these streams uses +/// weighted prediction, memory management operations, long-term references, gaps in frame_num, POC type 1, I_PCM or +/// CABAC pictures of several slices: those parts of the decoder have no reference MD5 here (some are reached by +/// , without an official reference). /// [TestClass] public sealed class H264ConformanceTests @@ -49,6 +52,38 @@ public sealed class H264ConformanceTests Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi"); } + [TestMethod] + [DataRow("CABA3_SVA_B")] + [DataRow("CANL1_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("FRExt3_Panasonic_E")] + [DataRow("HCAFR1_HHI_C")] + public void PicturesLeftOutDoNotChangeTheOthers(string name) + { + // Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame + // handed out must still be the one of the full decoding, in the same place of the output order. + var folder = Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); + var data = File.ReadAllBytes(Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc")); + var all = new List(); + var full = new H264Decoder(); + full.FrameDecoded += all.Add; + full.DecodeAnnexB(data); + + var some = new List(); + var partial = new H264Decoder { Wanted = index => index % 3 == 2 }; + partial.FrameDecoded += some.Add; + partial.DecodeAnnexB(data); + + Assert.AreEqual(full.FramesDecoded, partial.FramesDecoded); + CollectionAssert.AreEqual(all.Where(f => f.DecodeIndex % 3 == 2).Select(f => f.DecodeIndex).ToArray(), some.Select(f => f.DecodeIndex).ToArray()); + foreach (var frame in some) + { + var expected = all.Single(f => f.DecodeIndex == frame.DecodeIndex); + Assert.AreEqual((expected.Poc, expected.Period), (frame.Poc, frame.Period), $"{name}: ordine del fotogramma {frame.DecodeIndex}"); + CollectionAssert.AreEqual(expected.ToI420(), frame.ToI420(), $"{name}: fotogramma {frame.DecodeIndex}"); + } + } + private static List ReadReference(string path) { var frames = new List(); diff --git a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs index 27cb52e..fb326c1 100644 --- a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs +++ b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs @@ -66,14 +66,28 @@ public sealed class H264RobustnessTests [TestMethod] public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated() { - // 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does. + // 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does. A PPS and the + // start of an IDR slice follow, so a decoder without the bound would really allocate its pictures. + var huge = new SyntheticStreams.SequenceSettings(WidthInMbs: 1024, HeightInMbs: 1024); + byte[] stream = [.. SyntheticStreams.Sps(huge), .. SyntheticStreams.Pps(), .. SyntheticStreams.Idr(huge, 100, macroblocks: 1)]; var before = GC.GetAllocatedBytesForCurrentThread(); - var error = Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 1024, heightInMbs: 1024))); + var error = Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(stream)); StringAssert.Contains(error.Message, "livello"); Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before); // The largest frame of level 6.2 is still accepted. - new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 512, heightInMbs: 272)); + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272))); + } + + [TestMethod] + public void MoreReferenceFramesThanTheLargestBufferAreRefused() + { + // 8192 × 4352 with sixteen reference frames would be 1.4 GB of pictures; level 6.2 holds five of that size. + var error = Assert.ThrowsExactly(() => + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 16)))); + StringAssert.Contains(error.Message, "riferimento"); + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 5))); + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 120, HeightInMbs: 68, MaxNumRefFrames: 16))); } [TestMethod] @@ -85,83 +99,7 @@ public sealed class H264RobustnessTests Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0)))); } - /// A Baseline SPS NAL unit in Annex B form, written bit by bit (§7.3.2.1.1). - private static byte[] Sps(int widthInMbs, int heightInMbs, (int Left, int Right, int Top, int Bottom)? crop = null) - { - var bits = new BitWriter(); - bits.Bits(66, 8); // profile_idc: Baseline - bits.Bits(0, 8); // constraint flags - bits.Bits(30, 8); // level_idc - bits.Ue(0); // seq_parameter_set_id - bits.Ue(0); // log2_max_frame_num_minus4 - bits.Ue(2); // pic_order_cnt_type - bits.Ue(1); // max_num_ref_frames - bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag - bits.Ue((uint)widthInMbs - 1); - bits.Ue((uint)heightInMbs - 1); - bits.Bits(1, 1); // frame_mbs_only_flag - bits.Bits(1, 1); // direct_8x8_inference_flag - bits.Bits(crop is null ? 0u : 1u, 1); - if (crop is { } c) - { - bits.Ue((uint)c.Left); - bits.Ue((uint)c.Right); - bits.Ue((uint)c.Top); - bits.Ue((uint)c.Bottom); - } - - bits.Bits(0, 1); // vui_parameters_present_flag - bits.Bits(1, 1); // rbsp_stop_one_bit - return [0, 0, 0, 1, 0x67, .. bits.ToArray()]; - } - - private sealed class BitWriter - { - private readonly List bits = []; - - public void Bits(uint value, int count) - { - for (var i = count - 1; i >= 0; i--) - { - bits.Add(((value >> i) & 1) != 0); - } - } - - public void Ue(uint value) - { - var code = value + 1; - var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); - Bits(0, length - 1); - Bits(code, length); - } - - public byte[] ToArray() - { - var bytes = new byte[(bits.Count + 7) / 8]; - for (var i = 0; i < bits.Count; i++) - { - if (bits[i]) - { - bytes[i / 8] |= (byte)(0x80 >> (i % 8)); - } - } - - // Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3. - var output = new List(); - var zeros = 0; - foreach (var b in bytes) - { - if (zeros >= 2 && b <= 3) - { - output.Add(3); - zeros = 0; - } - - output.Add(b); - zeros = b == 0 ? zeros + 1 : 0; - } - - return [.. output]; - } - } -} + /// A Baseline SPS of the given size and crop. + private static byte[] Sps(int widthInMbs, int heightInMbs, (int, int, int, int) crop) => + SyntheticStreams.Sps(new(WidthInMbs: widthInMbs, HeightInMbs: heightInMbs, Crop: crop)); +} \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs b/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs new file mode 100644 index 0000000..5054d89 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs @@ -0,0 +1,106 @@ +using Febe.Core.Codecs.H264; +using static Febe.Tests.Codecs.H264.SyntheticStreams; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The decoder on tiny streams written by : the parts of the standard no conformance stream in +/// the repository exercises. +/// +[TestClass] +public sealed class H264SyntheticStreamTests +{ + [TestMethod] + [DataRow(16)] + [DataRow(2)] + public void AGapInFrameNumKeepsTheWrapInThePictureOrder(int maxNumRefFrames) + { + // POC type 2, MaxFrameNum 16: references 0..14, then frame_num 3. Frames 15, 0, 1 and 2 are missing (§8.2.5.2): + // the wrap at 0 is among them, so the frame after the gap has FrameNumOffset 16 and POC 2 × (16 + 3) (§8.2.1.3). + // With two reference frames, 15 and 0 are counted without becoming references. + var s = new SequenceSettings(MaxNumRefFrames: maxNumRefFrames, GapsAllowed: true); + var stream = new List([.. Sps(s), .. Pps(), .. Idr(s, 100)]); + for (var n = 1; n <= 14; n++) + { + stream.AddRange(SkippedP(s, n)); + } + + stream.AddRange(SkippedP(s, 3)); + var frames = Decode([.. stream]); + + Assert.HasCount(16, frames); + for (var n = 0; n <= 14; n++) + { + Assert.AreEqual(2 * n, frames[n].Poc, $"fotogramma {n}"); + } + + Assert.AreEqual(2 * (16 + 3), frames[15].Poc, "il fotogramma dopo il salto"); + } + + [TestMethod] + public void ARedundantPictureIsSkipped() + { + // The primary IDR picture (luma 100) and a redundant copy (redundant_pic_cnt 1) whose slice also starts at + // macroblock 0: one frame, the primary one. + var s = new SequenceSettings(); + byte[] stream = [.. Sps(s), .. Pps(redundantPicCntPresent: true), .. Idr(s, 100, redundantPicCnt: 0), .. Idr(s, 200, redundantPicCnt: 1)]; + var frames = Decode(stream); + Assert.HasCount(1, frames); + Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario"); + } + + [TestMethod] + public void APSliceWithNothingToPredictFromIsRefused() + { + // Decoding that starts at a P picture (an AVI without index, read from a sample that is not a key frame): the + // decoder refuses it instead of predicting the picture from itself. + var s = new SequenceSettings(); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + Assert.ThrowsExactly(() => decoder.DecodeAnnexB([.. Sps(s), .. Pps(), .. SkippedP(s, 1)])); + Assert.IsEmpty(frames); + } + + [TestMethod] + public void AnUnwantedPictureNobodyRefersToIsNotDecoded() + { + // The second picture is not a reference and its slice data is broken (a skip run past the picture): decoding it + // fails, so a decoder that skips it as unwanted shows it was never reconstructed. + var s = new SequenceSettings(PocType: 0); + byte[] broken = [.. SkippedP(s with { WidthInMbs = 2 }, 1, reference: false)]; // a run of 2 in a 1-macroblock picture + byte[] stream = [.. Sps(s), .. Pps(), .. Idr(s, 100), .. broken, .. SkippedP(s, 1, pocLsb: 4)]; + Assert.ThrowsExactly(() => Decode(stream)); + + var decoder = new H264Decoder { Wanted = index => index != 1 }; + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + Assert.AreEqual(3, decoder.FramesDecoded); + CollectionAssert.AreEqual(new long[] { 0, 2 }, frames.Select(f => f.DecodeIndex).ToArray()); + Assert.AreEqual(4, frames[1].Poc, "il fotogramma dopo quello saltato ha il suo ordine"); + Assert.IsTrue(frames[1].Y.All(v => v == 100)); + } + + [TestMethod] + public void TheStartOfDecodingIsRecognised() + { + var s = new SequenceSettings(); + Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. Idr(s, 100)], 0)); + Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. SkippedP(s, 1)], 0)); + Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([], 0)); + + // Length-prefixed (MP4): the same IDR picture without its start code. + var idr = Idr(s, 100)[4..]; + Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([0, 0, (byte)(idr.Length >> 8), (byte)idr.Length, .. idr], 4)); + } + + private static List Decode(byte[] stream) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H264/SyntheticStreams.cs b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs new file mode 100644 index 0000000..dd5997e --- /dev/null +++ b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs @@ -0,0 +1,216 @@ +namespace Febe.Tests.Codecs.H264; + +/// +/// Tiny H.264 streams written bit by bit from the syntax of the standard (§7.3): Baseline parameter sets, IDR pictures +/// made of I_PCM macroblocks (their samples are written as they are, so every pixel is known) and P pictures made only +/// of skipped macroblocks. They reach the parts of the decoder the conformance streams in the repository do not: gaps in +/// frame_num, redundant pictures, slices without references, huge parameter sets. +/// +internal static class SyntheticStreams +{ + /// Settings of the sequence parameter set. + internal sealed record SequenceSettings( + int WidthInMbs = 1, + int HeightInMbs = 1, + int PocType = 2, + int Log2MaxFrameNum = 4, + int MaxNumRefFrames = 1, + bool GapsAllowed = false, + (int Left, int Right, int Top, int Bottom)? Crop = null); + + /// A sequence parameter set NAL unit with its start code (§7.3.2.1.1). + internal static byte[] Sps(SequenceSettings s) + { + var bits = new BitWriter(); + bits.Bits(66, 8); // profile_idc: Baseline + bits.Bits(0, 8); // constraint flags + bits.Bits(30, 8); // level_idc + bits.Ue(0); // seq_parameter_set_id + bits.Ue((uint)s.Log2MaxFrameNum - 4); + bits.Ue((uint)s.PocType); + if (s.PocType == 0) + { + bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4 + } + + bits.Ue((uint)s.MaxNumRefFrames); + bits.Bits(s.GapsAllowed ? 1u : 0u, 1); + bits.Ue((uint)s.WidthInMbs - 1); + bits.Ue((uint)s.HeightInMbs - 1); + bits.Bits(1, 1); // frame_mbs_only_flag + bits.Bits(1, 1); // direct_8x8_inference_flag + bits.Bits(s.Crop is null ? 0u : 1u, 1); + if (s.Crop is { } c) + { + bits.Ue((uint)c.Left); + bits.Ue((uint)c.Right); + bits.Ue((uint)c.Top); + bits.Ue((uint)c.Bottom); + } + + bits.Bits(0, 1); // vui_parameters_present_flag + return Nal(0x67, bits); + } + + /// A Baseline picture parameter set (CAVLC, one slice group, deblocking control present, §7.3.2.2). + internal static byte[] Pps(bool redundantPicCntPresent = false) + { + var bits = new BitWriter(); + bits.Ue(0); // pic_parameter_set_id + bits.Ue(0); // seq_parameter_set_id + bits.Bits(0, 1); // entropy_coding_mode_flag: CAVLC + bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag + bits.Ue(0); // num_slice_groups_minus1 + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Bits(0, 1); // weighted_pred_flag + bits.Bits(0, 2); // weighted_bipred_idc + bits.Se(0); // pic_init_qp_minus26 + bits.Se(0); // pic_init_qs_minus26 + bits.Se(0); // chroma_qp_index_offset + bits.Bits(1, 1); // deblocking_filter_control_present_flag + bits.Bits(0, 1); // constrained_intra_pred_flag + bits.Bits(redundantPicCntPresent ? 1u : 0u, 1); + return Nal(0x68, bits); + } + + /// + /// An IDR picture of I_PCM macroblocks whose luma samples are all (chroma 128), as one slice. + /// + internal static byte[] Idr(SequenceSettings s, byte luma, int idrPicId = 0, int? redundantPicCnt = null, int macroblocks = -1) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Bits(0, s.Log2MaxFrameNum); // frame_num + bits.Ue((uint)idrPicId); + if (s.PocType == 0) + { + bits.Bits(0, 8); // pic_order_cnt_lsb + } + + if (redundantPicCnt is { } r) + { + bits.Ue((uint)r); + } + + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + var count = macroblocks < 0 ? s.WidthInMbs * s.HeightInMbs : macroblocks; + for (var m = 0; m < count; m++) + { + bits.Ue(25); // mb_type: I_PCM + bits.Align(); // pcm_alignment_zero_bit + for (var i = 0; i < 256; i++) + { + bits.Bits(luma, 8); + } + + for (var i = 0; i < 128; i++) + { + bits.Bits(128, 8); + } + } + + return Nal(0x65, bits); + } + + /// A P picture whose macroblocks are all skipped (a copy of the newest reference), as one slice. + /// The sequence. + /// frame_num. + /// False for nal_ref_idc 0. + /// pic_order_cnt_lsb with POC type 0 (default: twice frame_num). + internal static byte[] SkippedP(SequenceSettings s, int frameNum, bool reference = true, int? pocLsb = null) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(5); // slice_type: P (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Bits((uint)frameNum, s.Log2MaxFrameNum); + if (s.PocType == 0) + { + bits.Bits((uint)(pocLsb ?? (2 * frameNum)) & 0xFF, 8); // pic_order_cnt_lsb + } + + bits.Bits(0, 1); // num_ref_idx_active_override_flag + bits.Bits(0, 1); // ref_pic_list_modification_flag_l0 + if (reference) + { + bits.Bits(0, 1); // adaptive_ref_pic_marking_mode_flag + } + + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + bits.Ue((uint)(s.WidthInMbs * s.HeightInMbs)); // mb_skip_run: the whole picture + return Nal(reference ? (byte)0x41 : (byte)0x01, bits); + } + + private static byte[] Nal(byte header, BitWriter bits) + { + bits.Bits(1, 1); // rbsp_stop_one_bit + return [0, 0, 0, 1, header, .. bits.ToArray()]; + } + + private sealed class BitWriter + { + private readonly List bits = []; + + public void Bits(uint value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + bits.Add(((value >> i) & 1) != 0); + } + } + + public void Ue(uint value) + { + var code = value + 1; + var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); + Bits(0, length - 1); + Bits(code, length); + } + + public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1)); + + public void Align() + { + while (bits.Count % 8 != 0) + { + bits.Add(false); + } + } + + public byte[] ToArray() + { + var bytes = new byte[(bits.Count + 7) / 8]; + for (var i = 0; i < bits.Count; i++) + { + if (bits[i]) + { + bytes[i / 8] |= (byte)(0x80 >> (i % 8)); + } + } + + // Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3. + var output = new List(); + var zeros = 0; + foreach (var b in bytes) + { + if (zeros >= 2 && b <= 3) + { + output.Add(3); + zeros = 0; + } + + output.Add(b); + zeros = b == 0 ? zeros + 1 : 0; + } + + return [.. output]; + } + } +} diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index 170b799..60a42a7 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -75,7 +75,12 @@ public sealed partial class PipelineTests } // 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"); + var image = Code(Read(Repository.PathOf("docker", "Dockerfile"))); + foreach (var program in new[] { "ffmpeg", "ffprobe" }) + { + Assert.IsFalse(environment.Contains(program, StringComparison.Ordinal), $"{program} non serve più alle prove"); + Assert.IsFalse(image.Contains(program, StringComparison.Ordinal), $"{program} non va nell'immagine"); + } // tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project. foreach (var name in new[] { "verifica.yml", "rilascio.yml" })