using System.Buffers.Binary; using System.Text; using Febe.Core.Codecs.H264; namespace Febe.Core.Codecs.Containers; /// /// Reader of FLV files, written from the Adobe Flash Video File Format Specification (version 10.1, annex E): the header, /// the onMetaData script tag (AMF0), the first audio and video tags, and for H.264 the AVC sequence header and every /// NAL unit tag as a sample. HEVC, AV1 and VP9 stored with the enhanced video tag header are recognised by their FourCC. /// Width and height come from the SPS when there is one, then from the metadata, then from a Sorenson H.263 picture header. /// public static class FlvReader { private const int MaxSamples = IsoBmffReader.MaxSamples; /// The largest script tag read: metadata with a keyframe index of a long video stays far below. private const int MaxScriptBytes = 4 * 1024 * 1024; /// The largest AVC sequence header or AAC configuration read. private const int MaxConfigurationBytes = 64 * 1024; /// For the metadata alone, the tags looked at from the start (and their bytes) before giving up on the rest. private const int HeadTags = 4096; private const long HeadBytes = 32L * 1024 * 1024; /// Audio without a single video tag that, at the start of a file, proves it has no video. public const int AudioProofMilliseconds = 5000; /// Tags looked at back from the end of the file for its last time. private const int TailTags = 64; private const int AmfMaxDepth = 16; private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; /// True when the stream starts like an FLV file: «FLV», version 1 and a header of at least nine bytes. public static bool Looks(ReadOnlySpan start) => start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9; /// /// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, the tags /// in hold at least one whole audio tag and no video tag, and they reach far enough to rule /// video out — the exact end of (it is the whole file), /// of audio, or tags. Anything less (a head that ends inside a large onMetaData, a few tags, a /// tag that is not one) proves nothing, and the file stays a video: header flags are often wrong. /// public static bool IsAudioOnly(ReadOnlySpan head) { if (!Looks(head) || (head[4] & 0x01) != 0 || (head[4] & 0x04) == 0) { return false; } var position = (long)BinaryPrimitives.ReadUInt32BigEndian(head[5..]) + 4; long? firstAudio = null; long lastAudio = 0; var tags = 0; while (position + 11 <= head.Length && tags < HeadTags) { var tag = head.Slice((int)position, 11); var type = tag[0] & 0x1F; if (type == 9) { return false; } if ((tag[0] & 0xC0) != 0 || type is not (8 or 18)) { return false; // not a tag: what follows proves nothing } var next = position + 11 + ((tag[1] << 16) | (tag[2] << 8) | tag[3]) + 4; if (next > head.Length) { break; // a tag cut by the end of the head is not seen whole } if (type == 8) { var time = (long)(int)((uint)(tag[7] << 24) | (uint)(tag[4] << 16) | (uint)(tag[5] << 8) | tag[6]); firstAudio ??= time; lastAudio = time; } tags++; position = next; } return firstAudio is { } first && (position == head.Length || tags >= HeadTags || lastAudio - first >= AudioProofMilliseconds); } /// Reads a seekable stream from its start. public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(stream); var length = stream.Length; Span header = stackalloc byte[16]; stream.Position = 0; stream.ReadExactly(header[..9]); if (!Looks(header[..9])) { throw new ContainerException("Non è un file FLV."); } var flags = header[4]; var dataOffset = BinaryPrimitives.ReadUInt32BigEndian(header[5..]); var state = new State { HasAudioFlag = (flags & 0x04) != 0, HasVideoFlag = (flags & 0x01) != 0 }; var position = dataOffset + 4L; // after PreviousTagSize0 var tags = 0; while (position + 11 <= length) { if ((tags & 1023) == 0) { ct.ThrowIfCancellationRequested(); } stream.Position = position; var got = stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false); if (got < 11) { break; } var size = (header[1] << 16) | (header[2] << 8) | header[3]; var body = position + 11; if ((header[0] & 0xC0) != 0 || (header[0] & 0x1F) is not (8 or 9 or 18) || header[8] != 0 || header[9] != 0 || header[10] != 0) { break; // reserved bits, an unknown tag or a stream ID other than 0: what follows is not a tag } if (body + size > length) { break; // a tag cut short: the ones before it stand } var time = (long)(int)((uint)(header[7] << 24) | (uint)(header[4] << 16) | (uint)(header[5] << 8) | header[6]); var data = header[11..Math.Min(got, 16)]; if (size < data.Length) { data = data[..size]; } if ((header[0] & 0x20) == 0) { switch (header[0] & 0x1F) { case 8: Audio(stream, body, size, time, data, state); break; case 9: Video(stream, body, size, time, data, state, samples); break; case 18 when !state.HaveScript && size is >= 13 and <= MaxScriptBytes && IsMetadata(stream, body): state.HaveScript = Script(Read(stream, body, size), state, now); break; } } tags++; position = body + size + 4; if (!samples && (state.HaveEverything || tags >= HeadTags || position > HeadBytes)) { break; } } if (state.MetadataSeconds is null && state.FirstTime is { } first && EndTime(stream, dataOffset + 4L) is { } end && end > first) { state.LastSeconds = (end - first) / 1000.0; } return state.Build(); } /// True when a script tag starts with the AMF0 string «onMetaData»: other script tags (cue points) are not read. private static bool IsMetadata(Stream stream, long body) { Span start = stackalloc byte[13]; stream.Position = body; stream.ReadExactly(start); return start[..3].SequenceEqual((ReadOnlySpan)[2, 0, 10]) && start[3..].SequenceEqual("onMetaData"u8); } private static void Audio(Stream stream, long body, int size, long time, ReadOnlySpan data, State state) { if (data.Length < 1) { return; } state.FirstTime ??= time; var format = data[0] >> 4; if (!state.HaveAudio) { state.HaveAudio = true; state.AudioFormat = format; state.SampleRate = format == 10 ? 44100 : ((data[0] >> 2) & 3) switch { 0 => 5512, 1 => 11025, 2 => 22050, _ => 44100 }; state.Channels = (data[0] & 1) + 1; if (format is 4 or 14) { state.SampleRate = format == 4 ? 16000 : 8000; // Nellymoser 16 kHz, MP3 8 kHz: fixed rates } } if (format == 10 && state.AacConfiguration is null && data.Length >= 2 && data[1] == 0 && size - 2 is > 0 and <= MaxConfigurationBytes) { var config = Read(stream, body + 2, size - 2); state.AacConfiguration = config; if (AacRateAndChannels(config) is { } aac) { state.SampleRate = aac.Rate; state.Channels = aac.Channels > 0 ? aac.Channels : state.Channels; } } } private static void Video(Stream stream, long body, int size, long time, ReadOnlySpan data, State state, bool samples) { if (data.Length < 1) { return; } if ((data[0] & 0x80) != 0) { // Enhanced video tag header: frame type, packet type and a FourCC. Only the codec is taken. if (data.Length >= 5 && state.Codec is null) { state.FirstTime ??= time; state.CodecTag = Encoding.Latin1.GetString(data[1..5]); state.Codec = state.CodecTag switch { "avc1" => VideoCodec.H264, "hvc1" => VideoCodec.Hevc, "av01" => VideoCodec.Av1, "vp09" => VideoCodec.Vp9, _ => VideoCodec.Unknown, }; } return; } var frameType = data[0] >> 4; var codecId = data[0] & 0x0F; if (frameType == 5) { return; // video info or command frame: no picture } state.FirstTime ??= time; if (state.Codec is null) { state.CodecId = codecId; state.CodecTag = codecId.ToString(System.Globalization.CultureInfo.InvariantCulture); state.Codec = codecId switch { 2 => VideoCodec.H263, 4 or 5 => VideoCodec.Vp6, 7 => VideoCodec.H264, 12 => VideoCodec.Hevc, // the codec ID that HEVC writers outside the specification use _ => VideoCodec.Unknown, }; } if (codecId != state.CodecId) { return; // a second codec in the same file: only the first is followed } if (codecId == 2 && state.PictureWidth == 0 && size >= 10) { (state.PictureWidth, state.PictureHeight) = SorensonSize(Read(stream, body + 1, Math.Min(size - 1, 16))); } if (codecId != 7 || data.Length < 5) { return; } var packetType = data[1]; if (packetType == 0) { if (state.AvcConfiguration is null && size - 5 is > 0 and <= MaxConfigurationBytes) { var config = Read(stream, body + 5, size - 5); if (config.Length >= 7 && config[0] == 1) { state.AvcConfiguration = config; if (H264StreamInfo.TryPictureSizeFromConfiguration(config, out var w, out var h)) { (state.PictureWidth, state.PictureHeight) = (w, h); } } } } else if (packetType == 1 && samples && size > 5) { if (state.Samples.Count >= MaxSamples) { throw new ContainerException("Troppi campioni."); } var composition = (data[2] << 16) | (data[3] << 8) | data[4]; composition = (composition << 8) >> 8; // SI24 state.Samples.Add(new MediaSample(body + 5, size - 5, time, time + composition, frameType == 1)); } } /// The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields. /// /// The time the file ends, in milliseconds, from the tags at its end (walked back through their PreviousTagSize): the /// last video tag plus the interval from the video tag before it, that is one frame, as the MPEG reader adds one /// frame to the last time of its video; the same for audio when the end of the file holds no video tag. Null when /// the end of the file has no tag to trust. /// private static long? EndTime(Stream stream, long firstTag) { Span buffer = stackalloc byte[11]; var end = stream.Length; long? lastVideo = null, previousVideo = null, lastAudio = null, previousAudio = null; for (var step = 0; step < TailTags && end - 4 >= firstTag && previousVideo is null; step++) { stream.Position = end - 4; stream.ReadExactly(buffer[..4]); var previous = BinaryPrimitives.ReadUInt32BigEndian(buffer); var start = end - 4 - previous; if (previous < 11 || start < firstTag) { break; // no PreviousTagSize to trust (a file cut short ends inside a tag) } stream.Position = start; stream.ReadExactly(buffer); var size = (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; if (size + 11 != previous || (buffer[0] & 0xC0) != 0) { break; } var time = (long)(int)((uint)(buffer[7] << 24) | (uint)(buffer[4] << 16) | (uint)(buffer[5] << 8) | buffer[6]); switch (buffer[0] & 0x1F) { case 9: Note(ref lastVideo, ref previousVideo, time); break; case 8: Note(ref lastAudio, ref previousAudio, time); break; } end = start; } return lastVideo is { } video ? video + (video - (previousVideo ?? video)) : lastAudio is { } audio ? audio + (audio - (previousAudio ?? audio)) : null; // The first time seen walking back is the last of the track, the first earlier one the tag before it (a tag at the // same time, such as the end of an AVC sequence, is no frame of its own). static void Note(ref long? last, ref long? before, long time) { if (last is null) { last = time; } else if (before is null && time < last) { before = time; } } } private static byte[] Read(Stream stream, long offset, int count) { if (count < 0 || count > stream.Length - offset) { throw new ContainerException("Etichetta FLV danneggiata."); } var data = new byte[count]; stream.Position = offset; stream.ReadExactly(data); return data; } /// /// Width and height of a Sorenson H.263 picture header (FLV specification, «H.263 video packet»): the 17-bit start /// code, version, temporal reference, then a picture size code or the size itself. /// private static (int Width, int Height) SorensonSize(ReadOnlySpan data) { if (data.Length < 9 || data[0] != 0 || data[1] != 0 || (data[2] & 0x80) == 0) { return (0, 0); } var bits = new BitReader(data, 17 + 5 + 8); var code = bits.Read(3); return code switch { 0 => (bits.Read(8), bits.Read(8)), 1 => (bits.Read(16), bits.Read(16)), 2 => (352, 288), 3 => (176, 144), 4 => (128, 96), 5 => (320, 240), 6 => (160, 120), _ => (0, 0), }; } /// Sample rate and channels of an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1); null when damaged. internal static (int Rate, int Channels)? AacRateAndChannels(ReadOnlySpan config) { if (config.Length < 2) { return null; } var bits = new BitReader(config, 0); if (bits.Read(5) == 31) { bits.Read(6); } var index = bits.Read(4); int rate; if (index == 15) { if (config.Length < 5) { return null; } rate = bits.Read(24); } else if (index < AacRates.Length) { rate = AacRates[index]; } else { return null; } var channels = bits.Read(4); return (rate, channels switch { 7 => 8, > 7 => 0, _ => channels }); } /// Reads the onMetaData script tag; true when it was one (another script tag leaves the next to be read). private static bool Script(ReadOnlySpan data, State state, DateTimeOffset now) { var p = 0; if (!Byte(data, ref p, out var type) || type != 2 || !ShortString(data, ref p, out var name) || !name.SequenceEqual("onMetaData"u8)) { return false; } if (!Byte(data, ref p, out type)) { return true; } if (type == 8) { p += 4; // approximate count of an ECMA array: the end marker closes it } else if (type != 3) { return true; } var metadata = new Metadata(now); _ = Properties(data, ref p, 0, metadata); state.MetadataSeconds = metadata.Duration is > 0 and < 1e9 ? metadata.Duration : null; state.MetadataWidth = metadata.Width is > 0 and <= 65535 ? (int)metadata.Width : 0; state.MetadataHeight = metadata.Height is > 0 and <= 65535 ? (int)metadata.Height : 0; state.Created = metadata.Created; return true; } /// The properties of an AMF0 object up to its end marker; only the top level is kept. private static bool Properties(ReadOnlySpan data, ref int p, int depth, Metadata? metadata) { while (p < data.Length) { if (p + 3 <= data.Length && data[p] == 0 && data[p + 1] == 0 && data[p + 2] == 9) { p += 3; return true; } if (!ShortString(data, ref p, out var name) || !Value(data, ref p, depth, metadata, name)) { return false; } } return true; // an ECMA array may end with the tag, without its marker } /// One AMF0 value (Action Message Format AMF0, §2); false when the data is not AMF0 or runs out. private static bool Value(ReadOnlySpan data, ref int p, int depth, Metadata? metadata, ReadOnlySpan name) { if (!Byte(data, ref p, out var type)) { return false; } switch (type) { case 0: // number if (p + 8 > data.Length) { return false; } metadata?.Number(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); p += 8; return true; case 1: // boolean return Skip(data, ref p, 1); case 2: // string if (!ShortString(data, ref p, out var text)) { return false; } metadata?.Text(name, text); return true; case 3: // object return depth < AmfMaxDepth && Properties(data, ref p, depth + 1, null); case 5 or 6 or 13: // null, undefined, unsupported return true; case 7: // reference return Skip(data, ref p, 2); case 8: // ECMA array return depth < AmfMaxDepth && Skip(data, ref p, 4) && Properties(data, ref p, depth + 1, null); case 10: // strict array { if (depth >= AmfMaxDepth || p + 4 > data.Length) { return false; } var count = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); p += 4; if (count > (uint)(data.Length - p)) { return false; // every value takes at least a byte } for (var i = 0u; i < count; i++) { if (!Value(data, ref p, depth + 1, null, default)) { return false; } } return true; } case 11: // date: milliseconds from 1970 and a time zone that the specification says to ignore if (p + 10 > data.Length) { return false; } metadata?.Date(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); p += 10; return true; case 12 or 15: // long string, XML document { if (p + 4 > data.Length) { return false; } var length = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); p += 4; return length <= (uint)(data.Length - p) && Skip(data, ref p, (int)length); } case 16: // typed object: a class name, then the properties return depth < AmfMaxDepth && ShortString(data, ref p, out _) && Properties(data, ref p, depth + 1, null); default: return false; // movie clip and record set are reserved; anything else is not AMF0 } } private static bool Byte(ReadOnlySpan data, ref int p, out byte value) { value = p < data.Length ? data[p] : (byte)0; p++; return p <= data.Length; } private static bool Skip(ReadOnlySpan data, ref int p, int count) { p += count; return p <= data.Length; } private static bool ShortString(ReadOnlySpan data, ref int p, out ReadOnlySpan text) { text = default; if (p + 2 > data.Length) { return false; } var length = BinaryPrimitives.ReadUInt16BigEndian(data[p..]); p += 2; if (p + length > data.Length) { return false; } text = data.Slice(p, length); p += length; return true; } /// The onMetaData properties Febe uses. private sealed class Metadata(DateTimeOffset now) { internal double? Duration; internal double? Width; internal double? Height; internal DateTimeOffset? Created; internal void Number(ReadOnlySpan name, double value) { if (!double.IsFinite(value)) { return; } if (name.SequenceEqual("duration"u8)) { Duration = value; } else if (name.SequenceEqual("width"u8)) { Width = value; } else if (name.SequenceEqual("height"u8)) { Height = value; } } internal void Text(ReadOnlySpan name, ReadOnlySpan value) { if (name.SequenceEqual("creationdate"u8) && value.Length is > 0 and < 128) { Created = AviReader.ParseDate(Encoding.UTF8.GetString(value), now) ?? Created; } } internal void Date(ReadOnlySpan name, double milliseconds) { // From 1995 to a day past now, as the other readers. if (name.SequenceEqual("creationdate"u8) && double.IsFinite(milliseconds) && milliseconds >= 788_918_400_000d && milliseconds <= now.AddDays(1).ToUnixTimeMilliseconds()) { Created = DateTimeOffset.FromUnixTimeMilliseconds((long)milliseconds); } } } private sealed class State { internal bool HasAudioFlag; internal bool HasVideoFlag; internal bool HaveScript; internal bool HaveAudio; internal int AudioFormat; internal int SampleRate; internal int Channels; internal byte[]? AacConfiguration; internal VideoCodec? Codec; internal int CodecId = -1; internal string CodecTag = string.Empty; internal byte[]? AvcConfiguration; internal int PictureWidth; internal int PictureHeight; internal double? MetadataSeconds; internal int MetadataWidth; internal int MetadataHeight; internal double? LastSeconds; internal DateTimeOffset? Created; internal long? FirstTime; internal readonly List Samples = []; /// For the metadata alone: the script, the video codec (with its sequence header for H.264) and the audio are known. internal bool HaveEverything => HaveScript && (!HasVideoFlag || (Codec is not null && (Codec != VideoCodec.H264 || CodecId != 7 || AvcConfiguration is not null))) && (!HasAudioFlag || HaveAudio); internal MediaContainer Build() { var seconds = MetadataSeconds ?? LastSeconds; TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds.Value) : null; VideoTrack? video = null; if (Codec is { } codec) { var (width, height) = PictureWidth > 0 && PictureHeight > 0 ? (PictureWidth, PictureHeight) : (MetadataWidth, MetadataHeight); video = new VideoTrack { Codec = codec, CodecTag = CodecTag, Width = width, Height = height, AvcConfiguration = CodecId == 7 ? AvcConfiguration : null, Timescale = 1000, Duration = duration is { } d ? (long)d.TotalMilliseconds : 0, Samples = Samples, }; } else if (MetadataWidth > 0 && MetadataHeight > 0) { video = new VideoTrack { Width = MetadataWidth, Height = MetadataHeight, Timescale = 1000 }; // only the metadata knows it } AudioTrack? audio = HaveAudio ? new AudioTrack { Codec = AudioFormat switch { 10 => AudioCodec.Aac, 2 or 14 => AudioCodec.Mp3, 0 or 3 => AudioCodec.Pcm, _ => AudioCodec.Unknown, }, CodecTag = AudioFormat.ToString(System.Globalization.CultureInfo.InvariantCulture), SampleRate = SampleRate, Channels = Channels, AacConfiguration = AudioFormat == 10 ? AacConfiguration : null, Timescale = 1000, } : null; return new MediaContainer { Format = ContainerFormat.Flv, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; } } }