feat(video): add streaming MP4 muxer, decoder configuration records and MP4 inspector
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
6 files changed
+2018
No files matched your search
@@ -0,0 +1,106 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Titano.Core.Video.Mp4;
|
||||
|
||||
/// <summary>
|
||||
/// Big-endian ISO-BMFF box builder over a growable in-memory buffer. Boxes nest with
|
||||
/// <see cref="BeginBox"/>/<see cref="EndBox"/>; sizes (32-bit) are patched when a box closes.
|
||||
/// </summary>
|
||||
public sealed class BoxWriter
|
||||
{
|
||||
private readonly Stack<int> _open = new();
|
||||
private byte[] _buffer;
|
||||
private int _length;
|
||||
|
||||
public BoxWriter(int capacity = 4096) => _buffer = new byte[Math.Max(capacity, 64)];
|
||||
|
||||
public int Length => _length;
|
||||
|
||||
public ReadOnlySpan<byte> WrittenSpan => _buffer.AsSpan(0, _length);
|
||||
|
||||
public void BeginBox(string type)
|
||||
{
|
||||
_open.Push(_length);
|
||||
WriteUInt32(0);
|
||||
WriteFourCc(type);
|
||||
}
|
||||
|
||||
public void BeginFullBox(string type, byte version, uint flags)
|
||||
{
|
||||
BeginBox(type);
|
||||
WriteUInt32((uint)version << 24 | (flags & 0xFFFFFF));
|
||||
}
|
||||
|
||||
public void EndBox()
|
||||
{
|
||||
var start = _open.Pop();
|
||||
BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(start), (uint)(_length - start));
|
||||
}
|
||||
|
||||
public void WriteByte(int value) => Grow(1)[0] = (byte)value;
|
||||
|
||||
public void WriteUInt16(int value) => BinaryPrimitives.WriteUInt16BigEndian(Grow(2), (ushort)value);
|
||||
|
||||
public void WriteInt16(short value) => BinaryPrimitives.WriteInt16BigEndian(Grow(2), value);
|
||||
|
||||
public void WriteUInt24(uint value)
|
||||
{
|
||||
var span = Grow(3);
|
||||
span[0] = (byte)(value >> 16);
|
||||
span[1] = (byte)(value >> 8);
|
||||
span[2] = (byte)value;
|
||||
}
|
||||
|
||||
public void WriteUInt32(uint value) => BinaryPrimitives.WriteUInt32BigEndian(Grow(4), value);
|
||||
|
||||
public void WriteInt32(int value) => BinaryPrimitives.WriteInt32BigEndian(Grow(4), value);
|
||||
|
||||
public void WriteUInt48(ulong value)
|
||||
{
|
||||
WriteUInt16((int)(value >> 32));
|
||||
WriteUInt32((uint)value);
|
||||
}
|
||||
|
||||
public void WriteUInt64(ulong value) => BinaryPrimitives.WriteUInt64BigEndian(Grow(8), value);
|
||||
|
||||
public void WriteInt64(long value) => BinaryPrimitives.WriteInt64BigEndian(Grow(8), value);
|
||||
|
||||
public void WriteFourCc(string fourCc)
|
||||
{
|
||||
if (fourCc.Length != 4) throw new ArgumentException("A four-character code is required", nameof(fourCc));
|
||||
var span = Grow(4);
|
||||
for (var i = 0; i < 4; i++) span[i] = (byte)fourCc[i];
|
||||
}
|
||||
|
||||
public void WriteBytes(ReadOnlySpan<byte> bytes) => bytes.CopyTo(Grow(bytes.Length));
|
||||
|
||||
public void WriteZeros(int count) => Grow(count).Clear();
|
||||
|
||||
/// <summary>The identity transformation matrix of mvhd/tkhd.</summary>
|
||||
public void WriteUnityMatrix()
|
||||
{
|
||||
WriteUInt32(0x00010000);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0x00010000);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0);
|
||||
WriteUInt32(0x40000000);
|
||||
}
|
||||
|
||||
public byte[] ToArray()
|
||||
{
|
||||
if (_open.Count != 0) throw new InvalidOperationException("Unclosed box");
|
||||
return WrittenSpan.ToArray();
|
||||
}
|
||||
|
||||
private Span<byte> Grow(int count)
|
||||
{
|
||||
if (_length + count > _buffer.Length) Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + count));
|
||||
var span = _buffer.AsSpan(_length, count);
|
||||
_length += count;
|
||||
return span;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using Titano.Core.Video.Bitstream;
|
||||
|
||||
namespace Titano.Core.Video.Mp4;
|
||||
|
||||
/// <summary>
|
||||
/// A decoder configuration record (avcC, hvcC or av1C payload) with the stream properties it declares.
|
||||
/// </summary>
|
||||
public sealed record DecoderConfiguration(
|
||||
VideoCodec Codec,
|
||||
string BoxType,
|
||||
byte[] Payload,
|
||||
int Width,
|
||||
int Height,
|
||||
int BitDepth,
|
||||
string CodecString)
|
||||
{
|
||||
/// <summary>Builds avcC (ISO/IEC 14496-15 5.3.3) from SPS and PPS NAL units; the first SPS describes the stream.</summary>
|
||||
public static DecoderConfiguration ForAvc(IReadOnlyList<byte[]> sps, IReadOnlyList<byte[]> pps)
|
||||
{
|
||||
if (sps.Count is 0 or > 31 || pps.Count is 0 or > 255) throw new ArgumentException("avcC needs 1–31 SPS and 1–255 PPS");
|
||||
if (!H264SpsParser.TryParse(sps[0], out var info)) throw new ArgumentException("Unparseable H.264 SPS", nameof(sps));
|
||||
var w = new BoxWriter(256);
|
||||
w.WriteByte(1);
|
||||
w.WriteByte(info.ProfileIdc);
|
||||
w.WriteByte(info.ConstraintFlags);
|
||||
w.WriteByte(info.LevelIdc);
|
||||
w.WriteByte(0xFF); // reserved + lengthSizeMinusOne = 3
|
||||
w.WriteByte(0xE0 | sps.Count);
|
||||
foreach (var s in sps)
|
||||
{
|
||||
w.WriteUInt16(s.Length);
|
||||
w.WriteBytes(s);
|
||||
}
|
||||
w.WriteByte(pps.Count);
|
||||
foreach (var p in pps)
|
||||
{
|
||||
w.WriteUInt16(p.Length);
|
||||
w.WriteBytes(p);
|
||||
}
|
||||
if (info.ProfileIdc is 100 or 110 or 122 or 144)
|
||||
{
|
||||
w.WriteByte(0xFC | info.ChromaFormatIdc);
|
||||
w.WriteByte(0xF8 | (info.BitDepthLuma - 8));
|
||||
w.WriteByte(0xF8 | (info.BitDepthChroma - 8));
|
||||
w.WriteByte(0); // numOfSequenceParameterSetExt
|
||||
}
|
||||
return new DecoderConfiguration(VideoCodec.H264, "avcC", w.ToArray(), info.Width, info.Height, info.BitDepthLuma, AvcCodecString(info));
|
||||
}
|
||||
|
||||
/// <summary>Builds hvcC (ISO/IEC 14496-15 8.3.3) with complete VPS/SPS/PPS arrays; the first SPS describes the stream.</summary>
|
||||
public static DecoderConfiguration ForHevc(IReadOnlyList<byte[]> vps, IReadOnlyList<byte[]> sps, IReadOnlyList<byte[]> pps)
|
||||
{
|
||||
if (vps.Count == 0 || sps.Count == 0 || pps.Count == 0) throw new ArgumentException("hvcC needs VPS, SPS and PPS");
|
||||
if (!HevcSpsParser.TryParse(sps[0], out var info)) throw new ArgumentException("Unparseable HEVC SPS", nameof(sps));
|
||||
var ptl = info.ProfileTierLevel;
|
||||
var w = new BoxWriter(256);
|
||||
w.WriteByte(1);
|
||||
w.WriteByte(ptl.ProfileSpace << 6 | (ptl.HighTier ? 0x20 : 0) | ptl.ProfileIdc);
|
||||
w.WriteUInt32(ptl.ProfileCompatibilityFlags);
|
||||
w.WriteUInt48(ptl.ConstraintIndicatorFlags);
|
||||
w.WriteByte(ptl.LevelIdc);
|
||||
w.WriteUInt16(0xF000); // min_spatial_segmentation_idc = 0
|
||||
w.WriteByte(0xFC); // parallelismType = 0 (unknown)
|
||||
w.WriteByte(0xFC | info.ChromaFormatIdc);
|
||||
w.WriteByte(0xF8 | (info.BitDepthLuma - 8));
|
||||
w.WriteByte(0xF8 | (info.BitDepthChroma - 8));
|
||||
w.WriteUInt16(0); // avgFrameRate unspecified
|
||||
w.WriteByte((info.MaxSubLayers & 7) << 3 | (info.TemporalIdNesting ? 4 : 0) | 3);
|
||||
w.WriteByte(3);
|
||||
WriteArray(w, HevcNalUnitType.Vps, vps);
|
||||
WriteArray(w, HevcNalUnitType.Sps, sps);
|
||||
WriteArray(w, HevcNalUnitType.Pps, pps);
|
||||
return new DecoderConfiguration(VideoCodec.Hevc, "hvcC", w.ToArray(), info.Width, info.Height, info.BitDepthLuma, HevcCodecString(ptl));
|
||||
|
||||
static void WriteArray(BoxWriter w, HevcNalUnitType type, IReadOnlyList<byte[]> nals)
|
||||
{
|
||||
w.WriteByte(0x80 | (int)type); // array_completeness = 1: no parameter sets in-band (hvc1)
|
||||
w.WriteUInt16(nals.Count);
|
||||
foreach (var nal in nals)
|
||||
{
|
||||
w.WriteUInt16(nal.Length);
|
||||
w.WriteBytes(nal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds av1C (AV1-ISOBMFF 2.3) around a sequence header OBU written with obu_size.</summary>
|
||||
public static DecoderConfiguration ForAv1(byte[] sequenceHeaderObu)
|
||||
{
|
||||
if (!Av1ObuParser.TryReadObu(sequenceHeaderObu, 0, out var obu) || obu.Type != Av1ObuType.SequenceHeader || !obu.HasSizeField
|
||||
|| !Av1ObuParser.TryParseSequenceHeader(obu.Payload(sequenceHeaderObu), out var seq))
|
||||
throw new ArgumentException("A sized sequence header OBU is required", nameof(sequenceHeaderObu));
|
||||
var w = new BoxWriter(64);
|
||||
w.WriteByte(0x81); // marker + version 1
|
||||
w.WriteByte(seq.SeqProfile << 5 | seq.SeqLevelIdx);
|
||||
w.WriteByte((seq.SeqTier ? 0x80 : 0) | (seq.HighBitDepth ? 0x40 : 0) | (seq.TwelveBit ? 0x20 : 0) | (seq.MonoChrome ? 0x10 : 0)
|
||||
| (seq.ChromaSubsamplingX ? 0x08 : 0) | (seq.ChromaSubsamplingY ? 0x04 : 0) | seq.ChromaSamplePosition);
|
||||
w.WriteByte(seq.InitialDisplayDelay is { } delay ? 0x10 | ((delay - 1) & 0x0F) : 0);
|
||||
w.WriteBytes(sequenceHeaderObu.AsSpan(0, obu.TotalLength));
|
||||
return new DecoderConfiguration(VideoCodec.Av1, "av1C", w.ToArray(), seq.MaxFrameWidth, seq.MaxFrameHeight, seq.BitDepth, Av1CodecString(seq));
|
||||
}
|
||||
|
||||
/// <summary>Parses an avcC/hvcC/av1C payload back; <paramref name="error"/> explains a failure.</summary>
|
||||
public static bool TryParse(string boxType, ReadOnlySpan<byte> payload, out DecoderConfiguration? configuration, out string? error)
|
||||
{
|
||||
configuration = null;
|
||||
error = null;
|
||||
try
|
||||
{
|
||||
configuration = boxType switch
|
||||
{
|
||||
"avcC" => ParseAvc(payload, out error),
|
||||
"hvcC" => ParseHevc(payload, out error),
|
||||
"av1C" => ParseAv1(payload, out error),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
configuration = null;
|
||||
}
|
||||
error ??= configuration is null ? $"unsupported configuration box '{boxType}'" : null;
|
||||
return configuration is not null;
|
||||
}
|
||||
|
||||
private static DecoderConfiguration? ParseAvc(ReadOnlySpan<byte> p, out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (p.Length < 7 || p[0] != 1)
|
||||
{
|
||||
error = "avcC header invalid";
|
||||
return null;
|
||||
}
|
||||
if ((p[4] & 3) != 3) error = "avcC lengthSizeMinusOne is not 3";
|
||||
var pos = 5;
|
||||
var sps = ReadNalList(p, ref pos, p[5] & 0x1F, 1);
|
||||
var pps = pos < p.Length ? ReadNalList(p, ref pos, p[pos], 1) : null;
|
||||
if (sps is null || pps is null || sps.Count == 0 || pps.Count == 0)
|
||||
{
|
||||
error = "avcC parameter set lists truncated or empty";
|
||||
return null;
|
||||
}
|
||||
var config = ForAvc(sps, pps);
|
||||
if (config.Payload[1] != p[1] || config.Payload[3] != p[3]) error = "avcC profile/level differ from its SPS";
|
||||
return config;
|
||||
}
|
||||
|
||||
private static DecoderConfiguration? ParseHevc(ReadOnlySpan<byte> p, out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (p.Length < 23 || p[0] != 1)
|
||||
{
|
||||
error = "hvcC header invalid";
|
||||
return null;
|
||||
}
|
||||
if ((p[21] & 3) != 3) error = "hvcC lengthSizeMinusOne is not 3";
|
||||
var arrays = p[22];
|
||||
var pos = 23;
|
||||
List<byte[]> vps = [], sps = [], pps = [];
|
||||
for (var a = 0; a < arrays; a++)
|
||||
{
|
||||
if (pos + 3 > p.Length)
|
||||
{
|
||||
error = "hvcC arrays truncated";
|
||||
return null;
|
||||
}
|
||||
var type = (HevcNalUnitType)(p[pos] & 0x3F);
|
||||
var count = BinaryPrimitives.ReadUInt16BigEndian(p[(pos + 1)..]);
|
||||
pos += 3;
|
||||
var list = ReadNalList(p, ref pos, count, 0);
|
||||
if (list is null)
|
||||
{
|
||||
error = "hvcC NAL units truncated";
|
||||
return null;
|
||||
}
|
||||
(type switch { HevcNalUnitType.Vps => vps, HevcNalUnitType.Sps => sps, HevcNalUnitType.Pps => pps, _ => [] }).AddRange(list);
|
||||
}
|
||||
if (vps.Count == 0 || sps.Count == 0 || pps.Count == 0)
|
||||
{
|
||||
error = "hvcC lacks a VPS, SPS or PPS array";
|
||||
return null;
|
||||
}
|
||||
var config = ForHevc(vps, sps, pps);
|
||||
if (!config.Payload.AsSpan(1, 12).SequenceEqual(p.Slice(1, 12))) error = "hvcC profile/tier/level differ from its SPS";
|
||||
return config;
|
||||
}
|
||||
|
||||
private static DecoderConfiguration? ParseAv1(ReadOnlySpan<byte> p, out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (p.Length < 4 || p[0] != 0x81)
|
||||
{
|
||||
error = "av1C marker/version invalid";
|
||||
return null;
|
||||
}
|
||||
var obus = p[4..];
|
||||
foreach (var obu in Av1ObuParser.Split(obus))
|
||||
{
|
||||
if (obu.Type != Av1ObuType.SequenceHeader) continue;
|
||||
var config = ForAv1(obus.Slice(obu.Offset, obu.TotalLength).ToArray());
|
||||
if (config.Payload[1] != p[1] || config.Payload[2] != p[2]) error = "av1C fields differ from its sequence header";
|
||||
return config;
|
||||
}
|
||||
error = "av1C has no sequence header OBU";
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<byte[]>? ReadNalList(ReadOnlySpan<byte> p, ref int pos, int count, int countBytes)
|
||||
{
|
||||
pos += countBytes;
|
||||
var list = new List<byte[]>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (pos + 2 > p.Length) return null;
|
||||
var length = BinaryPrimitives.ReadUInt16BigEndian(p[pos..]);
|
||||
pos += 2;
|
||||
if (length == 0 || pos + length > p.Length) return null;
|
||||
list.Add(p.Slice(pos, length).ToArray());
|
||||
pos += length;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string AvcCodecString(H264Sps sps) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"avc1.{sps.ProfileIdc:x2}{sps.ConstraintFlags:x2}{sps.LevelIdc:x2}");
|
||||
|
||||
private static string HevcCodecString(HevcProfileTierLevel ptl)
|
||||
{
|
||||
var space = ptl.ProfileSpace == 0 ? string.Empty : ((char)('A' + ptl.ProfileSpace - 1)).ToString();
|
||||
var compatibility = ReverseBits(ptl.ProfileCompatibilityFlags);
|
||||
var s = string.Create(CultureInfo.InvariantCulture,
|
||||
$"hvc1.{space}{ptl.ProfileIdc}.{compatibility:X}.{(ptl.HighTier ? 'H' : 'L')}{ptl.LevelIdc}");
|
||||
var last = 5;
|
||||
while (last >= 0 && ((ptl.ConstraintIndicatorFlags >> (8 * (5 - last))) & 0xFF) == 0) last--;
|
||||
for (var i = 0; i <= last; i++) s += "." + ((ptl.ConstraintIndicatorFlags >> (8 * (5 - i))) & 0xFF).ToString("X", CultureInfo.InvariantCulture);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static string Av1CodecString(Av1SequenceHeader seq) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"av01.{seq.SeqProfile}.{seq.SeqLevelIdx:D2}{(seq.SeqTier ? 'H' : 'M')}.{seq.BitDepth:D2}");
|
||||
|
||||
private static uint ReverseBits(uint v)
|
||||
{
|
||||
uint r = 0;
|
||||
for (var i = 0; i < 32; i++, v >>= 1) r = (r << 1) | (v & 1);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,662 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Video.Bitstream;
|
||||
|
||||
namespace Titano.Core.Video.Mp4;
|
||||
|
||||
/// <summary>Parameters of the single video track written by <see cref="Mp4Muxer"/>.</summary>
|
||||
public sealed record VideoTrackConfig
|
||||
{
|
||||
/// <summary><see cref="VideoCodec.H264"/>, <see cref="VideoCodec.Hevc"/> or <see cref="VideoCodec.Av1"/>.</summary>
|
||||
public required VideoCodec Codec { get; init; }
|
||||
|
||||
/// <summary>Display width (tkhd); the sample entry uses the size declared by the bitstream.</summary>
|
||||
public required int Width { get; init; }
|
||||
|
||||
public required int Height { get; init; }
|
||||
|
||||
/// <summary>Moves moov in front of mdat when completing (progressive playback); the stream must be readable.</summary>
|
||||
public bool FastStart { get; init; }
|
||||
|
||||
/// <summary>Signalled in colr; Titano encodes limited (video) range.</summary>
|
||||
public bool FullRange { get; init; }
|
||||
|
||||
public DateTime CreationTime { get; init; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class Mp4Muxer
|
||||
{
|
||||
/// <summary>Media and movie timescale (ticks per second).</summary>
|
||||
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<uint> _sizes = [];
|
||||
private readonly List<uint> _durations = [];
|
||||
private readonly List<long> _compositionOffsets = [];
|
||||
private readonly List<uint> _syncSamples = [];
|
||||
private readonly List<long> _chunkOffsets = [];
|
||||
private readonly List<uint> _chunkSampleCounts = [];
|
||||
private readonly SortedDictionary<int, byte[]> _vps = [];
|
||||
private readonly SortedDictionary<int, byte[]> _sps = [];
|
||||
private readonly SortedDictionary<int, byte[]> _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;
|
||||
|
||||
/// <summary>Sum of the sample durations written so far, in 90 kHz ticks.</summary>
|
||||
public long Duration90k => _totalTicks;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void AddParameterSets(ReadOnlySpan<byte> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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. <paramref name="compositionOffset90k"/> is presentation minus decode time and may be negative.
|
||||
/// </summary>
|
||||
public void WriteSample(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>Patches mdat, writes moov (and relocates it when <see cref="VideoTrackConfig.FastStart"/> is set) and flushes.</summary>
|
||||
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<byte> data)
|
||||
{
|
||||
Span<byte> 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<byte> 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<byte> 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<byte> header, ReadOnlySpan<byte> 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<byte> data, Av1Obu obu)
|
||||
{
|
||||
Span<byte> 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;
|
||||
|
||||
/// <summary>Stores parameter sets for the sample entry; returns whether the NAL unit belongs in the sample.</summary>
|
||||
private bool RecordNal(ReadOnlySpan<byte> nal)
|
||||
{
|
||||
if (nal.Length < 2) return true;
|
||||
SortedDictionary<int, byte[]> 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<byte> 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<byte> 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<byte> 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
|
||||
}
|
||||
|
||||
/// <summary>Largest number of bits in any one-second window of decode time.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user