using System.Buffers.Binary;
using System.Globalization;
using System.Text;
namespace Febe.Core.Codecs.Containers;
///
/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF AVIX parts),
/// written from the format description: the main header, the first video and audio streams and the chunks of the
/// movi lists in file order. Key frames come from the idx1 index when there is one.
///
public static class AviReader
{
private const int MaxSamples = IsoBmffReader.MaxSamples;
private const int MaxHeaderBytes = 16 * 1024 * 1024;
/// True when the stream starts like an AVI file.
public static bool Looks(ReadOnlySpan start) =>
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
/// Reads a seekable stream from its start.
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var state = new State();
long position = 0;
var length = stream.Length;
Span header = stackalloc byte[12];
var first = true;
while (position + 12 <= length)
{
ct.ThrowIfCancellationRequested();
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 header = stackalloc byte[12];
var position = start;
while (position + 8 <= end)
{
stream.Position = position;
stream.ReadExactly(header[..8]);
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 (state.InMovi && !header[..4].SequenceEqual("LIST"u8))
{
AddChunk(header[..4], body, size, state); // the hot path: no string per chunk
position = next;
continue;
}
var id = Encoding.Latin1.GetString(header[..4]);
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
{
switch (id)
{
case "avih" when size >= 40:
{
var data = Read(stream, body, 40);
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, 36);
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:
// 16 bytes per entry: at most one entry per sample the reader keeps.
state.Index = Read(stream, body, (int)Math.Min(size, 16L * MaxSamples));
break;
}
}
position = next;
}
}
private static byte[] Read(Stream stream, long offset, int count)
{
if (count < 0 || count > 16L * MaxSamples || count > stream.Length - offset)
{
throw new ContainerException("Intestazione AVI danneggiata.");
}
var data = new byte[count];
stream.Position = offset;
stream.ReadExactly(data);
return data;
}
private static void AddChunk(ReadOnlySpan id, long body, uint size, State state)
{
if (!char.IsAsciiDigit((char)id[0]) || !char.IsAsciiDigit((char)id[1]) || size > int.MaxValue)
{
return; // JUNK, ix## indexes and the like
}
var stream = ((id[0] - '0') * 10) + (id[1] - '0');
if (stream == state.VideoStream && id[2] == 'd' && id[3] is (byte)'c' or (byte)'b')
{
if (state.Chunks.Count >= MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
state.Chunks.Add((body, (int)size));
}
else if (stream == state.AudioStream && id[2] == 'w' && id[3] == 'b' && state.AudioChunks.Count < MaxSamples)
{
state.AudioChunks.Add((body, (int)size)); // beyond the limit the audio chunks are not needed
}
}
/// The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».
internal 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(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;
// Header values are taken as stored: a damaged one never gives an overflowing or negative duration.
var trackDuration = frames <= long.MaxValue / frameTicks ? frames * frameTicks : 0;
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 = trackDuration,
Samples = samples,
};
AudioTrack? audio = null;
if (AudioStream >= 0)
{
var audioSamples = new List(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,
};
}
// As the other readers: beyond what a video can last (a damaged header) there is no duration, and the rest stands.
var seconds = video is { Duration: > 0 } ? video.Seconds(video.Duration) : 0;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
}
/// Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index.
private HashSet? KeyFrames()
{
if (Index is null || VideoStream < 0)
{
return null;
}
var keys = new HashSet();
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
}
}
}