using System.Buffers.Binary; namespace Febe.Core.Import; /// What the moov box of an MP4 or QuickTime file says. /// Creation time of the movie header (mvhd), when plausible. /// Duration from mvhd. /// Display width of the first video track (rotation applied). /// Display height of the first video track (rotation applied). public sealed record Mp4Info(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); /// /// Reads creation time, duration and size of MP4, MOV and 3GP files by walking their boxes (spec §9.2: «data di creazione /// dei video»), written by hand. Only box headers are read: the media data (mdat) is skipped with a seek, so the /// cost does not depend on the size of the file. The creation time is seconds since 1904-01-01 UTC; zero and /// implausible values (before 1995 or in the future) are ignored, since many encoders leave it empty. /// public static class Mp4Reader { 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); /// The largest moov box read into memory. private const long MaxMoovBytes = 64L * 1024 * 1024; private const int MaxTopLevelBoxes = 10_000; /// The most child boxes read inside one box (real files have a few dozen). private const int MaxChildBoxes = 10_000; /// Reads a file (read-only). Null when no moov box is found. /// The file. /// Current time: creation times after it (by more than a day) are ignored. public static Mp4Info? ReadFile(string path, DateTimeOffset now) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); return Read(stream, now); } /// Reads a seekable stream from its start. Null when no moov box is found. public static Mp4Info? Read(Stream stream, DateTimeOffset now) { ArgumentNullException.ThrowIfNull(stream); if (!stream.CanSeek) { throw new ArgumentException("Serve un flusso con posizionamento.", nameof(stream)); } Span header = stackalloc byte[16]; long position = 0; var length = stream.Length; for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) { stream.Position = position; if (stream.ReadAtLeast(header[..8], 8, throwOnEndOfStream: false) < 8) { return null; } long size = BinaryPrimitives.ReadUInt32BigEndian(header); var type = header.Slice(4, 4); var headerSize = 8; if (size == 1) { if (stream.ReadAtLeast(header.Slice(8, 8), 8, throwOnEndOfStream: false) < 8) { return null; } size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8)); headerSize = 16; } else if (size == 0) { size = length - position; // to the end of the file } // Compared without adding to the position: a 64-bit size close to 2^63 would overflow the sum and pass. if (size < headerSize || size > length - position + 8) { return null; // damaged } if (type.SequenceEqual("moov"u8)) { var bodyLength = Math.Min(size - headerSize, length - position - headerSize); if (bodyLength <= 0 || bodyLength > MaxMoovBytes) { return null; } var body = new byte[bodyLength]; stream.Position = position + headerSize; stream.ReadExactly(body); return ParseMoov(body, now); } position += size; } return null; } /// Parses the content of a moov box. internal static Mp4Info? ParseMoov(ReadOnlySpan moov, DateTimeOffset now) { DateTimeOffset? created = null; TimeSpan? duration = null; int? width = null, height = null; try { foreach (var (type, start, count) in Children(moov)) { var body = moov.Slice(start, count); if (type == "mvhd") { (created, duration) = ParseMvhd(body, now); } else if (type == "trak" && width is null) { foreach (var (childType, childStart, childCount) in Children(body)) { if (childType == "tkhd" && ParseTkhd(body.Slice(childStart, childCount)) is { } size) { (width, height) = size; } } } } } catch (ArgumentOutOfRangeException) { // A damaged box: keep what was read. } return new Mp4Info(created, duration, width, height); } private static (DateTimeOffset? Created, TimeSpan? Duration) ParseMvhd(ReadOnlySpan body, DateTimeOffset now) { var version = body[0]; ulong creation; uint timescale; ulong duration; if (version == 1) { creation = BinaryPrimitives.ReadUInt64BigEndian(body.Slice(4, 8)); timescale = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(20, 4)); duration = BinaryPrimitives.ReadUInt64BigEndian(body.Slice(24, 8)); } else { creation = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(4, 4)); timescale = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(12, 4)); duration = BinaryPrimitives.ReadUInt32BigEndian(body.Slice(16, 4)); } DateTimeOffset? created = null; if (creation > 0 && creation < (ulong)TimeSpan.FromDays(400 * 365).TotalSeconds) { var instant = Epoch1904.AddSeconds(creation); if (instant >= Earliest && instant <= now.AddDays(1)) { created = instant; } } TimeSpan? length = timescale > 0 && duration > 0 && duration != uint.MaxValue && duration != ulong.MaxValue ? TimeSpan.FromSeconds((double)duration / timescale) : null; return (created, length); } private static (int Width, int Height)? ParseTkhd(ReadOnlySpan body) { // version/flags (4), times and ids (20 or 32), reserved (8), layer, group, volume, reserved (8), matrix (36), width, height. var offset = body[0] == 1 ? 4 + 32 : 4 + 20; offset += 8 + 8; var matrix = body.Slice(offset, 36); var a = BinaryPrimitives.ReadInt32BigEndian(matrix[..4]); var b = BinaryPrimitives.ReadInt32BigEndian(matrix.Slice(4, 4)); offset += 36; var width = (int)(BinaryPrimitives.ReadUInt32BigEndian(body.Slice(offset, 4)) >> 16); var height = (int)(BinaryPrimitives.ReadUInt32BigEndian(body.Slice(offset + 4, 4)) >> 16); if (width <= 0 || height <= 0) { return null; // an audio track } // A rotation of 90 or 270 degrees: the matrix is [0 ±1; ∓1 0] in 16.16 fixed point. var rotated = a == 0 && Math.Abs(b) == 0x10000; return rotated ? (height, width) : (width, height); } /// Child boxes of a box body: type, start and length of each body. private static List<(string Type, int Start, int Length)> Children(ReadOnlySpan data) { var list = new List<(string, int, int)>(); var offset = 0; while (offset + 8 <= data.Length && list.Count < MaxChildBoxes) { long size = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4)); var type = System.Text.Encoding.Latin1.GetString(data.Slice(offset + 4, 4)); var headerSize = 8; if (size == 1) { size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.Slice(offset + 8, 8)); headerSize = 16; } else if (size == 0) { size = data.Length - offset; } // «size > remaining» cannot overflow (unlike «offset + size»), and with «size >= headerSize» it keeps the // offset moving forward: a damaged 64-bit size can neither loop back nor run past the end. if (size < headerSize || size > data.Length - offset) { break; } list.Add((type, offset + headerSize, (int)size - headerSize)); offset += (int)size; } return list; } }