Files
Febe/src/Febe.Core/Import/Mp4Reader.cs
T

229 lines
9.1 KiB
C#

using System.Buffers.Binary;
namespace Febe.Core.Import;
/// <summary>What the <c>moov</c> box of an MP4 or QuickTime file says.</summary>
/// <param name="CreatedAt">Creation time of the movie header (<c>mvhd</c>), when plausible.</param>
/// <param name="Duration">Duration from <c>mvhd</c>.</param>
/// <param name="Width">Display width of the first video track (rotation applied).</param>
/// <param name="Height">Display height of the first video track (rotation applied).</param>
public sealed record Mp4Info(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary>
/// 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 (<c>mdat</c>) 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.
/// </summary>
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);
/// <summary>The largest <c>moov</c> box read into memory.</summary>
private const long MaxMoovBytes = 64L * 1024 * 1024;
private const int MaxTopLevelBoxes = 10_000;
/// <summary>The most child boxes read inside one box (real files have a few dozen).</summary>
private const int MaxChildBoxes = 10_000;
/// <summary>Reads a file (read-only). Null when no <c>moov</c> box is found.</summary>
/// <param name="path">The file.</param>
/// <param name="now">Current time: creation times after it (by more than a day) are ignored.</param>
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);
}
/// <summary>Reads a seekable stream from its start. Null when no <c>moov</c> box is found.</summary>
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<byte> 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;
}
/// <summary>Parses the content of a <c>moov</c> box.</summary>
internal static Mp4Info? ParseMoov(ReadOnlySpan<byte> 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<byte> 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<byte> 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);
}
/// <summary>Child boxes of a box body: type, start and length of each body.</summary>
private static List<(string Type, int Start, int Length)> Children(ReadOnlySpan<byte> 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;
}
}