Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:13:45 +01:00
1 parent 479c95f899
commit b23632fc96
22 files changed
+1273 -282

No files matched your search

+142 -23
View File
@@ -60,13 +60,42 @@ public sealed class VideoFrameDecoder
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
public const double StillThreshold = 3.0;
/// <summary>
/// The longest a frame or a stillness analysis may take: what the ffmpeg extractor it replaces was given. A damaged
/// file never holds an import or a rebuild for longer.
/// </summary>
public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30);
private const int GridSize = 32;
private const int SampledPositions = 6;
private const int MaxSequentialSamples = 2000;
private const int MaxRunPerTarget = 300;
private const int DefaultMaxRun = 300;
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
private const int MaxRunStartSearch = 2000;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly TimeSpan budget;
private readonly int maxRun;
/// <summary>A decoder with the default budget and run length.</summary>
public VideoFrameDecoder()
: this(DefaultBudget, DefaultMaxRun)
{
}
/// <param name="budget">The longest one call may take (zero: no time at all).</param>
/// <param name="maxRun">
/// Samples decoded at most from a random access point to the frame asked for; a frame further away (a damaged time
/// table, a track with a single key frame) gives way to the frame of the random access point itself.
/// </param>
internal VideoFrameDecoder(TimeSpan budget, int maxRun)
{
this.budget = budget;
this.maxRun = maxRun;
}
/// <summary>The shared instance: it keeps no state between calls.</summary>
public static VideoFrameDecoder Instance { get; } = new();
@@ -92,7 +121,7 @@ public sealed class VideoFrameDecoder
public Task<VideoImage?> DecodeFrameAsync(string videoPath, TimeSpan at, int maxLongSide = 0, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => DecodeFrame(videoPath, at, maxLongSide, ct), ct);
return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct);
}
/// <summary>
@@ -102,24 +131,58 @@ public sealed class VideoFrameDecoder
public Task<VideoStillness?> AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => AnalyseStillness(videoPath, ct), ct);
return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct);
}
private static VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct)
/// <summary>Runs <paramref name="work"/> for at most the budget: past it the result is null, as for an unreadable file.</summary>
private T? WithinBudget<T>(Func<CancellationToken, T?> work, CancellationToken ct)
where T : class
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
if (budget <= TimeSpan.Zero)
{
limit.Cancel();
}
else
{
limit.CancelAfter(budget);
}
try
{
return work(limit.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return null;
}
}
private VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct)
{
try
{
ct.ThrowIfCancellationRequested();
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
return null;
}
var decoding = new Decoding(stream, video, maxRun);
var target = SampleAt(video, at);
var frames = new Decoding(stream, video).Decode([target], ct);
// Too far from where decoding can start: the frame there stands for it, so the work stays bounded.
var start = decoding.RunStart(target);
if (target - start > maxRun)
{
target = start;
}
var frames = decoding.Decode([target], ct);
if (!frames.TryGetValue(target, out var frame) && target != 0)
{
frames = new Decoding(stream, video).Decode([0], ct);
frames = new Decoding(stream, video, maxRun).Decode([0], ct);
frames.TryGetValue(0, out frame);
}
@@ -131,10 +194,11 @@ public sealed class VideoFrameDecoder
}
}
private static VideoStillness? AnalyseStillness(string path, CancellationToken ct)
private VideoStillness? AnalyseStillness(string path, CancellationToken ct)
{
try
{
ct.ThrowIfCancellationRequested();
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
@@ -155,18 +219,20 @@ public sealed class VideoFrameDecoder
last = Math.Max(last, s.PresentationTime);
}
var keys = KeyIndices(video);
var decoding = new Decoding(stream, video, maxRun);
var targets = new SortedSet<int>();
for (var i = 0; i < SampledPositions; i++)
{
ct.ThrowIfCancellationRequested();
var time = first + ((last - first) * i / (SampledPositions - 1));
var index = Closest(samples, time);
// Far from its key frame in a long video: the key frame stands for it, so the work stays bounded.
var key = KeyBefore(keys, index);
if (index - key > MaxRunPerTarget && samples.Count > MaxSequentialSamples)
// Far from where decoding can start in a long video: the frame there stands for it, so the work stays
// bounded.
var start = decoding.RunStart(index);
if (index - start > maxRun && samples.Count > MaxSequentialSamples)
{
index = key;
index = start;
}
targets.Add(index);
@@ -177,7 +243,7 @@ public sealed class VideoFrameDecoder
return null;
}
var frames = new Decoding(stream, video).Decode([.. targets], ct);
var frames = decoding.Decode([.. targets], ct);
if (frames.Count < 2)
{
return null;
@@ -276,22 +342,76 @@ public sealed class VideoFrameDecoder
return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys];
}
private static int KeyBefore(int[] keys, int index)
{
var found = Array.BinarySearch(keys, index);
return found >= 0 ? keys[found] : keys[Math.Max(0, ~found - 1)];
}
/// <summary>Decodes chosen samples, each from the key frame before it, reusing a run when the targets share it.</summary>
private sealed class Decoding(Stream stream, VideoTrack video)
/// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
{
private readonly Dictionary<int, H264Frame> found = [];
private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, H264AccessPoint> accessPoints = [];
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;
/// <summary>
/// The sample where decoding for <paramref name="index"/> starts. A container without an index (an AVI cut short,
/// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give
/// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest
/// IDR picture is taken when it is within the run limit (the frame comes out exact); otherwise the nearest
/// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture
/// further back, or the first sample.
/// </summary>
internal int RunStart(int index)
{
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
var intra = -1;
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
{
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
if (point == H264AccessPoint.Idr)
{
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
}
if (point == H264AccessPoint.IntraPicture && intra < 0)
{
intra = candidate;
}
if (index - candidate > maxRun && intra >= 0)
{
return intra; // no IDR picture within reach: the nearest picture of I slices
}
}
// The first sample, where every stream starts (or the end of the search): it counts as an IDR picture.
return index <= maxRun || intra < 0 ? 0 : intra;
}
private H264AccessPoint AccessPointOf(int index)
{
try
{
var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer);
var lengthSize = video.AnnexB ? 0 : video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4;
return H264Decoder.AccessPoint(sample, lengthSize);
}
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException)
{
return H264AccessPoint.None;
}
}
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
@@ -299,13 +419,12 @@ public sealed class VideoFrameDecoder
wanted.Add(t);
}
var keys = KeyIndices(video);
H264Decoder? decoder = null;
var next = 0;
var lengthSize = 4;
foreach (var target in targets)
{
var key = KeyBefore(keys, target);
var key = RunStart(target);
if (decoder is null || next > target || key >= next)
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a