Files
Chronos/src/Titano.Core/Video/Avi/AviMjpegWriter.cs
T

313 lines
12 KiB
C#

using System.Buffers.Binary;
namespace Titano.Core.Video.Avi;
/// <summary>
/// Streaming RIFF AVI writer for already-encoded JPEG frames ('MJPG', chunks '00dc'). Writes the legacy idx1 index
/// for the first RIFF and OpenDML indexes ('indx' super index, one 'ix00' per RIFF) so files can continue in
/// 'AVIX' RIFF lists past the per-RIFF size limit. AVI is constant frame rate: repeat a frame to hold it longer.
/// The output stream must be seekable and is not disposed.
/// </summary>
public sealed class AviMjpegWriter
{
/// <summary>Default size of each RIFF list; 1 GiB keeps the first RIFF readable by AVI 1.0 software.</summary>
public const long DefaultRiffSizeLimit = 1L << 30;
private const int SuperIndexCapacity = 256;
private const uint KeyFrameFlag = 0x10; // AVIIF_KEYFRAME
private static readonly uint ChunkId = FourCc("00dc");
private readonly Stream _stream;
private readonly int _width;
private readonly int _height;
private readonly uint _rate;
private readonly uint _scale;
private readonly long _riffLimit;
private readonly long _start;
private readonly List<(long Offset, uint Size, uint Frames)> _superIndex = [];
private readonly List<(long DataOffset, uint Size)> _segmentFrames = [];
private long _avih, _strh, _indx, _dmlh;
private long _riffStart, _moviStart, _position;
private int _framesInFirstRiff;
private int _totalFrames;
private uint _maxFrame;
private bool _completed;
/// <param name="riffSizeLimit">Bytes per RIFF list before an 'AVIX' list starts (tests use small values).</param>
public AviMjpegWriter(Stream output, int width, int height, Rational frameRate, long riffSizeLimit = DefaultRiffSizeLimit)
{
ArgumentNullException.ThrowIfNull(output);
if (!output.CanSeek || !output.CanWrite) throw new ArgumentException("The output stream must be writable and seekable", nameof(output));
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate));
ArgumentOutOfRangeException.ThrowIfLessThan(riffSizeLimit, 16 * 1024);
ArgumentOutOfRangeException.ThrowIfGreaterThan(riffSizeLimit, uint.MaxValue);
_stream = output;
_width = width;
_height = height;
var g = Gcd(frameRate.Numerator, frameRate.Denominator);
_rate = (uint)(frameRate.Numerator / g);
_scale = (uint)(frameRate.Denominator / g);
_riffLimit = riffSizeLimit;
_start = output.Position;
WriteHeaders();
}
public int FrameCount => _totalFrames;
/// <summary>Appends one JPEG (SOI-prefixed) frame.</summary>
public void WriteFrame(ReadOnlySpan<byte> jpeg)
{
if (_completed) throw new InvalidOperationException("The writer is complete");
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) throw new ArgumentException("Not a JPEG frame", nameof(jpeg));
var chunk = 8L + jpeg.Length + (jpeg.Length & 1);
if (_segmentFrames.Count > 0 && _position - _riffStart + chunk + IndexOverhead(_segmentFrames.Count + 1) > _riffLimit)
{
CloseSegment();
OpenSegment("AVIX");
}
Span<byte> header = stackalloc byte[8];
BinaryPrimitives.WriteUInt32LittleEndian(header, ChunkId);
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)jpeg.Length);
_stream.Write(header);
_stream.Write(jpeg);
if ((jpeg.Length & 1) != 0) _stream.WriteByte(0);
_segmentFrames.Add((_position + 8, (uint)jpeg.Length));
_position += chunk;
_maxFrame = Math.Max(_maxFrame, (uint)jpeg.Length);
_totalFrames++;
}
/// <summary>Writes the indexes, patches sizes and frame counts, and flushes.</summary>
public void Complete()
{
if (_completed) throw new InvalidOperationException("The writer is already complete");
CloseSegment();
var buffer = _maxFrame + 8;
var bytesPerSecond = (uint)Math.Min(uint.MaxValue, (double)_maxFrame * _rate / _scale);
Patch(_avih + 4, bytesPerSecond);
Patch(_avih + 16, (uint)_framesInFirstRiff);
Patch(_avih + 28, buffer);
Patch(_strh + 32, (uint)_totalFrames);
Patch(_strh + 36, buffer);
Patch(_dmlh, (uint)_totalFrames);
Patch(_indx + 4, (uint)_superIndex.Count);
Span<byte> entry = stackalloc byte[16];
for (var i = 0; i < _superIndex.Count; i++)
{
BinaryPrimitives.WriteInt64LittleEndian(entry, _superIndex[i].Offset);
BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], _superIndex[i].Size);
BinaryPrimitives.WriteUInt32LittleEndian(entry[12..], _superIndex[i].Frames);
_stream.Position = _indx + 24 + i * 16;
_stream.Write(entry);
}
_stream.Position = _position;
_stream.Flush();
_completed = true;
}
/// <summary>Bytes the segment's ix00 (and idx1 in the first RIFF) will need for <paramref name="frames"/> frames.</summary>
private long IndexOverhead(int frames) => 32 + 8L * frames + (_superIndex.Count == 0 ? 8 + 16L * frames : 0);
private void WriteHeaders()
{
var h = new List<byte>(4800);
var riff = Begin(h, "RIFF", "AVI ");
var hdrl = Begin(h, "LIST", "hdrl");
_avih = ChunkStart(h, "avih", 56);
Add32(h, (uint)Math.Round(1_000_000.0 * _scale / _rate)); // dwMicroSecPerFrame
Add32(h, 0); // dwMaxBytesPerSec (patched)
Add32(h, 0); // dwPaddingGranularity
Add32(h, 0x10 | 0x100); // AVIF_HASINDEX | AVIF_ISINTERLEAVED
Add32(h, 0); // dwTotalFrames of the first RIFF (patched)
Add32(h, 0); // dwInitialFrames
Add32(h, 1); // dwStreams
Add32(h, 0); // dwSuggestedBufferSize (patched)
Add32(h, (uint)_width);
Add32(h, (uint)_height);
AddZeros(h, 16);
var strl = Begin(h, "LIST", "strl");
_strh = ChunkStart(h, "strh", 56);
Add32(h, FourCc("vids"));
Add32(h, FourCc("MJPG"));
Add32(h, 0); // dwFlags
Add32(h, 0); // wPriority, wLanguage
Add32(h, 0); // dwInitialFrames
Add32(h, _scale);
Add32(h, _rate);
Add32(h, 0); // dwStart
Add32(h, 0); // dwLength (patched)
Add32(h, 0); // dwSuggestedBufferSize (patched)
Add32(h, uint.MaxValue); // dwQuality: default
Add32(h, 0); // dwSampleSize: variable
Add16(h, 0);
Add16(h, 0);
Add16(h, (ushort)Math.Min(_width, short.MaxValue));
Add16(h, (ushort)Math.Min(_height, short.MaxValue));
ChunkStart(h, "strf", 40);
Add32(h, 40); // BITMAPINFOHEADER.biSize
Add32(h, (uint)_width);
Add32(h, (uint)_height);
Add16(h, 1); // biPlanes
Add16(h, 24); // biBitCount
Add32(h, FourCc("MJPG"));
Add32(h, (uint)Math.Min(uint.MaxValue, (long)_width * _height * 3));
AddZeros(h, 16);
_indx = ChunkStart(h, "indx", 24 + 16 * SuperIndexCapacity);
Add16(h, 4); // wLongsPerEntry
h.Add(0); // bIndexSubType
h.Add(0); // bIndexType = AVI_INDEX_OF_INDEXES
Add32(h, 0); // nEntriesInUse (patched)
Add32(h, ChunkId);
AddZeros(h, 12 + 16 * SuperIndexCapacity);
End(h, strl);
var odml = Begin(h, "LIST", "odml");
_dmlh = ChunkStart(h, "dmlh", 248);
AddZeros(h, 248);
End(h, odml);
End(h, hdrl);
// The RIFF size is patched when the first segment closes; the movi list follows directly.
_riffStart = _start + riff;
_stream.Write(h.ToArray());
_avih += _start;
_strh += _start;
_indx += _start;
_dmlh += _start;
_position = _start + h.Count;
OpenMovi();
}
private void OpenSegment(string type)
{
_riffStart = _position;
Span<byte> header = stackalloc byte[12];
BinaryPrimitives.WriteUInt32LittleEndian(header, FourCc("RIFF"));
BinaryPrimitives.WriteUInt32LittleEndian(header[8..], FourCc(type));
_stream.Write(header);
_position += 12;
OpenMovi();
}
private void OpenMovi()
{
Span<byte> header = stackalloc byte[12];
BinaryPrimitives.WriteUInt32LittleEndian(header, FourCc("LIST"));
BinaryPrimitives.WriteUInt32LittleEndian(header[8..], FourCc("movi"));
_stream.Write(header);
_moviStart = _position + 8; // offsets in idx1 and ix00 are relative to the 'movi' four-cc
_position += 12;
}
private void CloseSegment()
{
if (_superIndex.Count == SuperIndexCapacity) throw new InvalidOperationException("AVI super index is full");
var frames = _segmentFrames.Count;
// Standard index (OpenDML ix00) closes the movi list.
var ixOffset = _position;
var ix = new byte[32 + 8 * frames];
BinaryPrimitives.WriteUInt32LittleEndian(ix, FourCc("ix00"));
BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(4), (uint)(ix.Length - 8));
BinaryPrimitives.WriteUInt16LittleEndian(ix.AsSpan(8), 2); // wLongsPerEntry
ix[11] = 1; // AVI_INDEX_OF_CHUNKS
BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(12), (uint)frames);
BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(16), ChunkId);
BinaryPrimitives.WriteInt64LittleEndian(ix.AsSpan(20), _moviStart);
for (var i = 0; i < frames; i++)
{
BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(32 + i * 8), (uint)(_segmentFrames[i].DataOffset - _moviStart));
BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(36 + i * 8), _segmentFrames[i].Size); // bit 31 clear: key frame
}
_stream.Position = ixOffset;
_stream.Write(ix);
_position += ix.Length;
Patch(_moviStart - 4, (uint)(_position - _moviStart));
if (_superIndex.Count == 0)
{
var idx1 = new byte[8 + 16 * frames];
BinaryPrimitives.WriteUInt32LittleEndian(idx1, FourCc("idx1"));
BinaryPrimitives.WriteUInt32LittleEndian(idx1.AsSpan(4), (uint)(idx1.Length - 8));
for (var i = 0; i < frames; i++)
{
var e = idx1.AsSpan(8 + i * 16);
BinaryPrimitives.WriteUInt32LittleEndian(e, ChunkId);
BinaryPrimitives.WriteUInt32LittleEndian(e[4..], KeyFrameFlag);
BinaryPrimitives.WriteUInt32LittleEndian(e[8..], (uint)(_segmentFrames[i].DataOffset - 8 - _moviStart));
BinaryPrimitives.WriteUInt32LittleEndian(e[12..], _segmentFrames[i].Size);
}
_stream.Position = _position;
_stream.Write(idx1);
_position += idx1.Length;
_framesInFirstRiff = frames;
}
Patch(_riffStart + 4, (uint)(_position - _riffStart - 8));
_superIndex.Add((ixOffset, (uint)ix.Length, (uint)frames));
_segmentFrames.Clear();
_stream.Position = _position;
}
private void Patch(long offset, uint value)
{
Span<byte> bytes = stackalloc byte[4];
BinaryPrimitives.WriteUInt32LittleEndian(bytes, value);
_stream.Position = offset;
_stream.Write(bytes);
}
private static int Begin(List<byte> h, string id, string type)
{
var start = h.Count;
Add32(h, FourCc(id));
Add32(h, 0);
Add32(h, FourCc(type));
return start;
}
private static void End(List<byte> h, int start)
{
var size = (uint)(h.Count - start - 8);
for (var i = 0; i < 4; i++) h[start + 4 + i] = (byte)(size >> (8 * i));
}
/// <summary>Writes a chunk header and returns the offset of its data.</summary>
private static int ChunkStart(List<byte> h, string id, int size)
{
Add32(h, FourCc(id));
Add32(h, (uint)size);
return h.Count;
}
private static void Add16(List<byte> h, ushort v)
{
h.Add((byte)v);
h.Add((byte)(v >> 8));
}
private static void Add32(List<byte> h, uint v)
{
for (var i = 0; i < 4; i++) h.Add((byte)(v >> (8 * i)));
}
private static void AddZeros(List<byte> h, int count)
{
for (var i = 0; i < count; i++) h.Add(0);
}
private static uint FourCc(string s) => (uint)(s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24);
private static int Gcd(int a, int b)
{
while (b != 0) (a, b) = (b, a % b);
return a;
}
}