WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58)

Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 12:32:33 +01:00
1 parent 697de97ec3
commit 6ffcb1bb18
39 files changed
+4235 -469

No files matched your search

@@ -0,0 +1,678 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// Reader of Matroska and WebM (EBML, RFC 8794, and the Matroska specification, RFC 9559), written from the
/// specifications: segment information, the first video and audio tracks and, when asked, the blocks of the clusters.
/// Elements are read one by one from the stream; the frames are never loaded here.
/// </summary>
public static class MatroskaReader
{
private static readonly DateTimeOffset Epoch2001 = new(2001, 1, 1, 0, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero);
private const uint EbmlId = 0x1A45DFA3;
private const uint SegmentId = 0x18538067;
private const uint InfoId = 0x1549A966;
private const uint TracksId = 0x1654AE6B;
private const uint ClusterId = 0x1F43B675;
private const uint CuesId = 0x1C53BB6B;
private const uint TagsId = 0x1254C367;
private const uint AttachmentsId = 0x1941A469;
private const uint ChaptersId = 0x1043A770;
private const uint SeekHeadId = 0x114D9B74;
private const long UnknownSize = -1;
private const int MaxSamples = 20_000_000;
private const long MaxElementInMemory = 64L * 1024 * 1024;
/// <summary>True when the stream starts with an EBML header.</summary>
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId;
/// <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 before the first cluster.</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
{
ArgumentNullException.ThrowIfNull(stream);
var reader = new Reader(stream);
stream.Position = 0;
var (id, size) = reader.Header();
if (id != EbmlId || size < 0)
{
throw new ContainerException("Intestazione EBML mancante.");
}
var docType = "matroska";
var end = stream.Position + size;
while (stream.Position < end)
{
var (cid, csize) = reader.Header();
if (cid == 0x4282)
{
docType = reader.String(csize);
}
else
{
reader.Skip(csize);
}
}
if (docType is not ("matroska" or "webm"))
{
throw new ContainerException("Documento EBML che non è Matroska.");
}
stream.Position = end;
(id, size) = reader.Header();
while (id != SegmentId)
{
if (size < 0)
{
throw new ContainerException("Segmento Matroska mancante.");
}
reader.Skip(size);
(id, size) = reader.Header();
}
var segmentEnd = size < 0 ? stream.Length : Math.Min(stream.Length, stream.Position + size);
var state = new State();
while (stream.Position < segmentEnd)
{
var elementStart = stream.Position;
if (segmentEnd - elementStart < 2)
{
break;
}
(id, size) = reader.Header();
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
if (bodyEnd > segmentEnd)
{
bodyEnd = segmentEnd; // truncated file
}
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;
}
return state.Build();
}
private static void ParseInfo(Reader reader, long end, State state, DateTimeOffset now)
{
var stream = reader.Stream;
while (stream.Position < end)
{
var (id, size) = reader.Header();
switch (id)
{
case 0x2AD7B1:
state.TimecodeScale = (long)reader.Unsigned(size);
break;
case 0x4489:
state.DurationTicks = reader.Float(size);
break;
case 0x4461:
{
var ns = reader.Signed(size);
var instant = Epoch2001.AddTicks(ns / 100);
if (instant >= Earliest && instant <= now.AddDays(1))
{
state.Created = instant;
}
break;
}
default:
reader.Skip(size);
break;
}
}
}
private static void ParseTracks(Reader reader, long end, State state)
{
var stream = reader.Stream;
while (stream.Position < end)
{
var (id, size) = reader.Header();
if (id != 0xAE)
{
reader.Skip(size);
continue;
}
var entryEnd = stream.Position + size;
var track = new TrackEntry();
while (stream.Position < entryEnd)
{
var (tid, tsize) = reader.Header();
switch (tid)
{
case 0xD7:
track.Number = (long)reader.Unsigned(tsize);
break;
case 0x83:
track.Type = (int)reader.Unsigned(tsize);
break;
case 0x86:
track.CodecId = reader.String(tsize);
break;
case 0x63A2:
track.CodecPrivate = reader.Bytes(tsize);
break;
case 0x23E383:
track.DefaultDuration = (long)reader.Unsigned(tsize);
break;
case 0x55EE: // MaxBlockAdditionID, and others: ignored
reader.Skip(tsize);
break;
case 0xE0:
{
var videoEnd = stream.Position + tsize;
while (stream.Position < videoEnd)
{
var (vid, vsize) = reader.Header();
switch (vid)
{
case 0xB0:
track.Width = (int)reader.Unsigned(vsize);
break;
case 0xBA:
track.Height = (int)reader.Unsigned(vsize);
break;
case 0x7670: // Projection
{
var projectionEnd = stream.Position + vsize;
while (stream.Position < projectionEnd)
{
var (pid, psize) = reader.Header();
if (pid == 0x7675)
{
track.Roll = reader.Float(psize);
}
else
{
reader.Skip(psize);
}
}
break;
}
default:
reader.Skip(vsize);
break;
}
}
break;
}
case 0xE1:
{
var audioEnd = stream.Position + tsize;
while (stream.Position < audioEnd)
{
var (aid, asize) = reader.Header();
switch (aid)
{
case 0xB5:
track.SampleRate = (int)reader.Float(asize);
break;
case 0x9F:
track.Channels = (int)reader.Unsigned(asize);
break;
default:
reader.Skip(asize);
break;
}
}
break;
}
default:
reader.Skip(tsize);
break;
}
}
stream.Position = entryEnd;
if (track.Type == 1 && state.Video is null)
{
state.Video = track;
}
else if (track.Type == 2 && state.Audio is null)
{
state.Audio = track;
}
}
}
private static void ParseCluster(Reader reader, long end, bool unknownSize, State state)
{
var stream = reader.Stream;
long clusterTime = 0;
while (stream.Position < end)
{
var start = stream.Position;
if (end - start < 2)
{
stream.Position = end;
return;
}
var (id, size) = reader.Header();
if (unknownSize && id is ClusterId or CuesId or TagsId or AttachmentsId or ChaptersId or SeekHeadId or InfoId or TracksId)
{
stream.Position = start; // the next top-level element ends a cluster of unknown size
return;
}
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
var bodyEnd = Math.Min(stream.Position + size, end);
switch (id)
{
case 0xE7:
clusterTime = (long)reader.Unsigned(size);
break;
case 0xA3: // SimpleBlock
AddBlock(reader, stream.Position, bodyEnd, clusterTime, simple: true, hasReference: false, state);
break;
case 0xA0: // BlockGroup
{
long blockStart = -1, blockEnd = -1;
var reference = false;
while (stream.Position < bodyEnd)
{
var (gid, gsize) = reader.Header();
if (gid == 0xA1)
{
blockStart = stream.Position;
blockEnd = Math.Min(blockStart + gsize, bodyEnd);
}
else if (gid == 0xFB)
{
reference = true;
}
reader.Skip(gsize);
}
if (blockStart >= 0)
{
AddBlock(reader, blockStart, blockEnd, clusterTime, simple: false, reference, state);
}
break;
}
}
stream.Position = bodyEnd;
}
}
private static void AddBlock(Reader reader, long start, long end, long clusterTime, bool simple, bool hasReference, State state)
{
var stream = reader.Stream;
stream.Position = start;
var track = (long)reader.VintValue();
Span<byte> fixedPart = stackalloc byte[3];
stream.ReadExactly(fixedPart);
var relative = BinaryPrimitives.ReadInt16BigEndian(fixedPart);
var flags = fixedPart[2];
var key = simple ? (flags & 0x80) != 0 : !hasReference;
var target = track == state.Video?.Number ? state.Video : track == state.Audio?.Number ? state.Audio : null;
if (target is null)
{
return;
}
if (target.Samples.Count >= MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
var time = clusterTime + relative;
var lacing = (flags >> 1) & 3;
var dataStart = stream.Position;
if (lacing == 0)
{
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
return;
}
var frames = stream.ReadByte() + 1;
var sizes = new long[frames];
switch (lacing)
{
case 1: // Xiph
for (var i = 0; i < frames - 1; i++)
{
long value = 0;
int b;
do
{
b = stream.ReadByte();
if (b < 0)
{
throw new ContainerException("Blocco Matroska troncato.");
}
value += b;
}
while (b == 255);
sizes[i] = value;
}
break;
case 3: // EBML
{
sizes[0] = (long)reader.VintValue();
for (var i = 1; i < frames - 1; i++)
{
var (raw, length) = reader.VintRaw();
var bias = (1L << ((7 * length) - 1)) - 1;
sizes[i] = sizes[i - 1] + ((long)raw - bias);
}
break;
}
}
var dataBegin = stream.Position;
var total = end - dataBegin;
if (lacing == 2)
{
for (var i = 0; i < frames; i++)
{
sizes[i] = total / frames;
}
}
else
{
long used = 0;
for (var i = 0; i < frames - 1; i++)
{
used += sizes[i];
}
sizes[frames - 1] = total - used;
}
var offset = dataBegin;
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)
{
throw new ContainerException("Blocco Matroska danneggiato.");
}
var t = time + (i * frameDuration);
target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key));
offset += sizes[i];
}
}
private sealed class TrackEntry
{
internal long Number = -1;
internal int Type;
internal string CodecId = string.Empty;
internal byte[]? CodecPrivate;
internal long DefaultDuration;
internal int Width;
internal int Height;
internal double Roll;
internal int SampleRate;
internal int Channels;
internal readonly List<MediaSample> Samples = [];
}
private sealed class State
{
internal long TimecodeScale = 1_000_000;
internal double DurationTicks;
internal DateTimeOffset? Created;
internal TrackEntry? Video;
internal TrackEntry? Audio;
internal MediaContainer Build()
{
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
VideoTrack? video = null;
if (Video is { } v)
{
var samples = v.Samples;
if (samples.Count > 0)
{
// Blocks carry presentation times in decoding order; decoding times are those times sorted.
var times = new long[samples.Count];
for (var i = 0; i < times.Length; i++)
{
times[i] = samples[i].PresentationTime;
}
Array.Sort(times);
for (var i = 0; i < times.Length; i++)
{
samples[i] = samples[i] with { DecodeTime = times[i] };
}
}
var roll = ((int)Math.Round(-v.Roll) % 360 + 360) % 360;
video = new VideoTrack
{
Codec = v.CodecId switch
{
"V_MPEG4/ISO/AVC" => VideoCodec.H264,
"V_MPEGH/ISO/HEVC" => VideoCodec.Hevc,
"V_VP8" => VideoCodec.Vp8,
"V_VP9" => VideoCodec.Vp9,
"V_AV1" => VideoCodec.Av1,
"V_MJPEG" => VideoCodec.Mjpeg,
_ when v.CodecId.StartsWith("V_MPEG4/ISO/", StringComparison.Ordinal) => VideoCodec.Mpeg4Part2,
_ => VideoCodec.Unknown,
},
CodecTag = v.CodecId,
Width = v.Width,
Height = v.Height,
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,
Samples = samples,
};
}
AudioTrack? audio = null;
if (Audio is { } a)
{
audio = new AudioTrack
{
Codec = a.CodecId switch
{
_ when a.CodecId.StartsWith("A_AAC", StringComparison.Ordinal) => AudioCodec.Aac,
"A_MPEG/L3" => AudioCodec.Mp3,
"A_OPUS" => AudioCodec.Opus,
"A_VORBIS" => AudioCodec.Vorbis,
_ when a.CodecId.StartsWith("A_PCM", StringComparison.Ordinal) => AudioCodec.Pcm,
_ => AudioCodec.Unknown,
},
CodecTag = a.CodecId,
SampleRate = a.SampleRate,
Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
Timescale = timescale,
Duration = (long)DurationTicks,
Samples = a.Samples,
};
}
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : null;
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
}
}
/// <summary>EBML primitives over the stream.</summary>
private sealed class Reader(Stream stream)
{
internal Stream Stream => stream;
internal (uint Id, long Size) Header()
{
var first = stream.ReadByte();
if (first <= 0)
{
throw new ContainerException("Elemento EBML non valido.");
}
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
if (length > 4)
{
throw new ContainerException("Identificatore EBML non valido.");
}
var id = (uint)first;
for (var i = 1; i < length; i++)
{
id = (id << 8) | (uint)ReadByteOrThrow();
}
var (raw, sizeLength) = VintRaw();
var allOnes = (1UL << (7 * sizeLength)) - 1;
return (id, raw == allOnes ? UnknownSize : (long)raw);
}
internal (ulong Raw, int Length) VintRaw()
{
var first = ReadByteOrThrow();
if (first == 0)
{
throw new ContainerException("Intero EBML non valido.");
}
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
ulong value = (ulong)(first & (0xFF >> length));
for (var i = 1; i < length; i++)
{
value = (value << 8) | (uint)ReadByteOrThrow();
}
return (value, length);
}
internal ulong VintValue() => VintRaw().Raw;
internal ulong Unsigned(long size)
{
if (size is < 0 or > 8)
{
throw new ContainerException("Intero EBML troppo lungo.");
}
ulong value = 0;
for (var i = 0; i < size; i++)
{
value = (value << 8) | (uint)ReadByteOrThrow();
}
return value;
}
internal long Signed(long size)
{
var value = Unsigned(size);
if (size is > 0 and < 8 && (value & (1UL << (int)((size * 8) - 1))) != 0)
{
value |= ulong.MaxValue << (int)(size * 8);
}
return (long)value;
}
internal double Float(long size)
{
Span<byte> buffer = stackalloc byte[8];
if (size == 4)
{
stream.ReadExactly(buffer[..4]);
return BinaryPrimitives.ReadSingleBigEndian(buffer);
}
if (size == 8)
{
stream.ReadExactly(buffer);
return BinaryPrimitives.ReadDoubleBigEndian(buffer);
}
Skip(size);
return 0;
}
internal string String(long size) => Encoding.UTF8.GetString(Bytes(size)).TrimEnd('\0');
internal byte[] Bytes(long size)
{
if (size < 0 || size > MaxElementInMemory)
{
throw new ContainerException("Elemento Matroska troppo grande.");
}
var data = new byte[size];
stream.ReadExactly(data);
return data;
}
internal void Skip(long size)
{
if (size < 0)
{
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
}
stream.Position += size;
}
private int ReadByteOrThrow()
{
var b = stream.ReadByte();
return b < 0 ? throw new ContainerException("File Matroska troncato.") : b;
}
}
}