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;
///
/// 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.
///
internal sealed class ElementaryStream
{
private ElementaryStream(string name, List> units, int[] rank, bool[] key, byte[] avcC, int width, int height, bool hevc = false)
{
Name = name;
Units = units;
Rank = rank;
Key = key;
AvcC = avcC;
Width = width;
Height = height;
Hevc = hevc;
}
public string Name { get; }
/// An HEVC stream (of the H.265.1 set): then holds its hvcC record.
public bool Hevc { get; }
/// The NAL units (without start codes) of each access unit, in decoding order.
public List> Units { get; }
/// Position of each access unit in presentation order.
public int[] Rank { get; }
/// True for access units with an IDR picture.
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"));
/// The official per-frame MD5 values, in output order.
public static List 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();
/// MD5 values of frames in output order.
public static List Md5InOutputOrder(IEnumerable frames) =>
frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex)
.Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToPlanar())))
.ToList();
public static ElementaryStream Load(string name) => FromAnnexB(name, AnnexB(name));
public static ElementaryStream FromAnnexB(string name, byte[] annexB)
{
var units = new List>();
List? 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();
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 { 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);
}
///
/// An HEVC stream of the H.265.1 set cut into access units (§7.4.2.4.4: parameter sets, delimiters and prefix SEI
/// open the next one), with an hvcC record of its VPS, SPS and PPS. Every access unit must give one output
/// frame: streams with skipped RASL pictures or pic_output_flag 0 do not fit.
///
public static ElementaryStream LoadHevc(string name)
{
var annexB = File.ReadAllBytes(H265.H265ConformanceStream.Load(name).BitstreamPath);
var units = new List>();
List? current = null;
var hasSlice = false;
foreach (var nal in SplitAnnexB(annexB))
{
var type = (nal[0] >> 1) & 63;
var startsPicture = type < 32 && nal.Length > 2 && (nal[2] & 0x80) != 0; // first_slice_segment_in_pic_flag
var beforePicture = type is (>= 32 and <= 35) or 39 or (>= 41 and <= 44) or (>= 48 and <= 55);
if (current is null || (hasSlice && (startsPicture || beforePicture)))
{
current = [];
units.Add(current);
hasSlice = false;
}
current.Add(nal);
hasSlice |= type < 32;
}
var key = units.Select(u => u.Any(n => ((n[0] >> 1) & 63) is >= 16 and <= 23)).ToArray();
var decoder = new Febe.Core.Codecs.H265.H265Decoder();
var frames = new List();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(annexB);
Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi");
var rank = new int[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
rank[frames[i].DecodeIndex] = i; // FrameOutput comes in output order
}
var sets = units.SelectMany(u => u).Where(n => ((n[0] >> 1) & 63) is >= 32 and <= 34).DistinctBy(Convert.ToBase64String).ToList();
var hvcC = new List(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
return new ElementaryStream(name, units, rank, key, [.. hvcC], frames[0].Width, frames[0].Height, hevc: true);
}
private static bool IsParameterSet(byte[] nal, bool hevc) => hevc ? ((nal[0] >> 1) & 63) is >= 32 and <= 34 : (nal[0] & 0x1F) is 7 or 8;
/// The same stream with only its first access unit, repeated: a video of a still picture.
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, Hevc);
}
///
/// The same stream with its parameter sets repeated in every access unit, as some cameras and recorders write them: a
/// decoder started at any of its P or B frames finds its parameter sets.
///
public ElementaryStream WithParameterSetsEverywhere()
{
var sets = Units[0].Where(n => IsParameterSet(n, Hevc)).ToList();
var units = Units.Select(u => u.Any(n => IsParameterSet(n, Hevc)) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height, Hevc);
}
/// An access unit with 4-byte length prefixes (MP4, Matroska).
public byte[] LengthPrefixed(int index)
{
using var output = new MemoryStream();
Span length = stackalloc byte[4];
foreach (var nal in Units[index])
{
BinaryPrimitives.WriteInt32BigEndian(length, nal.Length);
output.Write(length);
output.Write(nal);
}
return output.ToArray();
}
/// An access unit with start codes (AVI).
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 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();
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;
}
}
/// Builders of test videos in the three containers, from an .
internal static class TestVideos
{
/// Ticks per frame at timescale 30000: 30 frames per second.
public const int FrameTicks = 1000;
public const int Timescale = 30000;
/// An MP4 written with ; with , also an AAC track of silence-shaped samples.
public static byte[] Mp4(ElementaryStream es, DateTimeOffset? created = null, int rotation = 0, bool audio = false)
{
var samples = new List();
var data = new List();
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
{
new()
{
IsVideo = true,
Timescale = Timescale,
Samples = samples,
WriteSample = (i, s) => s.Write(data[i]),
Width = es.Width,
Height = es.Height,
Rotation = rotation,
AvcConfiguration = es.Hevc ? null : es.AvcC,
HevcConfiguration = es.Hevc ? es.AvcC : null,
},
};
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();
}
///
/// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames).
/// With the sample durations come from trex, each fragment has two runs that
/// both give their data_offset from the start of the moof, and an mehd box tells the duration.
///
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10, bool defaults = false)
{
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)]);
// trex: track_ID, default_sample_description_index, default duration, size and flags (non-sync).
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0x01010000)]);
var mvex = defaults
? Box("mvex", FullBox("mehd", 0, U32((uint)(es.Count * 1000 / 30))), trex) // movie timescale 1000
: Box("mvex", trex);
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), mvex));
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[] Run(int from, int length, int dataOffset)
{
var run = new List();
run.AddRange(U32((uint)length));
run.AddRange(U32((uint)dataOffset));
for (var k = from; k < from + length; k++)
{
var i = first + k;
if (!defaults)
{
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)));
}
// Without the duration field (0x100) every sample takes the trex default.
return FullBox("trun", defaults ? 0x000E01u : 0x000F01u, [.. run]);
}
var split = defaults ? (count + 1) / 2 : count;
var secondData = payloads.Take(split).Sum(p => p.Length);
byte[] Moof(int dataOffset)
{
var runs = new List { Run(0, split, dataOffset) };
if (split < count)
{
runs.Add(Run(split, count - split, dataOffset + secondData));
}
return Box("moof",
FullBox("mfhd", 0, U32((uint)sequence)),
Box("traf", [FullBox("tfhd", 0x020000, U32(1)), FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), .. runs]));
}
var size = Moof(0).Length;
output.Write(Moof(size + 8));
output.Write(Box("mdat", payloads.SelectMany(p => p).ToArray()));
}
return output.ToArray();
}
///
/// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of
/// nanoseconds (milliseconds by default).
///
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000)
{
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 tickMs = timecodeScale / 1e6;
var durationTicks = es.Count * 1000.0 / 30 / tickMs;
var info = new List { Element(0x2AD7B1, U32(timecodeScale)), Element(0x4489, F64(durationTicks)), 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, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++)
{
var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30 / tickMs);
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];
}
///
/// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless is false, as in a
/// recording cut short) and, when given, an IDIT date. The stream header says /
/// frames per second and frames (default: the stream's).
///
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true, uint scale = 1, uint rate = 30, uint? length = null)
{
var avih = new List();
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();
strh.AddRange(es.Hevc ? "vidsHEVC"u8.ToArray() : "vidsH264"u8.ToArray());
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
{
strh.AddRange(Le32(v));
}
strh.AddRange(new byte[8]);
var strf = new List();
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(es.Hevc ? "HEVC"u8.ToArray() : "H264"u8.ToArray());
strf.AddRange(new byte[20]);
var hdrl = new List { 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();
var idx = new List();
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 { 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(es.Hevc ? "hvc1" : "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(es.Hevc ? "hvcC" : "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;
}
}