diff --git a/docs/decisioni.md b/docs/decisioni.md index 5126fbc..4ddcec5 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -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 | 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 | 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 | diff --git a/src/Febe.Core/Codecs/Containers/AviReader.cs b/src/Febe.Core/Codecs/Containers/AviReader.cs index 6689501..aeb3c2e 100644 --- a/src/Febe.Core/Codecs/Containers/AviReader.cs +++ b/src/Febe.Core/Codecs/Containers/AviReader.cs @@ -11,7 +11,7 @@ namespace Febe.Core.Codecs.Containers; /// public static class AviReader { - private const int MaxSamples = 20_000_000; + private const int MaxSamples = IsoBmffReader.MaxSamples; private const int MaxHeaderBytes = 16 * 1024 * 1024; /// True when the stream starts like an AVI file. @@ -70,7 +70,6 @@ public static class AviReader { stream.Position = position; stream.ReadExactly(header[..8]); - var id = Encoding.Latin1.GetString(header[..4]); var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]); var body = position + 8; var next = body + size + (size & 1); @@ -80,6 +79,14 @@ public static class AviReader size = (uint)Math.Max(0, end - body); } + if (state.InMovi && !header[..4].SequenceEqual("LIST"u8)) + { + AddChunk(header[..4], body, size, state); // the hot path: no string per chunk + position = next; + continue; + } + + var id = Encoding.Latin1.GetString(header[..4]); if (id == "LIST" && size >= 4) { stream.ReadExactly(header.Slice(8, 4)); @@ -104,17 +111,13 @@ public static class AviReader } } } - else if (state.InMovi) - { - AddChunk(id, body, (int)size, state); - } else { switch (id) { case "avih" when size >= 40: { - var data = Read(stream, body, (int)size); + var data = Read(stream, body, 40); state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data); state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16)); state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32)); @@ -125,7 +128,7 @@ public static class AviReader 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 handler = Encoding.Latin1.GetString(data, 4, 4); 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); break; 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; } } @@ -188,9 +192,9 @@ public static class AviReader 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]; @@ -199,26 +203,26 @@ public static class AviReader return data; } - private static void AddChunk(string id, long body, int size, State state) + private static void AddChunk(ReadOnlySpan 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 } - var stream = (id[0] - '0') * 10 + (id[1] - '0'); - if (state.Chunks.Count >= MaxSamples) + var stream = ((id[0] - '0') * 10) + (id[1] - '0'); + 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, size)); + state.Chunks.Add((body, (int)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 } } diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs index 0cd10a2..6faf12d 100644 --- a/src/Febe.Core/Codecs/Containers/ContainerReader.cs +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -3,6 +3,9 @@ namespace Febe.Core.Codecs.Containers; /// Recognises the container of a video by its first bytes and reads it with the matching reader. public static class ContainerReader { + /// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below. + public const int MaxSampleSize = 64 * 1024 * 1024; + /// The format of a file from its first bytes; null when it is none of those read here. public static ContainerFormat? Detect(ReadOnlySpan start) { @@ -58,6 +61,11 @@ public static class ContainerReader throw new ContainerException("Campione fuori dal file."); } + if (sample.Size > MaxSampleSize) + { + throw new ContainerException("Campione troppo grande."); // no real frame comes near: a damaged table + } + if (buffer.Length < sample.Size) { buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)]; diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs index ce7c8c9..59abb64 100644 --- a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -14,7 +14,9 @@ public static class IsoBmffReader private const long MaxBoxInMemory = 128L * 1024 * 1024; private const int MaxTopLevelBoxes = 1_000_000; - private const int MaxSamples = 20_000_000; + + /// Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory). + internal const int MaxSamples = 2_000_000; /// True when the stream starts like an ISO media file (an ftyp, moov, mdat... box). public static bool Looks(ReadOnlySpan start) => @@ -33,7 +35,7 @@ public static class IsoBmffReader long position = 0; Span header = stackalloc byte[16]; 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++) { stream.Position = position; @@ -42,8 +44,14 @@ public static class IsoBmffReader var headerSize = 8; if (size == 1) { + if (position + 16 > length) + { + break; + } + 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; } else if (size == 0) @@ -62,17 +70,33 @@ public static class IsoBmffReader } 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); - if (!samples) + movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length); + foreach (var (start, body) in pending) + { + movie.AddFragment(start, body); + } + + pending.Clear(); + + // Metadata only: a fragmented file whose headers do not tell its duration is read on through its fragments. + if (!samples && !movie.NeedsFragmentsForDuration) { break; } } - else if (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; @@ -83,11 +107,6 @@ public static class IsoBmffReader throw new ContainerException("Manca il box moov."); } - foreach (var (start, body) in fragments) - { - movie.AddFragment(start, body); - } - return movie.Build(); } @@ -104,9 +123,9 @@ public static class IsoBmffReader 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 { foreach (var (type, start, count) in Children(moov, 0, moov.Length)) @@ -121,23 +140,32 @@ public static class IsoBmffReader movie.ParseTrak(moov, start, count); break; case "mvex": + movie.Fragmented = true; foreach (var (t, s, c) in Children(moov, start, count)) { if (t == "trex" && c >= 24) { + // version/flags, track_ID, default_sample_description_index, then the three defaults + // (ISO/IEC 14496-12 §8.8.3): duration, size, flags. var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); movie.TrackDefaults[id] = ( BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20))); } + else if (t == "mehd" && c >= 8) + { + movie.FragmentDuration = moov[s] == 1 && c >= 12 + ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(moov.AsSpan(s + 4)), long.MaxValue) + : BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); + } } break; } } } - catch (ArgumentOutOfRangeException) + catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException) { throw new ContainerException("Box moov danneggiato."); } @@ -229,14 +257,25 @@ public static class IsoBmffReader internal long FragmentTime = -1; } - private sealed class Movie(bool samples) + private sealed class Movie(bool samples, long fileLength) { - internal readonly Dictionary TrackDefaults = []; + /// The trex defaults of each track: sample duration, size and flags. + internal readonly Dictionary TrackDefaults = []; private readonly List tracks = []; private DateTimeOffset? created; private long timescale; private long duration; + /// True when the movie has an mvex box: its samples are in fragments. + internal bool Fragmented; + + /// fragment_duration of the mehd box, in movie units; 0 when absent. + internal long FragmentDuration; + + /// A fragmented movie whose headers give no duration: only its fragments tell it. + internal bool NeedsFragmentsForDuration => + Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0); + internal void ParseMvhd(ReadOnlySpan body, DateTimeOffset now) { ulong creation; @@ -406,7 +445,16 @@ public static class IsoBmffReader 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) @@ -514,7 +562,7 @@ public static class IsoBmffReader 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; uint fixedSize = 0; @@ -535,6 +583,14 @@ public static class IsoBmffReader throw new ContainerException("Troppi campioni."); } + // The table must be able to describe that many samples and the samples must fit in the file: a few damaged + // bytes never make the reader allocate more than the file can hold. + var tableBytes = stz2 ? 12 + ((((long)count * fieldSize) + 7) / 8) : fixedSize != 0 ? 12 : 12 + (4L * count); + if (stsz.Length < tableBytes || (fixedSize != 0 && (long)count * fixedSize > fileLength) || (stz2 && fieldSize is not (4 or 8 or 16))) + { + throw new ContainerException("Tabella delle dimensioni danneggiata."); + } + int SizeOf(int i) { if (!stz2) @@ -555,13 +611,19 @@ public static class IsoBmffReader ? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8))) : BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4))); - var keys = stss is null ? null : new HashSet(); + // 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) { - 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++) { - 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); - 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; dts += delta; 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) { 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; long? decodeTime = null; 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); if (TrackDefaults.TryGetValue(id, out var d)) { - (defDuration, defSize, defFlags) = (d.Duration, d.Size, 0); + (defDuration, defSize, defFlags) = d; } var p = 8; 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; } + nextData = dataBase; + if ((flags & 0x2) != 0) { p += 4; @@ -693,23 +759,20 @@ public static class IsoBmffReader } 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; case "trun" when track is not null: { var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; var signed = body[0] == 1; var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]); - if (n < 0 || track.Samples.Count + n > MaxSamples) - { - throw new ContainerException("Troppi campioni."); - } - var p = 8; - var offset = baseOffset; + var offset = nextData; 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; } @@ -720,6 +783,17 @@ public static class IsoBmffReader 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); 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 - 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; dts += duration; } track.FragmentTime = 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; } } @@ -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 }) { - 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 }; } + /// A duration in seconds; null when it is beyond what a video can last (a damaged header). + private static TimeSpan? Seconds(double seconds) => seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; + private static long DurationOf(Track track) { if (track.FragmentTime > track.Duration) diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs index 1f7a0a7..8c98c98 100644 --- a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -24,7 +24,7 @@ public static class MatroskaReader private const uint ChaptersId = 0x1043A770; private const uint SeekHeadId = 0x114D9B74; 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; /// True when the stream starts with an EBML header. @@ -65,7 +65,7 @@ public static class MatroskaReader throw new ContainerException("Documento EBML che non è Matroska."); } - stream.Position = end; + stream.Position = Math.Min(end, stream.Length); (id, size) = reader.Header(); while (id != SegmentId) { @@ -138,10 +138,15 @@ public static class MatroskaReader state.TimecodeScale = (long)reader.Unsigned(size); break; 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: { + // Nanoseconds from 2001: about ±292 years, always inside the range of a date. var ns = reader.Signed(size); var instant = Epoch2001.AddTicks(ns / 100); if (instant >= Earliest && instant <= now.AddDays(1)) @@ -171,6 +176,11 @@ public static class MatroskaReader continue; } + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + var entryEnd = stream.Position + size; var track = new TrackEntry(); while (stream.Position < entryEnd) @@ -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) { state.Video = track; @@ -372,12 +382,23 @@ public static class MatroskaReader var dataStart = stream.Position; if (lacing == 0) { + if (end - dataStart is <= 0 or > int.MaxValue) + { + throw new ContainerException("Blocco Matroska danneggiato."); + } + target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key)); return; } - var frames = stream.ReadByte() + 1; - var sizes = new long[frames]; + var count = stream.ReadByte(); + if (count < 0 || dataStart >= end) + { + throw new ContainerException("Blocco Matroska troncato."); + } + + var frames = count + 1; + Span sizes = stackalloc long[frames]; switch (lacing) { case 1: // Xiph @@ -438,12 +459,17 @@ public static class MatroskaReader var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0; for (var i = 0; i < frames; i++) { - if (sizes[i] < 0 || offset + sizes[i] > end) + if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end) { throw new ContainerException("Blocco Matroska danneggiato."); } var t = time + (i * frameDuration); + if (sizes[i] == 0) + { + continue; // an empty frame has nothing to decode (and costs no memory) + } + target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key)); offset += sizes[i]; } @@ -515,7 +541,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 = (long)DurationTicks, + Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0, Samples = samples, }; } @@ -539,12 +565,13 @@ public static class MatroskaReader Channels = a.Channels, AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, Timescale = timescale, - Duration = (long)DurationTicks, + Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0, 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 }; } } @@ -654,6 +681,11 @@ public static class MatroskaReader throw new ContainerException("Elemento Matroska troppo grande."); } + if (size > stream.Length - stream.Position) + { + throw new ContainerException("File Matroska troncato."); // before allocating what the file cannot hold + } + var data = new byte[size]; stream.ReadExactly(data); return data; @@ -666,7 +698,8 @@ public static class MatroskaReader 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() diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs index 07571e2..9cf4406 100644 --- a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -189,17 +189,21 @@ public static class Mp4Writer var samples = track.Samples; var first = 0; var limit = track.Timescale / 2; + var start = 0.0; for (var i = 1; i <= samples.Count; i++) { if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024) { - 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; } } } - 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)); } diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index bd8d194..27d595d 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -118,6 +118,24 @@ public sealed partial class H264Decoder /// Finishes the picture being decoded, if any. public void Flush() => FinishPicture(); + /// + /// Finishes the picture being decoded; a damaged picture whose deblocking or cropping fails raises an + /// like the rest of the stream, and is dropped. + /// + 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) { try @@ -151,11 +169,7 @@ public sealed partial class H264Decoder break; } } - catch (IndexOutOfRangeException) - { - throw new H264Exception("Flusso H.264 troncato o danneggiato."); - } - catch (ArgumentOutOfRangeException) + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException) { throw new H264Exception("Flusso H.264 troncato o danneggiato."); } @@ -378,7 +392,7 @@ public sealed partial class H264Decoder PruneDpb(); } - private void FinishPicture() + private void CompletePicture() { if (cur is null || picHeader is null || activeSps is null) { @@ -599,6 +613,51 @@ public sealed partial class H264Decoder } dpb.Add(picture); + LimitReferences(picture, sps); + } + + /// + /// 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. + /// + 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; + } } /// Sliding window marking (§8.2.5.3) before a new short-term frame is added. diff --git a/src/Febe.Core/Codecs/H264/ParameterSets.cs b/src/Febe.Core/Codecs/H264/ParameterSets.cs index 585f007..9b9b5c9 100644 --- a/src/Febe.Core/Codecs/H264/ParameterSets.cs +++ b/src/Febe.Core/Codecs/H264/ParameterSets.cs @@ -3,6 +3,9 @@ namespace Febe.Core.Codecs.H264; /// A sequence parameter set (§7.3.2.1.1), with the fields Febe uses. internal sealed class Sps { + /// MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits. + internal const int MaxFrameMbs = 139_264; + internal int ProfileIdc; internal int LevelIdc; internal int Id; @@ -95,6 +98,13 @@ internal sealed class Sps 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(); if (r.ReadFlag()) { @@ -102,6 +112,13 @@ internal sealed class Sps s.CropRight = r.ReadUe(8192); s.CropTop = r.ReadUe(8192); s.CropBottom = r.ReadUe(8192); + + // §7.4.2.1.1: the cropped frame keeps at least one sample (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()) diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index c465b63..98fbd02 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -45,7 +45,7 @@ public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMe return new VideoMetadata(container.CreatedAt, duration, width, height); } 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 } diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 420ef98..1722de5 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -72,10 +72,11 @@ public sealed class VideoFrameDecoder /// /// 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. /// public Task ExtractImageAsync(string videoPath, CancellationToken ct = default) => - ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 0, ct); + ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 2 * ThumbnailStore.LongSide, ct); /// /// A frame of the video 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 wanted = []; private byte[] buffer = new byte[64 * 1024]; + /// The sample being decoded: the picture it finishes is that sample's frame. + private int current; + internal Dictionary Decode(int[] targets, CancellationToken ct) { foreach (var t in targets) @@ -304,23 +308,24 @@ public sealed class VideoFrameDecoder var key = KeyBefore(keys, target); if (decoder is null || next > target || key >= next) { - decoder = new H264Decoder(); - var runStart = key; - decoder.Wanted = index => wanted.Contains(runStart + (int)index); - decoder.FrameDecoded += frame => found.TryAdd(runStart + (int)frame.DecodeIndex, frame); - if (!video.AnnexB) - { - lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); - } - + // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a + // sample without a picture (only parameter sets, or damaged) must not shift the frames after it. + decoder = new H264Decoder { Wanted = _ => wanted.Contains(current) }; + decoder.FrameDecoded += frame => found.TryAdd(current, frame); next = key; } try { + if (next == key && !video.AnnexB) + { + lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); + } + for (; next <= target; next++) { ct.ThrowIfCancellationRequested(); + current = next; var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer); if (video.AnnexB) { @@ -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; } } diff --git a/tests/Febe.Tests/Media/Containers/ContainerTests.cs b/tests/Febe.Tests/Media/Containers/ContainerTests.cs index 6254145..34da89a 100644 --- a/tests/Febe.Tests/Media/Containers/ContainerTests.cs +++ b/tests/Febe.Tests/Media/Containers/ContainerTests.cs @@ -30,15 +30,77 @@ public sealed class ContainerTests } [TestMethod] - [DataRow("CABA3_SVA_B")] - [DataRow("FRExt1_Panasonic_D")] - public void AFragmentedMp4IsReadFromItsFragments(string name) + [DataRow("CABA3_SVA_B", false)] + [DataRow("FRExt1_Panasonic_D", false)] + [DataRow("CABA3_SVA_B", true)] + [DataRow("FRExt1_Panasonic_D", true)] + public void AFragmentedMp4IsReadFromItsFragments(string name, bool defaults) { + // With defaults: durations from trex and two runs per fragment, each with its data_offset from the moof. var es = ElementaryStream.Load(name); - var file = TestVideos.FragmentedMp4(es, perFragment: 7); + var file = TestVideos.FragmentedMp4(es, perFragment: 7, defaults: defaults); var container = Read(file); AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!)); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void TheProbeTellsTheDurationOfAFragmentedMp4(bool mehd) + { + // Without mehd only the fragments tell the duration: the metadata reading goes on through them. + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("sonda-frammentato"); + var path = TestVideos.Write(temp, "frammentato.mp4", TestVideos.FragmentedMp4(es, perFragment: 5, defaults: mehd)); + var meta = ContainerVideoMetadataProbe.Probe(path, Now); + Assert.IsNotNull(meta); + Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05); + Assert.AreEqual((es.Width, es.Height), (meta.Width!.Value, meta.Height!.Value)); + } + + [TestMethod] + public void TheMp4WriterKeepsTheOrderOfSamplesWithEqualTimes() + { + // An audio track without times (as AVI gives): every chunk starts at zero, and the order must still hold. + var es = ElementaryStream.Load("BA1_Sony_D"); + var video = new Mp4OutputTrack + { + IsVideo = true, + Timescale = TestVideos.Timescale, + Samples = [.. Enumerable.Range(0, es.Count).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, (long)i * TestVideos.FrameTicks, (long)es.Rank[i] * TestVideos.FrameTicks, es.Key[i]))], + WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), + Width = es.Width, + Height = es.Height, + AvcConfiguration = es.AvcC, + }; + const int Count = 40_000; // 40 chunks of 1024: enough for the sort to be an unstable one + static byte[] Payload(int i) => [(byte)(i >> 8), (byte)i, 7]; + var audio = new Mp4OutputTrack + { + IsVideo = false, + Timescale = 44100, + Samples = [.. Enumerable.Range(0, Count).Select(_ => new Mp4OutputSample(3, 0, 0, true))], + WriteSample = (i, s) => s.Write(Payload(i)), + AacConfiguration = [0x12, 0x10], + SampleRate = 44100, + Channels = 2, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [video, audio]); + + var file = output.ToArray(); + var container = Read(file); + Assert.AreEqual(Count, container.Audio!.Samples.Count); + using var input = new MemoryStream(file); + var buffer = Array.Empty(); + 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] diff --git a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs new file mode 100644 index 0000000..ac39c87 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs @@ -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; + +/// +/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one +/// of them with a (or ), a null result or a frame, +/// and must never allocate much more than the file holds, whatever its damaged headers claim. +/// +[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(() => 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(); + 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), + }; + } + + /// A copy with a few bytes changed: mostly in the first kilobytes, where the headers are. + 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 pattern) + { + var index = data.AsSpan().IndexOf(pattern); + Assert.IsGreaterThanOrEqualTo(0, index); + return index; + } +} diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index 050b10a..62a3205 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -240,8 +240,12 @@ internal static class TestVideos return output.ToArray(); } - /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). - public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10) + /// + /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). + /// With the sample durations come from trex, each fragment has two runs that + /// both give their data_offset from the start of the moof, and an mehd box tells the duration. + /// + public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10, bool defaults = false) { var shift = 0; 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], .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000), .. new byte[24], .. U32(2)]); - var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0)]); - output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), Box("mvex", trex))); + // trex: track_ID, default_sample_description_index, default duration, size and flags (non-sync). + var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0x01010000)]); + var mvex = defaults + ? Box("mvex", FullBox("mehd", 0, U32((uint)(es.Count * 1000 / 30))), trex) // movie timescale 1000 + : Box("mvex", trex); + output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), mvex)); for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++) { var count = Math.Min(perFragment, es.Count - first); var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList(); - byte[] Moof(int dataOffset) + byte[] Run(int from, int length, int dataOffset) { var run = new List(); - run.AddRange(U32((uint)count)); + run.AddRange(U32((uint)length)); run.AddRange(U32((uint)dataOffset)); - for (var k = 0; k < count; k++) + for (var k = from; k < from + length; 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(es.Key[i] ? 0x02000000u : 0x01010000u)); run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks))); } + // Without the duration field (0x100) every sample takes the trex default. + return FullBox("trun", defaults ? 0x000E01u : 0x000F01u, [.. run]); + } + + var split = defaults ? (count + 1) / 2 : count; + var secondData = payloads.Take(split).Sum(p => p.Length); + byte[] Moof(int dataOffset) + { + var runs = new List { Run(0, split, dataOffset) }; + if (split < count) + { + runs.Add(Run(split, count - split, dataOffset + secondData)); + } + return Box("moof", FullBox("mfhd", 0, U32((uint)sequence)), - Box("traf", - FullBox("tfhd", 0x020000, U32(1)), - FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), - FullBox("trun", 0x000F01, [.. run]))); + Box("traf", [FullBox("tfhd", 0x020000, U32(1)), FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), .. runs])); } var size = Moof(0).Length; diff --git a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs new file mode 100644 index 0000000..27cb52e --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs @@ -0,0 +1,167 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// 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 , and a damaged parameter set must never make it allocate huge pictures. +/// +[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(() => 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(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (44, 44, 0, 0)))); + 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]; + } + } +}