using System.Buffers.Binary; using System.Text; namespace Febe.Tests.Codecs.Containers; /// What a test ASF file holds. internal sealed record AsfOptions { public int Width { get; init; } = 640; public int Height { get; init; } = 480; public string Compression { get; init; } = "WMV3"; public bool Video { get; init; } = true; public bool Audio { get; init; } = true; public TimeSpan Duration { get; init; } = TimeSpan.FromSeconds(12.5); public ulong PrerollMilliseconds { get; init; } = 3000; public bool Broadcast { get; init; } public DateTimeOffset? Created { get; init; } public DateTimeOffset? EncodingTime { get; init; } public string? Title { get; init; } /// The video stream properties sit in an extended stream properties object of the header extension. public bool VideoInExtension { get; init; } } /// What a test MPEG program stream holds. internal sealed record PsOptions { /// «mpeg2», «mpeg1» or «h264» (then gives the pictures). public string Video { get; init; } = "mpeg2"; public int Width { get; init; } = 720; public int Height { get; init; } = 576; public int Frames { get; init; } = 50; /// Bytes of slice data per picture: large values make a file longer than the windows the reader looks at. public int PictureBytes { get; init; } = 1500; public bool Mpeg1System { get; init; } public bool StreamMap { get; init; } /// «mp2», «ac3» or null. public string? Audio { get; init; } = "mp2"; public long FirstPts { get; init; } = 90_000; public ElementaryStream? Stream { get; init; } public int Seed { get; init; } = 7301; } /// /// Builders of ASF, FLV and MPEG program stream files from their specifications, for the readers' tests: no real sample /// file is needed, and the filler bytes come from a fixed seed. /// internal static class LegacyTestVideos { public static readonly Guid AsfHeader = new("75B22630-668E-11CF-A6D9-00AA0062CE6C"); private static readonly Guid AsfFileProperties = new("8CABDCA1-A947-11CF-8EE4-00C00C205365"); private static readonly Guid AsfStreamProperties = new("B7DC0791-A9B7-11CF-8EE6-00C00C205365"); private static readonly Guid AsfHeaderExtension = new("5FBF03B5-A92E-11CF-8EE3-00C00C205365"); private static readonly Guid AsfReserved1 = new("ABD3D211-A9BA-11CF-8EE6-00C00C205365"); private static readonly Guid AsfContentDescription = new("75B22633-668E-11CF-A6D9-00AA0062CE6C"); private static readonly Guid AsfExtendedContentDescription = new("D2D0A440-E307-11D2-97F0-00A0C95EA850"); private static readonly Guid AsfExtendedStreamProperties = new("14E6A5CB-C672-4332-8399-A96952065B5A"); private static readonly Guid AsfVideoMedia = new("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B"); private static readonly Guid AsfAudioMedia = new("F8699E40-5B4D-11CF-A8FD-00805F5C442B"); private static readonly Guid AsfNoErrorCorrection = new("20FB5700-5B55-11CF-A8FD-00805F5C442B"); private static readonly Guid AsfData = new("75B22636-668E-11CF-A6D9-00AA0062CE6C"); private static readonly DateTimeOffset Epoch1601 = new(1601, 1, 1, 0, 0, 0, TimeSpan.Zero); // ----- ASF ----- /// An ASF file: header object with the objects of , then a data object of filler packets. public static byte[] Asf(AsfOptions o) { var random = new Random(4101); var children = new List(); var fileId = new byte[16]; random.NextBytes(fileId); var play = (ulong)o.Duration.Ticks + (o.PrerollMilliseconds * 10_000); children.Add(AsfObject(AsfFileProperties, [.. fileId, .. Le64(0), .. Le64(o.Created is { } c ? FileTime(c) : 0), .. Le64(10), .. Le64(play), .. Le64(play), .. Le64(o.PrerollMilliseconds), .. Le32(o.Broadcast ? 1u : 2u), .. Le32(3200), .. Le32(3200), .. Le32(512_000)])); if (o.Video && !o.VideoInExtension) { children.Add(VideoStream(o, 1)); } if (o.Audio) { children.Add(AudioStream(2)); } if (o.Title is not null) { var title = Encoding.Unicode.GetBytes(o.Title + "\0"); var author = Encoding.Unicode.GetBytes("Febe\0"); children.Add(AsfObject(AsfContentDescription, [.. Le16((ushort)title.Length), .. Le16((ushort)author.Length), .. Le16(0), .. Le16(0), .. Le16(0), .. title, .. author])); } var descriptors = new List { Descriptor("WM/ToolName", 0, Encoding.Unicode.GetBytes("Prove di Febe\0")) }; if (o.EncodingTime is { } e) { descriptors.Add(Descriptor("WM/EncodingTime", 4, Le64(FileTime(e)))); } descriptors.Add(Descriptor("IsVBR", 2, Le32(1))); children.Add(AsfObject(AsfExtendedContentDescription, [.. Le16((ushort)descriptors.Count), .. descriptors.SelectMany(d => d)])); var extension = new List(); if (o.Video && o.VideoInExtension) { var name = Encoding.Unicode.GetBytes("Video\0"); extension.Add(AsfObject(AsfExtendedStreamProperties, [.. Le64(0), .. Le64(0), .. Le32(500_000), .. Le32(3000), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(65_536), .. Le32(0), .. Le16(1), .. Le16(0), .. Le64(400_000), .. Le16(1), .. Le16(1), .. Le16(0), .. Le16((ushort)name.Length), .. name, .. Enumerable.Repeat((byte)0x11, 16),.. Le16(4), .. Le32(4), 1, 2, 3, 4, .. VideoStream(o, 1)])); } var extensionData = extension.SelectMany(x => x).ToArray(); children.Add(AsfObject(AsfHeaderExtension, [.. AsfReserved1.ToByteArray(), .. Le16(6), .. Le32((uint)extensionData.Length), .. extensionData])); var body = children.SelectMany(x => x).ToArray(); byte[] header = [.. AsfHeader.ToByteArray(), .. Le64((ulong)(30 + body.Length)), .. Le32((uint)children.Count), 1, 2, .. body]; var packets = new byte[10 * 3200]; random.NextBytes(packets); var data = AsfObject(AsfData, [.. fileId, .. Le64(10), 1, 1, .. packets]); return [.. header, .. data]; } private static byte[] VideoStream(AsfOptions o, int number) { var bitmap = new List(); bitmap.AddRange(Le32(40)); bitmap.AddRange(Le32((uint)o.Width)); bitmap.AddRange(Le32((uint)o.Height)); bitmap.AddRange(Le16(1)); bitmap.AddRange(Le16(24)); bitmap.AddRange(Encoding.ASCII.GetBytes(o.Compression)); bitmap.AddRange(new byte[20]); byte[] specific = [.. Le32((uint)o.Width), .. Le32((uint)o.Height), 2, .. Le16((ushort)bitmap.Count), .. bitmap]; return StreamObject(AsfVideoMedia, number, specific); } private static byte[] AudioStream(int number) { // WAVEFORMATEX of WMA 2: 44.1 kHz stereo, with ten bytes of codec data. byte[] specific = [.. Le16(0x161), .. Le16(2), .. Le32(44_100), .. Le32(16_000), .. Le16(2_973), .. Le16(16), .. Le16(10), .. new byte[10]]; return StreamObject(AsfAudioMedia, number, specific); } private static byte[] StreamObject(Guid type, int number, byte[] specific) => AsfObject(AsfStreamProperties, [.. type.ToByteArray(), .. AsfNoErrorCorrection.ToByteArray(), .. Le64(0), .. Le32((uint)specific.Length), .. Le32(0), .. Le16((ushort)number), .. Le32(0), .. specific]); private static byte[] Descriptor(string name, ushort type, byte[] value) { var n = Encoding.Unicode.GetBytes(name + "\0"); return [.. Le16((ushort)n.Length), .. n, .. Le16(type), .. Le16((ushort)value.Length), .. value]; } private static byte[] AsfObject(Guid id, byte[] body) => [.. id.ToByteArray(), .. Le64((ulong)(24 + body.Length)), .. body]; private static ulong FileTime(DateTimeOffset instant) => (ulong)(instant - Epoch1601).Ticks; // ----- FLV ----- /// /// An FLV file of an H.264 stream at 30 frames per second: onMetaData (unless is false), /// the AVC sequence header, one tag per access unit with its composition time and, with , an /// AAC sequence header and AAC tags between the frames. /// public static byte[] Flv(ElementaryStream es, bool metadata = true, string? creationDate = null, bool audio = false, (int Width, int Height)? metadataSize = null, double? creationMilliseconds = null) { var shift = 0; for (var i = 0; i < es.Count; i++) { shift = Math.Max(shift, i - es.Rank[i]); } using var output = new MemoryStream(); FlvHeader(output, audio, video: true); if (metadata) { var size = metadataSize ?? (es.Width, es.Height); var properties = new List { AmfProperty("duration", AmfNumber(es.Count / 30.0)), AmfProperty("width", AmfNumber(size.Width)), AmfProperty("height", AmfNumber(size.Height)), AmfProperty("framerate", AmfNumber(30)), AmfProperty("videocodecid", AmfNumber(7)), AmfProperty("stereo", [1, 1]), AmfProperty("encoder", AmfString("Prove di Febe")), AmfProperty("keyframes", [3, .. AmfProperty("times", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i / 30.0))), .. AmfProperty("filepositions", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i * 1000.0))), 0, 0, 9]), }; if (creationDate is not null) { properties.Add(AmfProperty("creationdate", AmfString(creationDate))); } if (creationMilliseconds is { } ms) { properties.Add(AmfProperty("creationdate", [11, .. F64(ms), 0, 0])); } FlvTag(output, 18, 0, [.. AmfString("onMetaData"), 8, .. U32((uint)properties.Count), .. properties.SelectMany(p => p), 0, 0, 9]); } FlvTag(output, 9, 0, [0x17, 0, 0, 0, 0, .. es.AvcC]); if (audio) { FlvTag(output, 8, 0, [0xAF, 0, 0x12, 0x10]); // AAC LC, 44.1 kHz, stereo } for (var i = 0; i < es.Count; i++) { var dts = (int)Math.Round(i * 1000.0 / 30); var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30); var cts = pts - dts; FlvTag(output, 9, dts, [es.Key[i] ? (byte)0x17 : (byte)0x27, 1, (byte)(cts >> 16), (byte)(cts >> 8), (byte)cts, .. es.LengthPrefixed(i)]); if (audio && i % 2 == 0) { FlvTag(output, 8, dts, [0xAF, 1, 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C]); } } return output.ToArray(); } /// An FLV with one script tag of the given AMF0 body and one H.263 video tag. public static byte[] FlvWithScript(byte[] script) { using var output = new MemoryStream(); FlvHeader(output, audio: false, video: true); FlvTag(output, 18, 0, script); FlvTag(output, 9, 0, [0x12, 0, 0, 0x80, 0, 0x0A, 0x00, 0x00, 0x00, 0x00]); return output.ToArray(); } /// An FLV of Sorenson H.263 tags whose picture headers give the size (code 0, 1 or a fixed size code). public static byte[] SorensonFlv(int sizeCode, int width, int height, int frames = 10) { using var output = new MemoryStream(); FlvHeader(output, audio: false, video: true); var random = new Random(4102); for (var i = 0; i < frames; i++) { var bits = new BitWriterForTests(); bits.Write(1, 17); // picture start code bits.Write(0, 5); // version bits.Write(i & 0xFF, 8); // temporal reference bits.Write(sizeCode, 3); if (sizeCode == 0) { bits.Write(width, 8); bits.Write(height, 8); } else if (sizeCode == 1) { bits.Write(width, 16); bits.Write(height, 16); } bits.Write(i == 0 ? 0 : 1, 2); // picture type: intra, then inter var filler = new byte[200]; random.NextBytes(filler); FlvTag(output, 9, i * 40, [(byte)((i == 0 ? 0x10 : 0x20) | 2), .. bits.ToArray(), .. filler]); } return output.ToArray(); } /// An FLV whose video tags use the enhanced header with , or only audio tags. public static byte[] EnhancedOrAudioFlv(string? fourCc, bool audioFlag, bool videoFlag) { using var output = new MemoryStream(); FlvHeader(output, audioFlag, videoFlag); for (var i = 0; i < 20; i++) { if (fourCc is not null) { FlvTag(output, 9, i * 40, [(byte)(0x80 | (i == 0 ? 0x10 : 0x20) | 1), .. Encoding.ASCII.GetBytes(fourCc), 0, 0, 0, 0x55, 0x66]); } FlvTag(output, 8, i * 40, [0x2F, 0xFF, 0xFB, 0x90, 0x64, 0, 0, 0]); // MP3, 44 kHz, stereo } return output.ToArray(); } private static void FlvHeader(MemoryStream output, bool audio, bool video) { output.Write("FLV"u8); output.WriteByte(1); output.WriteByte((byte)((audio ? 4 : 0) | (video ? 1 : 0))); output.Write(U32(9)); output.Write(U32(0)); } private static void FlvTag(MemoryStream output, int type, int time, byte[] data) { output.Write([(byte)type, (byte)(data.Length >> 16), (byte)(data.Length >> 8), (byte)data.Length, (byte)(time >> 16), (byte)(time >> 8), (byte)time, (byte)(time >> 24), 0, 0, 0]); output.Write(data); output.Write(U32((uint)(11 + data.Length))); } private static byte[] AmfString(string text) { var bytes = Encoding.UTF8.GetBytes(text); return [2, .. U16((ushort)bytes.Length), .. bytes]; } private static byte[] AmfNumber(double value) => [0, .. F64(value)]; private static byte[] AmfArray(IEnumerable values) { var items = values.ToList(); return [10, .. U32((uint)items.Count), .. items.SelectMany(AmfNumber)]; } private static byte[] AmfProperty(string name, byte[] value) { var bytes = Encoding.UTF8.GetBytes(name); return [.. U16((ushort)bytes.Length), .. bytes, .. value]; } // ----- MPEG program stream ----- /// /// An MPEG program stream: a pack header before each picture, a system header, optionally a program stream map, the /// pictures as PES packets of at most 2,000 bytes (the first with its presentation time), and audio frames between. /// MPEG-1 and MPEG-2 pictures are a sequence header (with its extension in MPEG-2), a GOP header, a picture header /// and filler slice bytes; H.264 pictures are the access units of . /// public static byte[] MpegPs(PsOptions o) { var random = new Random(o.Seed); var frameTicks = o.Video == "h264" ? 3000 : 3600; // 30 or 25 pictures a second var frames = o.Video == "h264" ? o.Stream!.Count : o.Frames; using var output = new MemoryStream(); var audioTime = o.FirstPts; for (var i = 0; i < frames; i++) { var pts = (o.FirstPts + ((long)i * frameTicks)) & ((1L << 33) - 1); Pack(output, o, pts > 9000 ? pts - 9000 : 0); if (i == 0) { output.Write([0, 0, 1, 0xBB, 0, 12, 0x80, 0x00, 0x01, 0x04, 0xE1, 0xFF, 0xE0, 0xE0, 0xE8, 0xC0, 0xC0, 0x20]); if (o.StreamMap) { var videoType = o.Video switch { "h264" => (byte)0x1B, "mpeg1" => (byte)0x01, _ => (byte)0x02 }; byte[] map = [videoType, 0xE0, 0, 0, 0x04, 0xC0, 0, 0]; byte[] body = [0x80, 0x01, 0, 0, .. U16((ushort)map.Length), .. map, 0, 0, 0, 0]; output.Write([0, 0, 1, 0xBC, .. U16((ushort)body.Length), .. body]); } } var picture = o.Video == "h264" ? o.Stream!.WithStartCodes(i) : MpegPicture(o, i, random); for (var offset = 0; offset < picture.Length; offset += 2000) { var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray(); Pes(output, 0xE0, offset == 0 ? pts : -1, chunk, o.Mpeg1System); } while (o.Audio is not null && audioTime <= o.FirstPts + ((long)i * frameTicks)) { var t = audioTime & ((1L << 33) - 1); if (o.Audio == "ac3") { // Private stream 1, sub-stream 0x80: one AC-3 frame at 48 kHz, 3/2 channels with LFE (5.1). var frame = new byte[768]; frame[0] = 0x0B; frame[1] = 0x77; frame[4] = 0x00 | 0x0E; // fscod 0 (48 kHz), frmsizecod frame[5] = 0x08 << 3; // bsid 8, bsmod 0 var bits = new BitWriterForTests(); bits.Write(7, 3); // acmod 3/2 bits.Write(1, 2); // cmixlev bits.Write(1, 2); // surmixlev bits.Write(1, 1); // lfeon bits.ToArray().CopyTo(frame, 6); Pes(output, 0xBD, t, [0x80, 1, 0, 1, .. frame], o.Mpeg1System); audioTime += 2880; // 1,536 samples } else { var frame = new byte[576]; frame[0] = 0xFF; frame[1] = 0xFD; // MPEG-1 layer II, no CRC frame[2] = 0xA4; // 192 kbit/s, 48 kHz frame[3] = 0x04; // stereo Pes(output, 0xC0, t, frame, o.Mpeg1System); audioTime += 2160; // 1,152 samples } } } output.Write([0, 0, 1, 0xB9]); return output.ToArray(); } private static byte[] MpegPicture(PsOptions o, int index, Random random) { var data = new List(); if (index % 12 == 0) { var bits = new BitWriterForTests(); bits.Write(o.Width & 0xFFF, 12); bits.Write(o.Height & 0xFFF, 12); bits.Write(1, 4); // square pixels bits.Write(3, 4); // 25 pictures a second bits.Write(0x3FFFF, 18); bits.Write(1, 1); bits.Write(112, 10); bits.Write(0, 3); data.AddRange([0, 0, 1, 0xB3, .. bits.ToArray()]); if (o.Video == "mpeg2") { var ext = new BitWriterForTests(); ext.Write(1, 4); // sequence extension ext.Write(0x48, 8); // main profile, main level ext.Write(1, 1); // progressive ext.Write(1, 2); // 4:2:0 ext.Write(o.Width >> 12, 2); ext.Write(o.Height >> 12, 2); ext.Write(0, 12); ext.Write(1, 1); ext.Write(0, 8); ext.Write(0, 8); data.AddRange([0, 0, 1, 0xB5, .. ext.ToArray()]); } data.AddRange([0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); } data.AddRange([0, 0, 1, 0x00, (byte)(index >> 2), (byte)((index << 6) | 0x08), 0xFF, 0xF8]); var slice = new byte[o.PictureBytes]; random.NextBytes(slice); for (var k = 0; k < slice.Length; k++) { slice[k] |= 0x01; // no zero bytes: no start code inside the filler } data.AddRange([0, 0, 1, 0x01, .. slice]); return [.. data]; } private static void Pack(MemoryStream output, PsOptions o, long scr) { if (o.Mpeg1System) { // '0010', SCR in the layout of a time stamp, then the mux rate between two marker bits. output.Write([0, 0, 1, 0xBA, .. Timestamp(0x2, scr), 0x80, 0x1B, 0x83]); return; } var b = new byte[] { 0, 0, 1, 0xBA, (byte)(0x44 | ((scr >> 27) & 0x38) | ((scr >> 28) & 3)), (byte)(scr >> 20), (byte)(((scr >> 12) & 0xF8) | 0x04 | ((scr >> 13) & 3)), (byte)(scr >> 5), (byte)(((scr << 3) & 0xF8) | 0x04), 0x01, 0x01, 0x89, 0xC3, 0xF8 }; output.Write(b); } private static void Pes(MemoryStream output, int id, long pts, byte[] payload, bool mpeg1) { byte[] header = mpeg1 ? pts >= 0 ? Timestamp(0x2, pts) : [0x0F] : pts >= 0 ? [0x81, 0x80, 5, .. Timestamp(0x2, pts)] : [0x81, 0x00, 0]; var length = header.Length + payload.Length; output.Write([0, 0, 1, (byte)id, (byte)(length >> 8), (byte)length, .. header, .. payload]); } /// A 33-bit time in five bytes with a four-bit prefix and three marker bits. private static byte[] Timestamp(int prefix, long t) => [ (byte)((prefix << 4) | (int)((t >> 29) & 0x0E) | 1), (byte)(t >> 22), (byte)(((t >> 14) & 0xFE) | 1), (byte)(t >> 7), (byte)(((t << 1) & 0xFE) | 1), ]; // ----- bytes ----- 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[] F64(double v) { var b = new byte[8]; BinaryPrimitives.WriteDoubleBigEndian(b, v); return b; } private static byte[] Le16(ushort v) => [(byte)v, (byte)(v >> 8)]; private static byte[] Le32(uint v) { var b = new byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(b, v); return b; } private static byte[] Le64(ulong v) { var b = new byte[8]; BinaryPrimitives.WriteUInt64LittleEndian(b, v); return b; } /// Writes bits from the most significant one, as the codec headers want them. private sealed class BitWriterForTests { private readonly List bytes = []; private int used = 8; public void Write(int value, int count) { for (var i = count - 1; i >= 0; i--) { if (used == 8) { bytes.Add(0); used = 0; } if (((value >> i) & 1) != 0) { bytes[^1] |= (byte)(0x80 >> used); } used++; } } public byte[] ToArray() => [.. bytes]; } }