WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58)
Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
697de97ec3
commit
6ffcb1bb18
39 files changed
+4235
-469
No files matched your search
@@ -0,0 +1,385 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF <c>AVIX</c> parts),
|
||||
/// written from the format description: the main header, the first video and audio streams and the chunks of the
|
||||
/// <c>movi</c> lists in file order. Key frames come from the <c>idx1</c> index when there is one.
|
||||
/// </summary>
|
||||
public static class AviReader
|
||||
{
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const int MaxHeaderBytes = 16 * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts like an AVI file.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var state = new State();
|
||||
long position = 0;
|
||||
var length = stream.Length;
|
||||
Span<byte> header = stackalloc byte[12];
|
||||
var first = true;
|
||||
while (position + 12 <= length)
|
||||
{
|
||||
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<byte> header = stackalloc byte[12];
|
||||
var position = start;
|
||||
while (position + 8 <= end)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header[..8]);
|
||||
var id = Encoding.Latin1.GetString(header[..4]);
|
||||
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 (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 if (state.InMovi)
|
||||
{
|
||||
AddChunk(id, body, (int)size, state);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case "avih" when size >= 40:
|
||||
{
|
||||
var data = Read(stream, body, (int)size);
|
||||
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, (int)size);
|
||||
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:
|
||||
state.Index = Read(stream, body, (int)Math.Min(size, MaxHeaderBytes * 8L));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Read(Stream stream, long offset, int count)
|
||||
{
|
||||
if (count > MaxHeaderBytes * 8)
|
||||
{
|
||||
throw new ContainerException("Intestazione AVI troppo grande.");
|
||||
}
|
||||
|
||||
var data = new byte[count];
|
||||
stream.Position = offset;
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void AddChunk(string id, long body, int size, State state)
|
||||
{
|
||||
if (id.Length != 4 || !char.IsAsciiDigit(id[0]) || !char.IsAsciiDigit(id[1]))
|
||||
{
|
||||
return; // JUNK, ix## indexes and the like
|
||||
}
|
||||
|
||||
var stream = (id[0] - '0') * 10 + (id[1] - '0');
|
||||
if (state.Chunks.Count >= MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
if (stream == state.VideoStream && (id[2..] is "dc" or "db"))
|
||||
{
|
||||
state.Chunks.Add((body, size));
|
||||
}
|
||||
else if (stream == state.AudioStream && id[2..] == "wb")
|
||||
{
|
||||
state.AudioChunks.Add((body, size));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
|
||||
private 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<MediaSample>(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;
|
||||
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 = frames * frameTicks,
|
||||
Samples = samples,
|
||||
};
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (AudioStream >= 0)
|
||||
{
|
||||
var audioSamples = new List<MediaSample>(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,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
}
|
||||
|
||||
/// <summary>Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index.</summary>
|
||||
private HashSet<int>? KeyFrames()
|
||||
{
|
||||
if (Index is null || VideoStream < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var keys = new HashSet<int>();
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user