Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori di contenitori. - Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni), altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come l'estrattore con ffmpeg che sostituisce. - H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num; immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica. - Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano; scala dei tempi esatta per ogni TimecodeScale. - MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né campioni dei frammenti. - AVI: durata impossibile ignota senza perdere la data. - Sonda dei metadati davvero asincrona, annullabile fra i frammenti. - Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice), AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI, TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile. Provate contro il codice senza le correzioni: falliscono tutte. - decisioni.md: quattro righe del 18 novembre. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
80 lines
3.3 KiB
C#
80 lines
3.3 KiB
C#
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)
|
|
{
|
|
if (MatroskaReader.Looks(start))
|
|
{
|
|
return ContainerFormat.Matroska;
|
|
}
|
|
|
|
if (AviReader.Looks(start))
|
|
{
|
|
return ContainerFormat.Avi;
|
|
}
|
|
|
|
return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
|
|
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated); <paramref name="ct"/> is
|
|
/// checked between the top-level boxes, elements and fragments.
|
|
/// </summary>
|
|
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(stream);
|
|
Span<byte> start = stackalloc byte[16];
|
|
stream.Position = 0;
|
|
var read = stream.ReadAtLeast(start, start.Length, throwOnEndOfStream: false);
|
|
stream.Position = 0;
|
|
return Detect(start[..read]) switch
|
|
{
|
|
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct),
|
|
ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct),
|
|
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct),
|
|
_ => null,
|
|
};
|
|
}
|
|
|
|
/// <summary>Reads a file (read-only, shared); null when its format is not recognised.</summary>
|
|
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
|
|
{
|
|
using var stream = OpenRead(path);
|
|
return Read(stream, now, samples, ct);
|
|
}
|
|
|
|
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
|
|
public static FileStream OpenRead(string path) =>
|
|
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess);
|
|
|
|
/// <summary>The bytes of a sample, read into <paramref name="buffer"/> (grown when needed).</summary>
|
|
public static ReadOnlySpan<byte> ReadSample(Stream stream, in MediaSample sample, ref byte[] buffer)
|
|
{
|
|
if (sample.Size < 0 || sample.Offset < 0 || sample.Offset + sample.Size > stream.Length)
|
|
{
|
|
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)];
|
|
}
|
|
|
|
stream.Position = sample.Offset;
|
|
stream.ReadExactly(buffer, 0, sample.Size);
|
|
return buffer.AsSpan(0, sample.Size);
|
|
}
|
|
}
|