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:
1 parent
6ffcb1bb18
commit
479c95f899
14 files changed
+787
-113
No files matched your search
@@ -11,7 +11,7 @@ namespace Febe.Core.Codecs.Containers;
|
||||
/// </summary>
|
||||
public static class AviReader
|
||||
{
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const int MaxSamples = IsoBmffReader.MaxSamples;
|
||||
private const int MaxHeaderBytes = 16 * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts like an AVI file.</summary>
|
||||
@@ -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<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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
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>
|
||||
public static ContainerFormat? Detect(ReadOnlySpan<byte> 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)];
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <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>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
@@ -33,7 +35,7 @@ public static class IsoBmffReader
|
||||
long position = 0;
|
||||
Span<byte> 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<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 DateTimeOffset? created;
|
||||
private long timescale;
|
||||
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)
|
||||
{
|
||||
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<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)
|
||||
{
|
||||
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 };
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (track.FragmentTime > track.Duration)
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <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.");
|
||||
}
|
||||
|
||||
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<long> 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()
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -118,6 +118,24 @@ public sealed partial class H264Decoder
|
||||
/// <summary>Finishes the picture being decoded, if any.</summary>
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
|
||||
@@ -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>
|
||||
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 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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -72,10 +72,11 @@ public sealed class VideoFrameDecoder
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
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>
|
||||
/// 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 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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user