Files
Febe/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

1144 lines
47 KiB
C#

using System.Buffers.Binary;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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 (<c>moof</c>) of fragmented
/// files. Only boxes are read into memory; media data is never loaded here.
/// </summary>
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;
/// <summary>Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory).</summary>
internal const int MaxSamples = 2_000_000;
/// <summary>True when the stream starts like an ISO media file (an <c>ftyp</c>, <c>moov</c>, <c>mdat</c>... box).</summary>
public static bool Looks(ReadOnlySpan<byte> 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));
/// <summary>Reads a seekable stream from its start.</summary>
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">
/// 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).
/// </param>
/// <param name="ct">Checked between the top-level boxes (each fragment of a fragmented file).</param>
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<byte> 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;
}
/// <summary>Child boxes of the box body data[start..start+count]: type, body start and body length.</summary>
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<byte> 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<MediaSample> Samples = [];
internal long FragmentTime = -1;
}
private sealed class Movie(bool samples, long fileLength)
{
/// <summary>The <c>trex</c> defaults of each track: sample duration, size and flags.</summary>
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
private readonly List<Track> tracks = [];
private DateTimeOffset? created;
private DateTimeOffset? modified;
private long timescale;
private long duration;
/// <summary>True when the movie has an <c>mvex</c> box: its samples are in fragments.</summary>
internal bool Fragmented;
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
internal long FragmentDuration;
/// <summary>The <c>trak</c> boxes of the movie, of every kind.</summary>
internal int TrackCount;
/// <summary>True when the movie has a <c>udta</c> or <c>meta</c> box.</summary>
internal bool HasUserData;
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
internal bool NeedsFragmentsForDuration =>
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
{
ulong creation;
ulong modification;
if (body[0] == 1)
{
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
modification = BinaryPrimitives.ReadUInt64BigEndian(body[12..]);
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
}
else
{
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
modification = BinaryPrimitives.ReadUInt32BigEndian(body[8..]);
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
if (duration == uint.MaxValue)
{
duration = 0;
}
}
created = Plausible(creation, now);
modified = Plausible(modification, now);
}
private static DateTimeOffset? Plausible(ulong seconds, DateTimeOffset now)
{
if (seconds > 0 && seconds < 400UL * 366 * 86400)
{
var instant = Epoch1904.AddSeconds(seconds);
if (instant >= Earliest && instant <= now.AddDays(1))
{
return instant;
}
}
return null;
}
internal void ParseTrak(byte[] data, int start, int count)
{
var track = new Track();
foreach (var (type, s, c) in Children(data, start, count))
{
var body = data.AsSpan(s, c);
switch (type)
{
case "tkhd":
{
var v1 = body[0] == 1;
track.Id = BinaryPrimitives.ReadUInt32BigEndian(body[(v1 ? 20 : 12)..]);
var offset = (v1 ? 36 : 24) + 16;
track.Rotation = Rotation(body.Slice(offset, 36));
track.TkhdWidth = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 36)..]) >> 16);
track.TkhdHeight = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 40)..]) >> 16);
break;
}
case "edts":
foreach (var (t, es, ec) in Children(data, s, c))
{
if (t == "elst")
{
ParseElst(data.AsSpan(es, ec), track);
}
}
break;
case "mdia":
ParseMdia(data, s, c, track);
break;
}
}
tracks.Add(track);
}
private static void ParseElst(ReadOnlySpan<byte> body, Track track)
{
var v1 = body[0] == 1;
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
var offset = 8;
var leading = true;
for (var i = 0; i < entries && i < 16; i++)
{
var segment = v1 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[offset..]), long.MaxValue / 4) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
var rate = BinaryPrimitives.ReadInt16BigEndian(body[(offset + (v1 ? 16 : 8))..]);
offset += v1 ? 20 : 12;
if (leading && mediaTime < 0)
{
track.EmptyEditMovie += segment; // a delayed start
continue;
}
if (leading)
{
leading = false;
track.HasEdits = true;
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
track.EditSegmentMovie = segment; // and how long it is shown (movie units; 0: to the end)
}
// A rate other than 1 (a slowed or still segment) is not an ordinary edit either.
track.EditCount += rate == 1 ? 1 : 2;
}
if (entries > 16)
{
track.EditCount += 2;
}
}
private void ParseMdia(byte[] data, int start, int count, Track track)
{
foreach (var (type, s, c) in Children(data, start, count))
{
var body = data.AsSpan(s, c);
switch (type)
{
case "mdhd":
if (body[0] == 1)
{
track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
track.Duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
}
else
{
track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
var d = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
track.Duration = d == uint.MaxValue ? 0 : d;
}
track.Language = Language(body[0] == 1 ? body[32..] : body[20..]);
break;
case "hdlr":
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
break;
case "minf":
foreach (var (t, ms, mc) in Children(data, s, c))
{
if (t == "stbl")
{
ParseStbl(data, ms, mc, track);
}
}
break;
}
}
}
private void ParseStbl(byte[] data, int start, int count, Track track)
{
byte[]? stts = null, ctts = null, stsc = null, stsz = null, stco = null, stss = null;
var co64 = false;
var stz2 = false;
foreach (var (type, s, c) in Children(data, start, count))
{
if (!samples && type != "stsd")
{
continue; // metadata only: the tables are not even copied
}
switch (type)
{
case "stsd":
ParseStsd(data, s, c, track);
break;
case "stts":
stts = data[s..(s + c)];
break;
case "ctts":
ctts = data[s..(s + c)];
break;
case "stsc":
stsc = data[s..(s + c)];
break;
case "stsz":
stsz = data[s..(s + c)];
break;
case "stz2":
stsz = data[s..(s + c)];
stz2 = true;
break;
case "stco":
stco = data[s..(s + c)];
break;
case "co64":
stco = data[s..(s + c)];
co64 = true;
break;
case "stss":
stss = data[s..(s + c)];
break;
}
}
if (!samples || stts is null || stsc is null || stsz is null || stco is null)
{
return;
}
try
{
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss);
}
catch (Exception ex) when (ex is ContainerException or ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException)
{
// Damaged tables, or more samples than the limit (QuickTime PCM counts every audio sample): the track
// keeps its description without samples, and the other tracks are still read.
track.Samples = [];
}
}
/// <summary>
/// The ISO 639-2/T code packed in an <c>mdhd</c> (three letters of five bits each); null for «und», for a
/// QuickTime Macintosh language code (below 0x400) or for a damaged value.
/// </summary>
private static string? Language(ReadOnlySpan<byte> field)
{
if (field.Length < 2)
{
return null;
}
var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF;
if (packed < 0x400)
{
return null;
}
Span<char> code = stackalloc char[3];
for (var i = 0; i < 3; i++)
{
var letter = (packed >> (10 - (5 * i))) & 0x1F;
if (letter is < 1 or > 26)
{
return null;
}
code[i] = (char)('a' + letter - 1);
}
var text = new string(code);
return text == "und" ? null : text;
}
private static void ParseStsd(byte[] data, int start, int count, Track track)
{
if (count < 16)
{
return;
}
// version/flags, entry count, then the first sample entry.
var entry = start + 8;
var size = (int)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(entry));
if (size < 16 || entry + size > start + count)
{
return;
}
track.Format = System.Text.Encoding.Latin1.GetString(data, entry + 4, 4);
var body = entry + 8;
var bodyEnd = entry + size;
if (track.Handler == "vide" && size >= 8 + 78)
{
track.Width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 24));
track.Height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 26));
foreach (var (t, s, c) in Children(data, body + 78, bodyEnd - body - 78))
{
if (t == "avcC")
{
track.Avcc = data[s..(s + c)];
}
else if (t == "hvcC")
{
track.Hvcc = data[s..(s + c)];
}
}
}
else if (track.Handler == "soun" && size >= 8 + 28)
{
var version = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 8));
track.Channels = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 16));
track.SampleRate = (int)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(body + 24)) >> 16);
var children = body + 28 + (version == 1 ? 16 : version == 2 ? 36 : 0);
if (children < bodyEnd)
{
foreach (var (t, s, c) in Children(data, children, bodyEnd - children))
{
if (t == "esds")
{
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(s, c));
}
else if (t == "wave" && track.ObjectType == 0)
{
// QuickTime keeps the esds of an mp4a entry inside a wave box (QTFF, sound sample description).
foreach (var (wt, ws, wc) in Children(data, s, c))
{
if (wt == "esds")
{
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(ws, wc));
}
}
}
}
}
}
}
/// <summary>
/// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1
/// descriptors).
/// </summary>
private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan<byte> body)
{
var objectType = 0;
var p = 4; // version and flags
while (p + 2 <= body.Length)
{
var tag = body[p++];
var length = 0;
for (var i = 0; i < 4 && p < body.Length; i++)
{
var b = body[p++];
length = (length << 7) | (b & 0x7F);
if ((b & 0x80) == 0)
{
break;
}
}
switch (tag)
{
case 0x03: // ES_Descriptor
{
if (p + 3 > body.Length)
{
return (objectType, null);
}
var flags = body[p + 2];
p += 3;
if ((flags & 0x80) != 0)
{
p += 2;
}
if ((flags & 0x40) != 0)
{
if (p >= body.Length)
{
return (objectType, null);
}
p += 1 + body[p];
}
if ((flags & 0x20) != 0)
{
p += 2;
}
break;
}
case 0x04: // DecoderConfigDescriptor: objectTypeIndication and the other fixed fields, then the children
if (p < body.Length)
{
objectType = body[p];
}
p += 13;
break;
case 0x05:
return (objectType, p + length <= body.Length ? body.Slice(p, length).ToArray() : null);
default:
p += length;
break;
}
}
return (objectType, null);
}
private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
{
int count;
uint fixedSize = 0;
var fieldSize = 32;
if (stz2)
{
fieldSize = stsz[7];
count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8));
}
else
{
fixedSize = BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(4));
count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8));
}
if (count < 0 || count > MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
// The table must be able to describe that many samples and the samples must fit in the file: a few damaged
// bytes never make the reader allocate more than the file can hold.
var tableBytes = stz2 ? 12 + ((((long)count * fieldSize) + 7) / 8) : fixedSize != 0 ? 12 : 12 + (4L * count);
if (stsz.Length < tableBytes || (fixedSize != 0 && (long)count * fixedSize > fileLength) || (stz2 && fieldSize is not (4 or 8 or 16)))
{
throw new ContainerException("Tabella delle dimensioni danneggiata.");
}
int SizeOf(int i)
{
if (!stz2)
{
return (int)(fixedSize != 0 ? fixedSize : BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(12 + (i * 4))));
}
return fieldSize switch
{
4 => (stsz[12 + (i / 2)] >> ((i & 1) == 0 ? 4 : 0)) & 15,
8 => stsz[12 + i],
_ => BinaryPrimitives.ReadUInt16BigEndian(stsz.AsSpan(12 + (i * 2))),
};
}
var chunkCount = (int)BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(4));
long ChunkOffset(int i) => co64
? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8)))
: BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4)));
// Sync samples (stss, 1-based); without the box every sample is one. At most one flag per sample.
bool[]? keys = null;
if (stss is not null)
{
keys = new bool[count];
var n = Math.Min(BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4)), (uint)Math.Max(0, (stss.Length - 8) / 4));
for (var i = 0; i < n; i++)
{
var number = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4)));
if (number >= 1 && number <= (uint)count)
{
keys[number - 1] = true;
}
}
}
var list = new List<MediaSample>(count);
// Decode times (stts) and composition offsets (ctts) run along the samples.
var sttsEntries = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(4));
int sttsIndex = 0, sttsLeft = 0;
uint delta = 0;
var cttsEntries = ctts is null ? 0 : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(4));
var cttsSigned = ctts is not null && ctts[0] == 1;
int cttsIndex = 0, cttsLeft = 0;
long offsetCt = 0;
long dts = 0;
var stscEntries = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(4));
var sample = 0;
for (var e = 0; e < stscEntries && sample < count; e++)
{
var firstChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + (e * 12))) - 1;
var perChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(12 + (e * 12)));
var nextFirst = e + 1 < stscEntries ? (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + ((e + 1) * 12))) - 1 : chunkCount;
for (var chunk = firstChunk; chunk < nextFirst && chunk < chunkCount && sample < count; chunk++)
{
var offset = ChunkOffset(chunk);
for (var k = 0; k < perChunk && sample < count; k++)
{
while (sttsLeft == 0 && sttsIndex < sttsEntries)
{
sttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(8 + (sttsIndex * 8)));
delta = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(12 + (sttsIndex * 8)));
sttsIndex++;
}
while (ctts is not null && cttsLeft == 0 && cttsIndex < cttsEntries)
{
cttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(8 + (cttsIndex * 8)));
offsetCt = cttsSigned
? BinaryPrimitives.ReadInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8)))
: BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8)));
cttsIndex++;
}
var size = SizeOf(sample);
list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys[sample]));
offset += size;
dts += delta;
sttsLeft = Math.Max(0, sttsLeft - 1);
cttsLeft = Math.Max(0, cttsLeft - 1);
sample++;
}
}
}
track.Samples = list;
track.FragmentTime = dts;
}
/// <summary>Adds the samples of one movie fragment (ISO/IEC 14496-12 §8.8).</summary>
internal void AddFragment(long moofStart, byte[] moof)
{
try
{
foreach (var (type, s, c) in Children(moof, 0, moof.Length))
{
if (type == "traf")
{
AddTrackFragment(moofStart, moof, s, c);
}
}
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException or ContainerException)
{
// A damaged fragment (or one beyond the sample limit): the samples read so far stand.
}
}
private void AddTrackFragment(long moofStart, byte[] data, int start, int count)
{
Track? track = null;
var dataBase = moofStart; // base_data_offset, or the start of the moof (default-base-is-moof, §8.8.7.1)
var nextData = moofStart;
uint defDuration = 0, defSize = 0, defFlags = 0;
long? decodeTime = null;
foreach (var (type, s, c) in Children(data, start, count))
{
var body = data.AsSpan(s, c);
switch (type)
{
case "tfhd":
{
var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF;
var id = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
track = tracks.Find(t => t.Id == id);
if (TrackDefaults.TryGetValue(id, out var d))
{
(defDuration, defSize, defFlags) = d;
}
var p = 8;
if ((flags & 0x1) != 0)
{
var wide = BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
dataBase = wide > (ulong)fileLength ? fileLength : (long)wide;
p += 8;
}
nextData = dataBase;
if ((flags & 0x2) != 0)
{
p += 4;
}
if ((flags & 0x8) != 0)
{
defDuration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if ((flags & 0x10) != 0)
{
defSize = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if ((flags & 0x20) != 0)
{
defFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
}
break;
}
case "tfdt":
decodeTime = body[0] == 1
? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[4..]), long.MaxValue / 2)
: BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
break;
case "trun" when track is not null:
{
var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF;
var signed = body[0] == 1;
var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
var p = 8;
var offset = nextData;
if ((flags & 0x1) != 0)
{
offset = dataBase + BinaryPrimitives.ReadInt32BigEndian(body[p..]); // from the base, not from the run before
p += 4;
}
uint? firstFlags = null;
if ((flags & 0x4) != 0)
{
firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
// The samples either have their fields in the box or take the default size: the box or the
// file bounds how many there can be, before anything is allocated.
var perSample = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1));
var bounded = perSample > 0
? (long)n * perSample <= body.Length - p
: (long)n * Math.Max(1u, defSize) <= fileLength;
if (n < 0 || !bounded || (samples && track.Samples.Count + n > MaxSamples))
{
throw new ContainerException("Troppi campioni.");
}
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
if (!samples)
{
// Metadata only: the fragments are read for the duration, so only durations add up.
var run = RunDuration(body[p..], flags, n, defDuration);
dts = run > (long.MaxValue / 2) - dts ? long.MaxValue / 2 : dts + run;
track.FragmentTime = dts;
decodeTime = dts;
break;
}
for (var i = 0; i < n; i++)
{
var duration = defDuration;
var size = defSize;
var sampleFlags = i == 0 && firstFlags is { } ff ? ff : defFlags;
long ct = 0;
if ((flags & 0x100) != 0)
{
duration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if ((flags & 0x200) != 0)
{
size = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if ((flags & 0x400) != 0)
{
sampleFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if ((flags & 0x800) != 0)
{
ct = signed ? BinaryPrimitives.ReadInt32BigEndian(body[p..]) : BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample
track.Samples.Add(new MediaSample(offset, (int)Math.Min(size, int.MaxValue), dts, dts + ct - track.EditOffset, key));
offset += size;
dts += duration;
}
track.FragmentTime = dts;
decodeTime = dts;
nextData = offset; // a later trun without data_offset continues the data
break;
}
}
}
}
/// <summary>The total duration of the <paramref name="count"/> samples of a trun, from their fields after the header.</summary>
private static long RunDuration(ReadOnlySpan<byte> fields, uint flags, int count, uint defaultDuration)
{
if ((flags & 0x100) == 0)
{
return (long)count * defaultDuration;
}
var stride = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1));
long total = 0;
for (var i = 0; i < count; i++)
{
total += BinaryPrimitives.ReadUInt32BigEndian(fields[(i * stride)..]); // the duration comes first
}
return total;
}
internal MediaContainer Build(string? brand)
{
var video = tracks.Find(t => t.Handler == "vide");
var audio = tracks.Find(t => t.Handler == "soun");
VideoTrack? v = null;
if (video is not null)
{
v = new VideoTrack
{
Codec = video.Format switch
{
"avc1" or "avc3" => VideoCodec.H264,
"hvc1" or "hev1" => VideoCodec.Hevc,
"vp08" => VideoCodec.Vp8,
"vp09" => VideoCodec.Vp9,
"av01" => VideoCodec.Av1,
"mp4v" => VideoCodec.Mpeg4Part2,
"jpeg" or "mjpa" => VideoCodec.Mjpeg,
_ => VideoCodec.Unknown,
},
CodecTag = video.Format,
Width = video.Width > 0 ? video.Width : video.TkhdWidth,
Height = video.Height > 0 ? video.Height : video.TkhdHeight,
Rotation = video.Rotation,
Timescale = video.Timescale > 0 ? video.Timescale : 1,
Duration = DurationOf(video),
AvcConfiguration = video.Avcc,
HevcConfiguration = video.Hvcc,
Samples = video.Samples,
EditMediaTime = video.HasEdits ? video.EditOffset : null,
EmptyEditDuration = EmptyEdit(video),
EditSegmentDuration = EditSegment(video),
EditCount = video.EditCount,
Language = video.Language,
};
}
AudioTrack? a = null;
if (audio is not null)
{
a = new AudioTrack
{
Codec = audio.Format switch
{
// objectTypeIndication 0x69 and 0x6B are MPEG-1/2 audio (MP3) in an mp4a entry (ISO/IEC 14496-1 Table 5).
"mp4a" when audio.ObjectType is 0x69 or 0x6B => AudioCodec.Mp3,
"mp4a" => AudioCodec.Aac,
".mp3" => AudioCodec.Mp3,
"Opus" => AudioCodec.Opus,
"lpcm" or "sowt" or "twos" => AudioCodec.Pcm,
_ => AudioCodec.Unknown,
},
CodecTag = audio.Format,
Channels = audio.Channels,
SampleRate = audio.SampleRate,
AacConfiguration = audio.ObjectType is 0x69 or 0x6B ? null : audio.Asc,
AudioObjectType = audio.ObjectType is 0x69 or 0x6B ? null : AudioTrack.ObjectTypeOf(audio.Asc),
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
Duration = DurationOf(audio),
Samples = audio.Samples,
EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
EmptyEditDuration = EmptyEdit(audio),
EditSegmentDuration = EditSegment(audio),
EditCount = audio.EditCount,
Language = audio.Language,
};
}
var movieDuration = duration > 0 ? duration : FragmentDuration;
TimeSpan? total = timescale > 0 && movieDuration > 0 ? Seconds((double)movieDuration / timescale) : null;
if (total is null && v is { Duration: > 0 })
{
total = Seconds(v.Seconds(v.Duration));
}
return new MediaContainer
{
Format = ContainerFormat.IsoBmff,
CreatedAt = created,
ModifiedAt = modified,
MajorBrand = brand,
TrackCount = TrackCount,
HasUserData = HasUserData,
Duration = total,
Video = v,
Audio = a,
};
}
/// <summary>
/// The segment of the first non-empty edit (movie units) in track units, rounded to the nearest; null when the
/// edit has none (0, as fragmented files write it) or the track has no edit list.
/// </summary>
private long? EditSegment(Track track)
{
if (!track.HasEdits || track.EditSegmentMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
{
return null;
}
var value = (((Int128)track.EditSegmentMovie * track.Timescale) + (timescale / 2)) / timescale;
return value > long.MaxValue / 4 ? null : (long)value;
}
/// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
private long EmptyEdit(Track track)
{
if (track.EmptyEditMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
{
return 0;
}
var value = (((Int128)track.EmptyEditMovie * track.Timescale) + (timescale / 2)) / timescale;
return value > long.MaxValue / 4 ? 0 : (long)value;
}
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
private static TimeSpan? Seconds(double seconds) => seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
private static long DurationOf(Track track)
{
if (track.FragmentTime > track.Duration)
{
return track.FragmentTime; // fragmented: the header says 0
}
return track.Duration;
}
}
}