using System.Buffers.Binary; using Titano.Core.Diagnostics; using Titano.Core.Video.Bitstream; namespace Titano.Core.Video.Mp4; /// Parameters of the single video track written by . public sealed record VideoTrackConfig { /// , or . public required VideoCodec Codec { get; init; } /// Display width (tkhd); the sample entry uses the size declared by the bitstream. public required int Width { get; init; } public required int Height { get; init; } /// Moves moov in front of mdat when completing (progressive playback); the stream must be readable. public bool FastStart { get; init; } /// Signalled in colr; Titano encodes limited (video) range. public bool FullRange { get; init; } public DateTime CreationTime { get; init; } = DateTime.UtcNow; } /// /// Streaming MP4 writer for one video track: ftyp, then samples straight into mdat, then moov at the end /// (optionally moved to the front). Timescale 90 kHz; parameter sets are taken from the bitstream. /// The output stream is not disposed. /// public sealed class Mp4Muxer { /// Media and movie timescale (ticks per second). public const int TimeScale = 90_000; private const long ChunkTicks = TimeScale; private const long ChunkBytes = 4 << 20; private const string LogCategory = "Mp4Muxer"; private readonly Stream _stream; private readonly VideoTrackConfig _config; private readonly long _mdatHeader; private readonly List _sizes = []; private readonly List _durations = []; private readonly List _compositionOffsets = []; private readonly List _syncSamples = []; private readonly List _chunkOffsets = []; private readonly List _chunkSampleCounts = []; private readonly SortedDictionary _vps = []; private readonly SortedDictionary _sps = []; private readonly SortedDictionary _pps = []; private byte[]? _av1SequenceHeader; private long _position; private long _chunkTicks; private long _chunkBytes; private long _totalTicks; private long _totalBytes; private bool _warnedInBandChange; private bool _completed; public Mp4Muxer(Stream output, VideoTrackConfig config) { ArgumentNullException.ThrowIfNull(output); ArgumentNullException.ThrowIfNull(config); if (config.Codec is not (VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1)) throw new ArgumentException($"MP4 muxing supports H.264, HEVC and AV1, not {config.Codec}", nameof(config)); if (config.Width is <= 0 or > ushort.MaxValue || config.Height is <= 0 or > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(config), "Frame size out of range"); if (!output.CanSeek || !output.CanWrite) throw new ArgumentException("The output stream must be writable and seekable", nameof(output)); if (config.FastStart && !output.CanRead) throw new ArgumentException("FastStart needs a readable stream", nameof(output)); _stream = output; _config = config; var ftyp = new BoxWriter(64); ftyp.BeginBox("ftyp"); ftyp.WriteFourCc("isom"); ftyp.WriteUInt32(0x200); ftyp.WriteFourCc("isom"); ftyp.WriteFourCc("iso6"); ftyp.WriteFourCc("mp41"); if (config.Codec == VideoCodec.Av1) ftyp.WriteFourCc("av01"); ftyp.EndBox(); _stream.Write(ftyp.WrittenSpan); _mdatHeader = _stream.Position; // 16 bytes: 'free' + 32-bit 'mdat' header, or one 64-bit 'mdat' header when the payload exceeds 4 GiB. _stream.Write(stackalloc byte[16]); _position = _mdatHeader + 16; } public int SampleCount => _sizes.Count; /// Sum of the sample durations written so far, in 90 kHz ticks. public long Duration90k => _totalTicks; /// /// Records parameter sets (H.264/HEVC NAL units, Annex-B or length-prefixed) or an AV1 sequence header OBU /// delivered outside the samples, e.g. an encoder's MF_MT_MPEG_SEQUENCE_HEADER. /// public void AddParameterSets(ReadOnlySpan data) { if (_config.Codec == VideoCodec.Av1) { foreach (var obu in Av1ObuParser.Split(data)) { if (obu.Type == Av1ObuType.SequenceHeader) _av1SequenceHeader ??= SizedObu(data, obu); } return; } foreach (var unit in AnnexBParser.SplitAccessUnit(data, out _)) RecordNal(unit.Slice(data)); } /// /// Appends one access unit (H.264/HEVC: Annex-B or 4-byte length-prefixed NAL units; AV1: a temporal unit of OBUs) /// in decode order. is presentation minus decode time and may be negative. /// public void WriteSample(ReadOnlySpan data, long duration90k, bool isSync, long compositionOffset90k = 0) { if (_completed) throw new InvalidOperationException("The muxer is complete"); if (duration90k <= 0 || duration90k > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(duration90k)); if (Math.Abs(compositionOffset90k) > int.MaxValue / 2) throw new ArgumentOutOfRangeException(nameof(compositionOffset90k)); var start = _position; if (_stream.Position != start) _stream.Position = start; var size = _config.Codec == VideoCodec.Av1 ? WriteObus(data) : WriteNalUnits(data); if (size == 0) throw new ArgumentException("The sample contains no picture data", nameof(data)); if (_sizes.Count == 0 && !isSync) Log.Warning(LogCategory, "First sample is not a sync sample; players may not start decoding"); if (_chunkSampleCounts.Count == 0 || _chunkTicks >= ChunkTicks || _chunkBytes >= ChunkBytes) { _chunkOffsets.Add(start); _chunkSampleCounts.Add(0); _chunkTicks = 0; _chunkBytes = 0; } _chunkSampleCounts[^1]++; _chunkTicks += duration90k; _chunkBytes += size; _sizes.Add((uint)size); _durations.Add((uint)duration90k); _compositionOffsets.Add(compositionOffset90k); if (isSync) _syncSamples.Add((uint)_sizes.Count); _totalTicks += duration90k; _totalBytes += size; } /// Patches mdat, writes moov (and relocates it when is set) and flushes. public void Complete() { if (_completed) throw new InvalidOperationException("The muxer is already complete"); if (_sizes.Count == 0) throw new InvalidOperationException("No samples were written"); var configuration = BuildDecoderConfiguration(); if (configuration.Width != _config.Width || configuration.Height != _config.Height) { Log.Warning(LogCategory, $"Bitstream size {configuration.Width}×{configuration.Height} differs from the track size {_config.Width}×{_config.Height}"); } WriteMdatHeader(); var moov = BuildMoov(configuration, 0); _stream.Position = _position; _stream.Write(moov); if (_config.FastStart) MoveMoovToFront(configuration, moov.Length); else _position += moov.Length; _stream.Flush(); _completed = true; } private long WriteNalUnits(ReadOnlySpan data) { Span length = stackalloc byte[4]; long size = 0; var picture = false; foreach (var unit in AnnexBParser.SplitAccessUnit(data, out _)) { var nal = unit.Slice(data); if (!RecordNal(nal)) continue; BinaryPrimitives.WriteInt32BigEndian(length, nal.Length); _stream.Write(length); _stream.Write(nal); size += 4 + nal.Length; picture |= IsPicture(nal[0]); } _position += size; return picture ? size : 0; } private long WriteObus(ReadOnlySpan data) { var obus = Av1ObuParser.Split(data); if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length) throw new ArgumentException("Malformed AV1 temporal unit", nameof(data)); Span header = stackalloc byte[2 + 8]; long size = 0; var picture = false; foreach (var obu in obus) { if (obu.Type is Av1ObuType.TemporalDelimiter or Av1ObuType.Padding) continue; if (obu.Type == Av1ObuType.SequenceHeader) _av1SequenceHeader ??= SizedObu(data, obu); picture |= obu.Type is Av1ObuType.Frame or Av1ObuType.FrameHeader or Av1ObuType.TileGroup; if (obu.HasSizeField) { _stream.Write(data.Slice(obu.Offset, obu.TotalLength)); size += obu.TotalLength; continue; } // Samples carry every OBU with obu_size (AV1-ISOBMFF 2.4). var n = WriteSizedHeader(header, data, obu); _stream.Write(header[..n]); _stream.Write(obu.Payload(data)); size += n + obu.PayloadLength; } _position += size; return picture ? size : 0; } private static int WriteSizedHeader(Span header, ReadOnlySpan data, Av1Obu obu) { header[0] = (byte)(data[obu.Offset] | 0x02); var n = 1; if (obu.HasExtension) header[n++] = data[obu.Offset + 1]; return n + Av1ObuParser.WriteLeb128(header[n..], (ulong)obu.PayloadLength); } private static byte[] SizedObu(ReadOnlySpan data, Av1Obu obu) { Span header = stackalloc byte[2 + 8]; var n = WriteSizedHeader(header, data, obu); var result = new byte[n + obu.PayloadLength]; header[..n].CopyTo(result); obu.Payload(data).CopyTo(result.AsSpan(n)); return result; } private bool IsPicture(byte header) => _config.Codec == VideoCodec.H264 ? AnnexBParser.H264Type(header) is >= H264NalUnitType.NonIdrSlice and <= H264NalUnitType.IdrSlice : (int)AnnexBParser.HevcType(header) < 32; /// Stores parameter sets for the sample entry; returns whether the NAL unit belongs in the sample. private bool RecordNal(ReadOnlySpan nal) { if (nal.Length < 2) return true; SortedDictionary table; int id; if (_config.Codec == VideoCodec.H264) { switch (AnnexBParser.H264Type(nal[0])) { case H264NalUnitType.AccessUnitDelimiter or H264NalUnitType.FillerData: return false; case H264NalUnitType.Sps when H264SpsParser.TryParse(nal, out var sps): (table, id) = (_sps, sps.SpsId); break; case H264NalUnitType.Pps: (table, id) = (_pps, FirstUe(nal[1..])); break; default: return true; } } else { switch (AnnexBParser.HevcType(nal[0])) { case HevcNalUnitType.AccessUnitDelimiter or HevcNalUnitType.FillerData: return false; case HevcNalUnitType.Vps when nal.Length > 2: (table, id) = (_vps, nal[2] >> 4); break; case HevcNalUnitType.Sps when HevcSpsParser.TryParse(nal, out var sps): (table, id) = (_sps, sps.SpsId); break; case HevcNalUnitType.Pps: (table, id) = (_pps, FirstUe(nal[2..])); break; default: return true; } } if (id < 0) return true; if (!table.TryGetValue(id, out var known)) { table[id] = nal.ToArray(); return false; } if (nal.SequenceEqual(known)) return false; // A redefinition keeps working in-band, but the sample entry describes only the first definition. if (!_warnedInBandChange) { Log.Warning(LogCategory, "A parameter set changed mid-stream; keeping the new one in-band"); _warnedInBandChange = true; } return true; } private static int FirstUe(ReadOnlySpan payload) { var rbsp = AnnexBParser.RemoveEmulationPrevention(payload[..Math.Min(payload.Length, 8)]); var r = new BitReader(rbsp); var v = r.ReadUe(); return r.IsOverrun || v > 255 ? -1 : (int)v; } private DecoderConfiguration BuildDecoderConfiguration() => _config.Codec switch { VideoCodec.H264 when _sps.Count > 0 && _pps.Count > 0 => DecoderConfiguration.ForAvc([.. _sps.Values], [.. _pps.Values]), VideoCodec.Hevc when _vps.Count > 0 && _sps.Count > 0 && _pps.Count > 0 => DecoderConfiguration.ForHevc([.. _vps.Values], [.. _sps.Values], [.. _pps.Values]), VideoCodec.Av1 when _av1SequenceHeader is not null => DecoderConfiguration.ForAv1(_av1SequenceHeader), _ => throw new InvalidOperationException("The bitstream carried no parameter sets / sequence header"), }; private void WriteMdatHeader() { Span header = stackalloc byte[16]; var compact = _position - (_mdatHeader + 8); if (compact <= uint.MaxValue) { BinaryPrimitives.WriteUInt32BigEndian(header, 8); "free"u8.CopyTo(header[4..]); BinaryPrimitives.WriteUInt32BigEndian(header[8..], (uint)compact); "mdat"u8.CopyTo(header[12..]); } else { BinaryPrimitives.WriteUInt32BigEndian(header, 1); "mdat"u8.CopyTo(header[4..]); BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(_position - _mdatHeader)); } _stream.Position = _mdatHeader; _stream.Write(header); } private void MoveMoovToFront(DecoderConfiguration configuration, int moovAtEnd) { // Chunk offsets grow by the relocated moov size, which itself grows if they now need co64. var delta = moovAtEnd; byte[] moov; while (true) { moov = BuildMoov(configuration, delta); if (moov.Length == delta) break; delta = moov.Length; } var buffer = new byte[1 << 20]; var remaining = _position - _mdatHeader; while (remaining > 0) { var n = (int)Math.Min(buffer.Length, remaining); var source = _mdatHeader + remaining - n; _stream.Position = source; _stream.ReadExactly(buffer, 0, n); _stream.Position = source + delta; _stream.Write(buffer, 0, n); remaining -= n; } _stream.Position = _mdatHeader; _stream.Write(moov); _position += delta; } private byte[] BuildMoov(DecoderConfiguration configuration, long chunkOffsetDelta) { var count = _sizes.Count; long minOffset = 0; foreach (var o in _compositionOffsets) minOffset = Math.Min(minOffset, o); var shift = -minOffset; // Presentation span: earliest composition time to the latest composition end. long decode = 0, minCts = long.MaxValue, maxEnd = 0; var anyOffset = false; for (var i = 0; i < count; i++) { var cts = decode + _compositionOffsets[i] + shift; minCts = Math.Min(minCts, cts); maxEnd = Math.Max(maxEnd, cts + _durations[i]); anyOffset |= _compositionOffsets[i] + shift != 0; decode += _durations[i]; } var edit = minCts > 0; var presentation = edit ? Math.Max(1, maxEnd - minCts) : _totalTicks; var wide = presentation > uint.MaxValue || _totalTicks > uint.MaxValue; var created = (ulong)Math.Max(0, (_config.CreationTime.ToUniversalTime() - new DateTime(1904, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var w = new BoxWriter(4096 + count * 16); w.BeginBox("moov"); w.BeginFullBox("mvhd", wide ? (byte)1 : (byte)0, 0); WriteTimes(w, wide, created, presentation); w.WriteUInt32(0x00010000); // rate 1.0 w.WriteUInt16(0x0100); // volume 1.0 w.WriteZeros(10); w.WriteUnityMatrix(); w.WriteZeros(24); w.WriteUInt32(2); // next_track_ID w.EndBox(); w.BeginBox("trak"); w.BeginFullBox("tkhd", wide ? (byte)1 : (byte)0, 3); // enabled | in movie if (wide) { w.WriteUInt64(created); w.WriteUInt64(created); w.WriteUInt32(1); w.WriteUInt32(0); w.WriteUInt64((ulong)presentation); } else { w.WriteUInt32((uint)created); w.WriteUInt32((uint)created); w.WriteUInt32(1); w.WriteUInt32(0); w.WriteUInt32((uint)presentation); } w.WriteZeros(8); w.WriteZeros(8); // layer, alternate_group, volume, reserved w.WriteUnityMatrix(); w.WriteUInt32((uint)_config.Width << 16); w.WriteUInt32((uint)_config.Height << 16); w.EndBox(); if (edit) { w.BeginBox("edts"); w.BeginFullBox("elst", wide ? (byte)1 : (byte)0, 0); w.WriteUInt32(1); if (wide) { w.WriteUInt64((ulong)presentation); w.WriteInt64(minCts); } else { w.WriteUInt32((uint)presentation); w.WriteInt32((int)minCts); } w.WriteUInt32(0x00010000); // media_rate 1.0 w.EndBox(); w.EndBox(); } w.BeginBox("mdia"); w.BeginFullBox("mdhd", wide ? (byte)1 : (byte)0, 0); WriteTimes(w, wide, created, _totalTicks); w.WriteUInt16(0x55C4); // 'und' w.WriteUInt16(0); w.EndBox(); w.BeginFullBox("hdlr", 0, 0); w.WriteUInt32(0); w.WriteFourCc("vide"); w.WriteZeros(12); w.WriteBytes("VideoHandler\0"u8); w.EndBox(); w.BeginBox("minf"); w.BeginFullBox("vmhd", 0, 1); w.WriteZeros(8); w.EndBox(); w.BeginBox("dinf"); w.BeginFullBox("dref", 0, 0); w.WriteUInt32(1); w.BeginFullBox("url ", 0, 1); // media data in this file w.EndBox(); w.EndBox(); w.EndBox(); w.BeginBox("stbl"); WriteSampleDescription(w, configuration); WriteTimeToSample(w); if (anyOffset) WriteCompositionOffsets(w, shift); if (_syncSamples.Count != count) { w.BeginFullBox("stss", 0, 0); w.WriteUInt32((uint)_syncSamples.Count); foreach (var s in _syncSamples) w.WriteUInt32(s); w.EndBox(); } WriteSampleToChunk(w); WriteSampleSizes(w); WriteChunkOffsets(w, chunkOffsetDelta); w.EndBox(); // stbl w.EndBox(); // minf w.EndBox(); // mdia w.EndBox(); // trak w.EndBox(); // moov return w.ToArray(); } private static void WriteTimes(BoxWriter w, bool wide, ulong created, long duration) { if (wide) { w.WriteUInt64(created); w.WriteUInt64(created); w.WriteUInt32(TimeScale); w.WriteUInt64((ulong)duration); } else { w.WriteUInt32((uint)created); w.WriteUInt32((uint)created); w.WriteUInt32(TimeScale); w.WriteUInt32((uint)duration); } } private void WriteSampleDescription(BoxWriter w, DecoderConfiguration configuration) { w.BeginFullBox("stsd", 0, 0); w.WriteUInt32(1); w.BeginBox(_config.Codec switch { VideoCodec.H264 => "avc1", VideoCodec.Hevc => "hvc1", _ => "av01" }); w.WriteZeros(6); w.WriteUInt16(1); // data_reference_index w.WriteZeros(16); // pre_defined, reserved w.WriteUInt16(configuration.Width); w.WriteUInt16(configuration.Height); w.WriteUInt32(0x00480000); // 72 dpi w.WriteUInt32(0x00480000); w.WriteUInt32(0); w.WriteUInt16(1); // frame_count Span compressor = stackalloc byte[32]; compressor.Clear(); compressor[0] = 6; "Titano"u8.CopyTo(compressor[1..]); w.WriteBytes(compressor); w.WriteUInt16(0x0018); w.WriteInt16(-1); w.BeginBox(configuration.BoxType); w.WriteBytes(configuration.Payload); w.EndBox(); w.BeginBox("colr"); w.WriteFourCc("nclx"); w.WriteUInt16(1); // BT.709 primaries w.WriteUInt16(1); // BT.709 transfer w.WriteUInt16(1); // BT.709 matrix w.WriteByte(_config.FullRange ? 0x80 : 0); w.EndBox(); w.BeginBox("pasp"); w.WriteUInt32(1); w.WriteUInt32(1); w.EndBox(); w.BeginBox("btrt"); uint maxSize = 0; foreach (var s in _sizes) maxSize = Math.Max(maxSize, s); var seconds = _totalTicks / (double)TimeScale; w.WriteUInt32(maxSize); w.WriteUInt32((uint)Math.Min(uint.MaxValue, PeakBitrate())); w.WriteUInt32((uint)Math.Min(uint.MaxValue, _totalBytes * 8 / Math.Max(seconds, 1e-9))); w.EndBox(); w.EndBox(); // sample entry w.EndBox(); // stsd } /// Largest number of bits in any one-second window of decode time. private long PeakBitrate() { long peak = 0, window = 0, startTime = 0, time = 0; var first = 0; for (var i = 0; i < _sizes.Count; i++) { window += _sizes[i]; while (time - startTime >= TimeScale) { window -= _sizes[first]; startTime += _durations[first]; first++; } peak = Math.Max(peak, window * 8); time += _durations[i]; } return _totalTicks < TimeScale ? (long)(peak * (TimeScale / (double)_totalTicks)) : peak; } private void WriteTimeToSample(BoxWriter w) { var runs = new List<(uint Count, uint Delta)>(); foreach (var d in _durations) { if (runs.Count > 0 && runs[^1].Delta == d) runs[^1] = (runs[^1].Count + 1, d); else runs.Add((1, d)); } w.BeginFullBox("stts", 0, 0); w.WriteUInt32((uint)runs.Count); foreach (var (count, delta) in runs) { w.WriteUInt32(count); w.WriteUInt32(delta); } w.EndBox(); } private void WriteCompositionOffsets(BoxWriter w, long shift) { var runs = new List<(uint Count, uint Offset)>(); foreach (var o in _compositionOffsets) { var v = (uint)(o + shift); if (runs.Count > 0 && runs[^1].Offset == v) runs[^1] = (runs[^1].Count + 1, v); else runs.Add((1, v)); } w.BeginFullBox("ctts", 0, 0); w.WriteUInt32((uint)runs.Count); foreach (var (count, offset) in runs) { w.WriteUInt32(count); w.WriteUInt32(offset); } w.EndBox(); } private void WriteSampleToChunk(BoxWriter w) { var entries = new List<(uint FirstChunk, uint Samples)>(); for (var i = 0; i < _chunkSampleCounts.Count; i++) { if (entries.Count == 0 || entries[^1].Samples != _chunkSampleCounts[i]) entries.Add(((uint)i + 1, _chunkSampleCounts[i])); } w.BeginFullBox("stsc", 0, 0); w.WriteUInt32((uint)entries.Count); foreach (var (firstChunk, samples) in entries) { w.WriteUInt32(firstChunk); w.WriteUInt32(samples); w.WriteUInt32(1); } w.EndBox(); } private void WriteSampleSizes(BoxWriter w) { var constant = true; foreach (var s in _sizes) constant &= s == _sizes[0]; w.BeginFullBox("stsz", 0, 0); w.WriteUInt32(constant ? _sizes[0] : 0); w.WriteUInt32((uint)_sizes.Count); if (!constant) { foreach (var s in _sizes) w.WriteUInt32(s); } w.EndBox(); } private void WriteChunkOffsets(BoxWriter w, long delta) { var wide = _chunkOffsets.Count > 0 && _chunkOffsets[^1] + delta > uint.MaxValue; w.BeginFullBox(wide ? "co64" : "stco", 0, 0); w.WriteUInt32((uint)_chunkOffsets.Count); foreach (var offset in _chunkOffsets) { if (wide) w.WriteUInt64((ulong)(offset + delta)); else w.WriteUInt32((uint)(offset + delta)); } w.EndBox(); } }