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

+9 -3
View File
@@ -19,7 +19,7 @@ public static class AviReader
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
/// <summary>Reads a seekable stream from its start.</summary>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var state = new State();
@@ -29,6 +29,7 @@ public static class AviReader
var first = true;
while (position + 12 <= length)
{
ct.ThrowIfCancellationRequested();
stream.Position = position;
stream.ReadExactly(header);
if (!header[..4].SequenceEqual("RIFF"u8))
@@ -307,6 +308,9 @@ public static class AviReader
var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant();
var frames = VideoLength > 0 ? VideoLength : TotalFrames;
// Header values are taken as stored: a damaged one never gives an overflowing or negative duration.
var trackDuration = frames <= long.MaxValue / frameTicks ? frames * frameTicks : 0;
var video = VideoStream < 0 ? null : new VideoTrack
{
Codec = tag switch
@@ -322,7 +326,7 @@ public static class AviReader
Height = VideoHeight > 0 ? VideoHeight : Height,
AnnexB = true,
Timescale = timescale,
Duration = frames * frameTicks,
Duration = trackDuration,
Samples = samples,
};
@@ -353,7 +357,9 @@ public static class AviReader
};
}
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null;
// As the other readers: beyond what a video can last (a damaged header) there is no duration, and the rest stands.
var seconds = video is { Duration: > 0 } ? video.Seconds(video.Duration) : 0;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
}
@@ -24,9 +24,10 @@ public static class ContainerReader
/// <summary>
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated).
/// <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)
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
Span<byte> start = stackalloc byte[16];
@@ -35,18 +36,18 @@ public static class ContainerReader
stream.Position = 0;
return Detect(start[..read]) switch
{
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples),
ContainerFormat.Avi => AviReader.Read(stream, now, samples),
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples),
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)
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
using var stream = OpenRead(path);
return Read(stream, now, samples);
return Read(stream, now, samples, ct);
}
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
@@ -27,8 +27,12 @@ public static class IsoBmffReader
/// <summary>Reads a seekable stream from its start.</summary>
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">False to stop at the metadata (no sample tables, no fragments).</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
/// <param name="samples">
/// False to stop at the metadata: no sample tables, and fragments only when they alone tell the duration (then only
/// their durations are added up).
/// </param>
/// <param name="ct">Checked between the top-level boxes (each fragment of a fragmented file).</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var length = stream.Length;
@@ -38,6 +42,7 @@ public static class IsoBmffReader
var pending = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{
ct.ThrowIfCancellationRequested();
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
@@ -137,7 +142,17 @@ public static class IsoBmffReader
movie.ParseMvhd(body, now);
break;
case "trak":
movie.ParseTrak(moov, start, count);
try
{
movie.ParseTrak(moov, start, count);
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException
or ContainerException)
{
// A damaged track header, edit list or description (often of the audio track): that track is
// dropped, the others are still read.
}
break;
case "mvex":
movie.Fragmented = true;
@@ -406,6 +421,11 @@ public static class IsoBmffReader
var stz2 = false;
foreach (var (type, s, c) in Children(data, start, count))
{
if (!samples && type != "stsd")
{
continue; // metadata only: the tables are not even copied
}
switch (type)
{
case "stsd":
@@ -528,6 +548,11 @@ public static class IsoBmffReader
{
case 0x03: // ES_Descriptor
{
if (p + 3 > body.Length)
{
return null;
}
var flags = body[p + 2];
p += 3;
if ((flags & 0x80) != 0)
@@ -537,6 +562,11 @@ public static class IsoBmffReader
if ((flags & 0x40) != 0)
{
if (p >= body.Length)
{
return null;
}
p += 1 + body[p];
}
@@ -789,12 +819,22 @@ public static class IsoBmffReader
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)
if (n < 0 || !bounded || (samples && track.Samples.Count + n > MaxSamples))
{
throw new ContainerException("Troppi campioni.");
}
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
if (!samples)
{
// Metadata only: the fragments are read for the duration, so only durations add up.
var run = RunDuration(body[p..], flags, n, defDuration);
dts = run > (long.MaxValue / 2) - dts ? long.MaxValue / 2 : dts + run;
track.FragmentTime = dts;
decodeTime = dts;
break;
}
for (var i = 0; i < n; i++)
{
var duration = defDuration;
@@ -840,6 +880,24 @@ public static class IsoBmffReader
}
}
/// <summary>The total duration of the <paramref name="count"/> samples of a trun, from their fields after the header.</summary>
private static long RunDuration(ReadOnlySpan<byte> fields, uint flags, int count, uint defaultDuration)
{
if ((flags & 0x100) == 0)
{
return (long)count * defaultDuration;
}
var stride = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1));
long total = 0;
for (var i = 0; i < count; i++)
{
total += BinaryPrimitives.ReadUInt32BigEndian(fields[(i * stride)..]); // the duration comes first
}
return total;
}
internal MediaContainer Build()
{
var video = tracks.Find(t => t.Handler == "vide");
@@ -34,7 +34,8 @@ public static class MatroskaReader
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">False to stop before the first cluster.</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
/// <param name="ct">Checked between the top-level elements.</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var reader = new Reader(stream);
@@ -82,45 +83,55 @@ public static class MatroskaReader
var state = new State();
while (stream.Position < segmentEnd)
{
ct.ThrowIfCancellationRequested();
var elementStart = stream.Position;
if (segmentEnd - elementStart < 2)
{
break;
}
(id, size) = reader.Header();
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
if (bodyEnd > segmentEnd)
try
{
bodyEnd = segmentEnd; // truncated file
}
(id, size) = reader.Header();
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
if (bodyEnd > segmentEnd)
{
bodyEnd = segmentEnd; // truncated file
}
switch (id)
switch (id)
{
case InfoId:
ParseInfo(reader, bodyEnd, state, now);
break;
case TracksId:
ParseTracks(reader, bodyEnd, state);
break;
case ClusterId:
if (!samples)
{
return state.Build();
}
ParseCluster(reader, bodyEnd, size < 0, state);
continue; // the position is already past the cluster
default:
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
break;
}
stream.Position = bodyEnd;
}
catch (Exception ex) when ((ex is ContainerException or EndOfStreamException) && state.HasSamples)
{
case InfoId:
ParseInfo(reader, bodyEnd, state, now);
break;
case TracksId:
ParseTracks(reader, bodyEnd, state);
break;
case ClusterId:
if (!samples)
{
return state.Build();
}
ParseCluster(reader, bodyEnd, size < 0, state);
continue; // the position is already past the cluster
default:
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
break;
// A damaged or truncated block after the first ones, or more samples than the limit: what was read
// stands, as in the ISO reader.
break;
}
stream.Position = bodyEnd;
}
return state.Build();
@@ -377,7 +388,7 @@ public static class MatroskaReader
throw new ContainerException("Troppi campioni.");
}
var time = clusterTime + relative;
var time = state.ToUnits(clusterTime + relative);
var lacing = (flags >> 1) & 3;
var dataStart = stream.Position;
if (lacing == 0)
@@ -456,7 +467,7 @@ public static class MatroskaReader
}
var offset = dataBegin;
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
var frameDuration = target.DefaultDuration > 0 ? target.DefaultDuration / state.UnitNanoseconds : 0;
for (var i = 0; i < frames; i++)
{
if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end)
@@ -498,9 +509,53 @@ public static class MatroskaReader
internal TrackEntry? Video;
internal TrackEntry? Audio;
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
private long unit;
internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0;
/// <summary>
/// Nanoseconds of one unit of the sample times: the greatest common divisor of TimecodeScale and a second, so
/// that the timescale of the tracks (a second in units) is exact for any TimecodeScale (3 ms gives units of
/// 1 ms, 2 s units of 1 s) and the block times are whole units.
/// </summary>
internal long UnitNanoseconds
{
get
{
if (unit == 0)
{
long a = Scale, b = 1_000_000_000;
while (b != 0)
{
(a, b) = (b, a % b);
}
unit = a;
}
return unit;
}
}
/// <summary>TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value.</summary>
private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000;
/// <summary>Units of <see cref="UnitNanoseconds"/> in a tick (at least 1, should Info come after the first block).</summary>
private long Factor => Math.Max(1, Scale / UnitNanoseconds);
/// <summary>A time in TimecodeScale ticks as a time in units of <see cref="UnitNanoseconds"/>.</summary>
internal long ToUnits(long ticks)
{
var limit = long.MaxValue / 4 / Factor;
return Math.Clamp(ticks, -limit, limit) * Factor; // a damaged cluster time stays a (wrong) number
}
internal MediaContainer Build()
{
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
var timescale = 1_000_000_000L / UnitNanoseconds;
var trackDuration = DurationTicks * Factor;
var trackUnits = trackDuration is > 0 and < long.MaxValue / 2 ? (long)trackDuration : 0;
VideoTrack? video = null;
if (Video is { } v)
{
@@ -541,7 +596,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 = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Duration = trackUnits,
Samples = samples,
};
}
@@ -565,7 +620,7 @@ public static class MatroskaReader
Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
Timescale = timescale,
Duration = DurationTicks < long.MaxValue / 2 ? (long)DurationTicks : 0,
Duration = trackUnits,
Samples = a.Samples,
};
}
+65 -9
View File
@@ -1,17 +1,31 @@
using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), reading the slice data bit by bit, with the
/// context variables of the slice.
/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), with the context variables of the slice. The slice
/// data is read through a 64-bit window refilled four bytes at a time, and renormalisation shifts all its bits at once
/// (the count of leading zeros of the range): the arithmetic is the one of the standard, bit for bit.
/// </summary>
internal sealed class CabacEngine
{
private readonly byte[] state = new byte[CabacTables.ContextCount];
private readonly byte[] mps = new byte[CabacTables.ContextCount];
private RbspReader reader = null!;
private byte[] data = [];
private int range;
private int offset;
/// <summary>The next bits of the slice data, from the most significant bit.</summary>
private ulong window;
/// <summary>Valid bits at the top of <see cref="window"/>.</summary>
private int bits;
/// <summary>The next byte of <see cref="data"/> to load into the window.</summary>
private int next;
/// <summary>Initialises the context variables (§9.3.1.1).</summary>
internal void InitContexts(SliceHeader header, int sliceQp)
{
@@ -38,8 +52,18 @@ internal sealed class CabacEngine
internal void Start(RbspReader source)
{
reader = source;
data = source.Data;
var position = source.Position;
next = position >> 3;
window = 0;
bits = 0;
Refill();
var skip = position & 7;
window <<= skip;
bits -= skip;
range = 510;
offset = (int)source.Read(9);
offset = Take(9);
if (offset >= range)
{
throw new H264Exception("Dati CABAC non validi.");
@@ -73,10 +97,12 @@ internal sealed class CabacEngine
}
}
while (range < 256)
if (range < 256)
{
range <<= 1;
offset = (offset << 1) | reader.ReadBit();
// RenormD (§9.3.3.2.2): as many single-bit steps as the range has leading zeros below bit 8.
var shift = BitOperations.LeadingZeroCount((uint)range) - 23;
range <<= shift;
offset = (offset << shift) | Take(shift);
}
return bin;
@@ -84,7 +110,7 @@ internal sealed class CabacEngine
internal int Bypass()
{
offset = (offset << 1) | reader.ReadBit();
offset = (offset << 1) | Take(1);
if (offset >= range)
{
offset -= range;
@@ -99,15 +125,45 @@ internal sealed class CabacEngine
range -= 2;
if (offset >= range)
{
// The end of the slice or an I_PCM macroblock: the reader goes on exactly after the bits read here.
reader.Position = (next * 8) - bits;
return 1;
}
while (range < 256)
if (range < 256)
{
range <<= 1;
offset = (offset << 1) | reader.ReadBit();
offset = (offset << 1) | Take(1);
}
return 0;
}
/// <summary>The next <paramref name="count"/> bits (1 to 32) of the slice data.</summary>
private int Take(int count)
{
if (bits < count)
{
Refill();
}
var value = (int)(window >> (64 - count));
window <<= count;
bits -= count;
return value;
}
/// <summary>
/// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see
/// <see cref="RbspReader"/>); a damaged slice that reads beyond the padding fails as the bit reader would.
/// </summary>
private void Refill()
{
while (bits <= 32)
{
window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits);
next += 4;
bits += 32;
}
}
}
@@ -371,7 +371,8 @@ public sealed partial class H264Decoder
}
}
return cur!;
// Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged.
throw new H264Exception("Slice P o B senza immagini di riferimento.");
}
private void PrepareWeights()
+163 -29
View File
@@ -1,11 +1,26 @@
namespace Febe.Core.Codecs.H264;
/// <summary>What an access unit offers to start decoding from (see <see cref="H264Decoder.AccessPoint"/>).</summary>
public enum H264AccessPoint
{
/// <summary>A P or B picture, or no picture: decoding cannot start here.</summary>
None,
/// <summary>A picture of I slices that is not IDR: the pictures after it may still refer to earlier ones.</summary>
IntraPicture,
/// <summary>An IDR picture: nothing after it refers to anything before.</summary>
Idr,
}
/// <summary>
/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Main and High profiles for
/// progressive frames in 4:2:0 with 8-bit samples — CAVLC and CABAC, I, P and B slices, 8×8 transform and scaling
/// matrices, explicit and implicit weighted prediction, spatial and temporal direct prediction, multiple reference frames
/// with list modification and memory management, deblocking. Not handled (an <see cref="H264Exception"/>): interlaced
/// pictures (fields and MBAFF), slice groups, SP/SI slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits.
/// matrices, spatial and temporal direct prediction, list modification, deblocking. Written from the standard but not
/// yet checked against a conformance stream: explicit and implicit weighted prediction, memory management operations
/// and long-term references, gaps in frame_num, picture order count type 1, I_PCM and CABAC pictures of several
/// slices. Not handled (an <see cref="H264Exception"/>): interlaced pictures (fields and MBAFF), slice groups, SP/SI
/// slices, data partitioning, 4:2:2/4:4:4 and depths above 8 bits. Redundant coded pictures are skipped.
/// </summary>
public sealed partial class H264Decoder
{
@@ -20,8 +35,12 @@ public sealed partial class H264Decoder
private int picNalType;
private int picRefIdc;
private bool picMmco5;
private bool picSkipped;
private int sliceCounter;
/// <summary>The RBSP of the NAL unit being decoded: one buffer for the whole stream.</summary>
private byte[]? rbsp;
private int prevPocMsb;
private int prevPocLsb;
private int prevFrameNumOffset;
@@ -34,7 +53,10 @@ public sealed partial class H264Decoder
private int period;
private long decodeCounter;
/// <summary>Which frames to hand out, by decoding index; null hands out all of them.</summary>
/// <summary>
/// Which frames to hand out, by decoding index; null hands out all of them. A picture that is not used for reference
/// and is not wanted is not reconstructed at all: only its header counts.
/// </summary>
public Func<long, bool>? Wanted { get; set; }
/// <summary>Raised for each decoded frame that <see cref="Wanted"/> accepts, in decoding order.</summary>
@@ -46,11 +68,7 @@ public sealed partial class H264Decoder
/// <summary>Decodes a whole Annex B byte stream (start codes), then flushes the last picture.</summary>
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
{
foreach (var nal in NalUnits.SplitAnnexB(stream))
{
Decode(nal);
}
DecodeUnitsAnnexB(stream);
Flush();
}
@@ -85,7 +103,7 @@ public sealed partial class H264Decoder
throw new H264Exception("Configurazione avcC troncata.");
}
Decode(NalUnits.Parse(avcC.Slice(offset, size)));
Decode(NalUnits.Unescape(avcC.Slice(offset, size), ref rbsp));
offset += size;
}
}
@@ -96,9 +114,10 @@ public sealed partial class H264Decoder
/// <summary>Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.</summary>
public void DecodeSample(ReadOnlySpan<byte> sample, int lengthSize)
{
foreach (var nal in NalUnits.SplitLengthPrefixed(sample, lengthSize))
var position = 0;
while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
Decode(nal);
Decode(NalUnits.Unescape(sample[unit], ref rbsp));
}
FinishPicture();
@@ -107,14 +126,59 @@ public sealed partial class H264Decoder
/// <summary>Decodes one access unit in Annex B form and finishes its picture.</summary>
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
{
foreach (var nal in NalUnits.SplitAnnexB(accessUnit))
{
Decode(nal);
}
DecodeUnitsAnnexB(accessUnit);
FinishPicture();
}
/// <summary>
/// Whether decoding can start at this access unit: exactly at an IDR picture; only approximately at a picture whose
/// first slice is an I slice, since the pictures after it may still refer to earlier ones. <paramref name="lengthSize"/>
/// is the size of the NAL length fields, 0 for Annex B.
/// </summary>
public static H264AccessPoint AccessPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
{
var position = 0;
while (true)
{
Range unit;
var more = lengthSize == 0
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
if (!more)
{
return H264AccessPoint.None;
}
var nal = accessUnit[unit];
switch (nal[0] & 0x1F)
{
case 5:
return H264AccessPoint.Idr;
case 1:
try
{
// first_mb_in_slice and slice_type: a few bytes of the header are enough.
var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader();
_ = reader.ReadUe();
return reader.ReadUe(9) % 5 == (int)SliceType.I ? H264AccessPoint.IntraPicture : H264AccessPoint.None;
}
catch (H264Exception)
{
return H264AccessPoint.None;
}
}
}
}
private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
{
var position = 0;
while (NalUnits.NextAnnexB(stream, ref position, out var unit))
{
Decode(NalUnits.Unescape(stream[unit], ref rbsp));
}
}
/// <summary>Finishes the picture being decoded, if any.</summary>
public void Flush() => FinishPicture();
@@ -194,15 +258,64 @@ public sealed partial class H264Decoder
throw new H264Exception("La codifica senza perdita non è gestita.");
}
if (header.FirstMb == 0 || cur is null)
// A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped.
if (header.RedundantPicCnt > 0)
{
return;
}
if (cur is null || picHeader is null || StartsNewPicture(header, nal) || (header.FirstMb == 0 && mbSlice[0] >= 0))
{
FinishPicture();
StartPicture(nal, header, sps);
}
if (picSkipped)
{
return;
}
if (!header.IsIntra && !HasReference())
{
// A P or B slice without any picture to predict from: decoding started away from a random access point
// (a missing index, a damaged stream). Predicting from nothing would give a corrupt frame.
throw new H264Exception("Slice P o B senza immagini di riferimento.");
}
DecodeSliceData(reader, nal, header, sps, pps);
}
/// <summary>The first slice of a new primary picture (§7.4.1.2.4), compared with the first slice of the current one.</summary>
private bool StartsNewPicture(SliceHeader h, NalUnit nal)
{
var p = picHeader!;
if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || (nal.RefIdc == 0) != (picRefIdc == 0)
|| (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId))
{
return true;
}
return activeSps!.PocType switch
{
0 => h.PocLsb != p.PocLsb || h.DeltaPocBottom != p.DeltaPocBottom,
1 => h.DeltaPoc0 != p.DeltaPoc0 || h.DeltaPoc1 != p.DeltaPoc1,
_ => false,
};
}
private bool HasReference()
{
foreach (var p in dpb)
{
if (p.IsReference && !ReferenceEquals(p, cur))
{
return true;
}
}
return false;
}
private void StartPicture(NalUnit nal, SliceHeader header, Sps sps)
{
if (activeSps is null || !ReferenceEquals(activeSps, sps))
@@ -239,6 +352,9 @@ public sealed partial class H264Decoder
sliceCounter = 0;
sliceFilters.Clear();
Array.Fill(mbSlice, -1);
// A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded.
picSkipped = nal.RefIdc == 0 && Wanted is { } wanted && !wanted(cur.DecodeIndex);
}
private Picture NewPicture(Sps sps)
@@ -355,13 +471,16 @@ public sealed partial class H264Decoder
}
}
/// <summary>Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters.</summary>
/// <summary>
/// Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters, and their frame number offset
/// (§8.2.1), which carries the wraps of frame_num to the pictures after the gap. Of a gap longer than the buffer only
/// the last frames can stay references: the earlier ones are counted, never allocated.
/// </summary>
private void FillFrameNumGap(int frameNum, Sps sps)
{
var max = sps.MaxFrameNum;
var missing = ((frameNum - prevRefFrameNum - 1) % max + max) % max;
var keep = Math.Max(1, sps.MaxNumRefFrames);
var first = missing > keep ? (frameNum - keep + max) % max : (prevRefFrameNum + 1) % max;
if (missing > keep)
{
foreach (var p in dpb)
@@ -370,8 +489,24 @@ public sealed partial class H264Decoder
}
}
for (var n = first; n != frameNum; n = (n + 1) % max)
var skipped = missing - keep;
var i = 0;
for (var n = (prevRefFrameNum + 1) % max; n != frameNum; n = (n + 1) % max, i++)
{
if (sps.PocType != 0)
{
// UpdateFrameNumOffset for the inferred frame n (never an IDR picture).
frameNumOffset = prevFrameNum > n ? prevFrameNumOffset + max : prevFrameNumOffset;
prevFrameNumOffset = frameNumOffset;
}
prevRefFrameNum = n;
prevFrameNum = n;
if (i < skipped)
{
continue;
}
var gap = NewPicture(sps);
gap.FrameNum = n;
gap.NonExisting = true;
@@ -381,12 +516,6 @@ public sealed partial class H264Decoder
SlidingWindow(sps, n);
gap.ShortTerm = true;
dpb.Add(gap);
prevRefFrameNum = n;
prevFrameNum = n;
if (sps.PocType != 0)
{
prevFrameNumOffset = frameNumOffset;
}
}
PruneDpb();
@@ -401,7 +530,12 @@ public sealed partial class H264Decoder
var sps = activeSps;
var picture = cur;
Deblock(picture);
var skipped = picSkipped;
picSkipped = false;
if (!skipped)
{
Deblock(picture);
}
if (picRefIdc != 0)
{
@@ -437,7 +571,7 @@ public sealed partial class H264Decoder
haveReference = true;
}
if (Wanted?.Invoke(picture.DecodeIndex) ?? true)
if (!skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true))
{
FrameDecoded?.Invoke(Crop(picture, sps));
}
@@ -6,6 +6,9 @@ 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;
/// <summary>MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks.</summary>
internal const int MaxDpbMbs = 696_320;
internal int ProfileIdc;
internal int LevelIdc;
internal int Id;
@@ -105,6 +108,13 @@ internal sealed class Sps
throw new H264Exception("Immagine più grande di ogni livello H.264.");
}
// The reference frames must fit in the largest buffer of any level (MaxDpbMbs of level 6.2, table A-1; A.3.1
// and A.3.2 bound max_num_ref_frames by it): sixteen frames of the largest size would be 1.4 GB.
if ((long)s.MaxNumRefFrames * s.WidthInMbs * s.HeightInMbs > MaxDpbMbs)
{
throw new H264Exception("Troppe immagini di riferimento per ogni livello H.264.");
}
s.Direct8x8Inference = r.ReadFlag();
if (r.ReadFlag())
{
+118 -69
View File
@@ -129,105 +129,154 @@ internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int L
internal RbspReader Reader() => new(Rbsp, Length, 1);
}
/// <summary>Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units.</summary>
/// <summary>
/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units, one at a time, and
/// removal of their emulation prevention bytes into a buffer the caller keeps: decoding a sample allocates nothing.
/// </summary>
internal static class NalUnits
{
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1).</summary>
/// <summary>Bytes of zero padding a buffer keeps past the payload (see <see cref="RbspReader"/>).</summary>
internal const int Padding = 16;
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer.</summary>
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
{
byte[]? buffer = null;
return Unescape(nal, ref buffer);
}
/// <summary>
/// Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed; the
/// unit is valid until the buffer is used again.
/// </summary>
internal static NalUnit Unescape(ReadOnlySpan<byte> nal, ref byte[]? buffer)
{
if (nal.Length < 1)
{
throw new H264Exception("Unità NAL vuota.");
}
var buffer = new byte[nal.Length + 16];
var count = 0;
var zeros = 0;
for (var i = 0; i < nal.Length; i++)
if (buffer is null || buffer.Length < nal.Length + Padding)
{
var b = nal[i];
if (zeros >= 2 && b == 3)
{
zeros = 0;
continue;
}
buffer[count++] = b;
zeros = b == 0 ? zeros + 1 : 0;
buffer = new byte[Math.Max(nal.Length + Padding, (buffer?.Length ?? 0) * 2)];
}
// Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1.
ReadOnlySpan<byte> pattern = [0, 0, 3];
var target = buffer.AsSpan();
var count = 0;
var rest = nal;
while (true)
{
var i = rest.IndexOf(pattern);
if (i < 0)
{
rest.CopyTo(target[count..]);
count += rest.Length;
break;
}
rest[..(i + 2)].CopyTo(target[count..]);
count += i + 2;
rest = rest[(i + 3)..];
}
target.Slice(count, Padding).Clear();
return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count);
}
/// <summary>The NAL units of an Annex B byte stream (start codes 0x000001 or 0x00000001).</summary>
/// <summary>
/// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from <paramref name="position"/>,
/// which moves past it; false when there is none left.
/// </summary>
internal static bool NextAnnexB(ReadOnlySpan<byte> stream, ref int position, out Range unit)
{
ReadOnlySpan<byte> startCode = [0, 0, 1];
while (position < stream.Length)
{
var found = stream[position..].IndexOf(startCode);
if (found < 0)
{
break;
}
var start = position + found + 3;
var next = start < stream.Length ? stream[start..].IndexOf(startCode) : -1;
var end = next < 0 ? stream.Length : start + next;
position = end;
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
var trimmed = end;
while (trimmed > start && stream[trimmed - 1] == 0)
{
trimmed--;
}
if (trimmed > start)
{
unit = start..trimmed;
return true;
}
}
position = stream.Length;
unit = default;
return false;
}
/// <summary>
/// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from
/// <paramref name="position"/>; false at the end or at a damaged length (what was read stands).
/// </summary>
internal static bool NextLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize, ref int position, out Range unit)
{
unit = default;
if (position + lengthSize > sample.Length)
{
return false;
}
var size = 0;
for (var k = 0; k < lengthSize; k++)
{
size = (size << 8) | sample[position + k];
}
position += lengthSize;
if (size <= 0 || size > sample.Length - position)
{
position = sample.Length;
return false;
}
unit = position..(position + size);
position += size;
return true;
}
/// <summary>The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests).</summary>
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
{
var units = new List<NalUnit>();
var start = -1;
var i = 0;
while (i + 2 < stream.Length)
var position = 0;
while (NextAnnexB(stream, ref position, out var unit))
{
if (stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1)
{
if (start >= 0)
{
AddTrimmed(units, stream[start..i]);
}
i += 3;
start = i;
continue;
}
i++;
}
if (start >= 0 && start < stream.Length)
{
AddTrimmed(units, stream[start..]);
units.Add(Parse(stream[unit]));
}
return units;
}
/// <summary>The NAL units of a sample whose units are each prefixed by a big-endian length.</summary>
/// <summary>The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests).</summary>
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
{
var units = new List<NalUnit>();
var offset = 0;
while (offset + lengthSize <= sample.Length)
var position = 0;
while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
var size = 0;
for (var k = 0; k < lengthSize; k++)
{
size = (size << 8) | sample[offset + k];
}
offset += lengthSize;
if (size <= 0 || size > sample.Length - offset)
{
break; // damaged: keep what was read
}
units.Add(Parse(sample.Slice(offset, size)));
offset += size;
units.Add(Parse(sample[unit]));
}
return units;
}
private static void AddTrimmed(List<NalUnit> units, ReadOnlySpan<byte> nal)
{
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
var end = nal.Length;
while (end > 0 && nal[end - 1] == 0)
{
end--;
}
if (end > 0)
{
units.Add(Parse(nal[..end]));
}
}
}
+5 -1
View File
@@ -23,6 +23,10 @@ internal sealed class SliceHeader
internal int DeltaPocBottom;
internal int DeltaPoc0;
internal int DeltaPoc1;
/// <summary>redundant_pic_cnt: 0 for the primary coded picture, above 0 for a redundant one.</summary>
internal int RedundantPicCnt;
internal bool DirectSpatialMvPred;
internal int NumRefIdxActiveL0;
internal int NumRefIdxActiveL1;
@@ -105,7 +109,7 @@ internal sealed class SliceHeader
if (pps.RedundantPicCntPresent)
{
r.ReadUe(); // redundant_pic_cnt
h.RedundantPicCnt = r.ReadUe(127);
}
if (h.IsB)