using System.Buffers.Binary; namespace Febe.Core.Codecs.Containers; /// /// Reader of the ISO base media file format (ISO/IEC 14496-12: MP4, MOV, 3GP), written from the standard: the movie /// header, the first video and audio tracks with their sample tables, and the fragments (moof) of fragmented /// files. Only boxes are read into memory; media data is never loaded here. /// public static class IsoBmffReader { private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); private const long MaxBoxInMemory = 128L * 1024 * 1024; private const int MaxTopLevelBoxes = 1_000_000; private const int MaxSamples = 20_000_000; /// True when the stream starts like an ISO media file (an ftyp, moov, mdat... box). public static bool Looks(ReadOnlySpan start) => start.Length >= 8 && (start.Slice(4, 4).SequenceEqual("ftyp"u8) || start.Slice(4, 4).SequenceEqual("moov"u8) || start.Slice(4, 4).SequenceEqual("mdat"u8) || start.Slice(4, 4).SequenceEqual("wide"u8) || start.Slice(4, 4).SequenceEqual("free"u8) || start.Slice(4, 4).SequenceEqual("skip"u8)); /// Reads a seekable stream from its start. /// The file. /// Current time: later creation times are ignored. /// False to stop at the metadata (no sample tables, no fragments). public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true) { ArgumentNullException.ThrowIfNull(stream); var length = stream.Length; long position = 0; Span header = stackalloc byte[16]; Movie? movie = null; var fragments = new List<(long Start, byte[] Body)>(); for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) { stream.Position = position; stream.ReadExactly(header[..8]); long size = BinaryPrimitives.ReadUInt32BigEndian(header); var headerSize = 8; if (size == 1) { stream.ReadExactly(header.Slice(8, 8)); size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8)); headerSize = 16; } else if (size == 0) { size = length - position; } if (size < headerSize || size > length - position) { if (movie is not null) { break; // a truncated last box (often mdat): what was read stands } throw new ContainerException("Box ISO danneggiato."); } var type = header.Slice(4, 4); if (type.SequenceEqual("moov"u8)) { movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples); if (!samples) { break; } } else if (samples && type.SequenceEqual("moof"u8)) { fragments.Add((position, ReadBody(stream, position + headerSize, size - headerSize))); } position += size; } if (movie is null) { throw new ContainerException("Manca il box moov."); } foreach (var (start, body) in fragments) { movie.AddFragment(start, body); } return movie.Build(); } private static byte[] ReadBody(Stream stream, long offset, long count) { if (count > MaxBoxInMemory) { throw new ContainerException("Box ISO troppo grande."); } var body = new byte[count]; stream.Position = offset; stream.ReadExactly(body); return body; } private static Movie ParseMoov(byte[] moov, DateTimeOffset now, bool samples) { var movie = new Movie(samples); try { foreach (var (type, start, count) in Children(moov, 0, moov.Length)) { var body = moov.AsSpan(start, count); switch (type) { case "mvhd": movie.ParseMvhd(body, now); break; case "trak": movie.ParseTrak(moov, start, count); break; case "mvex": foreach (var (t, s, c) in Children(moov, start, count)) { if (t == "trex" && c >= 24) { var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); movie.TrackDefaults[id] = ( BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)), BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20))); } } break; } } } catch (ArgumentOutOfRangeException) { throw new ContainerException("Box moov danneggiato."); } return movie; } /// Child boxes of the box body data[start..start+count]: type, body start and body length. internal static List<(string Type, int Start, int Length)> Children(byte[] data, int start, int count) { var list = new List<(string, int, int)>(); var offset = start; var end = start + count; while (offset + 8 <= end && list.Count < 100_000) { long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(offset)); var type = System.Text.Encoding.Latin1.GetString(data, offset + 4, 4); var headerSize = 8; if (size == 1) { if (offset + 16 > end) { break; } size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(offset + 8)); headerSize = 16; } else if (size == 0) { size = end - offset; } if (size < headerSize || size > end - offset) { break; } list.Add((type, offset + headerSize, (int)size - headerSize)); offset += (int)size; } return list; } private static int Rotation(ReadOnlySpan matrix) { var a = BinaryPrimitives.ReadInt32BigEndian(matrix); var b = BinaryPrimitives.ReadInt32BigEndian(matrix[4..]); var c = BinaryPrimitives.ReadInt32BigEndian(matrix[12..]); var d = BinaryPrimitives.ReadInt32BigEndian(matrix[16..]); const int One = 0x10000; if (a == 0 && d == 0 && b == One && c == -One) { return 90; } if (a == -One && d == -One && b == 0 && c == 0) { return 180; } if (a == 0 && d == 0 && b == -One && c == One) { return 270; } return 0; } private sealed class Track { internal uint Id; internal string Handler = string.Empty; internal long Timescale; internal long Duration; internal int Rotation; internal int TkhdWidth; internal int TkhdHeight; internal string Format = string.Empty; internal int Width; internal int Height; internal int Channels; internal int SampleRate; internal byte[]? Avcc; internal byte[]? Asc; internal long EditOffset; internal List Samples = []; internal long FragmentTime = -1; } private sealed class Movie(bool samples) { internal readonly Dictionary TrackDefaults = []; private readonly List tracks = []; private DateTimeOffset? created; private long timescale; private long duration; internal void ParseMvhd(ReadOnlySpan body, DateTimeOffset now) { ulong creation; if (body[0] == 1) { creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); } else { creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); if (duration == uint.MaxValue) { duration = 0; } } if (creation > 0 && creation < 400UL * 366 * 86400) { var instant = Epoch1904.AddSeconds(creation); if (instant >= Earliest && instant <= now.AddDays(1)) { created = instant; } } } internal void ParseTrak(byte[] data, int start, int count) { var track = new Track(); foreach (var (type, s, c) in Children(data, start, count)) { var body = data.AsSpan(s, c); switch (type) { case "tkhd": { var v1 = body[0] == 1; track.Id = BinaryPrimitives.ReadUInt32BigEndian(body[(v1 ? 20 : 12)..]); var offset = (v1 ? 36 : 24) + 16; track.Rotation = Rotation(body.Slice(offset, 36)); track.TkhdWidth = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 36)..]) >> 16); track.TkhdHeight = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 40)..]) >> 16); break; } case "edts": foreach (var (t, es, ec) in Children(data, s, c)) { if (t == "elst") { ParseElst(data.AsSpan(es, ec), track); } } break; case "mdia": ParseMdia(data, s, c, track); break; } } tracks.Add(track); } private static void ParseElst(ReadOnlySpan body, Track track) { var v1 = body[0] == 1; var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); var offset = 8; for (var i = 0; i < entries && i < 16; i++) { long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]); offset += v1 ? 20 : 12; if (mediaTime >= 0) { track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero return; } } } private void ParseMdia(byte[] data, int start, int count, Track track) { foreach (var (type, s, c) in Children(data, start, count)) { var body = data.AsSpan(s, c); switch (type) { case "mdhd": if (body[0] == 1) { track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); track.Duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); } else { track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); var d = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); track.Duration = d == uint.MaxValue ? 0 : d; } break; case "hdlr": track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4)); break; case "minf": foreach (var (t, ms, mc) in Children(data, s, c)) { if (t == "stbl") { ParseStbl(data, ms, mc, track); } } break; } } } private void ParseStbl(byte[] data, int start, int count, Track track) { byte[]? stts = null, ctts = null, stsc = null, stsz = null, stco = null, stss = null; var co64 = false; var stz2 = false; foreach (var (type, s, c) in Children(data, start, count)) { switch (type) { case "stsd": ParseStsd(data, s, c, track); break; case "stts": stts = data[s..(s + c)]; break; case "ctts": ctts = data[s..(s + c)]; break; case "stsc": stsc = data[s..(s + c)]; break; case "stsz": stsz = data[s..(s + c)]; break; case "stz2": stsz = data[s..(s + c)]; stz2 = true; break; case "stco": stco = data[s..(s + c)]; break; case "co64": stco = data[s..(s + c)]; co64 = true; break; case "stss": stss = data[s..(s + c)]; break; } } if (!samples || stts is null || stsc is null || stsz is null || stco is null) { return; } BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss); } private static void ParseStsd(byte[] data, int start, int count, Track track) { if (count < 16) { return; } // version/flags, entry count, then the first sample entry. var entry = start + 8; var size = (int)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(entry)); if (size < 16 || entry + size > start + count) { return; } track.Format = System.Text.Encoding.Latin1.GetString(data, entry + 4, 4); var body = entry + 8; var bodyEnd = entry + size; if (track.Handler == "vide" && size >= 8 + 78) { track.Width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 24)); track.Height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 26)); foreach (var (t, s, c) in Children(data, body + 78, bodyEnd - body - 78)) { if (t == "avcC") { track.Avcc = data[s..(s + c)]; } } } else if (track.Handler == "soun" && size >= 8 + 28) { var version = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 8)); track.Channels = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 16)); track.SampleRate = (int)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(body + 24)) >> 16); var children = body + 28 + (version == 1 ? 16 : version == 2 ? 36 : 0); if (children < bodyEnd) { foreach (var (t, s, c) in Children(data, children, bodyEnd - children)) { if (t == "esds") { track.Asc = EsdsConfig(data.AsSpan(s, c)); } } } } } /// The DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 descriptors). private static byte[]? EsdsConfig(ReadOnlySpan body) { var p = 4; // version and flags while (p + 2 <= body.Length) { var tag = body[p++]; var length = 0; for (var i = 0; i < 4 && p < body.Length; i++) { var b = body[p++]; length = (length << 7) | (b & 0x7F); if ((b & 0x80) == 0) { break; } } switch (tag) { case 0x03: // ES_Descriptor { var flags = body[p + 2]; p += 3; if ((flags & 0x80) != 0) { p += 2; } if ((flags & 0x40) != 0) { p += 1 + body[p]; } if ((flags & 0x20) != 0) { p += 2; } break; } case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children p += 13; break; case 0x05: return p + length <= body.Length ? body.Slice(p, length).ToArray() : null; default: p += length; break; } } return null; } private static void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss) { int count; uint fixedSize = 0; var fieldSize = 32; if (stz2) { fieldSize = stsz[7]; count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8)); } else { fixedSize = BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(4)); count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8)); } if (count < 0 || count > MaxSamples) { throw new ContainerException("Troppi campioni."); } int SizeOf(int i) { if (!stz2) { return (int)(fixedSize != 0 ? fixedSize : BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(12 + (i * 4)))); } return fieldSize switch { 4 => (stsz[12 + (i / 2)] >> ((i & 1) == 0 ? 4 : 0)) & 15, 8 => stsz[12 + i], _ => BinaryPrimitives.ReadUInt16BigEndian(stsz.AsSpan(12 + (i * 2))), }; } var chunkCount = (int)BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(4)); long ChunkOffset(int i) => co64 ? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8))) : BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4))); var keys = stss is null ? null : new HashSet(); if (stss is not null) { var n = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4)); for (var i = 0; i < n; i++) { keys!.Add((int)BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))) - 1); } } var list = new List(count); // Decode times (stts) and composition offsets (ctts) run along the samples. var sttsEntries = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(4)); int sttsIndex = 0, sttsLeft = 0; uint delta = 0; var cttsEntries = ctts is null ? 0 : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(4)); var cttsSigned = ctts is not null && ctts[0] == 1; int cttsIndex = 0, cttsLeft = 0; long offsetCt = 0; long dts = 0; var stscEntries = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(4)); var sample = 0; for (var e = 0; e < stscEntries && sample < count; e++) { var firstChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + (e * 12))) - 1; var perChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(12 + (e * 12))); var nextFirst = e + 1 < stscEntries ? (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + ((e + 1) * 12))) - 1 : chunkCount; for (var chunk = firstChunk; chunk < nextFirst && chunk < chunkCount && sample < count; chunk++) { var offset = ChunkOffset(chunk); for (var k = 0; k < perChunk && sample < count; k++) { while (sttsLeft == 0 && sttsIndex < sttsEntries) { sttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(8 + (sttsIndex * 8))); delta = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(12 + (sttsIndex * 8))); sttsIndex++; } while (ctts is not null && cttsLeft == 0 && cttsIndex < cttsEntries) { cttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(8 + (cttsIndex * 8))); offsetCt = cttsSigned ? BinaryPrimitives.ReadInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8))) : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8))); cttsIndex++; } var size = SizeOf(sample); list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys.Contains(sample))); offset += size; dts += delta; sttsLeft = Math.Max(0, sttsLeft - 1); cttsLeft = Math.Max(0, cttsLeft - 1); sample++; } } } track.Samples = list; track.FragmentTime = dts; } /// Adds the samples of one movie fragment (ISO/IEC 14496-12 ยง8.8). internal void AddFragment(long moofStart, byte[] moof) { try { foreach (var (type, s, c) in Children(moof, 0, moof.Length)) { if (type == "traf") { AddTrackFragment(moofStart, moof, s, c); } } } catch (ArgumentOutOfRangeException) { // A damaged fragment: the samples read so far stand. } } private void AddTrackFragment(long moofStart, byte[] data, int start, int count) { Track? track = null; long baseOffset = moofStart; uint defDuration = 0, defSize = 0, defFlags = 0; long? decodeTime = null; foreach (var (type, s, c) in Children(data, start, count)) { var body = data.AsSpan(s, c); switch (type) { case "tfhd": { var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; var id = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); track = tracks.Find(t => t.Id == id); if (TrackDefaults.TryGetValue(id, out var d)) { (defDuration, defSize, defFlags) = (d.Duration, d.Size, 0); } var p = 8; if ((flags & 0x1) != 0) { baseOffset = (long)BinaryPrimitives.ReadUInt64BigEndian(body[p..]); p += 8; } if ((flags & 0x2) != 0) { p += 4; } if ((flags & 0x8) != 0) { defDuration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } if ((flags & 0x10) != 0) { defSize = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } if ((flags & 0x20) != 0) { defFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); } break; } case "tfdt": decodeTime = body[0] == 1 ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[4..]) : BinaryPrimitives.ReadUInt32BigEndian(body[4..]); break; case "trun" when track is not null: { var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; var signed = body[0] == 1; var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]); if (n < 0 || track.Samples.Count + n > MaxSamples) { throw new ContainerException("Troppi campioni."); } var p = 8; var offset = baseOffset; if ((flags & 0x1) != 0) { offset += BinaryPrimitives.ReadInt32BigEndian(body[p..]); p += 4; } uint? firstFlags = null; if ((flags & 0x4) != 0) { firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } var dts = decodeTime ?? Math.Max(0, track.FragmentTime); for (var i = 0; i < n; i++) { var duration = defDuration; var size = defSize; var sampleFlags = i == 0 && firstFlags is { } ff ? ff : defFlags; long ct = 0; if ((flags & 0x100) != 0) { duration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } if ((flags & 0x200) != 0) { size = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } if ((flags & 0x400) != 0) { sampleFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } if ((flags & 0x800) != 0) { ct = signed ? BinaryPrimitives.ReadInt32BigEndian(body[p..]) : BinaryPrimitives.ReadUInt32BigEndian(body[p..]); p += 4; } var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample track.Samples.Add(new MediaSample(offset, (int)size, dts, dts + ct - track.EditOffset, key)); offset += size; dts += duration; } track.FragmentTime = dts; decodeTime = dts; baseOffset = offset; // a later trun of the same traf continues the data break; } } } } internal MediaContainer Build() { var video = tracks.Find(t => t.Handler == "vide"); var audio = tracks.Find(t => t.Handler == "soun"); VideoTrack? v = null; if (video is not null) { v = new VideoTrack { Codec = video.Format switch { "avc1" or "avc3" => VideoCodec.H264, "hvc1" or "hev1" => VideoCodec.Hevc, "vp08" => VideoCodec.Vp8, "vp09" => VideoCodec.Vp9, "av01" => VideoCodec.Av1, "mp4v" => VideoCodec.Mpeg4Part2, "jpeg" or "mjpa" => VideoCodec.Mjpeg, _ => VideoCodec.Unknown, }, CodecTag = video.Format, Width = video.Width > 0 ? video.Width : video.TkhdWidth, Height = video.Height > 0 ? video.Height : video.TkhdHeight, Rotation = video.Rotation, Timescale = video.Timescale > 0 ? video.Timescale : 1, Duration = DurationOf(video), AvcConfiguration = video.Avcc, Samples = video.Samples, }; } AudioTrack? a = null; if (audio is not null) { a = new AudioTrack { Codec = audio.Format switch { "mp4a" => AudioCodec.Aac, ".mp3" => AudioCodec.Mp3, "Opus" => AudioCodec.Opus, "lpcm" or "sowt" or "twos" => AudioCodec.Pcm, _ => AudioCodec.Unknown, }, CodecTag = audio.Format, Channels = audio.Channels, SampleRate = audio.SampleRate, AacConfiguration = audio.Asc, Timescale = audio.Timescale > 0 ? audio.Timescale : 1, Duration = DurationOf(audio), Samples = audio.Samples, }; } TimeSpan? total = timescale > 0 && duration > 0 ? TimeSpan.FromSeconds((double)duration / timescale) : null; if (total is null && v is { Duration: > 0 }) { total = TimeSpan.FromSeconds(v.Seconds(v.Duration)); } return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a }; } private static long DurationOf(Track track) { if (track.FragmentTime > track.Duration) { return track.FragmentTime; // fragmented: the header says 0 } return track.Duration; } } }