using System.Buffers.Binary;
namespace Titano.Core.Metadata.Bmff;
/// One ISO-BMFF box header: four-character type, absolute start, total size and header size
/// (8, 16 with a 64-bit size, plus 16 for a uuid user type).
public readonly record struct BmffBox(uint Type, long Start, long Size, int HeaderSize, Guid UserType)
{
public long End => Start + Size;
public long PayloadStart => Start + HeaderSize;
public long PayloadLength => Size - HeaderSize;
public bool Is(string fourCC) => Type == FourCC.From(fourCC);
public override string ToString() => $"{FourCC.Format(Type)} @{Start} ({Size} bytes)";
}
/// Four-character codes as big-endian 32-bit integers.
public static class FourCC
{
public static uint From(ReadOnlySpan code)
{
if (code.Length != 4) throw new ArgumentException("A four-character code has exactly four characters.", nameof(code));
return (uint)(byte)code[0] << 24 | (uint)(byte)code[1] << 16 | (uint)(byte)code[2] << 8 | (byte)code[3];
}
public static string Format(uint code) =>
string.Create(4, code, static (span, c) =>
{
for (var i = 0; i < 4; i++)
{
var b = (char)((c >> (24 - 8 * i)) & 0xFF);
span[i] = b is >= ' ' and <= '~' ? b : '?';
}
});
}
///
/// Fuzz-safe ISO-BMFF box walker over a seekable stream: 32-bit, 64-bit (largesize) and to-end (size 0) boxes,
/// uuid user types, a cap on boxes per container and on descent depth. Only headers are read.
///
public static class BmffReader
{
public const int MaxBoxesPerContainer = 4096;
public const int MaxDepth = 16;
private static readonly uint Uuid = FourCC.From("uuid");
/// Box headers inside [, ). Stops at the first malformed header;
/// a box running past is clamped so truncated files still expose their leading boxes.
public static IReadOnlyList ReadChildren(Stream stream, long start, long end, ICollection? warnings = null)
{
ArgumentNullException.ThrowIfNull(stream);
var boxes = new List();
end = Math.Min(end, stream.Length);
Span h = stackalloc byte[32];
var pos = Math.Max(0, start);
while (pos <= end - 8)
{
if (boxes.Count == MaxBoxesPerContainer)
{
warnings?.Add($"More than {MaxBoxesPerContainer} boxes at {start}; rest ignored");
break;
}
var n = stream.ReadUpTo(pos, h[..(int)Math.Min(h.Length, end - pos)]);
if (n < 8) break;
long size = BinaryPrimitives.ReadUInt32BigEndian(h);
var type = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
var header = 8;
if (size == 1)
{
if (n < 16) break;
size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(h[8..]), long.MaxValue);
header = 16;
}
else if (size == 0)
{
size = end - pos;
}
var userType = Guid.Empty;
if (type == Uuid)
{
if (n < header + 16) break;
userType = new Guid(h.Slice(header, 16), bigEndian: true);
header += 16;
}
if (size < header)
{
warnings?.Add($"Malformed box header at {pos}");
break;
}
if (size > end - pos)
{
warnings?.Add($"Box '{FourCC.Format(type)}' at {pos} runs past its container");
size = end - pos;
}
boxes.Add(new BmffBox(type, pos, size, header, userType));
pos += size;
}
return boxes;
}
/// First box of in , or null.
public static BmffBox? Find(IReadOnlyList boxes, string type)
{
var code = FourCC.From(type);
foreach (var b in boxes)
{
if (b.Type == code) return b;
}
return null;
}
/// Follows a path of plain (non-full) container boxes from 's payload,
/// taking the first match at each level.
public static BmffBox? FindPath(Stream stream, BmffBox parent, params ReadOnlySpan path)
{
if (path.Length > MaxDepth) throw new ArgumentException($"Paths are limited to {MaxDepth} levels.", nameof(path));
BmffBox? current = parent;
foreach (var type in path)
{
if (current is not { } box) return null;
current = Find(ReadChildren(stream, box.PayloadStart, box.End), type);
}
return current;
}
}