using System.Buffers; using System.Buffers.Binary; using System.Globalization; using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H265; namespace Febe.Core.Codecs.Containers; /// /// Reader of MPEG program streams (MPG, MPEG, VOB), written from ISO/IEC 13818-1 §2.5 and, for the MPEG-1 system layer, /// ISO/IEC 11172-1: pack headers (MPEG-1 and MPEG-2), the system header, the program stream map and the PES packets. Only /// the first megabytes and the last megabyte of the file are read. The duration runs from the first presentation time of /// the video (or the audio, or the clock of the packs) to the last one, plus a frame; codec and size come from the /// program stream map and the start of the video stream: the sequence header of MPEG-1 and MPEG-2 video (ISO/IEC /// 11172-2 §2.4.2.3, ITU-T H.262 §6.2.2), the SPS of H.264. The samples of a program stream are cut into PES packets and /// are not listed: the tracks have no samples. /// public static class MpegPsReader { /// Bytes read from the start of the file. private const int HeadWindow = 2 * 1024 * 1024; /// Bytes read from the end of the file, for the last time. private const int TailWindow = 1024 * 1024; /// Bytes of the video stream gathered to find its headers. private const int MaxVideoProbe = 1024 * 1024; /// Presentation times are 33-bit numbers of a 90 kHz clock. private const long TimeWrap = 1L << 33; private const int ClockRate = 90_000; /// Ticks of 90 kHz per frame for each frame_rate_code of MPEG-1 and MPEG-2 video (0 = forbidden or reserved). private static readonly int[] FrameTicks = [0, 3754, 3750, 3600, 3003, 3000, 1800, 1502, 1500]; private static readonly int[] MpegAudioRates = [44100, 48000, 32000]; private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; /// True when the stream starts with an MPEG-1 or MPEG-2 pack header. public static bool Looks(ReadOnlySpan start) => start.Length >= 5 && start[0] == 0 && start[1] == 0 && start[2] == 1 && start[3] == 0xBA && ((start[4] & 0xC0) == 0x40 || (start[4] & 0xF0) == 0x20); /// Reads a seekable stream: its first megabytes and its last. public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); _ = now; // a program stream carries no date _ = samples; // nor samples that sit whole in the file var length = stream.Length; var headLength = (int)Math.Min(length, HeadWindow); var state = new State(); var buffer = ArrayPool.Shared.Rent(Math.Max(1, headLength)); try { stream.Position = 0; stream.ReadExactly(buffer, 0, headLength); if (!Looks(buffer.AsSpan(0, headLength))) { throw new ContainerException("Non è un flusso di programma MPEG."); } Scan(buffer.AsSpan(0, headLength), state, head: true, ct); state.FinishVideo(final: true, whole: headLength == length); if (length > headLength) { var tailStart = Math.Max(headLength, length - TailWindow); var tailLength = (int)(length - tailStart); stream.Position = tailStart; stream.ReadExactly(buffer, 0, tailLength); Scan(buffer.AsSpan(0, tailLength), state, head: false, ct); } } finally { ArrayPool.Shared.Return(buffer); state.Release(); } return state.Build(); } /// The packs and packets of a window of the file; anything else is skipped up to the next start code. private static void Scan(ReadOnlySpan data, State state, bool head, CancellationToken ct) { ReadOnlySpan startCode = [0, 0, 1]; var p = 0; var count = 0; while (p + 4 <= data.Length) { if ((++count & 1023) == 0) { ct.ThrowIfCancellationRequested(); } if (data[p] != 0 || data[p + 1] != 0 || data[p + 2] != 1) { var next = data[(p + 1)..].IndexOf(startCode); if (next < 0) { return; } p += 1 + next; continue; } var id = data[p + 3]; if (id == 0xBA) { if (p + 12 > data.Length) { return; } if ((data[p + 4] & 0xC0) == 0x40) { if (p + 14 > data.Length) { return; } state.Mpeg2System = true; state.Clocks.Add(Scr(data.Slice(p + 4, 6)), head); p += 14 + (data[p + 13] & 7); } else if ((data[p + 4] & 0xF0) == 0x20) { state.Clocks.Add(Timestamp(data.Slice(p + 4, 5)), head); p += 12; } else { p += 4; } continue; } if (id < 0xBB) { p += 3; // the end code, or a start code of an elementary stream met while looking for a packet continue; } if (p + 6 > data.Length) { return; } var size = BinaryPrimitives.ReadUInt16BigEndian(data[(p + 4)..]); var available = Math.Min(size, data.Length - p - 6); var body = data.Slice(p + 6, available); var whole = available == size; if (id == 0xBC) { if (whole) { StreamMap(body, state); } } else if (id is >= 0xC0 and <= 0xEF or 0xBD) { Packet(id, body, state, head); } if (!whole) { return; } p += 6 + size; } } /// A PES packet of an audio or video stream: its presentation time and, at the start of the file, its payload. private static void Packet(int id, ReadOnlySpan body, State state, bool head) { if (!PesHeader(body, out var pts, out var payloadStart)) { return; } var payload = body[payloadStart..]; var key = id; if (id == 0xBD) { if (payload.Length < 1) { return; } key = 0x100 | payload[0]; // private stream 1: the sub-stream number (DVD: AC-3, DTS, LPCM) if (payload[0] is not (>= 0x80 and <= 0x8F or >= 0xA0 and <= 0xA7)) { return; // subtitles and the like } } if (head) { if (id is >= 0xE0 and <= 0xEF && state.VideoId < 0) { state.VideoId = id; } else if (id is >= 0xC0 and <= 0xDF or 0xBD && state.AudioId < 0) { state.AudioId = key; Audio(id, payload, state); } } if (key == state.VideoId) { state.VideoTimes.Add(pts, head); if (head) { state.AddVideo(payload); } } else if (key == state.AudioId) { state.AudioTimes.Add(pts, head); } } /// /// The header of a PES packet, MPEG-2 (§2.4.3.7, «10» first) or MPEG-1 (stuffing, buffer size, then the times): /// its presentation time (-1 without one) and where its payload starts; false when it is not a header. /// private static bool PesHeader(ReadOnlySpan b, out long pts, out int payload) { pts = -1; payload = 0; if (b.Length < 1) { return false; } if ((b[0] & 0xC0) == 0x80) { if (b.Length < 3 || 3 + b[2] > b.Length) { return false; } payload = 3 + b[2]; if ((b[1] & 0x80) != 0) { if (b[2] < 5) { return false; } pts = Timestamp(b.Slice(3, 5)); return pts >= 0; } return true; } var i = 0; while (i < b.Length && i < 16 && b[i] == 0xFF) { i++; } if (i < b.Length && (b[i] & 0xC0) == 0x40) { i += 2; // STD buffer scale and size } if (i >= b.Length) { return false; } if ((b[i] & 0xF0) is 0x20 or 0x30) { var fields = (b[i] & 0xF0) == 0x20 ? 5 : 10; if (i + fields > b.Length) { return false; } pts = Timestamp(b.Slice(i, 5)); payload = i + fields; return pts >= 0; } if (b[i] != 0x0F) { return false; } payload = i + 1; return true; } /// A 33-bit time in five bytes with three marker bits (PTS, DTS, SCR of MPEG-1); -1 when a marker is wrong. private static long Timestamp(ReadOnlySpan b) { if ((b[0] & 1) == 0 || (b[2] & 1) == 0 || (b[4] & 1) == 0) { return -1; } return ((long)((b[0] >> 1) & 7) << 30) | ((long)b[1] << 22) | ((long)(b[2] >> 1) << 15) | ((long)b[3] << 7) | ((long)b[4] >> 1); } /// The base of the system clock reference of an MPEG-2 pack header (§2.5.3.4); -1 when a marker is wrong. private static long Scr(ReadOnlySpan b) { if ((b[0] & 4) == 0 || (b[2] & 4) == 0 || (b[4] & 4) == 0 || (b[5] & 1) == 0) { return -1; } return ((long)((b[0] >> 3) & 7) << 30) | ((long)(b[0] & 3) << 28) | ((long)b[1] << 20) | ((long)(b[2] >> 3) << 15) | ((long)(b[2] & 3) << 13) | ((long)b[3] << 5) | ((long)b[4] >> 3); } /// The stream types of the program stream map (§2.5.4), by elementary stream ID. private static void StreamMap(ReadOnlySpan body, State state) { if (body.Length < 6) { return; } var info = BinaryPrimitives.ReadUInt16BigEndian(body[2..]); var p = 4 + info; if (p + 2 > body.Length) { return; } var end = Math.Min(body.Length, p + 2 + BinaryPrimitives.ReadUInt16BigEndian(body[p..])); p += 2; while (p + 4 <= end) { state.StreamTypes[body[p + 1]] = body[p]; p += 4 + BinaryPrimitives.ReadUInt16BigEndian(body[(p + 2)..]); } } /// Codec, sample rate and channels of the first payload of the audio stream. private static void Audio(int id, ReadOnlySpan payload, State state) { if (id == 0xBD) { var sub = payload[0]; if (sub is >= 0xA0 and <= 0xA7) { state.AudioCodec = AudioCodec.Pcm; // DVD LPCM: frequency and channels in its sixth byte state.AudioTag = "LPCM"; if (payload.Length >= 6) { state.SampleRate = ((payload[5] >> 4) & 3) == 1 ? 96000 : 48000; state.Channels = (payload[5] & 7) + 1; } } else if (sub <= 0x87) { state.AudioCodec = AudioCodec.Ac3; state.AudioTag = "AC-3"; if (payload.Length > 4) { Ac3(payload[4..], state); } } else { state.AudioTag = "DTS"; } return; } state.AudioTag = "MPEG"; for (var i = 0; i + 4 <= payload.Length; i++) { var b = payload.Slice(i, 4); if (b[0] != 0xFF || (b[1] & 0xE0) != 0xE0) { continue; } if ((b[1] & 0xF6) == 0xF0) { // ADTS (ISO/IEC 13818-7): AAC in an MPEG-2 audio stream. var index = (b[2] >> 2) & 0xF; if (index < AacRates.Length) { state.AudioCodec = AudioCodec.Aac; state.SampleRate = AacRates[index]; var channels = ((b[2] & 1) << 2) | (b[3] >> 6); state.Channels = channels == 7 ? 8 : channels; return; } continue; } var version = (b[1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5 var layer = (b[1] >> 1) & 3; // 3 layer I, 2 layer II, 1 layer III var rate = (b[2] >> 2) & 3; if (version == 1 || layer == 0 || rate == 3 || (b[2] >> 4) == 15) { continue; } state.AudioCodec = layer == 1 ? AudioCodec.Mp3 : AudioCodec.Mp2; state.SampleRate = MpegAudioRates[rate] >> (version == 3 ? 0 : version == 2 ? 1 : 2); state.Channels = (b[3] >> 6) == 3 ? 1 : 2; return; } } /// Sample rate and channels of an AC-3 sync frame (ATSC A/52 §5.3): fscod, acmod and lfeon. private static void Ac3(ReadOnlySpan data, State state) { var sync = data.IndexOf((ReadOnlySpan)[0x0B, 0x77]); if (sync < 0 || sync + 8 > data.Length) { return; } var frame = data[sync..]; var fscod = frame[4] >> 6; if (fscod == 3) { return; } state.SampleRate = fscod switch { 0 => 48000, 1 => 44100, _ => 32000 }; var bits = new BitReader(frame, (5 * 8) + 8); // after syncword, crc1, fscod and frmsizecod, bsid and bsmod var acmod = bits.Read(3); if ((acmod & 1) != 0 && acmod != 1) { bits.Read(2); // cmixlev } if ((acmod & 4) != 0) { bits.Read(2); // surmixlev } if (acmod == 2) { bits.Read(2); // dsurmod } state.Channels = (acmod switch { 0 => 2, 1 => 1, 2 => 2, 3 or 4 => 3, 5 or 6 => 4, _ => 5 }) + bits.Read(1); } private sealed class State { internal readonly byte[] StreamTypes = new byte[256]; internal bool Mpeg2System; internal int VideoId = -1; internal int AudioId = -1; internal readonly Timeline Clocks = new(); internal readonly Timeline VideoTimes = new(); internal readonly Timeline AudioTimes = new(); internal VideoCodec Codec = VideoCodec.Unknown; internal int Width; internal int Height; internal int FrameDuration; internal bool VideoDone; private byte[]? probe; private int probed; private int nextLook = 16 * 1024; internal AudioCodec AudioCodec = AudioCodec.Unknown; internal string AudioTag = string.Empty; internal int SampleRate; internal int Channels; /// Gathers the start of the video stream and looks at it now and then, until its headers are found. internal void AddVideo(ReadOnlySpan payload) { if (VideoDone || payload.IsEmpty) { return; } probe ??= ArrayPool.Shared.Rent(MaxVideoProbe); var take = Math.Min(payload.Length, MaxVideoProbe - probed); payload[..take].CopyTo(probe.AsSpan(probed)); probed += take; if (probed >= nextLook || probed == MaxVideoProbe) { nextLook = probed * 4; FinishVideo(final: probed == MaxVideoProbe, whole: false); } } /// /// Codec and size from what was gathered; with nothing more will come, and with /// the stream ends there. /// internal void FinishVideo(bool final, bool whole) { if (VideoDone || VideoId < 0) { return; } var data = probe is null ? ReadOnlySpan.Empty : probe.AsSpan(0, probed); var type = StreamTypes[VideoId]; if (type is 0 or 1 or 2 && MpegVideo(data, type, final)) { VideoDone = true; return; } if (type is 0 or 0x1B && H264StreamInfo.TryPictureSizeFromAnnexB(data, whole, out var width, out var height)) { (Codec, Width, Height, VideoDone) = (VideoCodec.H264, width, height, true); return; } // HEVC only with its stream type (0x24) in the stream map: without one, the H.264 look above has the stream. if (type == 0x24 && H265StreamInfo.TryPictureSizeFromAnnexB(data, whole, out width, out height)) { (Codec, Width, Height, VideoDone) = (VideoCodec.Hevc, width, height, true); return; } if (final) { Codec = type switch { 1 => VideoCodec.Mpeg1, 2 => VideoCodec.Mpeg2, 0x10 => VideoCodec.Mpeg4Part2, 0x1B => VideoCodec.H264, 0x24 => VideoCodec.Hevc, 0xEA => VideoCodec.Vc1, _ => VideoCodec.Unknown, }; VideoDone = true; } } /// The sequence header of MPEG-1 or MPEG-2 video and, for MPEG-2, its sequence extension right after it. private bool MpegVideo(ReadOnlySpan data, byte type, bool final) { ReadOnlySpan sequence = [0, 0, 1, 0xB3]; ReadOnlySpan startCode = [0, 0, 1]; var at = data.IndexOf(sequence); if (at < 0 || at + 12 > data.Length) { return false; } var width = (data[at + 4] << 4) | (data[at + 5] >> 4); var height = ((data[at + 5] & 0xF) << 8) | data[at + 6]; var rate = data[at + 7] & 0xF; var next = data[(at + 12)..].IndexOf(startCode); bool mpeg2; if (next >= 0 && at + 12 + next + 7 <= data.Length) { // Sequence extension (H.262 §6.2.2.3): extension ID 1, then the two high bits of each size. var e = data[(at + 12 + next)..]; mpeg2 = e[3] == 0xB5 && (e[4] >> 4) == 1; if (mpeg2) { width |= (((e[5] & 1) << 1) | (e[6] >> 7)) << 12; height |= ((e[6] >> 5) & 3) << 12; } } else if (final) { mpeg2 = type == 2 || (type == 0 && Mpeg2System); } else { return false; } if (width == 0 || height == 0) { return false; } (Codec, Width, Height) = (mpeg2 ? VideoCodec.Mpeg2 : VideoCodec.Mpeg1, width, height); FrameDuration = rate < FrameTicks.Length ? FrameTicks[rate] : 0; return true; } internal void Release() { if (probe is not null) { ArrayPool.Shared.Return(probe); probe = null; } } internal MediaContainer Build() { long? ticks = null; if (VideoTimes.Elapsed() is { } video) { ticks = video + FrameDuration; } else if (AudioTimes.Elapsed() is { } audio) { ticks = audio; } else if (Clocks.Elapsed() is { } clock) { ticks = clock; } TimeSpan? duration = ticks is > 0 ? TimeSpan.FromSeconds((double)ticks.Value / ClockRate) : null; var videoTrack = VideoId < 0 ? null : new VideoTrack { Codec = Codec, CodecTag = StreamTypes[VideoId] != 0 ? "0x" + StreamTypes[VideoId].ToString("X2", CultureInfo.InvariantCulture) : Codec.ToString(), Width = Width, Height = Height, AnnexB = Codec is VideoCodec.H264 or VideoCodec.Hevc, Timescale = ClockRate, Duration = ticks ?? 0, }; var audioTrack = AudioId < 0 ? null : new AudioTrack { Codec = AudioCodec, CodecTag = AudioTag, SampleRate = SampleRate, Channels = Channels, Timescale = ClockRate, }; return new MediaContainer { Format = ContainerFormat.MpegPs, Duration = duration, Video = videoTrack, Audio = audioTrack }; } } /// /// The times of one stream, as distances from the first one seen, across the wrap of the 33-bit clock: at the start of /// the file a time up to half the clock (13 hours) away either way, at the end any time up to ten seconds before. /// private sealed class Timeline { private const long Mask = TimeWrap - 1; private const long TailSlack = 10L * ClockRate; private long reference = -1; private long headFirst; private long headLast; private long tailLast = long.MinValue; internal void Add(long time, bool head) { if (time < 0) { return; } if (reference < 0) { if (!head) { return; // nothing seen at the start: the end alone tells no length } reference = time; return; } var distance = (time - reference) & Mask; if (head) { distance = distance >= TimeWrap / 2 ? distance - TimeWrap : distance; headFirst = Math.Min(headFirst, distance); headLast = Math.Max(headLast, distance); } else { distance = distance > TimeWrap - TailSlack ? distance - TimeWrap : distance; tailLast = Math.Max(tailLast, distance); } } /// Ticks from the earliest time at the start to the latest at the end; null without two times. internal long? Elapsed() { if (reference < 0) { return null; } var last = tailLast != long.MinValue ? tailLast : headLast; return last > headFirst ? last - headFirst : null; } } }