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