Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
696 lines
27 KiB
C#
696 lines
27 KiB
C#
using System.Buffers.Binary;
|
|
using System.Globalization;
|
|
using System.Text;
|
|
using Titano.Core.Video.Bitstream;
|
|
using Titano.Core.Video.Mp4;
|
|
|
|
namespace Titano.Core.Video;
|
|
|
|
/// <summary>One ISO-BMFF box of an inspected file.</summary>
|
|
public sealed record Mp4Box(string Type, long Offset, long Size, int HeaderSize, IReadOnlyList<Mp4Box> Children)
|
|
{
|
|
/// <summary>Payload bytes (only kept for boxes inside moov).</summary>
|
|
internal ReadOnlyMemory<byte> Payload { get; init; }
|
|
|
|
public Mp4Box? Child(string type)
|
|
{
|
|
foreach (var c in Children)
|
|
{
|
|
if (c.Type == type) return c;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>One sample of the inspected video track, in decode order.</summary>
|
|
public readonly record struct Mp4SampleInfo(long Offset, int Size, long DecodeTime, uint Duration, long CompositionOffset, bool IsSync);
|
|
|
|
/// <summary>Result of <see cref="Mp4Inspector.Inspect(Stream)"/>: structure, stream properties and problems found.</summary>
|
|
public sealed class Mp4Report
|
|
{
|
|
private readonly List<string> _errors = [];
|
|
private readonly List<string> _warnings = [];
|
|
|
|
/// <summary>Problems that make the file invalid or unplayable.</summary>
|
|
public IReadOnlyList<string> Errors => _errors;
|
|
|
|
/// <summary>Oddities players usually tolerate.</summary>
|
|
public IReadOnlyList<string> Warnings => _warnings;
|
|
|
|
public bool IsValid => _errors.Count == 0;
|
|
public IReadOnlyList<Mp4Box> Boxes { get; internal set; } = [];
|
|
|
|
/// <summary>Sample entry four-character code ("avc1", "hvc1", "av01"…).</summary>
|
|
public string? SampleEntry { get; internal set; }
|
|
|
|
public VideoCodec? Codec { get; internal set; }
|
|
|
|
/// <summary>RFC 6381 codec string, e.g. "avc1.640029".</summary>
|
|
public string? CodecString { get; internal set; }
|
|
|
|
/// <summary>Coded picture size from the sample entry.</summary>
|
|
public int Width { get; internal set; }
|
|
|
|
public int Height { get; internal set; }
|
|
public int BitDepth { get; internal set; }
|
|
public int FrameCount { get; internal set; }
|
|
public int SyncSampleCount { get; internal set; }
|
|
public uint TimeScale { get; internal set; }
|
|
|
|
/// <summary>Presentation duration in <see cref="TimeScale"/> ticks (edit list applied).</summary>
|
|
public long DurationTicks { get; internal set; }
|
|
|
|
public TimeSpan Duration => TimeScale == 0 ? TimeSpan.Zero : TimeSpan.FromSeconds(DurationTicks / (double)TimeScale);
|
|
public long MediaBytes { get; internal set; }
|
|
|
|
/// <summary>Average bit rate in bits per second.</summary>
|
|
public double AverageBitrate { get; internal set; }
|
|
|
|
/// <summary>moov precedes mdat (progressive download).</summary>
|
|
public bool FastStart { get; internal set; }
|
|
|
|
public bool UsesCo64 { get; internal set; }
|
|
public bool UsesLargeMdat { get; internal set; }
|
|
public bool HasCompositionOffsets { get; internal set; }
|
|
public bool HasEditList { get; internal set; }
|
|
public IReadOnlyList<Mp4SampleInfo> Samples { get; internal set; } = [];
|
|
|
|
internal void Error(string message) => _errors.Add(message);
|
|
|
|
internal void Warning(string message) => _warnings.Add(message);
|
|
|
|
public override string ToString()
|
|
{
|
|
var sb = new StringBuilder();
|
|
var inv = CultureInfo.InvariantCulture;
|
|
sb.AppendLine(inv, $"{CodecString ?? SampleEntry ?? "unknown"} {Width}x{Height} {BitDepth}-bit, {FrameCount} frames ({SyncSampleCount} sync), {Duration.TotalSeconds:0.###} s, {AverageBitrate / 1000:0} kbit/s");
|
|
sb.AppendLine(inv, $"fast start: {FastStart}, co64: {UsesCo64}, 64-bit mdat: {UsesLargeMdat}, composition offsets: {HasCompositionOffsets}, edit list: {HasEditList}");
|
|
foreach (var e in Errors) sb.AppendLine("error: " + e);
|
|
foreach (var w in Warnings) sb.AppendLine("warning: " + w);
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses an MP4 into a box tree and validates the first video track: required boxes, sample-table consistency,
|
|
/// chunk offsets inside mdat, sync start, durations, decoder configuration versus sample entry. Never throws on
|
|
/// malformed input.
|
|
/// </summary>
|
|
public static class Mp4Inspector
|
|
{
|
|
private const int MaxDepth = 16;
|
|
private const int MaxBoxes = 100_000;
|
|
private const long MaxMoovBytes = 256L << 20;
|
|
private const int CheckedSamples = 4;
|
|
private const long MaxSamples = 20_000_000;
|
|
|
|
public static Mp4Report Inspect(string path)
|
|
{
|
|
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.RandomAccess);
|
|
return Inspect(stream);
|
|
}
|
|
|
|
public static Mp4Report Inspect(Stream stream)
|
|
{
|
|
var report = new Mp4Report();
|
|
if (!stream.CanSeek || !stream.CanRead)
|
|
{
|
|
report.Error("stream is not readable and seekable");
|
|
return report;
|
|
}
|
|
try
|
|
{
|
|
Run(stream, report);
|
|
}
|
|
catch (IOException ex)
|
|
{
|
|
report.Error("read failed: " + ex.Message);
|
|
}
|
|
return report;
|
|
}
|
|
|
|
private static void Run(Stream stream, Mp4Report report)
|
|
{
|
|
var length = stream.Length;
|
|
var top = new List<Mp4Box>();
|
|
var mdats = new List<(long Start, long End)>();
|
|
Mp4Box? moov = null;
|
|
long pos = 0;
|
|
var budget = MaxBoxes;
|
|
Span<byte> header = stackalloc byte[16];
|
|
while (pos + 8 <= length && budget-- > 0)
|
|
{
|
|
stream.Position = pos;
|
|
var want = (int)Math.Min(16, length - pos);
|
|
var read = stream.ReadAtLeast(header[..want], want, throwOnEndOfStream: false);
|
|
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
|
|
var type = FourCc(header[4..8]);
|
|
var headerSize = 8;
|
|
if (size == 1)
|
|
{
|
|
if (read < 16)
|
|
{
|
|
report.Error($"box '{type}' at {pos} is truncated");
|
|
break;
|
|
}
|
|
size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(header[8..]), long.MaxValue);
|
|
headerSize = 16;
|
|
if (type == "mdat") report.UsesLargeMdat = true;
|
|
}
|
|
else if (size == 0)
|
|
{
|
|
size = length - pos;
|
|
}
|
|
if (size < headerSize)
|
|
{
|
|
report.Error($"box '{type}' at {pos} has invalid size {size}");
|
|
break;
|
|
}
|
|
if (size > length - pos)
|
|
{
|
|
report.Error($"box '{type}' at {pos} extends past the end of the file ({size} > {length - pos} bytes)");
|
|
size = length - pos;
|
|
}
|
|
|
|
var children = (IReadOnlyList<Mp4Box>)[];
|
|
if (type == "moov")
|
|
{
|
|
if (moov is not null)
|
|
{
|
|
report.Error("more than one moov box");
|
|
}
|
|
else if (size - headerSize > MaxMoovBytes)
|
|
{
|
|
report.Error($"moov is implausibly large ({size} bytes)");
|
|
}
|
|
else
|
|
{
|
|
var data = new byte[size - headerSize];
|
|
stream.Position = pos + headerSize;
|
|
stream.ReadExactly(data);
|
|
children = ParseBoxes(data, 0, data.Length, pos + headerSize, 1, report, ref budget);
|
|
}
|
|
}
|
|
var box = new Mp4Box(type, pos, size, headerSize, children);
|
|
if (type == "moov" && moov is null && children.Count > 0) moov = box;
|
|
if (type == "mdat") mdats.Add((pos + headerSize, pos + size));
|
|
if (type == "moof") report.Warning("fragmented MP4 (moof) is not inspected");
|
|
top.Add(box);
|
|
pos += size;
|
|
}
|
|
if (pos < length && budget > 0) report.Warning($"{length - pos} trailing bytes after the last box");
|
|
report.Boxes = top;
|
|
|
|
if (top.Count == 0 || top[0].Type != "ftyp")
|
|
{
|
|
if (top.Exists(b => b.Type == "ftyp")) report.Warning("ftyp is not the first box");
|
|
else report.Error("ftyp box missing");
|
|
}
|
|
if (mdats.Count == 0) report.Error("mdat box missing");
|
|
if (moov is null)
|
|
{
|
|
report.Error("moov box missing or empty");
|
|
return;
|
|
}
|
|
report.FastStart = mdats.Count > 0 && moov.Offset < mdats[0].Start;
|
|
InspectMovie(stream, moov, mdats, report);
|
|
}
|
|
|
|
private static List<Mp4Box> ParseBoxes(byte[] data, int start, int end, long baseOffset, int depth, Mp4Report report, ref int budget)
|
|
{
|
|
var list = new List<Mp4Box>();
|
|
var pos = start;
|
|
while (end - pos >= 8 && budget-- > 0)
|
|
{
|
|
long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos));
|
|
var type = FourCc(data.AsSpan(pos + 4, 4));
|
|
var headerSize = 8;
|
|
if (size == 1)
|
|
{
|
|
if (end - pos < 16) break;
|
|
size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(pos + 8)), long.MaxValue);
|
|
headerSize = 16;
|
|
}
|
|
else if (size == 0)
|
|
{
|
|
size = end - pos;
|
|
}
|
|
if (size < headerSize || size > end - pos)
|
|
{
|
|
report.Error($"box '{type}' at {baseOffset + pos} overruns its parent");
|
|
return list;
|
|
}
|
|
var payloadStart = pos + headerSize;
|
|
var boxEnd = pos + (int)size;
|
|
var childStart = ChildrenStart(type, payloadStart);
|
|
var children = childStart >= 0 && childStart <= boxEnd && depth < MaxDepth
|
|
? ParseBoxes(data, childStart, boxEnd, baseOffset, depth + 1, report, ref budget)
|
|
: [];
|
|
list.Add(new Mp4Box(type, baseOffset + pos, size, headerSize, children)
|
|
{
|
|
Payload = data.AsMemory(payloadStart, boxEnd - payloadStart),
|
|
});
|
|
pos = boxEnd;
|
|
}
|
|
return list;
|
|
}
|
|
|
|
private static int ChildrenStart(string type, int payload) => type switch
|
|
{
|
|
"moov" or "trak" or "edts" or "mdia" or "minf" or "dinf" or "stbl" or "mvex" => payload,
|
|
"stsd" or "dref" => payload + 8,
|
|
"avc1" or "avc3" or "hvc1" or "hev1" or "av01" => payload + 78,
|
|
_ => -1,
|
|
};
|
|
|
|
private static void InspectMovie(Stream stream, Mp4Box moov, List<(long Start, long End)> mdats, Mp4Report report)
|
|
{
|
|
var mvhd = moov.Child("mvhd");
|
|
if (mvhd is null) report.Error("mvhd missing");
|
|
var movieScale = mvhd is null ? 0u : ReadTimescale(mvhd.Payload.Span, out _);
|
|
|
|
Mp4Box? trak = null;
|
|
foreach (var t in moov.Children)
|
|
{
|
|
if (t.Type == "trak" && Handler(t) == "vide")
|
|
{
|
|
trak = t;
|
|
break;
|
|
}
|
|
}
|
|
if (trak is null)
|
|
{
|
|
report.Error("no video track (trak with hdlr 'vide')");
|
|
return;
|
|
}
|
|
if (trak.Child("tkhd") is null) report.Error("tkhd missing");
|
|
var mdia = trak.Child("mdia");
|
|
var mdhd = mdia?.Child("mdhd");
|
|
var minf = mdia?.Child("minf");
|
|
var stbl = minf?.Child("stbl");
|
|
if (mdhd is null) report.Error("mdhd missing");
|
|
if (minf?.Child("vmhd") is null) report.Error("vmhd missing");
|
|
if (minf?.Child("dinf")?.Child("dref") is null) report.Error("dinf/dref missing");
|
|
if (stbl is null)
|
|
{
|
|
report.Error("stbl missing");
|
|
return;
|
|
}
|
|
long mdhdDuration = 0;
|
|
var mediaScale = mdhd is null ? 0u : ReadTimescale(mdhd.Payload.Span, out mdhdDuration);
|
|
if (mdhd is not null && mediaScale == 0) report.Error("mdhd timescale is zero");
|
|
report.TimeScale = mediaScale;
|
|
|
|
var config = InspectSampleDescription(stbl, report);
|
|
var durations = ReadTimeToSample(stbl, report);
|
|
var sizes = ReadSampleSizes(stbl, report);
|
|
var chunkOffsets = ReadChunkOffsets(stbl, report);
|
|
var samplesPerChunk = ReadSampleToChunk(stbl, chunkOffsets?.Length ?? 0, report);
|
|
if (durations is null || sizes is null || chunkOffsets is null || samplesPerChunk is null) return;
|
|
|
|
long stscTotal = 0;
|
|
foreach (var n in samplesPerChunk) stscTotal += n;
|
|
if (durations.Length != sizes.Length) report.Error($"stts covers {durations.Length} samples, stsz has {sizes.Length}");
|
|
if (stscTotal != sizes.Length) report.Error($"stsc/stco map {stscTotal} samples, stsz has {sizes.Length}");
|
|
var count = sizes.Length;
|
|
report.FrameCount = count;
|
|
if (count == 0)
|
|
{
|
|
report.Error("track has no samples");
|
|
return;
|
|
}
|
|
|
|
var offsets = ReadCompositionOffsets(stbl, count, report);
|
|
var sync = ReadSyncSamples(stbl, count, report);
|
|
report.SyncSampleCount = sync?.Count ?? count;
|
|
if (sync is not null && (sync.Count == 0 || sync[0] != 1)) report.Error("first sample is not a sync sample");
|
|
|
|
var samples = new Mp4SampleInfo[count];
|
|
var index = 0;
|
|
long decode = 0, bytes = 0;
|
|
var syncIndex = 0;
|
|
for (var c = 0; c < chunkOffsets.Length && index < count; c++)
|
|
{
|
|
var offset = chunkOffsets[c];
|
|
var chunkStart = offset;
|
|
for (var s = 0; s < samplesPerChunk[c] && index < count; s++, index++)
|
|
{
|
|
var isSync = sync is null || (syncIndex < sync.Count && sync[syncIndex] == index + 1);
|
|
if (isSync && sync is not null) syncIndex++;
|
|
var duration = index < durations.Length ? durations[index] : 0u;
|
|
samples[index] = new Mp4SampleInfo(offset, (int)Math.Min(sizes[index], int.MaxValue), decode, duration, offsets?[index] ?? 0, isSync);
|
|
offset += sizes[index];
|
|
decode += duration;
|
|
bytes += sizes[index];
|
|
}
|
|
if (!InsideMdat(chunkStart, offset, mdats)) report.Error($"chunk {c + 1} [{chunkStart}, {offset}) lies outside mdat");
|
|
}
|
|
report.Samples = samples;
|
|
report.MediaBytes = bytes;
|
|
|
|
for (var i = 0; i < durations.Length; i++)
|
|
{
|
|
if (durations[i] != 0) continue;
|
|
if (i == durations.Length - 1) report.Warning("last sample has zero duration");
|
|
else report.Error($"sample {i + 1} has zero duration");
|
|
}
|
|
if (mdhd is not null && mdhdDuration != decode) report.Warning($"mdhd duration {mdhdDuration} differs from the sample durations sum {decode}");
|
|
|
|
report.DurationTicks = decode;
|
|
var elst = trak.Child("edts")?.Child("elst");
|
|
if (elst is not null && ReadEditList(elst.Payload.Span, out var segment, out var mediaTime, report))
|
|
{
|
|
report.HasEditList = true;
|
|
if (mediaTime < 0 || (mediaTime >= decode && decode > 0)) report.Error($"edit list media_time {mediaTime} outside the media");
|
|
if (movieScale > 0) report.DurationTicks = (long)Math.Round(segment * (double)mediaScale / movieScale);
|
|
}
|
|
var seconds = mediaScale == 0 ? 0 : report.DurationTicks / (double)mediaScale;
|
|
report.AverageBitrate = seconds > 0 ? bytes * 8 / seconds : 0;
|
|
|
|
if (config is not null) CheckSamplePayloads(stream, samples, config.Codec, report);
|
|
}
|
|
|
|
private static DecoderConfiguration? InspectSampleDescription(Mp4Box stbl, Mp4Report report)
|
|
{
|
|
var stsd = stbl.Child("stsd");
|
|
if (stsd is null || stsd.Children.Count == 0)
|
|
{
|
|
report.Error("stsd missing or empty");
|
|
return null;
|
|
}
|
|
var entry = stsd.Children[0];
|
|
report.SampleEntry = entry.Type;
|
|
var payload = entry.Payload.Span;
|
|
if (payload.Length < 78)
|
|
{
|
|
report.Error($"sample entry '{entry.Type}' truncated");
|
|
return null;
|
|
}
|
|
report.Width = BinaryPrimitives.ReadUInt16BigEndian(payload[24..]);
|
|
report.Height = BinaryPrimitives.ReadUInt16BigEndian(payload[26..]);
|
|
var configBox = entry.Type switch
|
|
{
|
|
"avc1" or "avc3" => "avcC",
|
|
"hvc1" or "hev1" => "hvcC",
|
|
"av01" => "av1C",
|
|
_ => null,
|
|
};
|
|
if (configBox is null)
|
|
{
|
|
report.Warning($"sample entry '{entry.Type}' is not validated");
|
|
return null;
|
|
}
|
|
var box = entry.Child(configBox);
|
|
if (box is null)
|
|
{
|
|
report.Error($"{configBox} missing in '{entry.Type}'");
|
|
return null;
|
|
}
|
|
if (!DecoderConfiguration.TryParse(configBox, box.Payload.Span, out var config, out var error) || config is null)
|
|
{
|
|
report.Error($"{configBox} unparseable: {error}");
|
|
return null;
|
|
}
|
|
if (error is not null) report.Error(error);
|
|
report.Codec = config.Codec;
|
|
report.CodecString = config.CodecString;
|
|
report.BitDepth = config.BitDepth;
|
|
if (config.Width != report.Width || config.Height != report.Height)
|
|
report.Error($"{configBox} declares {config.Width}x{config.Height}, sample entry {report.Width}x{report.Height}");
|
|
return config;
|
|
}
|
|
|
|
/// <summary>Walks the NAL length prefixes / OBU sizes of the first samples and checks the first picture is a random access point.</summary>
|
|
private static void CheckSamplePayloads(Stream stream, Mp4SampleInfo[] samples, VideoCodec codec, Mp4Report report)
|
|
{
|
|
var length = stream.Length;
|
|
for (var i = 0; i < Math.Min(CheckedSamples, samples.Length); i++)
|
|
{
|
|
var s = samples[i];
|
|
if (s.Size <= 0 || s.Offset + s.Size > length || s.Size > 64 << 20) continue;
|
|
var data = new byte[s.Size];
|
|
stream.Position = s.Offset;
|
|
stream.ReadExactly(data);
|
|
if (codec == VideoCodec.Av1)
|
|
{
|
|
var obus = Av1ObuParser.Split(data);
|
|
if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length)
|
|
report.Error($"sample {i + 1}: OBU sizes do not cover the sample");
|
|
continue;
|
|
}
|
|
if (!AnnexBParser.TrySplitLengthPrefixed(data, 4, out var units))
|
|
{
|
|
report.Error($"sample {i + 1}: NAL length prefixes do not cover the sample");
|
|
continue;
|
|
}
|
|
if (i != 0) continue;
|
|
var randomAccess = false;
|
|
foreach (var u in units)
|
|
{
|
|
var h = data[u.Offset];
|
|
randomAccess |= codec == VideoCodec.H264
|
|
? AnnexBParser.H264Type(h) == H264NalUnitType.IdrSlice
|
|
: AnnexBParser.HevcType(h) is >= HevcNalUnitType.BlaWLp and <= HevcNalUnitType.Cra;
|
|
}
|
|
if (!randomAccess) report.Warning("first sample contains no IDR/IRAP picture");
|
|
}
|
|
}
|
|
|
|
private static uint[]? ReadTimeToSample(Mp4Box stbl, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("stts");
|
|
if (box is null)
|
|
{
|
|
report.Error("stts missing");
|
|
return null;
|
|
}
|
|
var p = box.Payload.Span;
|
|
if (!Entries(p, 8, report, "stts", out var entries)) return null;
|
|
var list = new List<uint>();
|
|
for (var i = 0; i < entries; i++)
|
|
{
|
|
var n = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 8)..]);
|
|
var delta = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 8)..]);
|
|
if (list.Count + (long)n > MaxSamples)
|
|
{
|
|
report.Error("stts sample count implausible");
|
|
return null;
|
|
}
|
|
for (var k = 0; k < n; k++) list.Add(delta);
|
|
}
|
|
return [.. list];
|
|
}
|
|
|
|
private static long[]? ReadCompositionOffsets(Mp4Box stbl, int count, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("ctts");
|
|
if (box is null) return null;
|
|
var p = box.Payload.Span;
|
|
if (!Entries(p, 8, report, "ctts", out var entries)) return null;
|
|
var signed = p[0] == 1;
|
|
var result = new long[count];
|
|
long covered = 0;
|
|
for (var i = 0; i < entries; i++)
|
|
{
|
|
var n = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 8)..]);
|
|
var raw = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 8)..]);
|
|
long offset = signed ? (int)raw : raw;
|
|
for (var k = covered; k < Math.Min(count, covered + n); k++) result[k] = offset;
|
|
covered += n;
|
|
}
|
|
report.HasCompositionOffsets = true;
|
|
if (covered != count) report.Error($"ctts covers {covered} of {count} samples");
|
|
return result;
|
|
}
|
|
|
|
private static List<uint>? ReadSyncSamples(Mp4Box stbl, int count, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("stss");
|
|
if (box is null) return null;
|
|
var p = box.Payload.Span;
|
|
if (!Entries(p, 4, report, "stss", out var entries)) return [];
|
|
var list = new List<uint>(entries);
|
|
for (var i = 0; i < entries; i++)
|
|
{
|
|
var s = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 4)..]);
|
|
if (s == 0 || s > count || (list.Count > 0 && s <= list[^1]))
|
|
{
|
|
report.Error($"stss entry {s} out of order or range");
|
|
break;
|
|
}
|
|
list.Add(s);
|
|
}
|
|
return list;
|
|
}
|
|
|
|
private static uint[]? ReadSampleSizes(Mp4Box stbl, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("stsz") ?? stbl.Child("stz2");
|
|
if (box is null)
|
|
{
|
|
report.Error("stsz missing");
|
|
return null;
|
|
}
|
|
var p = box.Payload.Span;
|
|
if (p.Length < 12)
|
|
{
|
|
report.Error($"{box.Type} truncated");
|
|
return null;
|
|
}
|
|
var count = BinaryPrimitives.ReadUInt32BigEndian(p[8..]);
|
|
if (count > MaxSamples)
|
|
{
|
|
report.Error($"{box.Type} sample count implausible");
|
|
return null;
|
|
}
|
|
var constant = box.Type == "stsz" ? BinaryPrimitives.ReadUInt32BigEndian(p[4..]) : 0;
|
|
if (box.Type == "stsz" && constant == 0 && p.Length < 12 + count * 4L)
|
|
{
|
|
report.Error("stsz truncated");
|
|
return null;
|
|
}
|
|
var sizes = new uint[count];
|
|
if (box.Type == "stsz")
|
|
{
|
|
if (constant != 0)
|
|
{
|
|
Array.Fill(sizes, constant);
|
|
return sizes;
|
|
}
|
|
for (var i = 0; i < count; i++) sizes[i] = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 4)..]);
|
|
return sizes;
|
|
}
|
|
var field = p[7];
|
|
if (field is not (4 or 8 or 16) || p.Length < 12 + (count * field + 7) / 8)
|
|
{
|
|
report.Error("stz2 invalid");
|
|
return null;
|
|
}
|
|
for (var i = 0; i < count; i++)
|
|
{
|
|
sizes[i] = field switch
|
|
{
|
|
16 => BinaryPrimitives.ReadUInt16BigEndian(p[(12 + i * 2)..]),
|
|
8 => p[12 + i],
|
|
_ => (uint)((p[12 + i / 2] >> ((i & 1) == 0 ? 4 : 0)) & 0x0F),
|
|
};
|
|
}
|
|
return sizes;
|
|
}
|
|
|
|
private static long[]? ReadChunkOffsets(Mp4Box stbl, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("stco") ?? stbl.Child("co64");
|
|
if (box is null)
|
|
{
|
|
report.Error("stco/co64 missing");
|
|
return null;
|
|
}
|
|
var wide = box.Type == "co64";
|
|
report.UsesCo64 = wide;
|
|
var p = box.Payload.Span;
|
|
if (!Entries(p, wide ? 8 : 4, report, box.Type, out var entries)) return null;
|
|
var offsets = new long[entries];
|
|
for (var i = 0; i < entries; i++)
|
|
{
|
|
offsets[i] = wide
|
|
? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[(8 + i * 8)..]), long.MaxValue)
|
|
: BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 4)..]);
|
|
}
|
|
return offsets;
|
|
}
|
|
|
|
private static uint[]? ReadSampleToChunk(Mp4Box stbl, int chunks, Mp4Report report)
|
|
{
|
|
var box = stbl.Child("stsc");
|
|
if (box is null)
|
|
{
|
|
report.Error("stsc missing");
|
|
return null;
|
|
}
|
|
var p = box.Payload.Span;
|
|
if (!Entries(p, 12, report, "stsc", out var entries)) return null;
|
|
var perChunk = new uint[chunks];
|
|
for (var i = 0; i < entries; i++)
|
|
{
|
|
var first = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 12)..]);
|
|
var samples = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 12)..]);
|
|
var next = i + 1 < entries ? BinaryPrimitives.ReadUInt32BigEndian(p[(8 + (i + 1) * 12)..]) : (uint)chunks + 1;
|
|
if (first == 0 || next <= first || (i == 0 && first != 1))
|
|
{
|
|
report.Error("stsc first_chunk values invalid");
|
|
return null;
|
|
}
|
|
if (BinaryPrimitives.ReadUInt32BigEndian(p[(16 + i * 12)..]) != 1) report.Error("stsc references a sample description other than 1");
|
|
for (var c = first; c < next && c <= chunks; c++) perChunk[c - 1] = samples;
|
|
}
|
|
return perChunk;
|
|
}
|
|
|
|
private static bool ReadEditList(ReadOnlySpan<byte> p, out long segment, out long mediaTime, Mp4Report report)
|
|
{
|
|
segment = mediaTime = 0;
|
|
var wide = p.Length > 0 && p[0] == 1;
|
|
if (!Entries(p, wide ? 20 : 12, report, "elst", out var entries) || entries == 0) return false;
|
|
if (entries > 1) report.Warning($"edit list has {entries} entries; only the first is evaluated");
|
|
segment = wide ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[8..]), long.MaxValue) : BinaryPrimitives.ReadUInt32BigEndian(p[8..]);
|
|
mediaTime = wide ? BinaryPrimitives.ReadInt64BigEndian(p[16..]) : BinaryPrimitives.ReadInt32BigEndian(p[12..]);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>Reads entry_count of a full box and checks the table fits its payload.</summary>
|
|
private static bool Entries(ReadOnlySpan<byte> p, int entrySize, Mp4Report report, string type, out int entries)
|
|
{
|
|
entries = 0;
|
|
if (p.Length < 8)
|
|
{
|
|
report.Error($"{type} truncated");
|
|
return false;
|
|
}
|
|
var n = BinaryPrimitives.ReadUInt32BigEndian(p[4..]);
|
|
if (n > (p.Length - 8) / entrySize)
|
|
{
|
|
report.Error($"{type} declares {n} entries but holds {(p.Length - 8) / entrySize}");
|
|
return false;
|
|
}
|
|
entries = (int)n;
|
|
return true;
|
|
}
|
|
|
|
private static uint ReadTimescale(ReadOnlySpan<byte> p, out long duration)
|
|
{
|
|
duration = 0;
|
|
if (p.Length < 20) return 0;
|
|
if (p[0] == 1)
|
|
{
|
|
if (p.Length < 32) return 0;
|
|
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[24..]), long.MaxValue);
|
|
return BinaryPrimitives.ReadUInt32BigEndian(p[20..]);
|
|
}
|
|
duration = BinaryPrimitives.ReadUInt32BigEndian(p[16..]);
|
|
return BinaryPrimitives.ReadUInt32BigEndian(p[12..]);
|
|
}
|
|
|
|
private static string? Handler(Mp4Box trak)
|
|
{
|
|
var hdlr = trak.Child("mdia")?.Child("hdlr");
|
|
return hdlr is null || hdlr.Payload.Length < 12 ? null : FourCc(hdlr.Payload.Span[8..12]);
|
|
}
|
|
|
|
private static bool InsideMdat(long start, long end, List<(long Start, long End)> mdats)
|
|
{
|
|
foreach (var (s, e) in mdats)
|
|
{
|
|
if (start >= s && end <= e) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private static string FourCc(ReadOnlySpan<byte> bytes)
|
|
{
|
|
Span<char> chars = stackalloc char[4];
|
|
for (var i = 0; i < 4; i++) chars[i] = bytes[i] is >= 0x20 and < 0x7F ? (char)bytes[i] : '?';
|
|
return new string(chars);
|
|
}
|
|
}
|