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:
Alby96andClaude Opus 5.5 committed 2026-11-18 12:32:33 +01:00
1 parent 697de97ec3
commit 6ffcb1bb18
39 files changed
+4235 -469

No files matched your search

@@ -0,0 +1,233 @@
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
using Febe.Core.Import;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// The container readers and the MP4 writer on videos built from the H.264 conformance streams: every decoded frame must
/// still have its official MD5 after a trip through MP4 (also fragmented), Matroska and AVI.
/// </summary>
[TestClass]
public sealed class ContainerTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
[TestMethod]
[DataRow("BA1_Sony_D")]
[DataRow("CABA3_SVA_B")]
[DataRow("CANL1_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
[DataRow("HCAFR1_HHI_C")]
public void AnMp4WrittenHereDecodesToTheReferenceFrames(string name)
{
var es = ElementaryStream.Load(name);
var container = Read(TestVideos.Mp4(es));
Assert.AreEqual(ContainerFormat.IsoBmff, container.Format);
AssertTrack(es, container.Video!);
CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(TestVideos.Mp4(es), container.Video!));
}
[TestMethod]
[DataRow("CABA3_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
public void AFragmentedMp4IsReadFromItsFragments(string name)
{
var es = ElementaryStream.Load(name);
var file = TestVideos.FragmentedMp4(es, perFragment: 7);
var container = Read(file);
AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay
CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!));
}
[TestMethod]
[DataRow("BA1_Sony_D", false)]
[DataRow("CABA3_SVA_B", true)]
public void AMatroskaOrWebmFileDecodesToTheReferenceFrames(string name, bool webm)
{
var es = ElementaryStream.Load(name);
var file = TestVideos.Matroska(es, webm: webm);
var container = Read(file);
Assert.AreEqual(ContainerFormat.Matroska, container.Format);
Assert.AreEqual(es.Count, container.Video!.Samples.Count);
Assert.AreEqual(VideoCodec.H264, container.Video.Codec);
Assert.AreEqual((es.Width, es.Height), (container.Video.Width, container.Video.Height));
CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video));
}
[TestMethod]
public void AnAviFileDecodesToTheReferenceFramesAndKeepsItsKeyFrames()
{
var es = ElementaryStream.Load("SVA_BA1_B");
var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021");
var container = Read(file);
Assert.AreEqual(ContainerFormat.Avi, container.Format);
Assert.IsTrue(container.Video!.AnnexB);
Assert.AreEqual(VideoCodec.H264, container.Video.Codec);
CollectionAssert.AreEqual(es.Key, container.Video.Samples.Select(s => s.Key).ToArray());
Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), container.CreatedAt);
Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.01);
CollectionAssert.AreEqual(ElementaryStream.Reference("SVA_BA1_B"), DecodeAll(file, container.Video));
}
[TestMethod]
public void TheMp4WriterKeepsDateRotationAudioAndStartsWithTheMovieBox()
{
var es = ElementaryStream.Load("BA1_Sony_D");
var created = new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.Zero);
var file = TestVideos.Mp4(es, created, rotation: 90, audio: true);
Assert.AreEqual("ftyp", System.Text.Encoding.ASCII.GetString(file, 4, 4));
var ftypSize = (int)System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(file);
Assert.AreEqual("moov", System.Text.Encoding.ASCII.GetString(file, ftypSize + 4, 4), "moov prima dei dati");
var container = Read(file);
Assert.AreEqual(created, container.CreatedAt);
Assert.AreEqual(90, container.Video!.Rotation);
Assert.AreEqual((es.Height, es.Width), (container.Video.DisplayWidth, container.Video.DisplayHeight));
Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05);
Assert.IsNotNull(container.Audio);
Assert.AreEqual(AudioCodec.Aac, container.Audio.Codec);
Assert.AreEqual((44100, 2), (container.Audio.SampleRate, container.Audio.Channels));
CollectionAssert.AreEqual(new byte[] { 0x12, 0x10 }, container.Audio.AacConfiguration);
// The hand-written header reader of the import agrees on the same file.
using var temp = new TempFolder("mp4-scritto");
var path = TestVideos.Write(temp, "video.mp4", file);
var info = Mp4Reader.ReadFile(path, Now);
Assert.IsNotNull(info);
Assert.AreEqual(created, info.CreatedAt);
}
[TestMethod]
public void TheMp4WriterRemuxesAMatroskaFileFrameForFrame()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
var mkv = TestVideos.Matroska(es);
var source = Read(mkv);
var video = source.Video!;
using var input = new MemoryStream(mkv);
var buffer = Array.Empty<byte>();
var track = new Mp4OutputTrack
{
IsVideo = true,
Timescale = video.Timescale,
Samples = [.. video.Samples.Select(s => new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime, s.Key))],
WriteSample = (i, o) => o.Write(ContainerReader.ReadSample(input, video.Samples[i], ref buffer)),
Width = video.Width,
Height = video.Height,
AvcConfiguration = video.AvcConfiguration,
};
using var output = new MemoryStream();
Mp4Writer.Write(output, [track]);
var remuxed = Read(output.ToArray());
Assert.AreEqual(video.Samples.Count, remuxed.Video!.Samples.Count);
CollectionAssert.AreEqual(ElementaryStream.Reference("CABA3_SVA_B"), DecodeAll(output.ToArray(), remuxed.Video));
}
[TestMethod]
public void TheMetadataProbeReadsEveryContainerWithoutExternalPrograms()
{
var es = ElementaryStream.Load("BA1_Sony_D");
var created = new DateTimeOffset(2022, 5, 6, 7, 8, 9, TimeSpan.Zero);
using var temp = new TempFolder("sonda");
var mp4 = TestVideos.Write(temp, "a.mp4", TestVideos.Mp4(es, created, rotation: 270));
var mkv = TestVideos.Write(temp, "b.mkv", TestVideos.Matroska(es, created));
var webm = TestVideos.Write(temp, "c.webm", TestVideos.Matroska(es, created, webm: true));
var avi = TestVideos.Write(temp, "d.avi", TestVideos.Avi(es, "Fri May 06 07:08:09 2022"));
var junk = TestVideos.Write(temp, "e.mp4", [0, 0, 0, 8, .. "ftyp"u8, 1, 2, 3]);
var other = TestVideos.Write(temp, "f.bin", [.. "non è un video"u8]);
foreach (var path in new[] { mp4, mkv, webm, avi })
{
var meta = ContainerVideoMetadataProbe.Probe(path, Now);
Assert.IsNotNull(meta, path);
Assert.AreEqual(created, meta.CreatedAt, path);
Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05, path);
var expected = path == mp4 ? (es.Height, es.Width) : (es.Width, es.Height);
Assert.AreEqual(expected, (meta.Width!.Value, meta.Height!.Value), path);
}
Assert.IsNull(ContainerVideoMetadataProbe.Probe(other, Now));
Assert.IsNull(ContainerVideoMetadataProbe.Probe(temp.Combine("non-esiste.mp4"), Now));
var damaged = ContainerVideoMetadataProbe.Probe(junk, Now);
Assert.IsTrue(damaged is null || damaged.Width is null);
// A creation time in the future is not believed.
Assert.IsNull(ContainerVideoMetadataProbe.Probe(mkv, created.AddDays(-10))!.CreatedAt);
}
[TestMethod]
public async Task TheProbeIsTheDefaultOfTheImport()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("sonda-predefinita");
var path = TestVideos.Write(temp, "a.webm", TestVideos.Matroska(es, new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero), webm: true));
var meta = await new ContainerVideoMetadataProbe(new FixedClock(Now)).ProbeAsync(path);
Assert.AreEqual(2020, meta!.CreatedAt!.Value.Year);
}
private static MediaContainer Read(byte[] file)
{
using var stream = new MemoryStream(file);
var container = ContainerReader.Read(stream, Now);
Assert.IsNotNull(container);
return container;
}
private static void AssertTrack(ElementaryStream es, VideoTrack video, bool startsAtZero = true)
{
Assert.AreEqual(VideoCodec.H264, video.Codec);
Assert.AreEqual((es.Width, es.Height), (video.Width, video.Height));
Assert.AreEqual(es.Count, video.Samples.Count);
CollectionAssert.AreEqual(es.Key, video.Samples.Select(s => s.Key).ToArray());
for (var i = 0; i < es.Count; i++)
{
Assert.AreEqual((long)i * TestVideos.FrameTicks, video.Samples[i].DecodeTime, $"decodifica {i}");
Assert.AreEqual(es.LengthPrefixed(i).Length, video.Samples[i].Size, $"dimensione {i}");
}
// Presentation order as the stream says, starting at zero.
var shown = video.Samples.Select((s, i) => (s.PresentationTime, i)).OrderBy(p => p.PresentationTime).Select(p => p.i).ToArray();
CollectionAssert.AreEqual(Enumerable.Range(0, es.Count).OrderBy(i => es.Rank[i]).ToArray(), shown);
if (startsAtZero)
{
Assert.AreEqual(0, video.Samples.Min(s => s.PresentationTime), "l'elenco delle modifiche porta il primo fotogramma a zero");
}
}
private static List<string> DecodeAll(byte[] file, VideoTrack video)
{
using var stream = new MemoryStream(file);
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
var lengthSize = video.AnnexB ? 0 : decoder.ConfigureAvcC(video.AvcConfiguration);
var buffer = Array.Empty<byte>();
foreach (var sample in video.Samples)
{
var bytes = ContainerReader.ReadSample(stream, sample, ref buffer);
if (video.AnnexB)
{
decoder.DecodeAccessUnitAnnexB(bytes);
}
else
{
decoder.DecodeSample(bytes, lengthSize);
}
}
decoder.Flush();
return ElementaryStream.Md5InOutputOrder(frames);
}
private sealed class FixedClock(DateTimeOffset now) : Febe.Core.Abstractions.IClock
{
public DateTimeOffset Now { get; } = now;
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask;
}
}
@@ -0,0 +1,461 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// An H.264 conformance stream cut into access units, with what a container needs: key frames, presentation order,
/// parameter sets. The test videos are built from these streams, so every frame has an official MD5.
/// </summary>
internal sealed class ElementaryStream
{
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height)
{
Name = name;
Units = units;
Rank = rank;
Key = key;
AvcC = avcC;
Width = width;
Height = height;
}
public string Name { get; }
/// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary>
public List<List<byte[]>> Units { get; }
/// <summary>Position of each access unit in presentation order.</summary>
public int[] Rank { get; }
/// <summary>True for access units with an IDR picture.</summary>
public bool[] Key { get; }
public byte[] AvcC { get; }
public int Width { get; }
public int Height { get; }
public int Count => Units.Count;
public static string Folder(string name) => Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name);
public static byte[] AnnexB(string name) =>
File.ReadAllBytes(Directory.EnumerateFiles(Folder(name)).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc"));
/// <summary>The official per-frame MD5 values, in output order.</summary>
public static List<string> Reference(string name) =>
File.ReadAllLines(Path.Combine(Folder(name), "riferimento.md5"))
.Select(l => l.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.Where(p => p.Length == 2 && int.TryParse(p[0], out _))
.Select(p => p[1])
.ToList();
/// <summary>MD5 values of frames in output order.</summary>
public static List<string> Md5InOutputOrder(IEnumerable<H264Frame> frames) =>
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex)
.Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToI420())))
.ToList();
public static ElementaryStream Load(string name) => FromAnnexB(name, AnnexB(name));
public static ElementaryStream FromAnnexB(string name, byte[] annexB)
{
var units = new List<List<byte[]>>();
List<byte[]>? current = null;
var hasSlice = false;
foreach (var nal in SplitAnnexB(annexB))
{
var type = nal[0] & 0x1F;
var startsPicture = type is 1 or 5 && nal.Length > 1 && (nal[1] & 0x80) != 0; // first_mb_in_slice == 0
var beforePicture = type is 6 or 7 or 8 or 9 or (>= 14 and <= 18);
if (current is null || (hasSlice && (startsPicture || beforePicture)))
{
current = [];
units.Add(current);
hasSlice = false;
}
current.Add(nal);
hasSlice |= type is 1 or 5;
}
var key = units.Select(u => u.Any(n => (n[0] & 0x1F) == 5)).ToArray();
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(annexB);
Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi");
var order = frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList();
var rank = new int[frames.Count];
for (var i = 0; i < order.Count; i++)
{
rank[order[i].DecodeIndex] = i;
}
var sps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 7).DistinctBy(Convert.ToBase64String).ToList();
var pps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 8).DistinctBy(Convert.ToBase64String).ToList();
var avcC = new List<byte> { 1, sps[0][1], sps[0][2], sps[0][3], 0xFF, (byte)(0xE0 | sps.Count) };
foreach (var s in sps)
{
avcC.Add((byte)(s.Length >> 8));
avcC.Add((byte)s.Length);
avcC.AddRange(s);
}
avcC.Add((byte)pps.Count);
foreach (var p in pps)
{
avcC.Add((byte)(p.Length >> 8));
avcC.Add((byte)p.Length);
avcC.AddRange(p);
}
return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height);
}
/// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary>
public ElementaryStream FirstPictureRepeated(int times)
{
var units = Enumerable.Repeat(Units[0], times).ToList();
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
}
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
public byte[] LengthPrefixed(int index)
{
using var output = new MemoryStream();
Span<byte> length = stackalloc byte[4];
foreach (var nal in Units[index])
{
BinaryPrimitives.WriteInt32BigEndian(length, nal.Length);
output.Write(length);
output.Write(nal);
}
return output.ToArray();
}
/// <summary>An access unit with start codes (AVI).</summary>
public byte[] WithStartCodes(int index)
{
using var output = new MemoryStream();
foreach (var nal in Units[index])
{
output.Write([0, 0, 0, 1]);
output.Write(nal);
}
return output.ToArray();
}
private static List<byte[]> SplitAnnexB(byte[] data)
{
var starts = new List<(int Payload, int Code)>();
for (var i = 0; i + 2 < data.Length; i++)
{
if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1)
{
var code = i > 0 && data[i - 1] == 0 ? i - 1 : i;
starts.Add((i + 3, code));
i += 2;
}
}
var nals = new List<byte[]>();
for (var k = 0; k < starts.Count; k++)
{
var end = k + 1 < starts.Count ? starts[k + 1].Code : data.Length;
while (end > starts[k].Payload && data[end - 1] == 0)
{
end--; // trailing zero bytes belong to no NAL unit
}
if (end > starts[k].Payload)
{
nals.Add(data[starts[k].Payload..end]);
}
}
return nals;
}
}
/// <summary>Builders of test videos in the three containers, from an <see cref="ElementaryStream"/>.</summary>
internal static class TestVideos
{
/// <summary>Ticks per frame at timescale 30000: 30 frames per second.</summary>
public const int FrameTicks = 1000;
public const int Timescale = 30000;
/// <summary>An MP4 written with <see cref="Mp4Writer"/>; with <paramref name="audio"/>, also an AAC track of silence-shaped samples.</summary>
public static byte[] Mp4(ElementaryStream es, DateTimeOffset? created = null, int rotation = 0, bool audio = false)
{
var samples = new List<Mp4OutputSample>();
var data = new List<byte[]>();
for (var i = 0; i < es.Count; i++)
{
var bytes = es.LengthPrefixed(i);
data.Add(bytes);
samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i]));
}
var tracks = new List<Mp4OutputTrack>
{
new()
{
IsVideo = true,
Timescale = Timescale,
Samples = samples,
WriteSample = (i, s) => s.Write(data[i]),
Width = es.Width,
Height = es.Height,
Rotation = rotation,
AvcConfiguration = es.AvcC,
},
};
if (audio)
{
var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024);
var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C };
tracks.Add(new Mp4OutputTrack
{
IsVideo = false,
Timescale = 44100,
Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))],
WriteSample = (_, s) => s.Write(payload),
AacConfiguration = [0x12, 0x10], // AAC LC, 44.1 kHz, stereo
SampleRate = 44100,
Channels = 2,
});
}
using var output = new MemoryStream();
Mp4Writer.Write(output, tracks, created);
return output.ToArray();
}
/// <summary>A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).</summary>
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10)
{
var shift = 0;
for (var i = 0; i < es.Count; i++)
{
shift = Math.Max(shift, i - es.Rank[i]);
}
using var output = new MemoryStream();
output.Write(Box("ftyp", [.. "iso6"u8, 0, 0, 2, 0, .. "iso6mp41"u8]));
var stbl = Box("stbl",
FullBox("stsd", 0, [0, 0, 0, 1, .. Avc1(es)]),
FullBox("stts", 0, [0, 0, 0, 0]),
FullBox("stsc", 0, [0, 0, 0, 0]),
FullBox("stsz", 0, [0, 0, 0, 0, 0, 0, 0, 0]),
FullBox("stco", 0, [0, 0, 0, 0]));
var minf = Box("minf", FullBox("vmhd", 1, new byte[8]), Box("dinf", FullBox("dref", 0, [0, 0, 0, 1, .. FullBox("url ", 1, [])])), stbl);
var mdia = Box("mdia",
FullBox("mdhd", 0, [.. new byte[8], .. U32(Timescale), .. U32(0), 0x55, 0xC4, 0, 0]),
FullBox("hdlr", 0, [0, 0, 0, 0, .. "vide"u8, .. new byte[12], 0]),
minf);
var tkhd = FullBox("tkhd", 3, [.. new byte[8], .. U32(1), .. new byte[4], .. U32(0), .. new byte[16],
.. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000),
.. U32((uint)es.Width << 16), .. U32((uint)es.Height << 16)]);
var mvhd = FullBox("mvhd", 0, [.. new byte[8], .. U32(1000), .. U32(0), .. U32(0x10000), 1, 0, .. new byte[10],
.. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000),
.. new byte[24], .. U32(2)]);
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0)]);
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), Box("mvex", trex)));
for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++)
{
var count = Math.Min(perFragment, es.Count - first);
var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList();
byte[] Moof(int dataOffset)
{
var run = new List<byte>();
run.AddRange(U32((uint)count));
run.AddRange(U32((uint)dataOffset));
for (var k = 0; k < count; k++)
{
var i = first + k;
run.AddRange(U32(FrameTicks));
run.AddRange(U32((uint)payloads[k].Length));
run.AddRange(U32(es.Key[i] ? 0x02000000u : 0x01010000u));
run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks)));
}
return Box("moof",
FullBox("mfhd", 0, U32((uint)sequence)),
Box("traf",
FullBox("tfhd", 0x020000, U32(1)),
FullBox("tfdt", 0, U32((uint)(first * FrameTicks))),
FullBox("trun", 0x000F01, [.. run])));
}
var size = Moof(0).Length;
output.Write(Moof(size + 8));
output.Write(Box("mdat", payloads.SelectMany(p => p).ToArray()));
}
return output.ToArray();
}
/// <summary>A Matroska file with one video track of SimpleBlocks (times in milliseconds).</summary>
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false)
{
var shift = 0;
for (var i = 0; i < es.Count; i++)
{
shift = Math.Max(shift, i - es.Rank[i]);
}
var header = Element(0x1A45DFA3,
Element(0x4286, [1]), Element(0x42F7, [1]), Element(0x42F2, [4]), Element(0x42F3, [8]),
Element(0x4282, Encoding.ASCII.GetBytes(webm ? "webm" : "matroska")), Element(0x4287, [4]), Element(0x4285, [2]));
var durationMs = es.Count * 1000.0 / 30;
var info = new List<byte[]> { Element(0x2AD7B1, U32(1_000_000)), Element(0x4489, F64(durationMs)), Element(0x4D80, "febe-prove"u8.ToArray()) };
if (created is { } c)
{
var ns = (c - new DateTimeOffset(2001, 1, 1, 0, 0, 0, TimeSpan.Zero)).Ticks * 100;
info.Add(Element(0x4461, I64(ns)));
}
var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height)));
var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]),
Element(0x86, "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List<byte[]> { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++)
{
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30);
var payload = es.LengthPrefixed(i);
blocks.Add(Element(0xA3, [0x81, (byte)(pts >> 8), (byte)pts, es.Key[i] ? (byte)0x80 : (byte)0, .. payload]));
}
var segment = Element(0x18538067, Element(0x1549A966, [.. info]), Element(0x1654AE6B, track), Element(0x1F43B675, [.. blocks]));
return [.. header, .. segment];
}
/// <summary>An AVI file with one H.264 stream in Annex B form, an idx1 index and, when given, an IDIT date.</summary>
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true)
{
var avih = new List<byte>();
foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 })
{
avih.AddRange(Le32(v));
}
var strh = new List<byte>();
strh.AddRange("vidsH264"u8.ToArray());
foreach (var v in new uint[] { 0, 0, 0, 1, 30, 0, (uint)es.Count, 0, 0xFFFFFFFF, 0 })
{
strh.AddRange(Le32(v));
}
strh.AddRange(new byte[8]);
var strf = new List<byte>();
foreach (var v in new uint[] { 40, (uint)es.Width, (uint)es.Height })
{
strf.AddRange(Le32(v));
}
strf.AddRange([1, 0, 24, 0]);
strf.AddRange("H264"u8.ToArray());
strf.AddRange(new byte[20]);
var hdrl = new List<byte[]> { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) };
if (idit is not null)
{
hdrl.Add(Chunk("IDIT", [.. Encoding.ASCII.GetBytes(idit), (byte)'\n', 0]));
}
var chunks = new List<byte[]>();
var idx = new List<byte>();
var offset = 4u; // from the «movi» code
for (var i = 0; i < es.Count; i++)
{
var chunk = Chunk("00dc", es.WithStartCodes(i));
chunks.Add(chunk);
idx.AddRange("00dc"u8.ToArray());
idx.AddRange(Le32(es.Key[i] ? 0x10u : 0));
idx.AddRange(Le32(offset));
idx.AddRange(Le32((uint)es.WithStartCodes(i).Length));
offset += (uint)chunk.Length;
}
var body = new List<byte[]> { List("hdrl", [.. hdrl]), List("movi", [.. chunks]) };
if (index)
{
body.Add(Chunk("idx1", [.. idx]));
}
var content = body.SelectMany(b => b).ToArray();
return [.. "RIFF"u8, .. Le32((uint)(content.Length + 4)), .. "AVI "u8, .. content];
}
public static string Write(TempFolder folder, string name, byte[] data)
{
var path = folder.Combine(name);
File.WriteAllBytes(path, data);
return path;
}
private static byte[] Avc1(ElementaryStream es) => Box("avc1",
[.. new byte[6], 0, 1, .. new byte[16], .. U16((ushort)es.Width), .. U16((ushort)es.Height), .. U32(0x00480000), .. U32(0x00480000),
.. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box("avcC", es.AvcC)]);
private static byte[] Box(string type, params byte[][] children)
{
var body = children.SelectMany(c => c).ToArray();
return [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
}
private static byte[] Box(string type, byte[] body) => [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
private static byte[] FullBox(string type, uint flags, byte[] body) => Box(type, [.. U32(flags & 0xFFFFFF), .. body]);
private static byte[] Element(uint id, params byte[][] children) => Element(id, children.SelectMany(c => c).ToArray());
private static byte[] Element(uint id, byte[] body)
{
var idBytes = id > 0xFFFFFF ? U32(id) : id > 0xFFFF ? U32(id)[1..] : id > 0xFF ? U16((ushort)id) : [(byte)id];
return [.. idBytes, 0x01, .. BitConverter.GetBytes((ulong)body.Length).Reverse().Skip(1), .. body];
}
private static byte[] Chunk(string id, byte[] body) =>
[.. Encoding.ASCII.GetBytes(id), .. Le32((uint)body.Length), .. body, .. (body.Length % 2 == 1 ? new byte[] { 0 } : [])];
private static byte[] List(string type, params byte[][] children)
{
var body = children.SelectMany(c => c).ToArray();
return [.. "LIST"u8, .. Le32((uint)(body.Length + 4)), .. Encoding.ASCII.GetBytes(type), .. body];
}
private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v];
private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v];
private static byte[] I64(long v)
{
var b = new byte[8];
BinaryPrimitives.WriteInt64BigEndian(b, v);
return b;
}
private static byte[] F64(double v)
{
var b = new byte[8];
BinaryPrimitives.WriteDoubleBigEndian(b, v);
return b;
}
private static byte[] Le32(uint v)
{
var b = new byte[4];
BinaryPrimitives.WriteUInt32LittleEndian(b, v);
return b;
}
}
@@ -0,0 +1,145 @@
using Febe.Core.Codecs.H264;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture.</summary>
[TestClass]
public sealed class VideoFrameDecoderTests
{
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("frammentato.mp4")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
using var temp = new TempFolder("fotogramma");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
"avi" => TestVideos.Avi(es),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone
};
var path = TestVideos.Write(temp, "video." + kind, data);
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// The same frame straight from the decoder: the one shown at frame 30 (30 frames per second). AVI has no
// presentation times: there frames are shown in decoding order.
var position = Math.Min(30, es.Count - 1);
var expected = kind == "avi" ? DecodedFrame(es, position) : ShownFrame(es, position);
var reference = VideoFrameDecoder.ToImage(expected, 0, 0);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
}
[TestMethod]
public async Task ShortVideosGiveTheirFirstFrameAndTheBmpIsWellFormed()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fotogramma-breve");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path, TimeSpan.FromSeconds(3600), 0);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
Assert.AreEqual((byte)'M', bmp[1]);
Assert.AreEqual(bmp.Length, BitConverter.ToInt32(bmp, 2));
Assert.AreEqual(es.Width, BitConverter.ToInt32(bmp, 18));
Assert.AreEqual(es.Height, BitConverter.ToInt32(bmp, 22));
Assert.AreEqual(24, BitConverter.ToInt16(bmp, 28));
var first = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0);
CollectionAssert.AreEqual(first.ToBmp(), bmp);
}
[TestMethod]
public async Task RotationAndSizeLimitAreApplied()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fotogramma-ruotato");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 90));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.AreEqual((es.Height, es.Width), (image!.Width, image.Height));
var upright = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0);
// Rotated clockwise: the top-left pixel of the frame ends at the top-right corner.
CollectionAssert.AreEqual(upright.Rgb[..3], image.Rgb[((image.Width - 1) * 3)..(image.Width * 3)]);
var small = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero, maxLongSide: es.Width / 2);
Assert.AreEqual((es.Height / 2, es.Width / 2), (small!.Width, small.Height));
}
[TestMethod]
public void ColoursFollowTheMatrixAndTheRange()
{
static H264Frame Flat(byte y, byte cb, byte cr, int matrix, bool full) =>
new(2, 2, [y, y, y, y], [cb], [cr], 0, 0, 0, matrix, full);
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(16, 128, 128, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(235, 128, 128, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 128, 128, 128 }, VideoFrameDecoder.ToImage(Flat(128, 128, 128, 6, true), 0, 0).Rgb[..3]);
// Pure red of BT.601 (limited range): Y 81, Cb 90, Cr 240.
var red = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
// The same values read as BT.709 are no longer pure red.
var other = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 1, false), 0, 0).Rgb;
Assert.IsTrue(other[1] > 20, $"{other[0]} {other[1]} {other[2]}");
}
[TestMethod]
public async Task AVideoOfAStillPictureIsRecognised()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var temp = new TempFolder("fermo");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.IsTrue(result.SampledFrames >= 2);
Assert.AreEqual(0, result.Difference);
}
[TestMethod]
[DataRow("CABA3_SVA_B")]
[DataRow("FRExt1_Panasonic_D")]
public async Task AVideoThatMovesIsNotStill(string name)
{
var es = ElementaryStream.Load(name);
using var temp = new TempFolder("movimento");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
Assert.IsNotNull(result);
Assert.IsFalse(result.IsStill, $"differenza {result.Difference}");
}
[TestMethod]
public async Task UnreadableFilesGiveNothing()
{
using var temp = new TempFolder("illeggibile");
var junk = TestVideos.Write(temp, "rotto.mp4", [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1]);
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(junk));
Assert.IsNull(await VideoFrameDecoder.Instance.AnalyseStillnessAsync(junk));
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mkv")));
}
/// <summary>The frame decoded at position <paramref name="index"/>, straight from the stream.</summary>
private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]);
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}