WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58)
Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
697de97ec3
commit
6ffcb1bb18
39 files changed
+4235
-469
No files matched your search
@@ -0,0 +1,385 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF <c>AVIX</c> parts),
|
||||
/// written from the format description: the main header, the first video and audio streams and the chunks of the
|
||||
/// <c>movi</c> lists in file order. Key frames come from the <c>idx1</c> index when there is one.
|
||||
/// </summary>
|
||||
public static class AviReader
|
||||
{
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const int MaxHeaderBytes = 16 * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts like an AVI file.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var state = new State();
|
||||
long position = 0;
|
||||
var length = stream.Length;
|
||||
Span<byte> header = stackalloc byte[12];
|
||||
var first = true;
|
||||
while (position + 12 <= length)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header);
|
||||
if (!header[..4].SequenceEqual("RIFF"u8))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);
|
||||
var form = header.Slice(8, 4);
|
||||
if (first && !form.SequenceEqual("AVI "u8))
|
||||
{
|
||||
throw new ContainerException("Non è un file AVI.");
|
||||
}
|
||||
|
||||
var end = Math.Min(length, position + 8 + size);
|
||||
ParseList(stream, position + 12, end, state, samples, now, depth: 0);
|
||||
if (!samples)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
first = false;
|
||||
position = position + 8 + size + (size & 1);
|
||||
}
|
||||
|
||||
if (!state.HaveHeader)
|
||||
{
|
||||
throw new ContainerException("Manca l'intestazione AVI.");
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
private static void ParseList(Stream stream, long start, long end, State state, bool samples, DateTimeOffset now, int depth)
|
||||
{
|
||||
Span<byte> header = stackalloc byte[12];
|
||||
var position = start;
|
||||
while (position + 8 <= end)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header[..8]);
|
||||
var id = Encoding.Latin1.GetString(header[..4]);
|
||||
var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);
|
||||
var body = position + 8;
|
||||
var next = body + size + (size & 1);
|
||||
if (next > end)
|
||||
{
|
||||
next = end; // truncated
|
||||
size = (uint)Math.Max(0, end - body);
|
||||
}
|
||||
|
||||
if (id == "LIST" && size >= 4)
|
||||
{
|
||||
stream.ReadExactly(header.Slice(8, 4));
|
||||
var type = Encoding.Latin1.GetString(header.Slice(8, 4));
|
||||
if (type == "movi" && !samples)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == "strl")
|
||||
{
|
||||
state.StreamIndex++;
|
||||
}
|
||||
|
||||
if (depth < 4 && type is "hdrl" or "strl" or "movi" or "rec " or "odml")
|
||||
{
|
||||
state.InMovi |= type == "movi";
|
||||
ParseList(stream, body + 4, body + size, state, samples, now, depth + 1);
|
||||
if (type == "movi")
|
||||
{
|
||||
state.InMovi = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (state.InMovi)
|
||||
{
|
||||
AddChunk(id, body, (int)size, state);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case "avih" when size >= 40:
|
||||
{
|
||||
var data = Read(stream, body, (int)size);
|
||||
state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data);
|
||||
state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16));
|
||||
state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32));
|
||||
state.Height = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(36));
|
||||
state.HaveHeader = true;
|
||||
break;
|
||||
}
|
||||
|
||||
case "strh" when size >= 36:
|
||||
{
|
||||
var data = Read(stream, body, (int)size);
|
||||
var type = Encoding.Latin1.GetString(data, 0, 4);
|
||||
var handler = Encoding.Latin1.GetString(data, 4, 4);
|
||||
var scale = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(20));
|
||||
var rate = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24));
|
||||
var frames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32));
|
||||
if (type == "vids" && state.VideoStream < 0)
|
||||
{
|
||||
state.VideoStream = state.StreamIndex - 1;
|
||||
state.VideoHandler = handler;
|
||||
(state.VideoScale, state.VideoRate, state.VideoLength) = (scale, rate, frames);
|
||||
}
|
||||
else if (type == "auds" && state.AudioStream < 0)
|
||||
{
|
||||
state.AudioStream = state.StreamIndex - 1;
|
||||
(state.AudioScale, state.AudioRate) = (scale, rate);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "strf":
|
||||
{
|
||||
var data = Read(stream, body, (int)Math.Min(size, 4096));
|
||||
if (state.StreamIndex - 1 == state.VideoStream && data.Length >= 20)
|
||||
{
|
||||
state.VideoWidth = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
|
||||
state.VideoHeight = Math.Abs(BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(8)));
|
||||
state.Compression = Encoding.Latin1.GetString(data, 16, 4);
|
||||
}
|
||||
else if (state.StreamIndex - 1 == state.AudioStream && data.Length >= 16)
|
||||
{
|
||||
state.AudioFormat = BinaryPrimitives.ReadUInt16LittleEndian(data);
|
||||
state.Channels = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(2));
|
||||
state.SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4));
|
||||
if (data.Length >= 18)
|
||||
{
|
||||
var extra = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(16));
|
||||
if (extra > 0 && 18 + extra <= data.Length)
|
||||
{
|
||||
state.AudioExtra = data[18..(18 + extra)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "IDIT" when size is > 0 and < 128:
|
||||
state.Created = ParseDate(Encoding.ASCII.GetString(Read(stream, body, (int)size)), now);
|
||||
break;
|
||||
case "idx1" when samples:
|
||||
state.Index = Read(stream, body, (int)Math.Min(size, MaxHeaderBytes * 8L));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Read(Stream stream, long offset, int count)
|
||||
{
|
||||
if (count > MaxHeaderBytes * 8)
|
||||
{
|
||||
throw new ContainerException("Intestazione AVI troppo grande.");
|
||||
}
|
||||
|
||||
var data = new byte[count];
|
||||
stream.Position = offset;
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void AddChunk(string id, long body, int size, State state)
|
||||
{
|
||||
if (id.Length != 4 || !char.IsAsciiDigit(id[0]) || !char.IsAsciiDigit(id[1]))
|
||||
{
|
||||
return; // JUNK, ix## indexes and the like
|
||||
}
|
||||
|
||||
var stream = (id[0] - '0') * 10 + (id[1] - '0');
|
||||
if (state.Chunks.Count >= MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
if (stream == state.VideoStream && (id[2..] is "dc" or "db"))
|
||||
{
|
||||
state.Chunks.Add((body, size));
|
||||
}
|
||||
else if (stream == state.AudioStream && id[2..] == "wb")
|
||||
{
|
||||
state.AudioChunks.Add((body, size));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
|
||||
private static DateTimeOffset? ParseDate(string text, DateTimeOffset now)
|
||||
{
|
||||
var value = text.Trim('\0', ' ', '\r', '\n');
|
||||
foreach (var format in new[] { "ddd MMM dd HH:mm:ss yyyy", "ddd MMM d HH:mm:ss yyyy", "yyyy:MM:dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss" })
|
||||
{
|
||||
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var local)
|
||||
&& local.Year >= 1995)
|
||||
{
|
||||
var instant = new DateTimeOffset(DateTime.SpecifyKind(local, DateTimeKind.Unspecified), TimeSpan.Zero);
|
||||
return instant <= now.AddDays(1) ? instant : null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
internal bool HaveHeader;
|
||||
internal bool InMovi;
|
||||
internal int StreamIndex;
|
||||
internal uint MicroSecondsPerFrame;
|
||||
internal uint TotalFrames;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal int VideoStream = -1;
|
||||
internal int AudioStream = -1;
|
||||
internal string VideoHandler = string.Empty;
|
||||
internal string Compression = string.Empty;
|
||||
internal uint VideoScale;
|
||||
internal uint VideoRate;
|
||||
internal uint VideoLength;
|
||||
internal int VideoWidth;
|
||||
internal int VideoHeight;
|
||||
internal uint AudioScale;
|
||||
internal uint AudioRate;
|
||||
internal int AudioFormat;
|
||||
internal int Channels;
|
||||
internal int SampleRate;
|
||||
internal byte[]? AudioExtra;
|
||||
internal DateTimeOffset? Created;
|
||||
internal byte[]? Index;
|
||||
internal readonly List<(long Offset, int Size)> Chunks = [];
|
||||
internal readonly List<(long Offset, int Size)> AudioChunks = [];
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
// Frame rate: the stream header first (rate / scale frames per second), then the main header.
|
||||
long timescale = 1000;
|
||||
long frameTicks = 40;
|
||||
if (VideoRate > 0 && VideoScale > 0)
|
||||
{
|
||||
timescale = VideoRate;
|
||||
frameTicks = VideoScale;
|
||||
}
|
||||
else if (MicroSecondsPerFrame > 0)
|
||||
{
|
||||
timescale = 1_000_000;
|
||||
frameTicks = MicroSecondsPerFrame;
|
||||
}
|
||||
|
||||
var keys = KeyFrames();
|
||||
var samples = new List<MediaSample>(Chunks.Count);
|
||||
var n = 0;
|
||||
for (var i = 0; i < Chunks.Count; i++)
|
||||
{
|
||||
var (offset, size) = Chunks[i];
|
||||
if (size == 0)
|
||||
{
|
||||
n++; // a dropped frame keeps its time slot
|
||||
continue;
|
||||
}
|
||||
|
||||
var t = n * frameTicks;
|
||||
samples.Add(new MediaSample(offset, size, t, t, keys is null || keys.Contains(i)));
|
||||
n++;
|
||||
}
|
||||
|
||||
var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant();
|
||||
var frames = VideoLength > 0 ? VideoLength : TotalFrames;
|
||||
var video = VideoStream < 0 ? null : new VideoTrack
|
||||
{
|
||||
Codec = tag switch
|
||||
{
|
||||
"H264" or "X264" or "AVC1" or "DAVC" or "VSSH" => VideoCodec.H264,
|
||||
"HEVC" or "H265" or "HVC1" => VideoCodec.Hevc,
|
||||
"MJPG" => VideoCodec.Mjpeg,
|
||||
"XVID" or "DIVX" or "DX50" or "FMP4" or "MP4V" => VideoCodec.Mpeg4Part2,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = Compression.Length == 4 ? Compression : VideoHandler,
|
||||
Width = VideoWidth > 0 ? VideoWidth : Width,
|
||||
Height = VideoHeight > 0 ? VideoHeight : Height,
|
||||
AnnexB = true,
|
||||
Timescale = timescale,
|
||||
Duration = frames * frameTicks,
|
||||
Samples = samples,
|
||||
};
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (AudioStream >= 0)
|
||||
{
|
||||
var audioSamples = new List<MediaSample>(AudioChunks.Count);
|
||||
foreach (var (offset, size) in AudioChunks)
|
||||
{
|
||||
audioSamples.Add(new MediaSample(offset, size, 0, 0, true));
|
||||
}
|
||||
|
||||
audio = new AudioTrack
|
||||
{
|
||||
Codec = AudioFormat switch
|
||||
{
|
||||
0x55 => AudioCodec.Mp3,
|
||||
0xFF or 0x1600 or 0x706D => AudioCodec.Aac,
|
||||
1 => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = AudioFormat.ToString("X4", CultureInfo.InvariantCulture),
|
||||
Channels = Channels,
|
||||
SampleRate = SampleRate,
|
||||
AacConfiguration = AudioFormat == 0xFF ? AudioExtra : null,
|
||||
Timescale = Math.Max(1, SampleRate),
|
||||
Samples = audioSamples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
}
|
||||
|
||||
/// <summary>Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index.</summary>
|
||||
private HashSet<int>? KeyFrames()
|
||||
{
|
||||
if (Index is null || VideoStream < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var keys = new HashSet<int>();
|
||||
var n = 0;
|
||||
for (var p = 0; p + 16 <= Index.Length; p += 16)
|
||||
{
|
||||
var id = Index.AsSpan(p, 4);
|
||||
if (!char.IsAsciiDigit((char)id[0]) || (id[0] - '0') * 10 + (id[1] - '0') != VideoStream || id[2] != 'd')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((BinaryPrimitives.ReadUInt32LittleEndian(Index.AsSpan(p + 4)) & 0x10) != 0)
|
||||
{
|
||||
keys.Add(n);
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
|
||||
return n == Chunks.Count ? keys : null; // an index that does not match the chunks is ignored
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary>
|
||||
public static class ContainerReader
|
||||
{
|
||||
/// <summary>The format of a file from its first bytes; null when it is none of those read here.</summary>
|
||||
public static ContainerFormat? Detect(ReadOnlySpan<byte> start)
|
||||
{
|
||||
if (MatroskaReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Matroska;
|
||||
}
|
||||
|
||||
if (AviReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Avi;
|
||||
}
|
||||
|
||||
return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
|
||||
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated).
|
||||
/// </summary>
|
||||
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
Span<byte> start = stackalloc byte[16];
|
||||
stream.Position = 0;
|
||||
var read = stream.ReadAtLeast(start, start.Length, throwOnEndOfStream: false);
|
||||
stream.Position = 0;
|
||||
return Detect(start[..read]) switch
|
||||
{
|
||||
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples),
|
||||
ContainerFormat.Avi => AviReader.Read(stream, now, samples),
|
||||
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Reads a file (read-only, shared); null when its format is not recognised.</summary>
|
||||
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
using var stream = OpenRead(path);
|
||||
return Read(stream, now, samples);
|
||||
}
|
||||
|
||||
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
|
||||
public static FileStream OpenRead(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess);
|
||||
|
||||
/// <summary>The bytes of a sample, read into <paramref name="buffer"/> (grown when needed).</summary>
|
||||
public static ReadOnlySpan<byte> ReadSample(Stream stream, in MediaSample sample, ref byte[] buffer)
|
||||
{
|
||||
if (sample.Size < 0 || sample.Offset < 0 || sample.Offset + sample.Size > stream.Length)
|
||||
{
|
||||
throw new ContainerException("Campione fuori dal file.");
|
||||
}
|
||||
|
||||
if (buffer.Length < sample.Size)
|
||||
{
|
||||
buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)];
|
||||
}
|
||||
|
||||
stream.Position = sample.Offset;
|
||||
stream.ReadExactly(buffer, 0, sample.Size);
|
||||
return buffer.AsSpan(0, sample.Size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,842 @@
|
||||
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;
|
||||
private const int MaxSamples = 20_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, no fragments).</param>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var length = stream.Length;
|
||||
long position = 0;
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
Movie? movie = null;
|
||||
var fragments = new List<(long Start, byte[] Body)>();
|
||||
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header[..8]);
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||
var headerSize = 8;
|
||||
if (size == 1)
|
||||
{
|
||||
stream.ReadExactly(header.Slice(8, 8));
|
||||
size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
|
||||
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("moov"u8))
|
||||
{
|
||||
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples);
|
||||
if (!samples)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (samples && type.SequenceEqual("moof"u8))
|
||||
{
|
||||
fragments.Add((position, ReadBody(stream, position + headerSize, size - headerSize)));
|
||||
}
|
||||
|
||||
position += size;
|
||||
}
|
||||
|
||||
if (movie is null)
|
||||
{
|
||||
throw new ContainerException("Manca il box moov.");
|
||||
}
|
||||
|
||||
foreach (var (start, body) in fragments)
|
||||
{
|
||||
movie.AddFragment(start, body);
|
||||
}
|
||||
|
||||
return movie.Build();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var movie = new Movie(samples);
|
||||
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 "trak":
|
||||
movie.ParseTrak(moov, start, count);
|
||||
break;
|
||||
case "mvex":
|
||||
foreach (var (t, s, c) in Children(moov, start, count))
|
||||
{
|
||||
if (t == "trex" && c >= 24)
|
||||
{
|
||||
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)));
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
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[]? Asc;
|
||||
internal long EditOffset;
|
||||
internal List<MediaSample> Samples = [];
|
||||
internal long FragmentTime = -1;
|
||||
}
|
||||
|
||||
private sealed class Movie(bool samples)
|
||||
{
|
||||
internal readonly Dictionary<uint, (uint Description, uint Duration, uint Size)> TrackDefaults = [];
|
||||
private readonly List<Track> tracks = [];
|
||||
private DateTimeOffset? created;
|
||||
private long timescale;
|
||||
private long duration;
|
||||
|
||||
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
|
||||
{
|
||||
ulong creation;
|
||||
if (body[0] == 1)
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
||||
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
||||
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
||||
if (duration == uint.MaxValue)
|
||||
{
|
||||
duration = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (creation > 0 && creation < 400UL * 366 * 86400)
|
||||
{
|
||||
var instant = Epoch1904.AddSeconds(creation);
|
||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||
{
|
||||
created = instant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
for (var i = 0; i < entries && i < 16; i++)
|
||||
{
|
||||
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
|
||||
offset += v1 ? 20 : 12;
|
||||
if (mediaTime >= 0)
|
||||
{
|
||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss);
|
||||
}
|
||||
|
||||
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 (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.Asc = EsdsConfig(data.AsSpan(s, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary>
|
||||
private static byte[]? EsdsConfig(ReadOnlySpan<byte> body)
|
||||
{
|
||||
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
|
||||
{
|
||||
var flags = body[p + 2];
|
||||
p += 3;
|
||||
if ((flags & 0x80) != 0)
|
||||
{
|
||||
p += 2;
|
||||
}
|
||||
|
||||
if ((flags & 0x40) != 0)
|
||||
{
|
||||
p += 1 + body[p];
|
||||
}
|
||||
|
||||
if ((flags & 0x20) != 0)
|
||||
{
|
||||
p += 2;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children
|
||||
p += 13;
|
||||
break;
|
||||
case 0x05:
|
||||
return p + length <= body.Length ? body.Slice(p, length).ToArray() : null;
|
||||
default:
|
||||
p += length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static 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.");
|
||||
}
|
||||
|
||||
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)));
|
||||
|
||||
var keys = stss is null ? null : new HashSet<int>();
|
||||
if (stss is not null)
|
||||
{
|
||||
var n = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4));
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
keys!.Add((int)BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))) - 1);
|
||||
}
|
||||
}
|
||||
|
||||
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.Contains(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 (ArgumentOutOfRangeException)
|
||||
{
|
||||
// A damaged fragment: the samples read so far stand.
|
||||
}
|
||||
}
|
||||
|
||||
private void AddTrackFragment(long moofStart, byte[] data, int start, int count)
|
||||
{
|
||||
Track? track = null;
|
||||
long baseOffset = 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.Duration, d.Size, 0);
|
||||
}
|
||||
|
||||
var p = 8;
|
||||
if ((flags & 0x1) != 0)
|
||||
{
|
||||
baseOffset = (long)BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
|
||||
p += 8;
|
||||
}
|
||||
|
||||
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)BinaryPrimitives.ReadUInt64BigEndian(body[4..]) : 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..]);
|
||||
if (n < 0 || track.Samples.Count + n > MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
var p = 8;
|
||||
var offset = baseOffset;
|
||||
if ((flags & 0x1) != 0)
|
||||
{
|
||||
offset += BinaryPrimitives.ReadInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
uint? firstFlags = null;
|
||||
if ((flags & 0x4) != 0)
|
||||
{
|
||||
firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
|
||||
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)size, dts, dts + ct - track.EditOffset, key));
|
||||
offset += size;
|
||||
dts += duration;
|
||||
}
|
||||
|
||||
track.FragmentTime = dts;
|
||||
decodeTime = dts;
|
||||
baseOffset = offset; // a later trun of the same traf continues the data
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
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,
|
||||
Samples = video.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
AudioTrack? a = null;
|
||||
if (audio is not null)
|
||||
{
|
||||
a = new AudioTrack
|
||||
{
|
||||
Codec = audio.Format switch
|
||||
{
|
||||
"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.Asc,
|
||||
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
|
||||
Duration = DurationOf(audio),
|
||||
Samples = audio.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? total = timescale > 0 && duration > 0 ? TimeSpan.FromSeconds((double)duration / timescale) : null;
|
||||
if (total is null && v is { Duration: > 0 })
|
||||
{
|
||||
total = TimeSpan.FromSeconds(v.Seconds(v.Duration));
|
||||
}
|
||||
|
||||
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
|
||||
}
|
||||
|
||||
private static long DurationOf(Track track)
|
||||
{
|
||||
if (track.FragmentTime > track.Duration)
|
||||
{
|
||||
return track.FragmentTime; // fragmented: the header says 0
|
||||
}
|
||||
|
||||
return track.Duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of Matroska and WebM (EBML, RFC 8794, and the Matroska specification, RFC 9559), written from the
|
||||
/// specifications: segment information, the first video and audio tracks and, when asked, the blocks of the clusters.
|
||||
/// Elements are read one by one from the stream; the frames are never loaded here.
|
||||
/// </summary>
|
||||
public static class MatroskaReader
|
||||
{
|
||||
private static readonly DateTimeOffset Epoch2001 = new(2001, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private const uint EbmlId = 0x1A45DFA3;
|
||||
private const uint SegmentId = 0x18538067;
|
||||
private const uint InfoId = 0x1549A966;
|
||||
private const uint TracksId = 0x1654AE6B;
|
||||
private const uint ClusterId = 0x1F43B675;
|
||||
private const uint CuesId = 0x1C53BB6B;
|
||||
private const uint TagsId = 0x1254C367;
|
||||
private const uint AttachmentsId = 0x1941A469;
|
||||
private const uint ChaptersId = 0x1043A770;
|
||||
private const uint SeekHeadId = 0x114D9B74;
|
||||
private const long UnknownSize = -1;
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const long MaxElementInMemory = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts with an EBML header.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId;
|
||||
|
||||
/// <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 before the first cluster.</param>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var reader = new Reader(stream);
|
||||
stream.Position = 0;
|
||||
var (id, size) = reader.Header();
|
||||
if (id != EbmlId || size < 0)
|
||||
{
|
||||
throw new ContainerException("Intestazione EBML mancante.");
|
||||
}
|
||||
|
||||
var docType = "matroska";
|
||||
var end = stream.Position + size;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (cid, csize) = reader.Header();
|
||||
if (cid == 0x4282)
|
||||
{
|
||||
docType = reader.String(csize);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip(csize);
|
||||
}
|
||||
}
|
||||
|
||||
if (docType is not ("matroska" or "webm"))
|
||||
{
|
||||
throw new ContainerException("Documento EBML che non è Matroska.");
|
||||
}
|
||||
|
||||
stream.Position = end;
|
||||
(id, size) = reader.Header();
|
||||
while (id != SegmentId)
|
||||
{
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Segmento Matroska mancante.");
|
||||
}
|
||||
|
||||
reader.Skip(size);
|
||||
(id, size) = reader.Header();
|
||||
}
|
||||
|
||||
var segmentEnd = size < 0 ? stream.Length : Math.Min(stream.Length, stream.Position + size);
|
||||
var state = new State();
|
||||
while (stream.Position < segmentEnd)
|
||||
{
|
||||
var elementStart = stream.Position;
|
||||
if (segmentEnd - elementStart < 2)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
(id, size) = reader.Header();
|
||||
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
|
||||
if (bodyEnd > segmentEnd)
|
||||
{
|
||||
bodyEnd = segmentEnd; // truncated file
|
||||
}
|
||||
|
||||
switch (id)
|
||||
{
|
||||
case InfoId:
|
||||
ParseInfo(reader, bodyEnd, state, now);
|
||||
break;
|
||||
case TracksId:
|
||||
ParseTracks(reader, bodyEnd, state);
|
||||
break;
|
||||
case ClusterId:
|
||||
if (!samples)
|
||||
{
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
ParseCluster(reader, bodyEnd, size < 0, state);
|
||||
continue; // the position is already past the cluster
|
||||
default:
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
stream.Position = bodyEnd;
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
private static void ParseInfo(Reader reader, long end, State state, DateTimeOffset now)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (id, size) = reader.Header();
|
||||
switch (id)
|
||||
{
|
||||
case 0x2AD7B1:
|
||||
state.TimecodeScale = (long)reader.Unsigned(size);
|
||||
break;
|
||||
case 0x4489:
|
||||
state.DurationTicks = reader.Float(size);
|
||||
break;
|
||||
case 0x4461:
|
||||
{
|
||||
var ns = reader.Signed(size);
|
||||
var instant = Epoch2001.AddTicks(ns / 100);
|
||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||
{
|
||||
state.Created = instant;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(size);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ParseTracks(Reader reader, long end, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (id, size) = reader.Header();
|
||||
if (id != 0xAE)
|
||||
{
|
||||
reader.Skip(size);
|
||||
continue;
|
||||
}
|
||||
|
||||
var entryEnd = stream.Position + size;
|
||||
var track = new TrackEntry();
|
||||
while (stream.Position < entryEnd)
|
||||
{
|
||||
var (tid, tsize) = reader.Header();
|
||||
switch (tid)
|
||||
{
|
||||
case 0xD7:
|
||||
track.Number = (long)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x83:
|
||||
track.Type = (int)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x86:
|
||||
track.CodecId = reader.String(tsize);
|
||||
break;
|
||||
case 0x63A2:
|
||||
track.CodecPrivate = reader.Bytes(tsize);
|
||||
break;
|
||||
case 0x23E383:
|
||||
track.DefaultDuration = (long)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x55EE: // MaxBlockAdditionID, and others: ignored
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
case 0xE0:
|
||||
{
|
||||
var videoEnd = stream.Position + tsize;
|
||||
while (stream.Position < videoEnd)
|
||||
{
|
||||
var (vid, vsize) = reader.Header();
|
||||
switch (vid)
|
||||
{
|
||||
case 0xB0:
|
||||
track.Width = (int)reader.Unsigned(vsize);
|
||||
break;
|
||||
case 0xBA:
|
||||
track.Height = (int)reader.Unsigned(vsize);
|
||||
break;
|
||||
case 0x7670: // Projection
|
||||
{
|
||||
var projectionEnd = stream.Position + vsize;
|
||||
while (stream.Position < projectionEnd)
|
||||
{
|
||||
var (pid, psize) = reader.Header();
|
||||
if (pid == 0x7675)
|
||||
{
|
||||
track.Roll = reader.Float(psize);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip(psize);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(vsize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 0xE1:
|
||||
{
|
||||
var audioEnd = stream.Position + tsize;
|
||||
while (stream.Position < audioEnd)
|
||||
{
|
||||
var (aid, asize) = reader.Header();
|
||||
switch (aid)
|
||||
{
|
||||
case 0xB5:
|
||||
track.SampleRate = (int)reader.Float(asize);
|
||||
break;
|
||||
case 0x9F:
|
||||
track.Channels = (int)reader.Unsigned(asize);
|
||||
break;
|
||||
default:
|
||||
reader.Skip(asize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stream.Position = entryEnd;
|
||||
if (track.Type == 1 && state.Video is null)
|
||||
{
|
||||
state.Video = track;
|
||||
}
|
||||
else if (track.Type == 2 && state.Audio is null)
|
||||
{
|
||||
state.Audio = track;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ParseCluster(Reader reader, long end, bool unknownSize, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
long clusterTime = 0;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var start = stream.Position;
|
||||
if (end - start < 2)
|
||||
{
|
||||
stream.Position = end;
|
||||
return;
|
||||
}
|
||||
|
||||
var (id, size) = reader.Header();
|
||||
if (unknownSize && id is ClusterId or CuesId or TagsId or AttachmentsId or ChaptersId or SeekHeadId or InfoId or TracksId)
|
||||
{
|
||||
stream.Position = start; // the next top-level element ends a cluster of unknown size
|
||||
return;
|
||||
}
|
||||
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
var bodyEnd = Math.Min(stream.Position + size, end);
|
||||
switch (id)
|
||||
{
|
||||
case 0xE7:
|
||||
clusterTime = (long)reader.Unsigned(size);
|
||||
break;
|
||||
case 0xA3: // SimpleBlock
|
||||
AddBlock(reader, stream.Position, bodyEnd, clusterTime, simple: true, hasReference: false, state);
|
||||
break;
|
||||
case 0xA0: // BlockGroup
|
||||
{
|
||||
long blockStart = -1, blockEnd = -1;
|
||||
var reference = false;
|
||||
while (stream.Position < bodyEnd)
|
||||
{
|
||||
var (gid, gsize) = reader.Header();
|
||||
if (gid == 0xA1)
|
||||
{
|
||||
blockStart = stream.Position;
|
||||
blockEnd = Math.Min(blockStart + gsize, bodyEnd);
|
||||
}
|
||||
else if (gid == 0xFB)
|
||||
{
|
||||
reference = true;
|
||||
}
|
||||
|
||||
reader.Skip(gsize);
|
||||
}
|
||||
|
||||
if (blockStart >= 0)
|
||||
{
|
||||
AddBlock(reader, blockStart, blockEnd, clusterTime, simple: false, reference, state);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stream.Position = bodyEnd;
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddBlock(Reader reader, long start, long end, long clusterTime, bool simple, bool hasReference, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
stream.Position = start;
|
||||
var track = (long)reader.VintValue();
|
||||
Span<byte> fixedPart = stackalloc byte[3];
|
||||
stream.ReadExactly(fixedPart);
|
||||
var relative = BinaryPrimitives.ReadInt16BigEndian(fixedPart);
|
||||
var flags = fixedPart[2];
|
||||
var key = simple ? (flags & 0x80) != 0 : !hasReference;
|
||||
var target = track == state.Video?.Number ? state.Video : track == state.Audio?.Number ? state.Audio : null;
|
||||
if (target is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.Samples.Count >= MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
var time = clusterTime + relative;
|
||||
var lacing = (flags >> 1) & 3;
|
||||
var dataStart = stream.Position;
|
||||
if (lacing == 0)
|
||||
{
|
||||
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
|
||||
return;
|
||||
}
|
||||
|
||||
var frames = stream.ReadByte() + 1;
|
||||
var sizes = new long[frames];
|
||||
switch (lacing)
|
||||
{
|
||||
case 1: // Xiph
|
||||
for (var i = 0; i < frames - 1; i++)
|
||||
{
|
||||
long value = 0;
|
||||
int b;
|
||||
do
|
||||
{
|
||||
b = stream.ReadByte();
|
||||
if (b < 0)
|
||||
{
|
||||
throw new ContainerException("Blocco Matroska troncato.");
|
||||
}
|
||||
|
||||
value += b;
|
||||
}
|
||||
while (b == 255);
|
||||
sizes[i] = value;
|
||||
}
|
||||
|
||||
break;
|
||||
case 3: // EBML
|
||||
{
|
||||
sizes[0] = (long)reader.VintValue();
|
||||
for (var i = 1; i < frames - 1; i++)
|
||||
{
|
||||
var (raw, length) = reader.VintRaw();
|
||||
var bias = (1L << ((7 * length) - 1)) - 1;
|
||||
sizes[i] = sizes[i - 1] + ((long)raw - bias);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var dataBegin = stream.Position;
|
||||
var total = end - dataBegin;
|
||||
if (lacing == 2)
|
||||
{
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
sizes[i] = total / frames;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
long used = 0;
|
||||
for (var i = 0; i < frames - 1; i++)
|
||||
{
|
||||
used += sizes[i];
|
||||
}
|
||||
|
||||
sizes[frames - 1] = total - used;
|
||||
}
|
||||
|
||||
var offset = dataBegin;
|
||||
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
if (sizes[i] < 0 || offset + sizes[i] > end)
|
||||
{
|
||||
throw new ContainerException("Blocco Matroska danneggiato.");
|
||||
}
|
||||
|
||||
var t = time + (i * frameDuration);
|
||||
target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key));
|
||||
offset += sizes[i];
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TrackEntry
|
||||
{
|
||||
internal long Number = -1;
|
||||
internal int Type;
|
||||
internal string CodecId = string.Empty;
|
||||
internal byte[]? CodecPrivate;
|
||||
internal long DefaultDuration;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal double Roll;
|
||||
internal int SampleRate;
|
||||
internal int Channels;
|
||||
internal readonly List<MediaSample> Samples = [];
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
internal long TimecodeScale = 1_000_000;
|
||||
internal double DurationTicks;
|
||||
internal DateTimeOffset? Created;
|
||||
internal TrackEntry? Video;
|
||||
internal TrackEntry? Audio;
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
|
||||
VideoTrack? video = null;
|
||||
if (Video is { } v)
|
||||
{
|
||||
var samples = v.Samples;
|
||||
if (samples.Count > 0)
|
||||
{
|
||||
// Blocks carry presentation times in decoding order; decoding times are those times sorted.
|
||||
var times = new long[samples.Count];
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
times[i] = samples[i].PresentationTime;
|
||||
}
|
||||
|
||||
Array.Sort(times);
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
samples[i] = samples[i] with { DecodeTime = times[i] };
|
||||
}
|
||||
}
|
||||
|
||||
var roll = ((int)Math.Round(-v.Roll) % 360 + 360) % 360;
|
||||
video = new VideoTrack
|
||||
{
|
||||
Codec = v.CodecId switch
|
||||
{
|
||||
"V_MPEG4/ISO/AVC" => VideoCodec.H264,
|
||||
"V_MPEGH/ISO/HEVC" => VideoCodec.Hevc,
|
||||
"V_VP8" => VideoCodec.Vp8,
|
||||
"V_VP9" => VideoCodec.Vp9,
|
||||
"V_AV1" => VideoCodec.Av1,
|
||||
"V_MJPEG" => VideoCodec.Mjpeg,
|
||||
_ when v.CodecId.StartsWith("V_MPEG4/ISO/", StringComparison.Ordinal) => VideoCodec.Mpeg4Part2,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = v.CodecId,
|
||||
Width = v.Width,
|
||||
Height = v.Height,
|
||||
Rotation = roll is 90 or 180 or 270 ? roll : 0,
|
||||
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
|
||||
Timescale = timescale,
|
||||
Duration = (long)DurationTicks,
|
||||
Samples = samples,
|
||||
};
|
||||
}
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (Audio is { } a)
|
||||
{
|
||||
audio = new AudioTrack
|
||||
{
|
||||
Codec = a.CodecId switch
|
||||
{
|
||||
_ when a.CodecId.StartsWith("A_AAC", StringComparison.Ordinal) => AudioCodec.Aac,
|
||||
"A_MPEG/L3" => AudioCodec.Mp3,
|
||||
"A_OPUS" => AudioCodec.Opus,
|
||||
"A_VORBIS" => AudioCodec.Vorbis,
|
||||
_ when a.CodecId.StartsWith("A_PCM", StringComparison.Ordinal) => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = a.CodecId,
|
||||
SampleRate = a.SampleRate,
|
||||
Channels = a.Channels,
|
||||
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
|
||||
Timescale = timescale,
|
||||
Duration = (long)DurationTicks,
|
||||
Samples = a.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>EBML primitives over the stream.</summary>
|
||||
private sealed class Reader(Stream stream)
|
||||
{
|
||||
internal Stream Stream => stream;
|
||||
|
||||
internal (uint Id, long Size) Header()
|
||||
{
|
||||
var first = stream.ReadByte();
|
||||
if (first <= 0)
|
||||
{
|
||||
throw new ContainerException("Elemento EBML non valido.");
|
||||
}
|
||||
|
||||
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
|
||||
if (length > 4)
|
||||
{
|
||||
throw new ContainerException("Identificatore EBML non valido.");
|
||||
}
|
||||
|
||||
var id = (uint)first;
|
||||
for (var i = 1; i < length; i++)
|
||||
{
|
||||
id = (id << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
var (raw, sizeLength) = VintRaw();
|
||||
var allOnes = (1UL << (7 * sizeLength)) - 1;
|
||||
return (id, raw == allOnes ? UnknownSize : (long)raw);
|
||||
}
|
||||
|
||||
internal (ulong Raw, int Length) VintRaw()
|
||||
{
|
||||
var first = ReadByteOrThrow();
|
||||
if (first == 0)
|
||||
{
|
||||
throw new ContainerException("Intero EBML non valido.");
|
||||
}
|
||||
|
||||
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
|
||||
ulong value = (ulong)(first & (0xFF >> length));
|
||||
for (var i = 1; i < length; i++)
|
||||
{
|
||||
value = (value << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
return (value, length);
|
||||
}
|
||||
|
||||
internal ulong VintValue() => VintRaw().Raw;
|
||||
|
||||
internal ulong Unsigned(long size)
|
||||
{
|
||||
if (size is < 0 or > 8)
|
||||
{
|
||||
throw new ContainerException("Intero EBML troppo lungo.");
|
||||
}
|
||||
|
||||
ulong value = 0;
|
||||
for (var i = 0; i < size; i++)
|
||||
{
|
||||
value = (value << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
internal long Signed(long size)
|
||||
{
|
||||
var value = Unsigned(size);
|
||||
if (size is > 0 and < 8 && (value & (1UL << (int)((size * 8) - 1))) != 0)
|
||||
{
|
||||
value |= ulong.MaxValue << (int)(size * 8);
|
||||
}
|
||||
|
||||
return (long)value;
|
||||
}
|
||||
|
||||
internal double Float(long size)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[8];
|
||||
if (size == 4)
|
||||
{
|
||||
stream.ReadExactly(buffer[..4]);
|
||||
return BinaryPrimitives.ReadSingleBigEndian(buffer);
|
||||
}
|
||||
|
||||
if (size == 8)
|
||||
{
|
||||
stream.ReadExactly(buffer);
|
||||
return BinaryPrimitives.ReadDoubleBigEndian(buffer);
|
||||
}
|
||||
|
||||
Skip(size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal string String(long size) => Encoding.UTF8.GetString(Bytes(size)).TrimEnd('\0');
|
||||
|
||||
internal byte[] Bytes(long size)
|
||||
{
|
||||
if (size < 0 || size > MaxElementInMemory)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska troppo grande.");
|
||||
}
|
||||
|
||||
var data = new byte[size];
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
internal void Skip(long size)
|
||||
{
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
stream.Position += size;
|
||||
}
|
||||
|
||||
private int ReadByteOrThrow()
|
||||
{
|
||||
var b = stream.ReadByte();
|
||||
return b < 0 ? throw new ContainerException("File Matroska troncato.") : b;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>The container formats Febe reads without external programs.</summary>
|
||||
public enum ContainerFormat
|
||||
{
|
||||
/// <summary>ISO base media file format: MP4, MOV, 3GP, M4V (also fragmented).</summary>
|
||||
IsoBmff,
|
||||
|
||||
/// <summary>Matroska and WebM.</summary>
|
||||
Matroska,
|
||||
|
||||
/// <summary>RIFF AVI (also OpenDML).</summary>
|
||||
Avi,
|
||||
}
|
||||
|
||||
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary>
|
||||
public enum VideoCodec
|
||||
{
|
||||
Unknown,
|
||||
H264,
|
||||
Hevc,
|
||||
Vp8,
|
||||
Vp9,
|
||||
Av1,
|
||||
Mpeg4Part2,
|
||||
Mjpeg,
|
||||
}
|
||||
|
||||
/// <summary>Audio codecs recognised in a container.</summary>
|
||||
public enum AudioCodec
|
||||
{
|
||||
Unknown,
|
||||
Aac,
|
||||
Mp3,
|
||||
Opus,
|
||||
Vorbis,
|
||||
Pcm,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One sample (an access unit) of a track: where its bytes are in the file and when it is decoded and shown, in units of
|
||||
/// the track's <see cref="MediaTrack.Timescale"/>. Samples are listed in decoding order.
|
||||
/// </summary>
|
||||
public readonly record struct MediaSample(long Offset, int Size, long DecodeTime, long PresentationTime, bool Key);
|
||||
|
||||
/// <summary>A track of a container.</summary>
|
||||
public abstract class MediaTrack
|
||||
{
|
||||
/// <summary>Ticks per second of the sample times.</summary>
|
||||
public long Timescale { get; init; } = 1000;
|
||||
|
||||
/// <summary>Duration of the track in <see cref="Timescale"/> units; 0 when unknown.</summary>
|
||||
public long Duration { get; init; }
|
||||
|
||||
/// <summary>Samples in decoding order (empty when the container was read for its metadata only).</summary>
|
||||
public IReadOnlyList<MediaSample> Samples { get; init; } = [];
|
||||
|
||||
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
|
||||
public string CodecTag { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>Time in seconds of a value in track units.</summary>
|
||||
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
|
||||
}
|
||||
|
||||
/// <summary>The video track of a container.</summary>
|
||||
public sealed class VideoTrack : MediaTrack
|
||||
{
|
||||
public VideoCodec Codec { get; init; }
|
||||
|
||||
/// <summary>Coded width in pixels (before rotation).</summary>
|
||||
public int Width { get; init; }
|
||||
|
||||
/// <summary>Coded height in pixels (before rotation).</summary>
|
||||
public int Height { get; init; }
|
||||
|
||||
/// <summary>Clockwise rotation to apply when showing the frames: 0, 90, 180 or 270.</summary>
|
||||
public int Rotation { get; init; }
|
||||
|
||||
/// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary>
|
||||
public byte[]? AvcConfiguration { get; init; }
|
||||
|
||||
/// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary>
|
||||
public bool AnnexB { get; init; }
|
||||
|
||||
/// <summary>Width as shown (rotation applied).</summary>
|
||||
public int DisplayWidth => Rotation % 180 == 0 ? Width : Height;
|
||||
|
||||
/// <summary>Height as shown (rotation applied).</summary>
|
||||
public int DisplayHeight => Rotation % 180 == 0 ? Height : Width;
|
||||
}
|
||||
|
||||
/// <summary>The audio track of a container.</summary>
|
||||
public sealed class AudioTrack : MediaTrack
|
||||
{
|
||||
public AudioCodec Codec { get; init; }
|
||||
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
|
||||
public byte[]? AacConfiguration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
|
||||
public sealed class MediaContainer
|
||||
{
|
||||
public ContainerFormat Format { get; init; }
|
||||
|
||||
/// <summary>Creation time written in the container, when plausible.</summary>
|
||||
public DateTimeOffset? CreatedAt { get; init; }
|
||||
|
||||
/// <summary>Duration of the whole presentation.</summary>
|
||||
public TimeSpan? Duration { get; init; }
|
||||
|
||||
public VideoTrack? Video { get; init; }
|
||||
|
||||
public AudioTrack? Audio { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A container that cannot be read: damaged, truncated or of a shape Febe does not handle.</summary>
|
||||
public sealed class ContainerException(string message) : Exception(message);
|
||||
@@ -0,0 +1,643 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary>
|
||||
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
|
||||
|
||||
/// <summary>A track to write: H.264 video (with its <c>avcC</c>) or AAC audio (with its AudioSpecificConfig).</summary>
|
||||
public sealed class Mp4OutputTrack
|
||||
{
|
||||
public required bool IsVideo { get; init; }
|
||||
|
||||
public required long Timescale { get; init; }
|
||||
|
||||
public required IReadOnlyList<Mp4OutputSample> Samples { get; init; }
|
||||
|
||||
/// <summary>Writes the bytes of sample <c>i</c> (exactly its <see cref="Mp4OutputSample.Size"/>) into the stream.</summary>
|
||||
public required Action<int, Stream> WriteSample { get; init; }
|
||||
|
||||
public int Width { get; init; }
|
||||
|
||||
public int Height { get; init; }
|
||||
|
||||
/// <summary>Clockwise rotation written in the track matrix: 0, 90, 180 or 270.</summary>
|
||||
public int Rotation { get; init; }
|
||||
|
||||
public byte[]? AvcConfiguration { get; init; }
|
||||
|
||||
public byte[]? AacConfiguration { get; init; }
|
||||
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
|
||||
public long LastSampleDuration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: <c>ftyp</c>, then the
|
||||
/// <c>moov</c> box (so the file plays while it downloads), then one <c>mdat</c> with the tracks interleaved about every
|
||||
/// half second.
|
||||
/// </summary>
|
||||
public static class Mp4Writer
|
||||
{
|
||||
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private const int MovieTimescale = 1000;
|
||||
|
||||
/// <summary>Writes the tracks into <paramref name="output"/> (from its current position).</summary>
|
||||
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
ArgumentNullException.ThrowIfNull(tracks);
|
||||
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
|
||||
{
|
||||
throw new ArgumentException("Servono tracce con campioni.", nameof(tracks));
|
||||
}
|
||||
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
if (track.IsVideo ? track.AvcConfiguration is null : track.AacConfiguration is null)
|
||||
{
|
||||
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
|
||||
}
|
||||
}
|
||||
|
||||
var timing = tracks.Select(Timing.Of).ToArray();
|
||||
var chunks = Interleave(tracks);
|
||||
long payload = 0;
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
foreach (var s in track.Samples)
|
||||
{
|
||||
payload += s.Size;
|
||||
}
|
||||
}
|
||||
|
||||
var wideMdat = payload + 8 > uint.MaxValue;
|
||||
var ftyp = Ftyp();
|
||||
var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
||||
|
||||
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
|
||||
var co64 = false;
|
||||
var moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time);
|
||||
var dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8);
|
||||
if (dataStart + payload > uint.MaxValue)
|
||||
{
|
||||
co64 = true;
|
||||
moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time);
|
||||
dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8);
|
||||
}
|
||||
|
||||
var offsets = new long[chunks.Count];
|
||||
var position = (long)dataStart;
|
||||
for (var i = 0; i < chunks.Count; i++)
|
||||
{
|
||||
offsets[i] = position;
|
||||
var (track, first, count) = chunks[i];
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
position += tracks[track].Samples[k].Size;
|
||||
}
|
||||
}
|
||||
|
||||
moov = Moov(tracks, timing, chunks, offsets, co64, time);
|
||||
output.Write(ftyp);
|
||||
output.Write(moov);
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
if (wideMdat)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, 1);
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
|
||||
output.Write(header);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
output.Write(header[..8]);
|
||||
}
|
||||
|
||||
foreach (var (track, first, count) in chunks)
|
||||
{
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
var before = output.CanSeek ? output.Position : -1;
|
||||
tracks[track].WriteSample(k, output);
|
||||
if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size)
|
||||
{
|
||||
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Times of a track as the boxes need them.</summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey)
|
||||
{
|
||||
internal static Timing Of(Mp4OutputTrack track)
|
||||
{
|
||||
var samples = track.Samples;
|
||||
var n = samples.Count;
|
||||
var durations = new long[n];
|
||||
for (var i = 0; i < n - 1; i++)
|
||||
{
|
||||
durations[i] = Math.Max(0, samples[i + 1].DecodeTime - samples[i].DecodeTime);
|
||||
}
|
||||
|
||||
durations[n - 1] = track.LastSampleDuration > 0 ? track.LastSampleDuration : n > 1 ? durations[n - 2] : 1;
|
||||
|
||||
// Decoding must not come after presentation: delay the decoding times when it would.
|
||||
long shift = 0;
|
||||
var minPts = long.MaxValue;
|
||||
foreach (var s in samples)
|
||||
{
|
||||
shift = Math.Max(shift, s.DecodeTime - s.PresentationTime);
|
||||
minPts = Math.Min(minPts, s.PresentationTime);
|
||||
}
|
||||
|
||||
var first = samples[0].DecodeTime;
|
||||
var offsets = new int[n];
|
||||
var allKey = true;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
offsets[i] = (int)Math.Clamp(samples[i].PresentationTime - samples[i].DecodeTime + shift, 0, int.MaxValue);
|
||||
allKey &= samples[i].Key;
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
foreach (var d in durations)
|
||||
{
|
||||
total += d;
|
||||
}
|
||||
|
||||
// The edit list starts the presentation at the first shown sample.
|
||||
var editTime = minPts - first + shift;
|
||||
return new Timing(durations, offsets, total, editTime, allKey);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<(int Track, int First, int Count)> Interleave(IReadOnlyList<Mp4OutputTrack> tracks)
|
||||
{
|
||||
var list = new List<(int Track, int First, int Count, double Start)>();
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
var track = tracks[t];
|
||||
var samples = track.Samples;
|
||||
var first = 0;
|
||||
var limit = track.Timescale / 2;
|
||||
for (var i = 1; i <= samples.Count; i++)
|
||||
{
|
||||
if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024)
|
||||
{
|
||||
list.Add((t, first, i - first, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale));
|
||||
first = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track.CompareTo(b.Track));
|
||||
return list.ConvertAll(c => (c.Track, c.First, c.Count));
|
||||
}
|
||||
|
||||
private static byte[] Ftyp()
|
||||
{
|
||||
var box = new Box("ftyp");
|
||||
box.Bytes("isom"u8);
|
||||
box.U32(512);
|
||||
box.Bytes("isomiso2avc1mp41"u8);
|
||||
return box.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
{
|
||||
long movieDuration = 0;
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
|
||||
}
|
||||
|
||||
var moov = new Box("moov");
|
||||
var mvhd = new Box("mvhd");
|
||||
var wide = movieDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
mvhd.U32(wide ? 0x01000000u : 0);
|
||||
Times(mvhd, wide, time, MovieTimescale, movieDuration);
|
||||
mvhd.U32(0x00010000);
|
||||
mvhd.U16(0x0100);
|
||||
mvhd.Zero(10);
|
||||
Matrix(mvhd, 0, 0, 0);
|
||||
mvhd.Zero(24);
|
||||
mvhd.U32((uint)tracks.Count + 1);
|
||||
moov.Child(mvhd);
|
||||
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
moov.Child(Trak(tracks[t], timing[t], t, chunks, offsets, co64, time));
|
||||
}
|
||||
|
||||
return moov.ToArray();
|
||||
}
|
||||
|
||||
private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
|
||||
|
||||
private static void Times(Box box, bool wide, ulong time, long timescale, long duration)
|
||||
{
|
||||
if (wide)
|
||||
{
|
||||
box.U64(time);
|
||||
box.U64(time);
|
||||
box.U32((uint)timescale);
|
||||
box.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)timescale);
|
||||
box.U32((uint)duration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Matrix(Box box, int rotation, int width, int height)
|
||||
{
|
||||
int a = 0x10000, b = 0, c = 0, d = 0x10000, x = 0, y = 0;
|
||||
switch (rotation)
|
||||
{
|
||||
case 90:
|
||||
(a, b, c, d, x) = (0, 0x10000, -0x10000, 0, height << 16);
|
||||
break;
|
||||
case 180:
|
||||
(a, d, x, y) = (-0x10000, -0x10000, width << 16, height << 16);
|
||||
break;
|
||||
case 270:
|
||||
(a, b, c, d, y) = (0, -0x10000, 0x10000, 0, width << 16);
|
||||
break;
|
||||
}
|
||||
|
||||
foreach (var v in new[] { a, b, 0, c, d, 0, x, y, 0x40000000 })
|
||||
{
|
||||
box.U32((uint)v);
|
||||
}
|
||||
}
|
||||
|
||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
{
|
||||
var trak = new Box("trak");
|
||||
var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
|
||||
var wide = duration > uint.MaxValue || time > uint.MaxValue;
|
||||
var tkhd = new Box("tkhd");
|
||||
tkhd.U32((wide ? 0x01000000u : 0) | 3);
|
||||
if (wide)
|
||||
{
|
||||
tkhd.U64(time);
|
||||
tkhd.U64(time);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U32((uint)duration);
|
||||
}
|
||||
|
||||
tkhd.Zero(8);
|
||||
tkhd.U16(0);
|
||||
tkhd.U16(0);
|
||||
tkhd.U16(track.IsVideo ? (ushort)0 : (ushort)0x0100);
|
||||
tkhd.U16(0);
|
||||
Matrix(tkhd, track.IsVideo ? track.Rotation : 0, track.Width, track.Height);
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Width << 16 : 0);
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
||||
trak.Child(tkhd);
|
||||
|
||||
if (timing.EditMediaTime != 0)
|
||||
{
|
||||
var edts = new Box("edts");
|
||||
var elst = new Box("elst");
|
||||
elst.U32(0x01000000);
|
||||
elst.U32(1);
|
||||
elst.U64((ulong)duration);
|
||||
elst.U64((ulong)timing.EditMediaTime);
|
||||
elst.U16(1);
|
||||
elst.U16(0);
|
||||
edts.Child(elst);
|
||||
trak.Child(edts);
|
||||
}
|
||||
|
||||
var mdia = new Box("mdia");
|
||||
var mdhd = new Box("mdhd");
|
||||
var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
mdhd.U32(mediaWide ? 0x01000000u : 0);
|
||||
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
|
||||
mdhd.U16(0x55C4); // «und»
|
||||
mdhd.U16(0);
|
||||
mdia.Child(mdhd);
|
||||
|
||||
var hdlr = new Box("hdlr");
|
||||
hdlr.U32(0);
|
||||
hdlr.U32(0);
|
||||
hdlr.Bytes(track.IsVideo ? "vide"u8 : "soun"u8);
|
||||
hdlr.Zero(12);
|
||||
hdlr.Bytes(track.IsVideo ? "VideoHandler\0"u8 : "SoundHandler\0"u8);
|
||||
mdia.Child(hdlr);
|
||||
|
||||
var minf = new Box("minf");
|
||||
if (track.IsVideo)
|
||||
{
|
||||
var vmhd = new Box("vmhd");
|
||||
vmhd.U32(1);
|
||||
vmhd.Zero(8);
|
||||
minf.Child(vmhd);
|
||||
}
|
||||
else
|
||||
{
|
||||
var smhd = new Box("smhd");
|
||||
smhd.U32(0);
|
||||
smhd.Zero(4);
|
||||
minf.Child(smhd);
|
||||
}
|
||||
|
||||
var dinf = new Box("dinf");
|
||||
var dref = new Box("dref");
|
||||
dref.U32(0);
|
||||
dref.U32(1);
|
||||
var url = new Box("url ");
|
||||
url.U32(1);
|
||||
dref.Child(url);
|
||||
dinf.Child(dref);
|
||||
minf.Child(dinf);
|
||||
minf.Child(Stbl(track, timing, index, chunks, offsets, co64));
|
||||
mdia.Child(minf);
|
||||
trak.Child(mdia);
|
||||
return trak;
|
||||
}
|
||||
|
||||
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
|
||||
{
|
||||
var stbl = new Box("stbl");
|
||||
var stsd = new Box("stsd");
|
||||
stsd.U32(0);
|
||||
stsd.U32(1);
|
||||
stsd.Child(track.IsVideo ? Avc1(track) : Mp4a(track));
|
||||
stbl.Child(stsd);
|
||||
|
||||
// stts: runs of equal durations.
|
||||
var stts = new Box("stts");
|
||||
var runs = new List<(int Count, long Delta)>();
|
||||
foreach (var d in timing.Durations)
|
||||
{
|
||||
if (runs.Count > 0 && runs[^1].Delta == d)
|
||||
{
|
||||
runs[^1] = (runs[^1].Count + 1, d);
|
||||
}
|
||||
else
|
||||
{
|
||||
runs.Add((1, d));
|
||||
}
|
||||
}
|
||||
|
||||
stts.U32(0);
|
||||
stts.U32((uint)runs.Count);
|
||||
foreach (var (count, delta) in runs)
|
||||
{
|
||||
stts.U32((uint)count);
|
||||
stts.U32((uint)delta);
|
||||
}
|
||||
|
||||
stbl.Child(stts);
|
||||
|
||||
var anyOffset = false;
|
||||
foreach (var o in timing.CompositionOffsets)
|
||||
{
|
||||
anyOffset |= o != 0;
|
||||
}
|
||||
|
||||
if (anyOffset)
|
||||
{
|
||||
var ctts = new Box("ctts");
|
||||
var cruns = new List<(int Count, int Offset)>();
|
||||
foreach (var o in timing.CompositionOffsets)
|
||||
{
|
||||
if (cruns.Count > 0 && cruns[^1].Offset == o)
|
||||
{
|
||||
cruns[^1] = (cruns[^1].Count + 1, o);
|
||||
}
|
||||
else
|
||||
{
|
||||
cruns.Add((1, o));
|
||||
}
|
||||
}
|
||||
|
||||
ctts.U32(0);
|
||||
ctts.U32((uint)cruns.Count);
|
||||
foreach (var (count, offset) in cruns)
|
||||
{
|
||||
ctts.U32((uint)count);
|
||||
ctts.U32((uint)offset);
|
||||
}
|
||||
|
||||
stbl.Child(ctts);
|
||||
}
|
||||
|
||||
if (track.IsVideo && !timing.AllKey)
|
||||
{
|
||||
var stss = new Box("stss");
|
||||
var keys = new List<int>();
|
||||
for (var i = 0; i < track.Samples.Count; i++)
|
||||
{
|
||||
if (track.Samples[i].Key)
|
||||
{
|
||||
keys.Add(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
stss.U32(0);
|
||||
stss.U32((uint)keys.Count);
|
||||
foreach (var k in keys)
|
||||
{
|
||||
stss.U32((uint)k);
|
||||
}
|
||||
|
||||
stbl.Child(stss);
|
||||
}
|
||||
|
||||
// stsc and the chunk offsets of this track, in file order.
|
||||
var stsc = new Box("stsc");
|
||||
var entries = new List<(int FirstChunk, int PerChunk)>();
|
||||
var mine = new List<long>();
|
||||
for (var c = 0; c < chunks.Count; c++)
|
||||
{
|
||||
if (chunks[c].Track != index)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
mine.Add(offsets[c]);
|
||||
if (entries.Count == 0 || entries[^1].PerChunk != chunks[c].Count)
|
||||
{
|
||||
entries.Add((mine.Count, chunks[c].Count));
|
||||
}
|
||||
}
|
||||
|
||||
stsc.U32(0);
|
||||
stsc.U32((uint)entries.Count);
|
||||
foreach (var (firstChunk, perChunk) in entries)
|
||||
{
|
||||
stsc.U32((uint)firstChunk);
|
||||
stsc.U32((uint)perChunk);
|
||||
stsc.U32(1);
|
||||
}
|
||||
|
||||
stbl.Child(stsc);
|
||||
|
||||
var stsz = new Box("stsz");
|
||||
stsz.U32(0);
|
||||
stsz.U32(0);
|
||||
stsz.U32((uint)track.Samples.Count);
|
||||
foreach (var s in track.Samples)
|
||||
{
|
||||
stsz.U32((uint)s.Size);
|
||||
}
|
||||
|
||||
stbl.Child(stsz);
|
||||
|
||||
var stco = new Box(co64 ? "co64" : "stco");
|
||||
stco.U32(0);
|
||||
stco.U32((uint)mine.Count);
|
||||
foreach (var o in mine)
|
||||
{
|
||||
if (co64)
|
||||
{
|
||||
stco.U64((ulong)o);
|
||||
}
|
||||
else
|
||||
{
|
||||
stco.U32((uint)o);
|
||||
}
|
||||
}
|
||||
|
||||
stbl.Child(stco);
|
||||
return stbl;
|
||||
}
|
||||
|
||||
private static Box Avc1(Mp4OutputTrack track)
|
||||
{
|
||||
var entry = new Box("avc1");
|
||||
entry.Zero(6);
|
||||
entry.U16(1);
|
||||
entry.Zero(16);
|
||||
entry.U16((ushort)track.Width);
|
||||
entry.U16((ushort)track.Height);
|
||||
entry.U32(0x00480000);
|
||||
entry.U32(0x00480000);
|
||||
entry.U32(0);
|
||||
entry.U16(1);
|
||||
entry.Zero(32);
|
||||
entry.U16(0x0018);
|
||||
entry.U16(0xFFFF);
|
||||
var avcC = new Box("avcC");
|
||||
avcC.Bytes(track.AvcConfiguration);
|
||||
entry.Child(avcC);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static Box Mp4a(Mp4OutputTrack track)
|
||||
{
|
||||
var entry = new Box("mp4a");
|
||||
entry.Zero(6);
|
||||
entry.U16(1);
|
||||
entry.Zero(8);
|
||||
entry.U16((ushort)Math.Max(1, track.Channels));
|
||||
entry.U16(16);
|
||||
entry.U16(0);
|
||||
entry.U16(0);
|
||||
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
|
||||
|
||||
var asc = track.AacConfiguration!;
|
||||
var decoderSpecific = Descriptor(0x05, asc);
|
||||
var config = new byte[13 + decoderSpecific.Length];
|
||||
config[0] = 0x40; // MPEG-4 audio
|
||||
config[1] = 0x15; // audio stream
|
||||
decoderSpecific.CopyTo(config, 13);
|
||||
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
||||
var esds = new Box("esds");
|
||||
esds.U32(0);
|
||||
esds.Bytes(Descriptor(0x03, es));
|
||||
entry.Child(esds);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static byte[] Descriptor(byte tag, ReadOnlySpan<byte> body)
|
||||
{
|
||||
var data = new byte[5 + body.Length];
|
||||
data[0] = tag;
|
||||
var length = body.Length;
|
||||
data[1] = (byte)(0x80 | ((length >> 21) & 0x7F));
|
||||
data[2] = (byte)(0x80 | ((length >> 14) & 0x7F));
|
||||
data[3] = (byte)(0x80 | ((length >> 7) & 0x7F));
|
||||
data[4] = (byte)(length & 0x7F);
|
||||
body.CopyTo(data.AsSpan(5));
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>A box being built in memory.</summary>
|
||||
private sealed class Box
|
||||
{
|
||||
private readonly MemoryStream body = new();
|
||||
|
||||
internal Box(string type) => Type = type;
|
||||
|
||||
internal string Type { get; }
|
||||
|
||||
internal void U16(ushort v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[2];
|
||||
BinaryPrimitives.WriteUInt16BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void U32(uint v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void U64(ulong v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteUInt64BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void Zero(int count)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
body.WriteByte(0);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Bytes(ReadOnlySpan<byte> data) => body.Write(data);
|
||||
|
||||
internal void Child(Box child) => body.Write(child.ToArray());
|
||||
|
||||
internal byte[] ToArray()
|
||||
{
|
||||
var size = body.Length + 8;
|
||||
var result = new byte[size];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(result, (uint)size);
|
||||
Encoding.Latin1.GetBytes(Type, result.AsSpan(4, 4));
|
||||
body.Position = 0;
|
||||
body.ReadExactly(result, 8, (int)body.Length);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user