Correzioni dopo la revisione del decodificatore H.264, dei lettori FLV e della CI (#58)

- CI: le due prove MVC di FeaturesStillToDo finivano con «da verificare: …», che
  riepilogo-prove.sh contava come saltate: ogni verifica del ramo sarebbe fallita.
  Ora cominciano con «da fare: », e lo script esenta solo le inconclusive di
  FeaturesStillToDo il cui motivo comincia con «da fare: » subito dopo la cornice
  di MSTest (prima bastava la parola in qualunque punto di qualunque prova).
  PipelineTests prova lo script su .trx con le cornici inglese e italiana;
  processo.md, Sviluppo.md e verifica.yml descrivono la categoria.
- Partizionamento dei dati: una partizione B o C sperduta (partizione A persa)
  sovrascriveva il buffer delle partizioni della slice in attesa. Ora slice_id e
  redundant_pic_cnt si leggono prima di copiare, e contano l'ordine A, B, C.
- MVC: le viste tengono insieme al massimo 2 × MaxDpbMbs di immagini, e il
  decodificatore di una vista nuova si tiene solo dopo il controllo dell'SPS di
  sottoinsieme; Wanted vale per ogni vista.
- FLV: senza durata nei metadati la durata arriva alla fine dell'ultimo
  fotogramma, come per MPEG; «solo audio» solo con una prova vera nella testa
  (un onMetaData grande non fa più scartare un video).
- Flussi di conformità: tolti i 48 readme e schede di terzi (decisione di
  Alberto: nel repository solo flussi e MD5).
- Prove nuove: partizioni A perse, limite delle viste e Wanted in MVC, unità di
  estensione troncate, flussi rovinati 4:2:2, 10 bit, 4:0:0, SVC e MVC.
- Commenti sulla provenienza che citano i file di ricostruzione ufficiali e
  §8.7 invece del decodificatore di riferimento; commento di
  ImportEnvironment.VideoProbe aggiornato; righe nuove in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 19:30:45 +01:00
1 parent 6c8b228333
commit cdc3cc11b9
71 files changed
+668 -2223

No files matched your search

+73 -15
View File
@@ -25,6 +25,9 @@ public static class FlvReader
private const long HeadBytes = 32L * 1024 * 1024;
/// <summary>Audio without a single video tag that, at the start of a file, proves it has no video.</summary>
public const int AudioProofMilliseconds = 5000;
/// <summary>Tags looked at back from the end of the file for its last time.</summary>
private const int TailTags = 64;
@@ -37,8 +40,11 @@ public static class FlvReader
start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9;
/// <summary>
/// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, and no
/// video tag is among the tags in <paramref name="head"/>.
/// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, the tags
/// in <paramref name="head"/> hold at least one whole audio tag and no video tag, and they reach far enough to rule
/// video out — the exact end of <paramref name="head"/> (it is the whole file), <see cref="AudioProofMilliseconds"/>
/// of audio, or <see cref="HeadTags"/> tags. Anything less (a head that ends inside a large onMetaData, a few tags, a
/// tag that is not one) proves nothing, and the file stays a video: header flags are often wrong.
/// </summary>
public static bool IsAudioOnly(ReadOnlySpan<byte> head)
{
@@ -48,18 +54,41 @@ public static class FlvReader
}
var position = (long)BinaryPrimitives.ReadUInt32BigEndian(head[5..]) + 4;
for (var tags = 0; position + 11 <= head.Length && tags < HeadTags; tags++)
long? firstAudio = null;
long lastAudio = 0;
var tags = 0;
while (position + 11 <= head.Length && tags < HeadTags)
{
var type = head[(int)position] & 0x1F;
var tag = head.Slice((int)position, 11);
var type = tag[0] & 0x1F;
if (type == 9)
{
return false;
}
position += 11 + ((head[(int)position + 1] << 16) | (head[(int)position + 2] << 8) | head[(int)position + 3]) + 4;
if ((tag[0] & 0xC0) != 0 || type is not (8 or 18))
{
return false; // not a tag: what follows proves nothing
}
var next = position + 11 + ((tag[1] << 16) | (tag[2] << 8) | tag[3]) + 4;
if (next > head.Length)
{
break; // a tag cut by the end of the head is not seen whole
}
if (type == 8)
{
var time = (long)(int)((uint)(tag[7] << 24) | (uint)(tag[4] << 16) | (uint)(tag[5] << 8) | tag[6]);
firstAudio ??= time;
lastAudio = time;
}
tags++;
position = next;
}
return true;
return firstAudio is { } first && (position == head.Length || tags >= HeadTags || lastAudio - first >= AudioProofMilliseconds);
}
/// <summary>Reads a seekable stream from its start.</summary>
@@ -137,9 +166,9 @@ public static class FlvReader
}
}
if (state.MetadataSeconds is null && state.FirstTime is { } first && LastTime(stream, dataOffset + 4L) is { } last && last > first)
if (state.MetadataSeconds is null && state.FirstTime is { } first && EndTime(stream, dataOffset + 4L) is { } end && end > first)
{
state.LastSeconds = (last - first) / 1000.0;
state.LastSeconds = (end - first) / 1000.0;
}
return state.Build();
@@ -281,11 +310,18 @@ public static class FlvReader
}
/// <summary>The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields.</summary>
private static long? LastTime(Stream stream, long firstTag)
/// <summary>
/// The time the file ends, in milliseconds, from the tags at its end (walked back through their PreviousTagSize): the
/// last video tag plus the interval from the video tag before it, that is one frame, as the MPEG reader adds one
/// frame to the last time of its video; the same for audio when the end of the file holds no video tag. Null when
/// the end of the file has no tag to trust.
/// </summary>
private static long? EndTime(Stream stream, long firstTag)
{
Span<byte> buffer = stackalloc byte[11];
var end = stream.Length;
for (var step = 0; step < TailTags && end - 4 >= firstTag; step++)
long? lastVideo = null, previousVideo = null, lastAudio = null, previousAudio = null;
for (var step = 0; step < TailTags && end - 4 >= firstTag && previousVideo is null; step++)
{
stream.Position = end - 4;
stream.ReadExactly(buffer[..4]);
@@ -293,7 +329,7 @@ public static class FlvReader
var start = end - 4 - previous;
if (previous < 11 || start < firstTag)
{
return null; // no PreviousTagSize to trust (a file cut short ends inside a tag)
break; // no PreviousTagSize to trust (a file cut short ends inside a tag)
}
stream.Position = start;
@@ -301,18 +337,40 @@ public static class FlvReader
var size = (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
if (size + 11 != previous || (buffer[0] & 0xC0) != 0)
{
return null;
break;
}
if ((buffer[0] & 0x1F) is 8 or 9)
var time = (long)(int)((uint)(buffer[7] << 24) | (uint)(buffer[4] << 16) | (uint)(buffer[5] << 8) | buffer[6]);
switch (buffer[0] & 0x1F)
{
return (int)((uint)(buffer[7] << 24) | (uint)(buffer[4] << 16) | (uint)(buffer[5] << 8) | buffer[6]);
case 9:
Note(ref lastVideo, ref previousVideo, time);
break;
case 8:
Note(ref lastAudio, ref previousAudio, time);
break;
}
end = start;
}
return null;
return lastVideo is { } video ? video + (video - (previousVideo ?? video))
: lastAudio is { } audio ? audio + (audio - (previousAudio ?? audio))
: null;
// The first time seen walking back is the last of the track, the first earlier one the tag before it (a tag at the
// same time, such as the end of an AVC sequence, is no frame of its own).
static void Note(ref long? last, ref long? before, long time)
{
if (last is null)
{
last = time;
}
else if (before is null && time < last)
{
before = time;
}
}
}
private static byte[] Read(Stream stream, long offset, int count)
+42 -7
View File
@@ -40,6 +40,13 @@ public sealed partial class H264Decoder
/// <summary>A subset SPS with the multiview extension was read: the stream is MVC.</summary>
private bool multiview;
/// <summary>
/// The frame stores of all views together are kept within twice the largest buffer of any level (MaxDpbMbs of level
/// 6.2, table A-1, times the mvcScaleFactor 2 that Annex H applies to the buffer of a multiview stream): a damaged
/// subset SPS that lists up to 1,024 views cannot make the decoder allocate one buffer per view beyond it.
/// </summary>
internal const long MaxAllViewsMbs = 2L * Sps.MaxDpbMbs;
public H264Decoder()
{
}
@@ -52,6 +59,7 @@ public sealed partial class H264Decoder
sequences = root.subsetSequences;
pictures = root.pictures;
FrameDecoded += frame => root.FrameDecoded?.Invoke(frame);
// Wanted is read from the root decoder (see Wanted): a filter set there applies to every view.
}
/// <summary>
@@ -102,6 +110,9 @@ public sealed partial class H264Decoder
}
}
// A view seen for the first time gets a decoder of its own, kept only once its first slice has shown that the
// subset SPS lists the view and that the buffers of all views fit (RegisterView): until then it holds nothing.
var seen = decoder is not null;
if (decoder is null)
{
if (viewDecoders.Count >= 1023)
@@ -110,16 +121,35 @@ public sealed partial class H264Decoder
}
decoder = new H264Decoder(this, id);
viewDecoders.Add(decoder);
}
decoder.anchorPicture = (nal.Rbsp[3] & 4) != 0;
decoder.pendingInterView = (nal.Rbsp[3] & 2) != 0;
decoder.DecodeViewComponentSlice(nal, idr: !nonIdr);
decoder.DecodeViewComponentSlice(nal, idr: !nonIdr, register: !seen);
}
/// <summary>One slice of the view of this decoder: parsed with the subset SPS, decoded like a slice of the base view.</summary>
private void DecodeViewComponentSlice(NalUnit nal, bool idr)
/// <summary>
/// Keeps the decoder of a new view, when the frame stores of the base view and of every view decoded so far, this one
/// included, stay within <see cref="MaxAllViewsMbs"/>: each view holds at most max_num_ref_frames reference frames
/// and the picture being decoded.
/// </summary>
private void RegisterView(H264Decoder decoder, Sps sps)
{
var views = viewDecoders.Count + 2L;
var perView = (long)(Math.Max(1, sps.MaxNumRefFrames) + 1) * sps.WidthInMbs * sps.HeightInMbs;
if (views * perView > MaxAllViewsMbs)
{
throw new H264Exception("Troppe viste per la memoria di ogni livello H.264.");
}
viewDecoders.Add(decoder);
}
/// <summary>
/// One slice of the view of this decoder: parsed with the subset SPS, decoded like a slice of the base view. The first
/// slice of a new view (<paramref name="register"/>) also has the root decoder keep this decoder.
/// </summary>
private void DecodeViewComponentSlice(NalUnit nal, bool idr, bool register)
{
var reader = nal.Reader();
@@ -131,6 +161,11 @@ public sealed partial class H264Decoder
throw new H264Exception("Vista assente dall'SPS di sottoinsieme.");
}
if (register)
{
root!.RegisterView(this, sps);
}
if (header.RedundantPicCnt > 0)
{
return;
@@ -171,10 +206,10 @@ public sealed partial class H264Decoder
}
/// <summary>
/// A picture of the base view that nobody refers to in time may still be needed by the other views of its access
/// unit (inter_view_flag): it is then always reconstructed.
/// A view component that nobody refers to in time may still be needed by the views after it in the same access unit
/// (inter_view_flag): it is then always reconstructed, whatever <see cref="Wanted"/> says.
/// </summary>
private bool NeededByOtherViews => root is null && multiview && DecodeAllViews && pendingInterView;
private bool NeededByOtherViews => (root ?? this) is { multiview: true, DecodeAllViews: true } && pendingInterView;
/// <summary>The view_ids of the inter-view references of list <paramref name="list"/> of the current view component.</summary>
private int[] InterViewRefs(int list)
@@ -65,21 +65,34 @@ public sealed partial class H264Decoder
partitionPending = true;
}
/// <summary>Partition B or C (§7.3.2.10) of the slice waiting in partition A; one of another slice is ignored.</summary>
/// <summary>
/// Partition B or C (§7.3.2.10) of the slice waiting in partition A. One of another slice (its partition A lost),
/// of a redundant picture, a second B or C, or a B after the C (§7.4.1.2.5 puts them in the order A, B, C) is
/// ignored, and never touches the partitions already kept for the waiting slice.
/// </summary>
private void StorePartition(NalUnit nal)
{
if (!partitionPending)
if (!partitionPending || pendingC is not null || (nal.Type == 3 && pendingB is not null))
{
return;
}
// slice_id and redundant_pic_cnt are read from the unit as it came: only a partition of the waiting slice is
// copied, so a stray one cannot overwrite the buffer the reader of an earlier partition still reads.
var probe = nal.Reader();
var sliceId = probe.ReadUe(Sps.MaxFrameMbs - 1);
var redundant = pendingPps!.RedundantPicCntPresent ? probe.ReadUe(127) : 0;
if (sliceId != pendingSliceId || redundant != 0)
{
return;
}
var copy = nal.Type == 3 ? Keep(nal, ref partitionB) : Keep(nal, ref partitionC);
var reader = copy.Reader();
var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1);
var redundant = pendingPps!.RedundantPicCntPresent ? reader.ReadUe(127) : 0;
if (sliceId != pendingSliceId || redundant != 0)
reader.ReadUe(Sps.MaxFrameMbs - 1);
if (pendingPps.RedundantPicCntPresent)
{
return;
reader.ReadUe(127);
}
if (nal.Type == 3)
+13 -3
View File
@@ -81,9 +81,18 @@ public sealed partial class H264Decoder
/// <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.
/// and is not wanted is not reconstructed at all: only its header counts. In an MVC stream decoded with
/// <see cref="DecodeAllViews"/> the same filter applies to every view, each with its own decoding index
/// (<see cref="H264Frame.DecodeIndex"/> counts the view components of a view): when every access unit has all the
/// views, index n of each view is the n-th access unit.
/// </summary>
public Func<long, bool>? Wanted { get; set; }
public Func<long, bool>? Wanted
{
get => root is null ? wanted : root.Wanted;
set => wanted = value;
}
private Func<long, bool>? wanted;
/// <summary>Raised for each decoded frame that <see cref="Wanted"/> accepts, in decoding order.</summary>
public event Action<H264Frame>? FrameDecoded;
@@ -890,7 +899,8 @@ public sealed partial class H264Decoder
if (p.Decoded != 3)
{
// A field without its pair: the rows of the missing field are grey, as the reference decoder writes them.
// A field without its pair: the rows of the missing field are grey (the middle value), since the stream has none
// for them and the decoder does not invent any; H.264 leaves the output of an unpaired field open.
var missing = p.Decoded == 1 ? 1 : 0;
var rowY = width * bps;
for (var r = 0; r < height; r++)
+5 -4
View File
@@ -207,9 +207,10 @@ internal readonly record struct RefEntry(Picture? Pic, int Parity, bool InterVie
}
/// <summary>
/// A decoded frame, cropped, in planar YUV. Up to 8 bits each sample is a byte; above, two bytes, little-endian (as the
/// reference decoders write their files). A monochrome frame (4:0:0) comes with Cb and Cr planes of 4:2:0 size at the
/// middle value 2^(BitDepthChroma − 1), as reference decoders write it too.
/// A decoded frame, cropped, in planar YUV. Up to 8 bits each sample is a byte; above, two bytes, little-endian (the
/// layout of the official reconstruction files of the ITU-T H.264.1 series). A monochrome frame (4:0:0) comes with Cb and
/// Cr planes of 4:2:0 size at the middle value 2^(BitDepthChroma − 1), as the official reconstructions of the monochrome
/// conformance streams hold them. H.264 itself specifies neither layout.
/// </summary>
/// <param name="Width">Luma width after cropping.</param>
/// <param name="Height">Luma height after cropping.</param>
@@ -244,7 +245,7 @@ public sealed record H264Frame(
/// <summary>Sample <paramref name="index"/> of a chroma plane (row × ChromaWidth + column), whatever the bit depth.</summary>
public int ChromaAt(byte[] plane, int index) => BytesPerSample == 2 ? plane[2 * index] | (plane[(2 * index) + 1] << 8) : plane[index];
/// <summary>The frame as one planar buffer (Y, then Cb, then Cr), as reference decoders write it.</summary>
/// <summary>The frame as one planar buffer (Y, then Cb, then Cr), as the official reconstruction files lay it out.</summary>
public byte[] ToPlanar()
{
var buffer = new byte[Y.Length + Cb.Length + Cr.Length];