Contenitori e decodificatore H.264 provati sui file rovinati; corretti trex, data_offset e ordine dei blocchi MP4 (#58)

Revisione del lavoro in corso sui lettori in casa che sostituiscono ffmpeg e ffprobe. La corsa completa di tests/Febe.Tests ora è verde.

Difetti corretti:
- ISO BMFF frammentato: i valori di trex erano letti con i campi scambiati (la durata predefinita prendeva la dimensione, i flag andavano persi) e il data_offset di un secondo trun si sommava alla fine del primo invece che alla base del moof.
- Mp4Writer: i blocchi di una traccia con tempi uguali (audio senza tempi, come da AVI) potevano uscire fuori ordine, perché l'ordinamento non è stabile; ora restano nell'ordine dei campioni.
- Durata di un MP4 frammentato nella sola lettura dei metadati: da mehd o, se manca, dai frammenti (prima restava ignota).
- File danneggiati: un stsz o un trun di pochi byte poteva chiedere centinaia di MB, un elemento Matroska più grande del file veniva allocato, un salto oltre i 2 GB faceva fallire MemoryStream, IndexOutOfRange e conversioni di date e durate uscivano come eccezioni non previste. Ora ogni tabella si controlla contro il file prima di allocare, al più 2.000.000 di campioni per traccia e 64 MB per campione, e una traccia MP4 con tabelle rovinate resta senza campioni senza togliere le altre.
- H.264: un SPS oltre il MaxFS del livello 6.2 o con un ritaglio che non lascia immagine è rifiutato prima di allocare; mai più riferimenti di Max(max_num_ref_frames, 1); gli errori di deblocco e ritaglio escono come H264Exception.
- VideoFrameDecoder: i fotogrammi si associano al campione decodificato, non al conteggio del decodificatore (un campione senza immagine non sposta più quelli dopo); un campione oltre la fine di un file troncato non toglie i fotogrammi già decodificati; il fotogramma per la miniatura è ridotto a 960 pixel sul lato lungo.

Prove nuove: file troncati e rovinati con semi fissi per MP4, MP4 frammentato, Matroska e AVI (lettori, sonda e decodificatore dei fotogrammi, con limite di memoria allocata), flussi di conformità rovinati per il decodificatore H.264, SPS troppo grande e ritaglio non valido, MP4 frammentato con valori predefiniti e due trun, ordine dei blocchi con tempi uguali. Le prove nuove dei difetti falliscono sul codice di prima.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 13:15:52 +01:00
1 parent 6ffcb1bb18
commit 479c95f899
14 files changed
+787 -113

No files matched your search

+2
View File
@@ -421,3 +421,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano | | 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano |
| 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» | | 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» |
| 2026-11-18 | Video senza programmi esterni: ffmpeg e ffprobe tolti dall'immagine Docker, dalla CI e dal codice. I metadati vengono dai lettori di contenitori scritti in casa (`Febe.Core.Codecs.Containers`: ISO BMFF anche frammentato, Matroska/WebM, AVI; `ContainerVideoMetadataProbe` è la sonda predefinita), i fotogrammi delle miniature dal decodificatore H.264 scritto in casa (`Febe.Core.Codecs.H264`, `VideoFrameDecoder`, BMP ruotato come il video), che dice anche se un video mostra solo un'immagine ferma; c'è uno scrittore MP4 (moov in testa) per rimpacchettare. Le tabelle CABAC sono trascritte dal testo della Raccomandazione ITU-T H.264, non a memoria; il decodificatore è provato fotogramma per fotogramma sugli MD5 dei flussi di conformità ITU-T H.264.1 | Decisione di Alberto del 18 novembre 2026 (niente componenti esterni, tutto il codice in casa). Limiti: si decodifica solo H.264 a immagini intere, 4:2:0, 8 bit; HEVC, VP9 e AV1 si leggono nei contenitori ma restano senza fotogramma (tessera neutra) | | 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 |
+26 -22
View File
@@ -11,7 +11,7 @@ namespace Febe.Core.Codecs.Containers;
/// </summary> /// </summary>
public static class AviReader public static class AviReader
{ {
private const int MaxSamples = 20_000_000; private const int MaxSamples = IsoBmffReader.MaxSamples;
private const int MaxHeaderBytes = 16 * 1024 * 1024; private const int MaxHeaderBytes = 16 * 1024 * 1024;
/// <summary>True when the stream starts like an AVI file.</summary> /// <summary>True when the stream starts like an AVI file.</summary>
@@ -70,7 +70,6 @@ public static class AviReader
{ {
stream.Position = position; stream.Position = position;
stream.ReadExactly(header[..8]); stream.ReadExactly(header[..8]);
var id = Encoding.Latin1.GetString(header[..4]);
var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]); var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);
var body = position + 8; var body = position + 8;
var next = body + size + (size & 1); var next = body + size + (size & 1);
@@ -80,6 +79,14 @@ public static class AviReader
size = (uint)Math.Max(0, end - body); size = (uint)Math.Max(0, end - body);
} }
if (state.InMovi && !header[..4].SequenceEqual("LIST"u8))
{
AddChunk(header[..4], body, size, state); // the hot path: no string per chunk
position = next;
continue;
}
var id = Encoding.Latin1.GetString(header[..4]);
if (id == "LIST" && size >= 4) if (id == "LIST" && size >= 4)
{ {
stream.ReadExactly(header.Slice(8, 4)); stream.ReadExactly(header.Slice(8, 4));
@@ -104,17 +111,13 @@ public static class AviReader
} }
} }
} }
else if (state.InMovi)
{
AddChunk(id, body, (int)size, state);
}
else else
{ {
switch (id) switch (id)
{ {
case "avih" when size >= 40: case "avih" when size >= 40:
{ {
var data = Read(stream, body, (int)size); var data = Read(stream, body, 40);
state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data); state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data);
state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16)); state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16));
state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32)); state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32));
@@ -125,7 +128,7 @@ public static class AviReader
case "strh" when size >= 36: case "strh" when size >= 36:
{ {
var data = Read(stream, body, (int)size); var data = Read(stream, body, 36);
var type = Encoding.Latin1.GetString(data, 0, 4); var type = Encoding.Latin1.GetString(data, 0, 4);
var handler = Encoding.Latin1.GetString(data, 4, 4); var handler = Encoding.Latin1.GetString(data, 4, 4);
var scale = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(20)); var scale = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(20));
@@ -177,7 +180,8 @@ public static class AviReader
state.Created = ParseDate(Encoding.ASCII.GetString(Read(stream, body, (int)size)), now); state.Created = ParseDate(Encoding.ASCII.GetString(Read(stream, body, (int)size)), now);
break; break;
case "idx1" when samples: case "idx1" when samples:
state.Index = Read(stream, body, (int)Math.Min(size, MaxHeaderBytes * 8L)); // 16 bytes per entry: at most one entry per sample the reader keeps.
state.Index = Read(stream, body, (int)Math.Min(size, 16L * MaxSamples));
break; break;
} }
} }
@@ -188,9 +192,9 @@ public static class AviReader
private static byte[] Read(Stream stream, long offset, int count) private static byte[] Read(Stream stream, long offset, int count)
{ {
if (count > MaxHeaderBytes * 8) if (count < 0 || count > 16L * MaxSamples || count > stream.Length - offset)
{ {
throw new ContainerException("Intestazione AVI troppo grande."); throw new ContainerException("Intestazione AVI danneggiata.");
} }
var data = new byte[count]; var data = new byte[count];
@@ -199,26 +203,26 @@ public static class AviReader
return data; return data;
} }
private static void AddChunk(string id, long body, int size, State state) private static void AddChunk(ReadOnlySpan<byte> id, long body, uint size, State state)
{ {
if (id.Length != 4 || !char.IsAsciiDigit(id[0]) || !char.IsAsciiDigit(id[1])) if (!char.IsAsciiDigit((char)id[0]) || !char.IsAsciiDigit((char)id[1]) || size > int.MaxValue)
{ {
return; // JUNK, ix## indexes and the like return; // JUNK, ix## indexes and the like
} }
var stream = (id[0] - '0') * 10 + (id[1] - '0'); var stream = ((id[0] - '0') * 10) + (id[1] - '0');
if (state.Chunks.Count >= MaxSamples) if (stream == state.VideoStream && id[2] == 'd' && id[3] is (byte)'c' or (byte)'b')
{ {
throw new ContainerException("Troppi campioni."); if (state.Chunks.Count >= MaxSamples)
} {
throw new ContainerException("Troppi campioni.");
}
if (stream == state.VideoStream && (id[2..] is "dc" or "db")) state.Chunks.Add((body, (int)size));
{
state.Chunks.Add((body, size));
} }
else if (stream == state.AudioStream && id[2..] == "wb") else if (stream == state.AudioStream && id[2] == 'w' && id[3] == 'b' && state.AudioChunks.Count < MaxSamples)
{ {
state.AudioChunks.Add((body, size)); state.AudioChunks.Add((body, (int)size)); // beyond the limit the audio chunks are not needed
} }
} }
@@ -3,6 +3,9 @@ namespace Febe.Core.Codecs.Containers;
/// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary> /// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary>
public static class ContainerReader public static class ContainerReader
{ {
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
public const int MaxSampleSize = 64 * 1024 * 1024;
/// <summary>The format of a file from its first bytes; null when it is none of those read here.</summary> /// <summary>The format of a file from its first bytes; null when it is none of those read here.</summary>
public static ContainerFormat? Detect(ReadOnlySpan<byte> start) public static ContainerFormat? Detect(ReadOnlySpan<byte> start)
{ {
@@ -58,6 +61,11 @@ public static class ContainerReader
throw new ContainerException("Campione fuori dal file."); throw new ContainerException("Campione fuori dal file.");
} }
if (sample.Size > MaxSampleSize)
{
throw new ContainerException("Campione troppo grande."); // no real frame comes near: a damaged table
}
if (buffer.Length < sample.Size) if (buffer.Length < sample.Size)
{ {
buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)]; buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)];
+119 -41
View File
@@ -14,7 +14,9 @@ public static class IsoBmffReader
private const long MaxBoxInMemory = 128L * 1024 * 1024; private const long MaxBoxInMemory = 128L * 1024 * 1024;
private const int MaxTopLevelBoxes = 1_000_000; private const int MaxTopLevelBoxes = 1_000_000;
private const int MaxSamples = 20_000_000;
/// <summary>Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory).</summary>
internal const int MaxSamples = 2_000_000;
/// <summary>True when the stream starts like an ISO media file (an <c>ftyp</c>, <c>moov</c>, <c>mdat</c>... box).</summary> /// <summary>True when the stream starts like an ISO media file (an <c>ftyp</c>, <c>moov</c>, <c>mdat</c>... box).</summary>
public static bool Looks(ReadOnlySpan<byte> start) => public static bool Looks(ReadOnlySpan<byte> start) =>
@@ -33,7 +35,7 @@ public static class IsoBmffReader
long position = 0; long position = 0;
Span<byte> header = stackalloc byte[16]; Span<byte> header = stackalloc byte[16];
Movie? movie = null; Movie? movie = null;
var fragments = new List<(long Start, byte[] Body)>(); var pending = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{ {
stream.Position = position; stream.Position = position;
@@ -42,8 +44,14 @@ public static class IsoBmffReader
var headerSize = 8; var headerSize = 8;
if (size == 1) if (size == 1)
{ {
if (position + 16 > length)
{
break;
}
stream.ReadExactly(header.Slice(8, 8)); stream.ReadExactly(header.Slice(8, 8));
size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8)); var wide = BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
size = wide > long.MaxValue ? -1 : (long)wide;
headerSize = 16; headerSize = 16;
} }
else if (size == 0) else if (size == 0)
@@ -62,17 +70,33 @@ public static class IsoBmffReader
} }
var type = header.Slice(4, 4); var type = header.Slice(4, 4);
if (type.SequenceEqual("moov"u8)) if (type.SequenceEqual("moov"u8) && movie is null)
{ {
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples); movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
if (!samples) foreach (var (start, body) in pending)
{
movie.AddFragment(start, body);
}
pending.Clear();
// Metadata only: a fragmented file whose headers do not tell its duration is read on through its fragments.
if (!samples && !movie.NeedsFragmentsForDuration)
{ {
break; break;
} }
} }
else if (samples && type.SequenceEqual("moof"u8)) else if (type.SequenceEqual("moof"u8) && (samples || movie is null || movie.NeedsFragmentsForDuration))
{ {
fragments.Add((position, ReadBody(stream, position + headerSize, size - headerSize))); var body = ReadBody(stream, position + headerSize, size - headerSize);
if (movie is null)
{
pending.Add((position, body)); // fragments before the moov: unusual, but kept
}
else
{
movie.AddFragment(position, body); // at once: the fragments of a long file are never all in memory
}
} }
position += size; position += size;
@@ -83,11 +107,6 @@ public static class IsoBmffReader
throw new ContainerException("Manca il box moov."); throw new ContainerException("Manca il box moov.");
} }
foreach (var (start, body) in fragments)
{
movie.AddFragment(start, body);
}
return movie.Build(); return movie.Build();
} }
@@ -104,9 +123,9 @@ public static class IsoBmffReader
return body; return body;
} }
private static Movie ParseMoov(byte[] moov, DateTimeOffset now, bool samples) private static Movie ParseMoov(byte[] moov, DateTimeOffset now, bool samples, long fileLength)
{ {
var movie = new Movie(samples); var movie = new Movie(samples, fileLength);
try try
{ {
foreach (var (type, start, count) in Children(moov, 0, moov.Length)) foreach (var (type, start, count) in Children(moov, 0, moov.Length))
@@ -121,23 +140,32 @@ public static class IsoBmffReader
movie.ParseTrak(moov, start, count); movie.ParseTrak(moov, start, count);
break; break;
case "mvex": case "mvex":
movie.Fragmented = true;
foreach (var (t, s, c) in Children(moov, start, count)) foreach (var (t, s, c) in Children(moov, start, count))
{ {
if (t == "trex" && c >= 24) if (t == "trex" && c >= 24)
{ {
// version/flags, track_ID, default_sample_description_index, then the three defaults
// (ISO/IEC 14496-12 §8.8.3): duration, size, flags.
var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4));
movie.TrackDefaults[id] = ( movie.TrackDefaults[id] = (
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)),
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)),
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20))); BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20)));
} }
else if (t == "mehd" && c >= 8)
{
movie.FragmentDuration = moov[s] == 1 && c >= 12
? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(moov.AsSpan(s + 4)), long.MaxValue)
: BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4));
}
} }
break; break;
} }
} }
} }
catch (ArgumentOutOfRangeException) catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException)
{ {
throw new ContainerException("Box moov danneggiato."); throw new ContainerException("Box moov danneggiato.");
} }
@@ -229,14 +257,25 @@ public static class IsoBmffReader
internal long FragmentTime = -1; internal long FragmentTime = -1;
} }
private sealed class Movie(bool samples) private sealed class Movie(bool samples, long fileLength)
{ {
internal readonly Dictionary<uint, (uint Description, uint Duration, uint Size)> TrackDefaults = []; /// <summary>The <c>trex</c> defaults of each track: sample duration, size and flags.</summary>
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
private readonly List<Track> tracks = []; private readonly List<Track> tracks = [];
private DateTimeOffset? created; private DateTimeOffset? created;
private long timescale; private long timescale;
private long duration; private long duration;
/// <summary>True when the movie has an <c>mvex</c> box: its samples are in fragments.</summary>
internal bool Fragmented;
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
internal long FragmentDuration;
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
internal bool NeedsFragmentsForDuration =>
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now) internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
{ {
ulong creation; ulong creation;
@@ -406,7 +445,16 @@ public static class IsoBmffReader
return; return;
} }
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss); try
{
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss);
}
catch (Exception ex) when (ex is ContainerException or ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException)
{
// Damaged tables, or more samples than the limit (QuickTime PCM counts every audio sample): the track
// keeps its description without samples, and the other tracks are still read.
track.Samples = [];
}
} }
private static void ParseStsd(byte[] data, int start, int count, Track track) private static void ParseStsd(byte[] data, int start, int count, Track track)
@@ -514,7 +562,7 @@ public static class IsoBmffReader
return null; return null;
} }
private static void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss) private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
{ {
int count; int count;
uint fixedSize = 0; uint fixedSize = 0;
@@ -535,6 +583,14 @@ public static class IsoBmffReader
throw new ContainerException("Troppi campioni."); throw new ContainerException("Troppi campioni.");
} }
// The table must be able to describe that many samples and the samples must fit in the file: a few damaged
// bytes never make the reader allocate more than the file can hold.
var tableBytes = stz2 ? 12 + ((((long)count * fieldSize) + 7) / 8) : fixedSize != 0 ? 12 : 12 + (4L * count);
if (stsz.Length < tableBytes || (fixedSize != 0 && (long)count * fixedSize > fileLength) || (stz2 && fieldSize is not (4 or 8 or 16)))
{
throw new ContainerException("Tabella delle dimensioni danneggiata.");
}
int SizeOf(int i) int SizeOf(int i)
{ {
if (!stz2) if (!stz2)
@@ -555,13 +611,19 @@ public static class IsoBmffReader
? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8))) ? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8)))
: BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4))); : BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4)));
var keys = stss is null ? null : new HashSet<int>(); // Sync samples (stss, 1-based); without the box every sample is one. At most one flag per sample.
bool[]? keys = null;
if (stss is not null) if (stss is not null)
{ {
var n = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4)); keys = new bool[count];
var n = Math.Min(BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4)), (uint)Math.Max(0, (stss.Length - 8) / 4));
for (var i = 0; i < n; i++) for (var i = 0; i < n; i++)
{ {
keys!.Add((int)BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))) - 1); var number = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4)));
if (number >= 1 && number <= (uint)count)
{
keys[number - 1] = true;
}
} }
} }
@@ -606,7 +668,7 @@ public static class IsoBmffReader
} }
var size = SizeOf(sample); var size = SizeOf(sample);
list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys.Contains(sample))); list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys[sample]));
offset += size; offset += size;
dts += delta; dts += delta;
sttsLeft = Math.Max(0, sttsLeft - 1); sttsLeft = Math.Max(0, sttsLeft - 1);
@@ -633,16 +695,17 @@ public static class IsoBmffReader
} }
} }
} }
catch (ArgumentOutOfRangeException) catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException or ContainerException)
{ {
// A damaged fragment: the samples read so far stand. // A damaged fragment (or one beyond the sample limit): the samples read so far stand.
} }
} }
private void AddTrackFragment(long moofStart, byte[] data, int start, int count) private void AddTrackFragment(long moofStart, byte[] data, int start, int count)
{ {
Track? track = null; Track? track = null;
long baseOffset = moofStart; var dataBase = moofStart; // base_data_offset, or the start of the moof (default-base-is-moof, §8.8.7.1)
var nextData = moofStart;
uint defDuration = 0, defSize = 0, defFlags = 0; uint defDuration = 0, defSize = 0, defFlags = 0;
long? decodeTime = null; long? decodeTime = null;
foreach (var (type, s, c) in Children(data, start, count)) foreach (var (type, s, c) in Children(data, start, count))
@@ -657,16 +720,19 @@ public static class IsoBmffReader
track = tracks.Find(t => t.Id == id); track = tracks.Find(t => t.Id == id);
if (TrackDefaults.TryGetValue(id, out var d)) if (TrackDefaults.TryGetValue(id, out var d))
{ {
(defDuration, defSize, defFlags) = (d.Duration, d.Size, 0); (defDuration, defSize, defFlags) = d;
} }
var p = 8; var p = 8;
if ((flags & 0x1) != 0) if ((flags & 0x1) != 0)
{ {
baseOffset = (long)BinaryPrimitives.ReadUInt64BigEndian(body[p..]); var wide = BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
dataBase = wide > (ulong)fileLength ? fileLength : (long)wide;
p += 8; p += 8;
} }
nextData = dataBase;
if ((flags & 0x2) != 0) if ((flags & 0x2) != 0)
{ {
p += 4; p += 4;
@@ -693,23 +759,20 @@ public static class IsoBmffReader
} }
case "tfdt": case "tfdt":
decodeTime = body[0] == 1 ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[4..]) : BinaryPrimitives.ReadUInt32BigEndian(body[4..]); decodeTime = body[0] == 1
? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[4..]), long.MaxValue / 2)
: BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
break; break;
case "trun" when track is not null: case "trun" when track is not null:
{ {
var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF;
var signed = body[0] == 1; var signed = body[0] == 1;
var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]); var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
if (n < 0 || track.Samples.Count + n > MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
var p = 8; var p = 8;
var offset = baseOffset; var offset = nextData;
if ((flags & 0x1) != 0) if ((flags & 0x1) != 0)
{ {
offset += BinaryPrimitives.ReadInt32BigEndian(body[p..]); offset = dataBase + BinaryPrimitives.ReadInt32BigEndian(body[p..]); // from the base, not from the run before
p += 4; p += 4;
} }
@@ -720,6 +783,17 @@ public static class IsoBmffReader
p += 4; p += 4;
} }
// The samples either have their fields in the box or take the default size: the box or the
// file bounds how many there can be, before anything is allocated.
var perSample = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1));
var bounded = perSample > 0
? (long)n * perSample <= body.Length - p
: (long)n * Math.Max(1u, defSize) <= fileLength;
if (n < 0 || !bounded || track.Samples.Count + n > MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
var dts = decodeTime ?? Math.Max(0, track.FragmentTime); var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
for (var i = 0; i < n; i++) for (var i = 0; i < n; i++)
{ {
@@ -752,14 +826,14 @@ public static class IsoBmffReader
} }
var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample
track.Samples.Add(new MediaSample(offset, (int)size, dts, dts + ct - track.EditOffset, key)); track.Samples.Add(new MediaSample(offset, (int)Math.Min(size, int.MaxValue), dts, dts + ct - track.EditOffset, key));
offset += size; offset += size;
dts += duration; dts += duration;
} }
track.FragmentTime = dts; track.FragmentTime = dts;
decodeTime = dts; decodeTime = dts;
baseOffset = offset; // a later trun of the same traf continues the data nextData = offset; // a later trun without data_offset continues the data
break; break;
} }
} }
@@ -820,15 +894,19 @@ public static class IsoBmffReader
}; };
} }
TimeSpan? total = timescale > 0 && duration > 0 ? TimeSpan.FromSeconds((double)duration / timescale) : null; var movieDuration = duration > 0 ? duration : FragmentDuration;
TimeSpan? total = timescale > 0 && movieDuration > 0 ? Seconds((double)movieDuration / timescale) : null;
if (total is null && v is { Duration: > 0 }) if (total is null && v is { Duration: > 0 })
{ {
total = TimeSpan.FromSeconds(v.Seconds(v.Duration)); total = Seconds(v.Seconds(v.Duration));
} }
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a }; return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
} }
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
private static TimeSpan? Seconds(double seconds) => seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
private static long DurationOf(Track track) private static long DurationOf(Track track)
{ {
if (track.FragmentTime > track.Duration) if (track.FragmentTime > track.Duration)
@@ -24,7 +24,7 @@ public static class MatroskaReader
private const uint ChaptersId = 0x1043A770; private const uint ChaptersId = 0x1043A770;
private const uint SeekHeadId = 0x114D9B74; private const uint SeekHeadId = 0x114D9B74;
private const long UnknownSize = -1; private const long UnknownSize = -1;
private const int MaxSamples = 20_000_000; private const int MaxSamples = IsoBmffReader.MaxSamples;
private const long MaxElementInMemory = 64L * 1024 * 1024; private const long MaxElementInMemory = 64L * 1024 * 1024;
/// <summary>True when the stream starts with an EBML header.</summary> /// <summary>True when the stream starts with an EBML header.</summary>
@@ -65,7 +65,7 @@ public static class MatroskaReader
throw new ContainerException("Documento EBML che non è Matroska."); throw new ContainerException("Documento EBML che non è Matroska.");
} }
stream.Position = end; stream.Position = Math.Min(end, stream.Length);
(id, size) = reader.Header(); (id, size) = reader.Header();
while (id != SegmentId) while (id != SegmentId)
{ {
@@ -138,10 +138,15 @@ public static class MatroskaReader
state.TimecodeScale = (long)reader.Unsigned(size); state.TimecodeScale = (long)reader.Unsigned(size);
break; break;
case 0x4489: case 0x4489:
state.DurationTicks = reader.Float(size); {
break; var ticks = reader.Float(size);
state.DurationTicks = double.IsFinite(ticks) && ticks > 0 ? ticks : 0;
break;
}
case 0x4461: case 0x4461:
{ {
// Nanoseconds from 2001: about ±292 years, always inside the range of a date.
var ns = reader.Signed(size); var ns = reader.Signed(size);
var instant = Epoch2001.AddTicks(ns / 100); var instant = Epoch2001.AddTicks(ns / 100);
if (instant >= Earliest && instant <= now.AddDays(1)) if (instant >= Earliest && instant <= now.AddDays(1))
@@ -171,6 +176,11 @@ public static class MatroskaReader
continue; continue;
} }
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
var entryEnd = stream.Position + size; var entryEnd = stream.Position + size;
var track = new TrackEntry(); var track = new TrackEntry();
while (stream.Position < entryEnd) while (stream.Position < entryEnd)
@@ -267,7 +277,7 @@ public static class MatroskaReader
} }
} }
stream.Position = entryEnd; stream.Position = Math.Min(entryEnd, stream.Length);
if (track.Type == 1 && state.Video is null) if (track.Type == 1 && state.Video is null)
{ {
state.Video = track; state.Video = track;
@@ -372,12 +382,23 @@ public static class MatroskaReader
var dataStart = stream.Position; var dataStart = stream.Position;
if (lacing == 0) if (lacing == 0)
{ {
if (end - dataStart is <= 0 or > int.MaxValue)
{
throw new ContainerException("Blocco Matroska danneggiato.");
}
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key)); target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
return; return;
} }
var frames = stream.ReadByte() + 1; var count = stream.ReadByte();
var sizes = new long[frames]; if (count < 0 || dataStart >= end)
{
throw new ContainerException("Blocco Matroska troncato.");
}
var frames = count + 1;
Span<long> sizes = stackalloc long[frames];
switch (lacing) switch (lacing)
{ {
case 1: // Xiph case 1: // Xiph
@@ -438,12 +459,17 @@ public static class MatroskaReader
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0; var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
for (var i = 0; i < frames; i++) for (var i = 0; i < frames; i++)
{ {
if (sizes[i] < 0 || offset + sizes[i] > end) if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end)
{ {
throw new ContainerException("Blocco Matroska danneggiato."); throw new ContainerException("Blocco Matroska danneggiato.");
} }
var t = time + (i * frameDuration); var t = time + (i * frameDuration);
if (sizes[i] == 0)
{
continue; // an empty frame has nothing to decode (and costs no memory)
}
target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key)); target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key));
offset += sizes[i]; offset += sizes[i];
} }
@@ -515,7 +541,7 @@ public static class MatroskaReader
Rotation = roll is 90 or 180 or 270 ? roll : 0, Rotation = roll is 90 or 180 or 270 ? roll : 0,
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null, AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
Timescale = timescale, Timescale = timescale,
Duration = (long)DurationTicks, Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Samples = samples, Samples = samples,
}; };
} }
@@ -539,12 +565,13 @@ public static class MatroskaReader
Channels = a.Channels, Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
Timescale = timescale, Timescale = timescale,
Duration = (long)DurationTicks, Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Samples = a.Samples, Samples = a.Samples,
}; };
} }
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : null; var seconds = DurationTicks * TimecodeScale / 1e9;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
} }
} }
@@ -654,6 +681,11 @@ public static class MatroskaReader
throw new ContainerException("Elemento Matroska troppo grande."); throw new ContainerException("Elemento Matroska troppo grande.");
} }
if (size > stream.Length - stream.Position)
{
throw new ContainerException("File Matroska troncato."); // before allocating what the file cannot hold
}
var data = new byte[size]; var data = new byte[size];
stream.ReadExactly(data); stream.ReadExactly(data);
return data; return data;
@@ -666,7 +698,8 @@ public static class MatroskaReader
throw new ContainerException("Elemento Matroska di lunghezza ignota."); throw new ContainerException("Elemento Matroska di lunghezza ignota.");
} }
stream.Position += size; // Past the end of a truncated or damaged file the reading simply ends there.
stream.Position = size > stream.Length - stream.Position ? stream.Length : stream.Position + size;
} }
private int ReadByteOrThrow() private int ReadByteOrThrow()
+6 -2
View File
@@ -189,17 +189,21 @@ public static class Mp4Writer
var samples = track.Samples; var samples = track.Samples;
var first = 0; var first = 0;
var limit = track.Timescale / 2; var limit = track.Timescale / 2;
var start = 0.0;
for (var i = 1; i <= samples.Count; i++) for (var i = 1; i <= samples.Count; i++)
{ {
if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024) 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)); // Never earlier than the chunk before: the chunks of a track stay in sample order whatever its times.
start = Math.Max(start, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale);
list.Add((t, first, i - first, start));
first = i; first = i;
} }
} }
} }
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track.CompareTo(b.Track)); // Ties (equal times, as tracks without times have) keep each track's chunks in order: the sort is not stable.
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track != b.Track ? a.Track.CompareTo(b.Track) : a.First.CompareTo(b.First));
return list.ConvertAll(c => (c.Track, c.First, c.Count)); return list.ConvertAll(c => (c.Track, c.First, c.Count));
} }
+65 -6
View File
@@ -118,6 +118,24 @@ public sealed partial class H264Decoder
/// <summary>Finishes the picture being decoded, if any.</summary> /// <summary>Finishes the picture being decoded, if any.</summary>
public void Flush() => FinishPicture(); public void Flush() => FinishPicture();
/// <summary>
/// Finishes the picture being decoded; a damaged picture whose deblocking or cropping fails raises an
/// <see cref="H264Exception"/> like the rest of the stream, and is dropped.
/// </summary>
private void FinishPicture()
{
try
{
CompletePicture();
}
catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
{
cur = null;
picHeader = null;
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
}
}
private void Decode(NalUnit nal) private void Decode(NalUnit nal)
{ {
try try
@@ -151,11 +169,7 @@ public sealed partial class H264Decoder
break; break;
} }
} }
catch (IndexOutOfRangeException) catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException)
{
throw new H264Exception("Flusso H.264 troncato o danneggiato.");
}
catch (ArgumentOutOfRangeException)
{ {
throw new H264Exception("Flusso H.264 troncato o danneggiato."); throw new H264Exception("Flusso H.264 troncato o danneggiato.");
} }
@@ -378,7 +392,7 @@ public sealed partial class H264Decoder
PruneDpb(); PruneDpb();
} }
private void FinishPicture() private void CompletePicture()
{ {
if (cur is null || picHeader is null || activeSps is null) if (cur is null || picHeader is null || activeSps is null)
{ {
@@ -599,6 +613,51 @@ public sealed partial class H264Decoder
} }
dpb.Add(picture); dpb.Add(picture);
LimitReferences(picture, sps);
}
/// <summary>
/// A stream may never keep more than Max(max_num_ref_frames, 1) reference frames (§8.2.5.4 and §7.4.2.1.1); a damaged
/// one whose marking operations never release any would make the buffer grow with every picture. Here the oldest
/// references beyond the limit are released, as the sliding window would.
/// </summary>
private void LimitReferences(Picture current, Sps sps)
{
var limit = Math.Max(1, sps.MaxNumRefFrames);
while (true)
{
var count = 0;
Picture? oldestShort = null, oldestLong = null;
foreach (var p in dpb)
{
if (!p.IsReference)
{
continue;
}
count++;
if (ReferenceEquals(p, current))
{
continue;
}
if (p.ShortTerm && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap))
{
oldestShort = p;
}
else if (p.LongTerm && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx))
{
oldestLong = p;
}
}
if (count <= limit || (oldestShort ?? oldestLong) is not { } victim)
{
return;
}
victim.ShortTerm = victim.LongTerm = false;
}
} }
/// <summary>Sliding window marking (§8.2.5.3) before a new short-term frame is added.</summary> /// <summary>Sliding window marking (§8.2.5.3) before a new short-term frame is added.</summary>
@@ -3,6 +3,9 @@ namespace Febe.Core.Codecs.H264;
/// <summary>A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.</summary> /// <summary>A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.</summary>
internal sealed class Sps internal sealed class Sps
{ {
/// <summary>MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits.</summary>
internal const int MaxFrameMbs = 139_264;
internal int ProfileIdc; internal int ProfileIdc;
internal int LevelIdc; internal int LevelIdc;
internal int Id; internal int Id;
@@ -95,6 +98,13 @@ internal sealed class Sps
s.MbAdaptiveFrameField = r.ReadFlag(); s.MbAdaptiveFrameField = r.ReadFlag();
} }
// The largest frame of any level (MaxFS of level 6.2, table A-1): a damaged SPS never makes the decoder
// allocate pictures larger than a real stream can have.
if ((long)s.WidthInMbs * s.HeightInMbs > MaxFrameMbs)
{
throw new H264Exception("Immagine più grande di ogni livello H.264.");
}
s.Direct8x8Inference = r.ReadFlag(); s.Direct8x8Inference = r.ReadFlag();
if (r.ReadFlag()) if (r.ReadFlag())
{ {
@@ -102,6 +112,13 @@ internal sealed class Sps
s.CropRight = r.ReadUe(8192); s.CropRight = r.ReadUe(8192);
s.CropTop = r.ReadUe(8192); s.CropTop = r.ReadUe(8192);
s.CropBottom = r.ReadUe(8192); s.CropBottom = r.ReadUe(8192);
// §7.4.2.1.1: the cropped frame keeps at least one sample (CropUnitX = 2, CropUnitY = 2 for frames in 4:2:0).
var cropUnitY = 2 * (s.FrameMbsOnly ? 1 : 2);
if (2 * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || cropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16)
{
throw new H264Exception("Ritaglio dell'immagine non valido.");
}
} }
if (r.ReadFlag()) if (r.ReadFlag())
+1 -1
View File
@@ -45,7 +45,7 @@ public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMe
return new VideoMetadata(container.CreatedAt, duration, width, height); return new VideoMetadata(container.CreatedAt, duration, width, height);
} }
catch (Exception ex) when (ex is ContainerException or IOException or EndOfStreamException or UnauthorizedAccessException catch (Exception ex) when (ex is ContainerException or IOException or EndOfStreamException or UnauthorizedAccessException
or ArgumentException or OverflowException or InvalidDataException) or ArgumentException or IndexOutOfRangeException or OverflowException or InvalidDataException)
{ {
return null; // a damaged or unreadable file: as if the container had nothing to say return null; // a damaged or unreadable file: as if the container had nothing to say
} }
+21 -13
View File
@@ -72,10 +72,11 @@ public sealed class VideoFrameDecoder
/// <summary> /// <summary>
/// A frame of the video as a BMP image, taken one second in (or the first frame of shorter videos), rotated as the /// 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. /// video is shown, reduced to at most twice the long side of a thumbnail (a 4K frame would be a 24 MB bitmap);
/// null when the file cannot be read or decoded.
/// </summary> /// </summary>
public Task<byte[]?> ExtractImageAsync(string videoPath, CancellationToken ct = default) => public Task<byte[]?> ExtractImageAsync(string videoPath, CancellationToken ct = default) =>
ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 0, ct); ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 2 * ThumbnailStore.LongSide, ct);
/// <summary> /// <summary>
/// A frame of the video at <paramref name="at"/> (the first frame when the video is shorter), as a BMP image whose /// A frame of the video at <paramref name="at"/> (the first frame when the video is shorter), as a BMP image whose
@@ -288,6 +289,9 @@ public sealed class VideoFrameDecoder
private readonly HashSet<int> wanted = []; private readonly HashSet<int> wanted = [];
private byte[] buffer = new byte[64 * 1024]; private byte[] buffer = new byte[64 * 1024];
/// <summary>The sample being decoded: the picture it finishes is that sample's frame.</summary>
private int current;
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct) internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct)
{ {
foreach (var t in targets) foreach (var t in targets)
@@ -304,23 +308,24 @@ public sealed class VideoFrameDecoder
var key = KeyBefore(keys, target); var key = KeyBefore(keys, target);
if (decoder is null || next > target || key >= next) if (decoder is null || next > target || key >= next)
{ {
decoder = new H264Decoder(); // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
var runStart = key; // sample without a picture (only parameter sets, or damaged) must not shift the frames after it.
decoder.Wanted = index => wanted.Contains(runStart + (int)index); decoder = new H264Decoder { Wanted = _ => wanted.Contains(current) };
decoder.FrameDecoded += frame => found.TryAdd(runStart + (int)frame.DecodeIndex, frame); decoder.FrameDecoded += frame => found.TryAdd(current, frame);
if (!video.AnnexB)
{
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
}
next = key; next = key;
} }
try try
{ {
if (next == key && !video.AnnexB)
{
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
}
for (; next <= target; next++) for (; next <= target; next++)
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
current = next;
var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer); var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer);
if (video.AnnexB) if (video.AnnexB)
{ {
@@ -332,9 +337,12 @@ public sealed class VideoFrameDecoder
} }
} }
} }
catch (Exception ex) when (ex is H264Exception or IndexOutOfRangeException or ArgumentException or InvalidOperationException) catch (Exception ex) when (ex is H264Exception or ContainerException or EndOfStreamException or IndexOutOfRangeException
or ArgumentException or InvalidOperationException)
{ {
decoder = null; // this run is damaged: the next target starts again from its own key frame // This run is damaged (or its samples lie past the end of a truncated file): the next target starts
// again from its own key frame, and what was decoded so far stands.
decoder = null;
} }
} }
@@ -30,15 +30,77 @@ public sealed class ContainerTests
} }
[TestMethod] [TestMethod]
[DataRow("CABA3_SVA_B")] [DataRow("CABA3_SVA_B", false)]
[DataRow("FRExt1_Panasonic_D")] [DataRow("FRExt1_Panasonic_D", false)]
public void AFragmentedMp4IsReadFromItsFragments(string name) [DataRow("CABA3_SVA_B", true)]
[DataRow("FRExt1_Panasonic_D", true)]
public void AFragmentedMp4IsReadFromItsFragments(string name, bool defaults)
{ {
// With defaults: durations from trex and two runs per fragment, each with its data_offset from the moof.
var es = ElementaryStream.Load(name); var es = ElementaryStream.Load(name);
var file = TestVideos.FragmentedMp4(es, perFragment: 7); var file = TestVideos.FragmentedMp4(es, perFragment: 7, defaults: defaults);
var container = Read(file); var container = Read(file);
AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay
CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!)); CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!));
Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05);
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void TheProbeTellsTheDurationOfAFragmentedMp4(bool mehd)
{
// Without mehd only the fragments tell the duration: the metadata reading goes on through them.
var es = ElementaryStream.Load("CABA3_SVA_B");
using var temp = new TempFolder("sonda-frammentato");
var path = TestVideos.Write(temp, "frammentato.mp4", TestVideos.FragmentedMp4(es, perFragment: 5, defaults: mehd));
var meta = ContainerVideoMetadataProbe.Probe(path, Now);
Assert.IsNotNull(meta);
Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05);
Assert.AreEqual((es.Width, es.Height), (meta.Width!.Value, meta.Height!.Value));
}
[TestMethod]
public void TheMp4WriterKeepsTheOrderOfSamplesWithEqualTimes()
{
// An audio track without times (as AVI gives): every chunk starts at zero, and the order must still hold.
var es = ElementaryStream.Load("BA1_Sony_D");
var video = new Mp4OutputTrack
{
IsVideo = true,
Timescale = TestVideos.Timescale,
Samples = [.. Enumerable.Range(0, es.Count).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, (long)i * TestVideos.FrameTicks, (long)es.Rank[i] * TestVideos.FrameTicks, es.Key[i]))],
WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)),
Width = es.Width,
Height = es.Height,
AvcConfiguration = es.AvcC,
};
const int Count = 40_000; // 40 chunks of 1024: enough for the sort to be an unstable one
static byte[] Payload(int i) => [(byte)(i >> 8), (byte)i, 7];
var audio = new Mp4OutputTrack
{
IsVideo = false,
Timescale = 44100,
Samples = [.. Enumerable.Range(0, Count).Select(_ => new Mp4OutputSample(3, 0, 0, true))],
WriteSample = (i, s) => s.Write(Payload(i)),
AacConfiguration = [0x12, 0x10],
SampleRate = 44100,
Channels = 2,
};
using var output = new MemoryStream();
Mp4Writer.Write(output, [video, audio]);
var file = output.ToArray();
var container = Read(file);
Assert.AreEqual(Count, container.Audio!.Samples.Count);
using var input = new MemoryStream(file);
var buffer = Array.Empty<byte>();
for (var i = 0; i < Count; i++)
{
CollectionAssert.AreEqual(Payload(i), ContainerReader.ReadSample(input, container.Audio.Samples[i], ref buffer).ToArray(), $"campione {i}");
}
CollectionAssert.AreEqual(ElementaryStream.Reference("BA1_Sony_D"), DecodeAll(file, container.Video!));
} }
[TestMethod] [TestMethod]
@@ -0,0 +1,209 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one
/// of them with a <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/>), a null result or a frame,
/// and must never allocate much more than the file holds, whatever its damaged headers claim.
/// </summary>
[TestClass]
public sealed class MalformedInputTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
[TestMethod]
[DataRow("mp4")]
[DataRow("frammentato.mp4")]
[DataRow("mkv")]
[DataRow("avi")]
public void TruncatedFilesNeverBreakTheReaders(string kind)
{
var file = Build(kind);
var step = Math.Max(1, file.Length / 300);
for (var length = 0; length < file.Length; length += step)
{
AssertReadersSurvive(file[..length], $"{kind} troncato a {length}");
}
}
[TestMethod]
[DataRow("mp4", 5801)]
[DataRow("frammentato.mp4", 5802)]
[DataRow("mkv", 5803)]
[DataRow("avi", 5804)]
public void GarbledFilesNeverBreakTheReaders(string kind, int seed)
{
var file = Build(kind);
var random = new Random(seed);
for (var trial = 0; trial < 400; trial++)
{
AssertReadersSurvive(Garble(file, random), $"{kind}, variante {trial} del seme {seed}");
}
}
[TestMethod]
[DataRow("mp4", 5811)]
[DataRow("frammentato.mp4", 5812)]
[DataRow("mkv", 5813)]
[DataRow("avi", 5814)]
public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed)
{
var file = Build(kind);
var random = new Random(seed);
using var temp = new TempFolder("rovinati");
var decoded = 0;
for (var trial = 0; trial < 60; trial++)
{
var path = TestVideos.Write(temp, $"{trial}.{kind}", Garble(file, random));
_ = ContainerVideoMetadataProbe.Probe(path, Now); // null or metadata, never an exception
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
var stillness = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
decoded += image is null ? 0 : 1;
_ = stillness;
}
// Most damage hits frame data, not headers: many variants still give a frame.
Assert.IsGreaterThan(0, decoded, "nessuna variante ha dato un fotogramma");
}
[TestMethod]
public void AHugeSampleCountInATinyMp4AllocatesNothing()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
// stsz with a fixed sample size of 1 and almost two million samples: far more than the file can hold.
var file = TestVideos.Mp4(es);
var stsz = IndexOf(file, "stsz"u8);
BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 8), 1);
BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 12), 1_999_999);
var container = ReadMeasured(file, out var allocated);
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
Assert.IsEmpty(container!.Video!.Samples, "una tabella impossibile non dà campioni");
// A trun of two billion samples without per-sample fields.
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);
container = ReadMeasured(fragmented, out allocated);
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
Assert.IsNotNull(container);
}
[TestMethod]
public void AMatroskaElementLargerThanTheFileAllocatesNothing()
{
var es = ElementaryStream.Load("BA1_Sony_D");
var file = TestVideos.Matroska(es);
// CodecPrivate (0x63A2) with an eight-byte size: claim 60 MB in a file of a few kilobytes.
var codecPrivate = IndexOf(file, [0x63, 0xA2, 0x01]);
file[codecPrivate + 2] = 0x01;
var size = new byte[8];
BinaryPrimitives.WriteUInt64BigEndian(size, 60L * 1024 * 1024);
size.AsSpan(1).CopyTo(file.AsSpan(codecPrivate + 3));
long allocated = 0;
Assert.ThrowsExactly<ContainerException>(() => ReadMeasured(file, out allocated));
Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati");
}
private static void AssertReadersSurvive(byte[] data, string what)
{
foreach (var samples in new[] { false, true })
{
var before = GC.GetAllocatedBytesForCurrentThread();
try
{
using var stream = new MemoryStream(data, writable: false);
var container = ContainerReader.Read(stream, Now, samples);
if (samples && container?.Video is { } video)
{
// Every sample listed is inside the file, or reading it says so.
var buffer = Array.Empty<byte>();
foreach (var sample in video.Samples.Take(50))
{
try
{
_ = ContainerReader.ReadSample(stream, sample, ref buffer);
}
catch (ContainerException)
{
}
}
}
}
catch (ContainerException)
{
}
catch (EndOfStreamException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (campioni: {samples}): {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
}
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.IsLessThan((16L * 1024 * 1024) + (64L * data.Length), allocated, $"{what}: {allocated} byte allocati per {data.Length} byte di file");
}
}
private static MediaContainer? ReadMeasured(byte[] file, out long allocated)
{
var before = GC.GetAllocatedBytesForCurrentThread();
try
{
using var stream = new MemoryStream(file, writable: false);
return ContainerReader.Read(stream, Now);
}
finally
{
allocated = GC.GetAllocatedBytesForCurrentThread() - before;
}
}
private static byte[] Build(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
return kind switch
{
"frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true),
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
"avi" => TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021"),
_ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero), rotation: 90, audio: true),
};
}
/// <summary>A copy with a few bytes changed: mostly in the first kilobytes, where the headers are.</summary>
private static byte[] Garble(byte[] file, Random random)
{
var copy = (byte[])file.Clone();
var changes = 1 + random.Next(12);
for (var k = 0; k < changes; k++)
{
var range = random.Next(3) == 0 ? copy.Length : Math.Min(copy.Length, 2048);
var p = random.Next(range);
copy[p] = random.Next(4) switch
{
0 => (byte)random.Next(256),
1 => (byte)(copy[p] ^ (1 << random.Next(8))),
2 => 0xFF,
_ => 0,
};
}
return random.Next(5) == 0 ? copy[..random.Next(copy.Length)] : copy;
}
private static int IndexOf(byte[] data, ReadOnlySpan<byte> pattern)
{
var index = data.AsSpan().IndexOf(pattern);
Assert.IsGreaterThanOrEqualTo(0, index);
return index;
}
}
+35 -12
View File
@@ -240,8 +240,12 @@ internal static class TestVideos
return output.ToArray(); return output.ToArray();
} }
/// <summary>A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).</summary> /// <summary>
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10) /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).
/// With <paramref name="defaults"/> the sample durations come from <c>trex</c>, each fragment has two runs that
/// both give their <c>data_offset</c> from the start of the moof, and an <c>mehd</c> box tells the duration.
/// </summary>
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10, bool defaults = false)
{ {
var shift = 0; var shift = 0;
for (var i = 0; i < es.Count; i++) for (var i = 0; i < es.Count; i++)
@@ -268,33 +272,52 @@ internal static class TestVideos
var mvhd = FullBox("mvhd", 0, [.. new byte[8], .. U32(1000), .. U32(0), .. U32(0x10000), 1, 0, .. new byte[10], 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), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000),
.. new byte[24], .. U32(2)]); .. new byte[24], .. U32(2)]);
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0)]); // trex: track_ID, default_sample_description_index, default duration, size and flags (non-sync).
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), Box("mvex", trex))); var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0x01010000)]);
var mvex = defaults
? Box("mvex", FullBox("mehd", 0, U32((uint)(es.Count * 1000 / 30))), trex) // movie timescale 1000
: Box("mvex", trex);
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), mvex));
for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++) for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++)
{ {
var count = Math.Min(perFragment, es.Count - first); var count = Math.Min(perFragment, es.Count - first);
var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList(); var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList();
byte[] Moof(int dataOffset) byte[] Run(int from, int length, int dataOffset)
{ {
var run = new List<byte>(); var run = new List<byte>();
run.AddRange(U32((uint)count)); run.AddRange(U32((uint)length));
run.AddRange(U32((uint)dataOffset)); run.AddRange(U32((uint)dataOffset));
for (var k = 0; k < count; k++) for (var k = from; k < from + length; k++)
{ {
var i = first + k; var i = first + k;
run.AddRange(U32(FrameTicks)); if (!defaults)
{
run.AddRange(U32(FrameTicks));
}
run.AddRange(U32((uint)payloads[k].Length)); run.AddRange(U32((uint)payloads[k].Length));
run.AddRange(U32(es.Key[i] ? 0x02000000u : 0x01010000u)); run.AddRange(U32(es.Key[i] ? 0x02000000u : 0x01010000u));
run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks))); run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks)));
} }
// Without the duration field (0x100) every sample takes the trex default.
return FullBox("trun", defaults ? 0x000E01u : 0x000F01u, [.. run]);
}
var split = defaults ? (count + 1) / 2 : count;
var secondData = payloads.Take(split).Sum(p => p.Length);
byte[] Moof(int dataOffset)
{
var runs = new List<byte[]> { Run(0, split, dataOffset) };
if (split < count)
{
runs.Add(Run(split, count - split, dataOffset + secondData));
}
return Box("moof", return Box("moof",
FullBox("mfhd", 0, U32((uint)sequence)), FullBox("mfhd", 0, U32((uint)sequence)),
Box("traf", Box("traf", [FullBox("tfhd", 0x020000, U32(1)), FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), .. runs]));
FullBox("tfhd", 0x020000, U32(1)),
FullBox("tfdt", 0, U32((uint)(first * FrameTicks))),
FullBox("trun", 0x000F01, [.. run])));
} }
var size = Moof(0).Length; var size = Moof(0).Length;
@@ -0,0 +1,167 @@
using Febe.Core.Codecs.H264;
namespace Febe.Tests.Codecs.H264;
/// <summary>
/// Damaged H.264 streams: the decoder reads bytes of any file the library holds, so whatever they are it must end with
/// frames or an <see cref="H264Exception"/>, and a damaged parameter set must never make it allocate huge pictures.
/// </summary>
[TestClass]
public sealed class H264RobustnessTests
{
[TestMethod]
[DataRow("BA1_Sony_D", 2641)]
[DataRow("SVA_BA1_B", 2642)]
[DataRow("BA3_SVA_C", 2643)]
[DataRow("BASQP1_Sony_C", 2644)]
[DataRow("CI_MW_D", 2645)]
[DataRow("CABA1_SVA_B", 2646)]
[DataRow("CABA2_SVA_B", 2647)]
[DataRow("CABA3_SVA_B", 2648)]
[DataRow("CANL1_SVA_B", 2649)]
[DataRow("FRExt1_Panasonic_D", 2650)]
[DataRow("FRExt3_Panasonic_E", 2651)]
[DataRow("HCAFR1_HHI_C", 2652)]
public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed)
{
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 random = new Random(seed);
for (var trial = 0; trial < 60; trial++)
{
var copy = (byte[])data.Clone();
var changes = 1 + random.Next(20);
for (var k = 0; k < changes; k++)
{
var p = random.Next(copy.Length);
copy[p] = random.Next(3) switch
{
0 => (byte)random.Next(256),
1 => (byte)(copy[p] ^ (1 << random.Next(8))),
_ => 0xFF,
};
}
if (random.Next(4) == 0)
{
copy = copy[..random.Next(copy.Length)];
}
try
{
var decoder = new H264Decoder();
decoder.FrameDecoded += _ => { };
decoder.DecodeAnnexB(copy);
}
catch (H264Exception)
{
}
catch (Exception ex)
{
Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}");
}
}
}
[TestMethod]
public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated()
{
// 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does.
var before = GC.GetAllocatedBytesForCurrentThread();
var error = Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(widthInMbs: 1024, heightInMbs: 1024)));
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));
}
[TestMethod]
public void ACropThatLeavesNoPictureIsRefused()
{
// 176 × 144 (11 × 9 macroblocks): crop units are two samples in 4:2:0 frames.
new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (4, 4, 2, 2)));
Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (44, 44, 0, 0))));
Assert.ThrowsExactly<H264Exception>(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0))));
}
/// <summary>A Baseline SPS NAL unit in Annex B form, written bit by bit (§7.3.2.1.1).</summary>
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<bool> 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<byte>();
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];
}
}
}