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