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,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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user