Lettori in casa di WMV/ASF, FLV e MPEG: data, durata, dimensioni e codec anche per questi video (#58)
Finora MediaSniffer riconosceva WMV, FLV e MPEG ma la sonda dei metadati non ne sapeva nulla: data, durata e dimensioni venivano solo dal nome e dalla data di modifica. Tre lettori nuovi, scritti dalle specifiche pubbliche senza componenti esterni, stanno dietro ContainerReader e quindi dietro ContainerVideoMetadataProbe e VideoFrameDecoder. - AsfReader: proprietà del file (data FILETIME, durata meno il preroll, niente durata per le trasmissioni), proprietà dei flussi anche dentro l'estensione dell'intestazione, titolo della descrizione del contenuto, WM/EncodingTime quando manca la data. Nessun campione. - FlvReader: onMetaData in AMF0 (durata, dimensioni, creationdate come testo o come data), dimensioni dall'SPS della sequenza AVC o dall'intestazione H.263 di Sorenson, durata dall'ultimo tag senza metadati, codec degli FLV «enhanced» dal FourCC; i tag H.264 sono campioni, così anche un FLV ha la miniatura. - MpegPsReader: pacchetti MPEG-1 e MPEG-2, intestazione di sistema, mappa del flusso, PES; codec e dimensioni dall'intestazione di sequenza (con l'estensione di MPEG-2) o dall'SPS H.264, audio MPEG, ADTS, AC-3 e LPCM; durata dal primo all'ultimo PTS attraverso il giro dei 33 bit, leggendo solo i primi 2 MB e l'ultimo MB. - H264StreamInfo: dimensioni ritagliate di un SPS, da un avcC o da un flusso Annex B. - MediaSniffer: un WMA o un FLV di solo audio non è più un video, quando l'intestazione intera nei primi byte lo dimostra. Prove con file costruiti dalle prove stesse (LegacyTestVideos, semi fissi): metadati, MD5 ufficiali dei fotogrammi da FLV, miniatura dell'FLV uguale a quella dell'MP4, file lunghi e giro dell'orologio, file troncati e rovinati, AMF annidato senza fine e oggetti ASF più grandi del file. LEGGIMI dell'importazione e una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
898e9d60e7
commit
6c8b228333
18 files changed
+2983
-13
No files matched your search
@@ -0,0 +1,438 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of Advanced Systems Format files (WMV, WMA, ASF), written from the ASF specification (revision 01.20.03): the
|
||||
/// objects of the header — file properties (creation date, duration), stream properties (codec, size, audio format),
|
||||
/// also when they sit inside an extended stream properties object of the header extension, content description (title)
|
||||
/// and extended content description (<c>WM/EncodingTime</c> when the file properties have no date). The data packets
|
||||
/// are not read: Febe decodes no codec carried in ASF, so the tracks have no samples.
|
||||
/// </summary>
|
||||
public static class AsfReader
|
||||
{
|
||||
private static readonly Guid HeaderObject = new("75B22630-668E-11CF-A6D9-00AA0062CE6C");
|
||||
private static readonly Guid FilePropertiesObject = new("8CABDCA1-A947-11CF-8EE4-00C00C205365");
|
||||
private static readonly Guid StreamPropertiesObject = new("B7DC0791-A9B7-11CF-8EE6-00C00C205365");
|
||||
private static readonly Guid HeaderExtensionObject = new("5FBF03B5-A92E-11CF-8EE3-00C00C205365");
|
||||
private static readonly Guid ContentDescriptionObject = new("75B22633-668E-11CF-A6D9-00AA0062CE6C");
|
||||
private static readonly Guid ExtendedContentDescriptionObject = new("D2D0A440-E307-11D2-97F0-00A0C95EA850");
|
||||
private static readonly Guid ExtendedStreamPropertiesObject = new("14E6A5CB-C672-4332-8399-A96952065B5A");
|
||||
private static readonly Guid VideoMedia = new("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B");
|
||||
private static readonly Guid AudioMedia = new("F8699E40-5B4D-11CF-A8FD-00805F5C442B");
|
||||
|
||||
private static readonly DateTimeOffset Epoch1601 = new(1601, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>Bytes of an object header: its GUID and its 64-bit size.</summary>
|
||||
private const int ObjectHeader = 24;
|
||||
|
||||
/// <summary>Header objects looked at, in all: a real header has a few dozen.</summary>
|
||||
private const int MaxObjects = 4096;
|
||||
|
||||
/// <summary>The largest header object read into memory; the extended content description may hold a cover picture, cut here.</summary>
|
||||
private const int MaxObjectBytes = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts with the GUID of the ASF header object.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 16 && new Guid(start[..16]) == HeaderObject;
|
||||
|
||||
/// <summary>
|
||||
/// True only when the first bytes of a file hold its whole header object and that header lists audio streams and no
|
||||
/// video stream: a WMA file. An incomplete header proves nothing.
|
||||
/// </summary>
|
||||
public static bool IsAudioOnly(ReadOnlySpan<byte> head)
|
||||
{
|
||||
if (!Looks(head) || head.Length < 30)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var size = BinaryPrimitives.ReadUInt64LittleEndian(head[16..]);
|
||||
if (size < 30 || size > (ulong)head.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var state = new State();
|
||||
try
|
||||
{
|
||||
Objects(head[30..(int)size], state, DateTimeOffset.MaxValue.AddDays(-1), depth: 0);
|
||||
}
|
||||
catch (ContainerException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return state.Complete && state.VideoStream < 0 && state.AudioStream >= 0;
|
||||
}
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
_ = samples; // nothing in ASF is decoded: the tracks never have samples
|
||||
Span<byte> top = stackalloc byte[30];
|
||||
stream.Position = 0;
|
||||
stream.ReadExactly(top);
|
||||
if (!Looks(top))
|
||||
{
|
||||
throw new ContainerException("Non è un file ASF.");
|
||||
}
|
||||
|
||||
var size = BinaryPrimitives.ReadUInt64LittleEndian(top[16..]);
|
||||
if (size < 30)
|
||||
{
|
||||
throw new ContainerException("Intestazione ASF danneggiata.");
|
||||
}
|
||||
|
||||
var end = (long)Math.Min(size, (ulong)stream.Length); // a file cut inside its header keeps the objects before the cut
|
||||
var state = new State();
|
||||
var position = 30L;
|
||||
Span<byte> head = stackalloc byte[ObjectHeader];
|
||||
while (position + ObjectHeader <= end && state.Objects < MaxObjects)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(head);
|
||||
var objectSize = BinaryPrimitives.ReadUInt64LittleEndian(head[16..]);
|
||||
if (objectSize < ObjectHeader || objectSize > (ulong)(end - position))
|
||||
{
|
||||
break; // a damaged size, or an object cut by the end of the file
|
||||
}
|
||||
|
||||
var id = new Guid(head[..16]);
|
||||
if (id == FilePropertiesObject || id == StreamPropertiesObject || id == HeaderExtensionObject
|
||||
|| id == ContentDescriptionObject || id == ExtendedContentDescriptionObject)
|
||||
{
|
||||
var length = (int)Math.Min(objectSize, MaxObjectBytes);
|
||||
var data = new byte[length];
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(data);
|
||||
Objects(data, state, now, depth: 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
state.Objects++;
|
||||
}
|
||||
|
||||
position += (long)objectSize;
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
/// <summary>The objects in <paramref name="data"/>, one after the other, up to its end or the first damaged one.</summary>
|
||||
private static void Objects(ReadOnlySpan<byte> data, State state, DateTimeOffset now, int depth)
|
||||
{
|
||||
var p = 0;
|
||||
while (p + ObjectHeader <= data.Length && state.Objects < MaxObjects)
|
||||
{
|
||||
state.Objects++;
|
||||
var size = BinaryPrimitives.ReadUInt64LittleEndian(data[(p + 16)..]);
|
||||
if (size < ObjectHeader)
|
||||
{
|
||||
state.Complete = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var cut = size > (ulong)(data.Length - p);
|
||||
var body = data.Slice(p + ObjectHeader, (int)(cut ? data.Length - p : (long)size) - ObjectHeader);
|
||||
var id = new Guid(data.Slice(p, 16));
|
||||
if (id == FilePropertiesObject)
|
||||
{
|
||||
FileProperties(body, state, now);
|
||||
}
|
||||
else if (id == StreamPropertiesObject)
|
||||
{
|
||||
StreamProperties(body, state);
|
||||
}
|
||||
else if (id == ContentDescriptionObject)
|
||||
{
|
||||
ContentDescription(body, state);
|
||||
}
|
||||
else if (id == ExtendedContentDescriptionObject)
|
||||
{
|
||||
ExtendedContentDescription(body, state, now);
|
||||
}
|
||||
else if (id == HeaderExtensionObject && depth == 0 && body.Length >= 22)
|
||||
{
|
||||
// Reserved GUID and field, then the size of the objects that follow.
|
||||
var extension = BinaryPrimitives.ReadUInt32LittleEndian(body[18..]);
|
||||
var inner = body[22..];
|
||||
Objects(inner[..(int)Math.Min(extension, (uint)inner.Length)], state, now, depth + 1);
|
||||
}
|
||||
else if (id == ExtendedStreamPropertiesObject)
|
||||
{
|
||||
ExtendedStreamProperties(body, state);
|
||||
}
|
||||
|
||||
if (cut)
|
||||
{
|
||||
state.Complete = false;
|
||||
return;
|
||||
}
|
||||
|
||||
p += (int)size;
|
||||
}
|
||||
|
||||
state.Complete = p == data.Length;
|
||||
}
|
||||
|
||||
private static void FileProperties(ReadOnlySpan<byte> body, State state, DateTimeOffset now)
|
||||
{
|
||||
if (body.Length < 80)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
state.Created ??= FileTime(BinaryPrimitives.ReadUInt64LittleEndian(body[24..]), now);
|
||||
var play = BinaryPrimitives.ReadUInt64LittleEndian(body[40..]); // 100-nanosecond units, preroll included
|
||||
var preroll = BinaryPrimitives.ReadUInt64LittleEndian(body[56..]); // milliseconds
|
||||
var broadcast = (BinaryPrimitives.ReadUInt32LittleEndian(body[64..]) & 1) != 0;
|
||||
if (!broadcast && play is > 0 and < 10_000_000UL * 1_000_000_000 && preroll < play / 10_000)
|
||||
{
|
||||
state.Duration = TimeSpan.FromTicks((long)(play - (preroll * 10_000)));
|
||||
}
|
||||
}
|
||||
|
||||
private static void StreamProperties(ReadOnlySpan<byte> body, State state)
|
||||
{
|
||||
if (body.Length < 54)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var type = new Guid(body[..16]);
|
||||
var specificLength = BinaryPrimitives.ReadUInt32LittleEndian(body[40..]);
|
||||
var number = BinaryPrimitives.ReadUInt16LittleEndian(body[48..]) & 0x7F;
|
||||
var specific = body[54..];
|
||||
specific = specific[..(int)Math.Min(specificLength, (uint)specific.Length)];
|
||||
if (type == VideoMedia && state.VideoStream < 0 && specific.Length >= 11)
|
||||
{
|
||||
state.VideoStream = number;
|
||||
state.Width = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific), 65535);
|
||||
state.Height = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific[4..]), 65535);
|
||||
var format = specific[11..];
|
||||
if (format.Length >= 20)
|
||||
{
|
||||
// BITMAPINFOHEADER: its size when the encoded size is missing, and the compression code.
|
||||
state.Width = state.Width > 0 ? state.Width : (int)Math.Min(Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(format[4..])), 65535);
|
||||
state.Height = state.Height > 0 ? state.Height : (int)Math.Min(Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(format[8..])), 65535);
|
||||
state.Compression = Encoding.Latin1.GetString(format.Slice(16, 4));
|
||||
}
|
||||
}
|
||||
else if (type == AudioMedia && state.AudioStream < 0 && specific.Length >= 16)
|
||||
{
|
||||
state.AudioStream = number;
|
||||
state.AudioFormat = BinaryPrimitives.ReadUInt16LittleEndian(specific);
|
||||
state.Channels = BinaryPrimitives.ReadUInt16LittleEndian(specific[2..]);
|
||||
state.SampleRate = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific[4..]), int.MaxValue);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The extended stream properties object (§4.1): fixed fields, stream names and payload extension systems, then the
|
||||
/// stream properties object of a stream that the header itself does not list.
|
||||
/// </summary>
|
||||
private static void ExtendedStreamProperties(ReadOnlySpan<byte> body, State state)
|
||||
{
|
||||
if (body.Length < 64)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var names = BinaryPrimitives.ReadUInt16LittleEndian(body[60..]);
|
||||
var systems = BinaryPrimitives.ReadUInt16LittleEndian(body[62..]);
|
||||
var p = 64;
|
||||
for (var i = 0; i < names; i++)
|
||||
{
|
||||
if (p + 4 > body.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
p += 4 + BinaryPrimitives.ReadUInt16LittleEndian(body[(p + 2)..]);
|
||||
}
|
||||
|
||||
for (var i = 0; i < systems; i++)
|
||||
{
|
||||
if (p + 22 > body.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var info = BinaryPrimitives.ReadUInt32LittleEndian(body[(p + 18)..]);
|
||||
if (info > (uint)(body.Length - p - 22))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
p += 22 + (int)info;
|
||||
}
|
||||
|
||||
if (p + ObjectHeader <= body.Length && new Guid(body.Slice(p, 16)) == StreamPropertiesObject)
|
||||
{
|
||||
var size = BinaryPrimitives.ReadUInt64LittleEndian(body[(p + 16)..]);
|
||||
if (size >= ObjectHeader && size <= (ulong)(body.Length - p))
|
||||
{
|
||||
StreamProperties(body.Slice(p + ObjectHeader, (int)size - ObjectHeader), state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ContentDescription(ReadOnlySpan<byte> body, State state)
|
||||
{
|
||||
if (body.Length < 10)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var title = BinaryPrimitives.ReadUInt16LittleEndian(body);
|
||||
if (10 + title <= body.Length)
|
||||
{
|
||||
var text = Encoding.Unicode.GetString(body.Slice(10, title & ~1)).TrimEnd('\0').Trim();
|
||||
state.Title ??= text.Length > 0 ? text : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Name and value pairs (§3.11); only <c>WM/EncodingTime</c> is used, for the date.</summary>
|
||||
private static void ExtendedContentDescription(ReadOnlySpan<byte> body, State state, DateTimeOffset now)
|
||||
{
|
||||
if (body.Length < 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var count = BinaryPrimitives.ReadUInt16LittleEndian(body);
|
||||
var p = 2;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (p + 2 > body.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var nameLength = BinaryPrimitives.ReadUInt16LittleEndian(body[p..]);
|
||||
if (p + 2 + nameLength + 4 > body.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var name = body.Slice(p + 2, nameLength);
|
||||
p += 2 + nameLength;
|
||||
var type = BinaryPrimitives.ReadUInt16LittleEndian(body[p..]);
|
||||
var valueLength = BinaryPrimitives.ReadUInt16LittleEndian(body[(p + 2)..]);
|
||||
p += 4;
|
||||
if (p + valueLength > body.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == 4 && valueLength == 8 && IsName(name, "WM/EncodingTime"))
|
||||
{
|
||||
state.EncodingTime ??= FileTime(BinaryPrimitives.ReadUInt64LittleEndian(body[p..]), now);
|
||||
}
|
||||
|
||||
p += valueLength;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when a null-terminated UTF-16LE name is <paramref name="expected"/>.</summary>
|
||||
private static bool IsName(ReadOnlySpan<byte> name, string expected)
|
||||
{
|
||||
if (name.Length < expected.Length * 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < expected.Length; i++)
|
||||
{
|
||||
if (name[2 * i] != expected[i] || name[(2 * i) + 1] != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return name.Length == expected.Length * 2 || (name.Length >= (expected.Length * 2) + 2 && name[expected.Length * 2] == 0 && name[(expected.Length * 2) + 1] == 0);
|
||||
}
|
||||
|
||||
/// <summary>A FILETIME (100-nanosecond units from 1601, UTC) from 1995 to a day past now; null otherwise.</summary>
|
||||
private static DateTimeOffset? FileTime(ulong ticks, DateTimeOffset now)
|
||||
{
|
||||
if (ticks == 0 || ticks > (ulong)(DateTimeOffset.MaxValue - Epoch1601).Ticks)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var instant = Epoch1601.AddTicks((long)ticks);
|
||||
return instant >= Earliest && instant <= now.AddDays(1) ? instant : null;
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
internal int Objects;
|
||||
internal bool Complete;
|
||||
internal DateTimeOffset? Created;
|
||||
internal DateTimeOffset? EncodingTime;
|
||||
internal TimeSpan? Duration;
|
||||
internal string? Title;
|
||||
internal int VideoStream = -1;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal string Compression = string.Empty;
|
||||
internal int AudioStream = -1;
|
||||
internal int AudioFormat;
|
||||
internal int Channels;
|
||||
internal int SampleRate;
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
var tag = Compression.ToUpperInvariant();
|
||||
var video = VideoStream < 0 ? null : new VideoTrack
|
||||
{
|
||||
Codec = tag switch
|
||||
{
|
||||
"WMV1" or "WMV2" => VideoCodec.Wmv,
|
||||
"WMV3" or "WMVA" or "WVC1" or "WMVP" or "WVP2" => VideoCodec.Vc1,
|
||||
"H264" or "AVC1" or "X264" => VideoCodec.H264,
|
||||
"MP4S" or "M4S2" or "XVID" or "DIVX" or "DX50" or "FMP4" => VideoCodec.Mpeg4Part2,
|
||||
"MJPG" => VideoCodec.Mjpeg,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = Compression,
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
Timescale = 1000,
|
||||
Duration = Duration is { } d ? (long)d.TotalMilliseconds : 0,
|
||||
};
|
||||
var audio = AudioStream < 0 ? null : new AudioTrack
|
||||
{
|
||||
Codec = AudioFormat switch
|
||||
{
|
||||
0x160 or 0x161 or 0x162 or 0x163 or 0x0A => AudioCodec.Wma,
|
||||
0x55 => AudioCodec.Mp3,
|
||||
0x50 => AudioCodec.Mp2,
|
||||
0xFF or 0x1610 => AudioCodec.Aac,
|
||||
0x2000 => AudioCodec.Ac3,
|
||||
1 => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = AudioFormat.ToString("X4", CultureInfo.InvariantCulture),
|
||||
Channels = Channels,
|
||||
SampleRate = SampleRate,
|
||||
Timescale = Math.Max(1, SampleRate),
|
||||
};
|
||||
return new MediaContainer
|
||||
{
|
||||
Format = ContainerFormat.Asf,
|
||||
CreatedAt = Created ?? EncodingTime,
|
||||
Duration = Duration,
|
||||
Title = Title,
|
||||
Video = video,
|
||||
Audio = audio,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,7 +228,7 @@ public static class AviReader
|
||||
}
|
||||
|
||||
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
|
||||
private static DateTimeOffset? ParseDate(string text, DateTimeOffset now)
|
||||
internal static DateTimeOffset? ParseDate(string text, DateTimeOffset now)
|
||||
{
|
||||
var value = text.Trim('\0', ' ', '\r', '\n');
|
||||
foreach (var format in new[] { "ddd MMM dd HH:mm:ss yyyy", "ddd MMM d HH:mm:ss yyyy", "yyyy:MM:dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss" })
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>A big-endian bit reader over the few bytes of a codec header; past the end it gives zeros.</summary>
|
||||
internal ref struct BitReader(ReadOnlySpan<byte> data, int position)
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> data = data;
|
||||
private int position = position;
|
||||
|
||||
/// <summary>The next <paramref name="count"/> bits (at most 31) as an unsigned number.</summary>
|
||||
internal int Read(int count)
|
||||
{
|
||||
var value = 0;
|
||||
for (var i = 0; i < count; i++, position++)
|
||||
{
|
||||
var index = position >> 3;
|
||||
var bit = index < data.Length ? (data[index] >> (7 - (position & 7))) & 1 : 0;
|
||||
value = (value << 1) | bit;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary>
|
||||
/// <summary>
|
||||
/// Recognises the container of a video by its first bytes (MP4 and MOV, Matroska and WebM, AVI, ASF and WMV, FLV, MPEG
|
||||
/// program stream) and reads it with the matching reader.
|
||||
/// </summary>
|
||||
public static class ContainerReader
|
||||
{
|
||||
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
|
||||
@@ -19,6 +22,21 @@ public static class ContainerReader
|
||||
return ContainerFormat.Avi;
|
||||
}
|
||||
|
||||
if (AsfReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Asf;
|
||||
}
|
||||
|
||||
if (FlvReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Flv;
|
||||
}
|
||||
|
||||
if (MpegPsReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.MpegPs;
|
||||
}
|
||||
|
||||
return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null;
|
||||
}
|
||||
|
||||
@@ -38,6 +56,9 @@ public static class ContainerReader
|
||||
{
|
||||
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct),
|
||||
ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct),
|
||||
ContainerFormat.Asf => AsfReader.Read(stream, now, samples, ct),
|
||||
ContainerFormat.Flv => FlvReader.Read(stream, now, samples, ct),
|
||||
ContainerFormat.MpegPs => MpegPsReader.Read(stream, now, samples, ct),
|
||||
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,693 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Febe.Core.Codecs.H264;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of FLV files, written from the Adobe Flash Video File Format Specification (version 10.1, annex E): the header,
|
||||
/// the <c>onMetaData</c> 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.
|
||||
/// </summary>
|
||||
public static class FlvReader
|
||||
{
|
||||
private const int MaxSamples = IsoBmffReader.MaxSamples;
|
||||
|
||||
/// <summary>The largest script tag read: metadata with a keyframe index of a long video stays far below.</summary>
|
||||
private const int MaxScriptBytes = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>The largest AVC sequence header or AAC configuration read.</summary>
|
||||
private const int MaxConfigurationBytes = 64 * 1024;
|
||||
|
||||
/// <summary>For the metadata alone, the tags looked at from the start (and their bytes) before giving up on the rest.</summary>
|
||||
private const int HeadTags = 4096;
|
||||
|
||||
private const long HeadBytes = 32L * 1024 * 1024;
|
||||
|
||||
/// <summary>Tags looked at back from the end of the file for its last time.</summary>
|
||||
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];
|
||||
|
||||
/// <summary>True when the stream starts like an FLV file: «FLV», version 1 and a header of at least nine bytes.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9;
|
||||
|
||||
/// <summary>
|
||||
/// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, and no
|
||||
/// video tag is among the tags in <paramref name="head"/>.
|
||||
/// </summary>
|
||||
public static bool IsAudioOnly(ReadOnlySpan<byte> head)
|
||||
{
|
||||
if (!Looks(head) || (head[4] & 0x01) != 0 || (head[4] & 0x04) == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var position = (long)BinaryPrimitives.ReadUInt32BigEndian(head[5..]) + 4;
|
||||
for (var tags = 0; position + 11 <= head.Length && tags < HeadTags; tags++)
|
||||
{
|
||||
var type = head[(int)position] & 0x1F;
|
||||
if (type == 9)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
position += 11 + ((head[(int)position + 1] << 16) | (head[(int)position + 2] << 8) | head[(int)position + 3]) + 4;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var length = stream.Length;
|
||||
Span<byte> 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 && LastTime(stream, dataOffset + 4L) is { } last && last > first)
|
||||
{
|
||||
state.LastSeconds = (last - first) / 1000.0;
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
/// <summary>True when a script tag starts with the AMF0 string «onMetaData»: other script tags (cue points) are not read.</summary>
|
||||
private static bool IsMetadata(Stream stream, long body)
|
||||
{
|
||||
Span<byte> start = stackalloc byte[13];
|
||||
stream.Position = body;
|
||||
stream.ReadExactly(start);
|
||||
return start[..3].SequenceEqual((ReadOnlySpan<byte>)[2, 0, 10]) && start[3..].SequenceEqual("onMetaData"u8);
|
||||
}
|
||||
|
||||
private static void Audio(Stream stream, long body, int size, long time, ReadOnlySpan<byte> 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<byte> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields.</summary>
|
||||
private static long? LastTime(Stream stream, long firstTag)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[11];
|
||||
var end = stream.Length;
|
||||
for (var step = 0; step < TailTags && end - 4 >= firstTag; step++)
|
||||
{
|
||||
stream.Position = end - 4;
|
||||
stream.ReadExactly(buffer[..4]);
|
||||
var previous = BinaryPrimitives.ReadUInt32BigEndian(buffer);
|
||||
var start = end - 4 - previous;
|
||||
if (previous < 11 || start < firstTag)
|
||||
{
|
||||
return null; // 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)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((buffer[0] & 0x1F) is 8 or 9)
|
||||
{
|
||||
return (int)((uint)(buffer[7] << 24) | (uint)(buffer[4] << 16) | (uint)(buffer[5] << 8) | buffer[6]);
|
||||
}
|
||||
|
||||
end = start;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static (int Width, int Height) SorensonSize(ReadOnlySpan<byte> 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),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Sample rate and channels of an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1); null when damaged.</summary>
|
||||
internal static (int Rate, int Channels)? AacRateAndChannels(ReadOnlySpan<byte> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Reads the onMetaData script tag; true when it was one (another script tag leaves the next to be read).</summary>
|
||||
private static bool Script(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>The properties of an AMF0 object up to its end marker; only the top level is kept.</summary>
|
||||
private static bool Properties(ReadOnlySpan<byte> 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
|
||||
}
|
||||
|
||||
/// <summary>One AMF0 value (Action Message Format AMF0, §2); false when the data is not AMF0 or runs out.</summary>
|
||||
private static bool Value(ReadOnlySpan<byte> data, ref int p, int depth, Metadata? metadata, ReadOnlySpan<byte> 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<byte> 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<byte> data, ref int p, int count)
|
||||
{
|
||||
p += count;
|
||||
return p <= data.Length;
|
||||
}
|
||||
|
||||
private static bool ShortString(ReadOnlySpan<byte> data, ref int p, out ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>The onMetaData properties Febe uses.</summary>
|
||||
private sealed class Metadata(DateTimeOffset now)
|
||||
{
|
||||
internal double? Duration;
|
||||
internal double? Width;
|
||||
internal double? Height;
|
||||
internal DateTimeOffset? Created;
|
||||
|
||||
internal void Number(ReadOnlySpan<byte> 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<byte> name, ReadOnlySpan<byte> 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<byte> 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<MediaSample> Samples = [];
|
||||
|
||||
/// <summary>For the metadata alone: the script, the video codec (with its sequence header for H.264) and the audio are known.</summary>
|
||||
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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,15 @@ public enum ContainerFormat
|
||||
|
||||
/// <summary>RIFF AVI (also OpenDML).</summary>
|
||||
Avi,
|
||||
|
||||
/// <summary>Advanced Systems Format: WMV, WMA and ASF files (metadata only).</summary>
|
||||
Asf,
|
||||
|
||||
/// <summary>Flash Video (FLV).</summary>
|
||||
Flv,
|
||||
|
||||
/// <summary>MPEG program stream (ISO/IEC 11172-1 and 13818-1): MPG, MPEG, VOB (metadata only).</summary>
|
||||
MpegPs,
|
||||
}
|
||||
|
||||
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary>
|
||||
@@ -24,6 +33,24 @@ public enum VideoCodec
|
||||
Av1,
|
||||
Mpeg4Part2,
|
||||
Mjpeg,
|
||||
|
||||
/// <summary>MPEG-1 video (ISO/IEC 11172-2).</summary>
|
||||
Mpeg1,
|
||||
|
||||
/// <summary>MPEG-2 video (ITU-T H.262).</summary>
|
||||
Mpeg2,
|
||||
|
||||
/// <summary>Windows Media Video 7 and 8 (WMV1, WMV2).</summary>
|
||||
Wmv,
|
||||
|
||||
/// <summary>Windows Media Video 9 and VC-1 (WMV3, WMVA, WVC1).</summary>
|
||||
Vc1,
|
||||
|
||||
/// <summary>H.263 and its Sorenson Spark variant of FLV.</summary>
|
||||
H263,
|
||||
|
||||
/// <summary>On2 VP6 of FLV.</summary>
|
||||
Vp6,
|
||||
}
|
||||
|
||||
/// <summary>Audio codecs recognised in a container.</summary>
|
||||
@@ -35,6 +62,15 @@ public enum AudioCodec
|
||||
Opus,
|
||||
Vorbis,
|
||||
Pcm,
|
||||
|
||||
/// <summary>MPEG audio layer I or II.</summary>
|
||||
Mp2,
|
||||
|
||||
/// <summary>AC-3 (Dolby Digital).</summary>
|
||||
Ac3,
|
||||
|
||||
/// <summary>Windows Media Audio (all versions).</summary>
|
||||
Wma,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -113,6 +149,9 @@ public sealed class MediaContainer
|
||||
/// <summary>Duration of the whole presentation.</summary>
|
||||
public TimeSpan? Duration { get; init; }
|
||||
|
||||
/// <summary>The title written in the container (ASF content description), when there is one.</summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
public VideoTrack? Video { get; init; }
|
||||
|
||||
public AudioTrack? Audio { get; init; }
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using Febe.Core.Codecs.H264;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class MpegPsReader
|
||||
{
|
||||
/// <summary>Bytes read from the start of the file.</summary>
|
||||
private const int HeadWindow = 2 * 1024 * 1024;
|
||||
|
||||
/// <summary>Bytes read from the end of the file, for the last time.</summary>
|
||||
private const int TailWindow = 1024 * 1024;
|
||||
|
||||
/// <summary>Bytes of the video stream gathered to find its headers.</summary>
|
||||
private const int MaxVideoProbe = 1024 * 1024;
|
||||
|
||||
/// <summary>Presentation times are 33-bit numbers of a 90 kHz clock.</summary>
|
||||
private const long TimeWrap = 1L << 33;
|
||||
|
||||
private const int ClockRate = 90_000;
|
||||
|
||||
/// <summary>Ticks of 90 kHz per frame for each frame_rate_code of MPEG-1 and MPEG-2 video (0 = forbidden or reserved).</summary>
|
||||
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];
|
||||
|
||||
/// <summary>True when the stream starts with an MPEG-1 or MPEG-2 pack header.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 5 && start[0] == 0 && start[1] == 0 && start[2] == 1 && start[3] == 0xBA
|
||||
&& ((start[4] & 0xC0) == 0x40 || (start[4] & 0xF0) == 0x20);
|
||||
|
||||
/// <summary>Reads a seekable stream: its first megabytes and its last.</summary>
|
||||
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<byte>.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<byte>.Shared.Return(buffer);
|
||||
state.Release();
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
/// <summary>The packs and packets of a window of the file; anything else is skipped up to the next start code.</summary>
|
||||
private static void Scan(ReadOnlySpan<byte> data, State state, bool head, CancellationToken ct)
|
||||
{
|
||||
ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A PES packet of an audio or video stream: its presentation time and, at the start of the file, its payload.</summary>
|
||||
private static void Packet(int id, ReadOnlySpan<byte> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static bool PesHeader(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>A 33-bit time in five bytes with three marker bits (PTS, DTS, SCR of MPEG-1); -1 when a marker is wrong.</summary>
|
||||
private static long Timestamp(ReadOnlySpan<byte> 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);
|
||||
}
|
||||
|
||||
/// <summary>The base of the system clock reference of an MPEG-2 pack header (§2.5.3.4); -1 when a marker is wrong.</summary>
|
||||
private static long Scr(ReadOnlySpan<byte> 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);
|
||||
}
|
||||
|
||||
/// <summary>The stream types of the program stream map (§2.5.4), by elementary stream ID.</summary>
|
||||
private static void StreamMap(ReadOnlySpan<byte> 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)..]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Codec, sample rate and channels of the first payload of the audio stream.</summary>
|
||||
private static void Audio(int id, ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sample rate and channels of an AC-3 sync frame (ATSC A/52 §5.3): fscod, acmod and lfeon.</summary>
|
||||
private static void Ac3(ReadOnlySpan<byte> data, State state)
|
||||
{
|
||||
var sync = data.IndexOf((ReadOnlySpan<byte>)[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;
|
||||
|
||||
/// <summary>Gathers the start of the video stream and looks at it now and then, until its headers are found.</summary>
|
||||
internal void AddVideo(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
if (VideoDone || payload.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
probe ??= ArrayPool<byte>.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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Codec and size from what was gathered; with <paramref name="final"/> nothing more will come, and with
|
||||
/// <paramref name="whole"/> the stream ends there.
|
||||
/// </summary>
|
||||
internal void FinishVideo(bool final, bool whole)
|
||||
{
|
||||
if (VideoDone || VideoId < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var data = probe is null ? ReadOnlySpan<byte>.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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence header of MPEG-1 or MPEG-2 video and, for MPEG-2, its sequence extension right after it.</summary>
|
||||
private bool MpegVideo(ReadOnlySpan<byte> data, byte type, bool final)
|
||||
{
|
||||
ReadOnlySpan<byte> sequence = [0, 0, 1, 0xB3];
|
||||
ReadOnlySpan<byte> 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<byte>.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 == VideoCodec.H264,
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ticks from the earliest time at the start to the latest at the end; null without two times.</summary>
|
||||
internal long? Elapsed()
|
||||
{
|
||||
if (reference < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var last = tailLast != long.MinValue ? tailLast : headLast;
|
||||
return last > headFirst ? last - headFirst : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user