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>
462 lines
18 KiB
C#
462 lines
18 KiB
C#
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;
|
|
}
|
|
}
|