using System.Buffers.Binary; using System.Text; namespace Febe.Core.Codecs.Containers; /// /// 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. /// 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 = IsoBmffReader.MaxSamples; private const long MaxElementInMemory = 64L * 1024 * 1024; /// True when the stream starts with an EBML header. public static bool Looks(ReadOnlySpan start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId; /// Reads a seekable stream from its start. /// The file. /// Current time: later creation times are ignored. /// False to stop before the first cluster. /// Checked between the top-level elements. public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { 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 = Math.Min(end, stream.Length); (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) { ct.ThrowIfCancellationRequested(); var elementStart = stream.Position; if (segmentEnd - elementStart < 2) { break; } try { (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 TagsId: state.HasTags = true; 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) { // 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; } } 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: { var ticks = reader.Float(size); state.DurationTicks = double.IsFinite(ticks) && ticks > 0 ? ticks : 0; break; } case 0x4461: { // Nanoseconds from 2001: about ±292 years, always inside the range of a date. 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; } if (size < 0) { throw new ContainerException("Elemento Matroska di lunghezza ignota."); } 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 0x22B59C: track.Language = reader.String(tsize); break; case 0x6D80: // ContentEncodings: the frames are compressed, stripped or encrypted track.Encoded = true; reader.Skip(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 = Math.Min(entryEnd, stream.Length); state.TrackCount++; 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 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 = state.ToUnits(clusterTime + relative); var lacing = (flags >> 1) & 3; var dataStart = stream.Position; if (lacing == 0) { if (end - dataStart is <= 0 or > int.MaxValue) { throw new ContainerException("Blocco Matroska danneggiato."); } target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key)); return; } var count = stream.ReadByte(); if (count < 0 || dataStart >= end) { throw new ContainerException("Blocco Matroska troncato."); } var frames = count + 1; Span sizes = stackalloc 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 ? target.DefaultDuration / state.UnitNanoseconds : 0; for (var i = 0; i < frames; i++) { if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end) { throw new ContainerException("Blocco Matroska danneggiato."); } var t = time + (i * frameDuration); if (sizes[i] == 0) { continue; // an empty frame has nothing to decode (and costs no memory) } 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 string? Language; internal bool Encoded; internal readonly List Samples = []; } private sealed class State { internal long TimecodeScale = 1_000_000; internal double DurationTicks; internal DateTimeOffset? Created; internal TrackEntry? Video; internal TrackEntry? Audio; /// Every TrackEntry of the file. internal int TrackCount; /// True when the segment has a Tags element. internal bool HasTags; /// Nanoseconds of one unit of the sample times; fixed by the first block, 0 before. private long unit; internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0; /// /// 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. /// 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; } } /// TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value. private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000; /// Units of in a tick (at least 1, should Info come after the first block). private long Factor => Math.Max(1, Scale / UnitNanoseconds); /// A time in TimecodeScale ticks as a time in units of . 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 = 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) { 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, HevcConfiguration = v.CodecId == "V_MPEGH/ISO/HEVC" ? v.CodecPrivate : null, Timescale = timescale, Duration = trackUnits, Samples = samples, Language = Language(v.Language), Encoded = v.Encoded, }; } AudioTrack? audio = null; if (Audio is { } a) { var asc = a.CodecId == "A_AAC" ? a.CodecPrivate : a.CodecId.StartsWith("A_AAC/", StringComparison.Ordinal) ? LegacyAacConfig(a) : null; 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 = asc, AudioObjectType = AudioTrack.ObjectTypeOf(asc), Timescale = timescale, Duration = trackUnits, Samples = a.Samples, Language = Language(a.Language), Encoded = a.Encoded, }; } var seconds = DurationTicks * TimecodeScale / 1e9; TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio, TrackCount = TrackCount, HasUserData = HasTags, }; } /// A three-letter ISO 639-2 language; null for «und», absent or malformed. private static string? Language(string? code) => code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null; /// /// The AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) of a track with an old codec ID that names the profile /// («A_AAC/MPEG4/LC», «A_AAC/MPEG2/MAIN», «…/SBR»...) instead of carrying the configuration in CodecPrivate: /// object type, sampling frequency index (or the explicit frequency), channel configuration, then a /// GASpecificConfig of zeros (1024-sample frames, no core coder, no extension). /// private static byte[]? LegacyAacConfig(TrackEntry track) { if (track.CodecPrivate is { Length: >= 2 }) { return track.CodecPrivate; } var profile = track.CodecId[(track.CodecId.LastIndexOf('/') + 1)..]; var objectType = profile switch { "MAIN" => 1, "LC" or "SBR" => 2, // SBR is signalled implicitly: the core rate in SamplingFrequency "SSR" => 3, "LTP" => 4, _ => 0, }; if (objectType == 0 || track.SampleRate <= 0 || track.Channels is < 1 or > 7) { return null; } int[] rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; var index = Array.IndexOf(rates, track.SampleRate); var bits = new List<(int Value, int Count)> { (objectType, 5) }; if (index >= 0) { bits.Add((index, 4)); } else { bits.Add((15, 4)); bits.Add((track.SampleRate & 0xFFFFFF, 24)); } bits.Add((track.Channels, 4)); bits.Add((0, 3)); var total = bits.Sum(b => b.Count); var config = new byte[(total + 7) / 8]; var position = 0; foreach (var (value, count) in bits) { for (var i = count - 1; i >= 0; i--, position++) { if (((value >> i) & 1) != 0) { config[position / 8] |= (byte)(0x80 >> (position % 8)); } } } return config; } } /// EBML primitives over the stream. 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 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."); } if (size > stream.Length - stream.Position) { throw new ContainerException("File Matroska troncato."); // before allocating what the file cannot hold } 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."); } // Past the end of a truncated or damaged file the reading simply ends there. stream.Position = size > stream.Length - stream.Position ? stream.Length : stream.Position + size; } private int ReadByteOrThrow() { var b = stream.ReadByte(); return b < 0 ? throw new ContainerException("File Matroska troncato.") : b; } } }