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;
/// Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory).
internal const int MaxSamples = 2_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, and fragments only when they alone tell the duration (then only
/// their durations are added up).
///
/// Checked between the top-level boxes (each fragment of a fragmented file).
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var length = stream.Length;
long position = 0;
Span header = stackalloc byte[16];
Movie? movie = null;
string? brand = null;
var pending = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{
ct.ThrowIfCancellationRequested();
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
var headerSize = 8;
if (size == 1)
{
if (position + 16 > length)
{
break;
}
stream.ReadExactly(header.Slice(8, 8));
var wide = BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
size = wide > long.MaxValue ? -1 : (long)wide;
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("ftyp"u8) && brand is null && size - headerSize >= 4)
{
stream.ReadExactly(header[..4]); // the size field is read already: its bytes can hold the brand
brand = System.Text.Encoding.Latin1.GetString(header[..4]);
}
if (type.SequenceEqual("moov"u8) && movie is null)
{
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
foreach (var (start, body) in pending)
{
movie.AddFragment(start, body);
}
pending.Clear();
// Metadata only: a fragmented file whose headers do not tell its duration is read on through its fragments.
if (!samples && !movie.NeedsFragmentsForDuration)
{
break;
}
}
else if (type.SequenceEqual("moof"u8) && (samples || movie is null || movie.NeedsFragmentsForDuration))
{
var body = ReadBody(stream, position + headerSize, size - headerSize);
if (movie is null)
{
pending.Add((position, body)); // fragments before the moov: unusual, but kept
}
else
{
movie.AddFragment(position, body); // at once: the fragments of a long file are never all in memory
}
}
position += size;
}
if (movie is null)
{
throw new ContainerException("Manca il box moov.");
}
return movie.Build(brand);
}
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, long fileLength)
{
var movie = new Movie(samples, fileLength);
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 "udta" or "meta":
movie.HasUserData = true;
break;
case "trak":
movie.TrackCount++;
try
{
movie.ParseTrak(moov, start, count);
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException
or ContainerException)
{
// A damaged track header, edit list or description (often of the audio track): that track is
// dropped, the others are still read.
}
break;
case "mvex":
movie.Fragmented = true;
foreach (var (t, s, c) in Children(moov, start, count))
{
if (t == "trex" && c >= 24)
{
// version/flags, track_ID, default_sample_description_index, then the three defaults
// (ISO/IEC 14496-12 §8.8.3): duration, size, flags.
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)));
}
else if (t == "mehd" && c >= 8)
{
movie.FragmentDuration = moov[s] == 1 && c >= 12
? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(moov.AsSpan(s + 4)), long.MaxValue)
: BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4));
}
}
break;
}
}
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException)
{
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[]? Hvcc;
internal byte[]? Asc;
internal long EditOffset;
internal bool HasEdits;
internal long EmptyEditMovie;
internal long EditSegmentMovie;
internal int EditCount;
internal string? Language;
internal int ObjectType;
internal List Samples = [];
internal long FragmentTime = -1;
}
private sealed class Movie(bool samples, long fileLength)
{
/// The trex defaults of each track: sample duration, size and flags.
internal readonly Dictionary TrackDefaults = [];
private readonly List