using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// A sample to write: its size, its times in track units, whether it is a sync sample.
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
/// A track to write: H.264 video (with its avcC) or AAC audio (with its AudioSpecificConfig).
public sealed class Mp4OutputTrack
{
public required bool IsVideo { get; init; }
public required long Timescale { get; init; }
public required IReadOnlyList Samples { get; init; }
/// Writes the bytes of sample i (exactly its ) into the stream.
public required Action WriteSample { get; init; }
public int Width { get; init; }
public int Height { get; init; }
/// Clockwise rotation written in the track matrix: 0, 90, 180 or 270.
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; }
/// Duration of the last sample, when the times cannot tell it (0: as the one before it).
public long LastSampleDuration { get; init; }
}
///
/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: ftyp, then the
/// moov box (so the file plays while it downloads), then one mdat with the tracks interleaved about every
/// half second.
///
public static class Mp4Writer
{
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
private const int MovieTimescale = 1000;
/// Writes the tracks into (from its current position).
public static void Write(Stream output, IReadOnlyList 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 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.");
}
}
}
}
/// Times of a track as the boxes need them.
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 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;
var start = 0.0;
for (var i = 1; i <= samples.Count; i++)
{
if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024)
{
// Never earlier than the chunk before: the chunks of a track stay in sample order whatever its times.
start = Math.Max(start, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale);
list.Add((t, first, i - first, start));
first = i;
}
}
}
// Ties (equal times, as tracks without times have) keep each track's chunks in order: the sort is not stable.
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track != b.Track ? a.Track.CompareTo(b.Track) : a.First.CompareTo(b.First));
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 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();
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();
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 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;
}
/// A box being built in memory.
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 b = stackalloc byte[2];
BinaryPrimitives.WriteUInt16BigEndian(b, v);
body.Write(b);
}
internal void U32(uint v)
{
Span b = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(b, v);
body.Write(b);
}
internal void U64(ulong v)
{
Span 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 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;
}
}
}