diff --git a/docs/decisioni.md b/docs/decisioni.md index 0252694..8456b4f 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -432,3 +432,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Il decodificatore H.264 gestisce gli strumenti di Baseline ed Extended: gruppi di slice (FMO, tipi da 0 a 6 e cambio con `slice_group_change_cycle`), slice in ordine qualunque (ASO), slice ridondanti (si decodifica la primaria, le ridondanti si saltano), partizionamento dei dati (NAL 2, 3 e 4, solo CAVLC come vuole lo standard) e slice SP e SI con QS (§8.6). Una partizione B o C che manca lascia a zero il residuo che porta e, da quel macroblocco in poi, anche quello della partizione che ne dipende (il nC delle due partizioni conta i coefficienti dei vicini dell'altra, tranne che con la predizione intra vincolata). I macroblocchi delle slice SP e SI contano come intra per il filtro di deblocking. Dove la serie ITU-T non ha flussi (partizionamento, slice ridondanti, SI, `sp_for_switch_flag`) la prova riscrive flussi verificati lasciando intatti i bit dei macroblocchi (`StreamRewriter`) e chiede di nuovo il riferimento ufficiale; le SI con un flusso sintetico i cui valori sono calcolati a mano | I cinque flussi FMO, ASO e SP della serie coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Riscrivere flussi già verificati dà un riferimento vero anche alle parti che nessun flusso ufficiale usa, senza inventare formati né scaricare altro; restano senza riferimento ufficiale le slice SI, `sp_for_switch_flag` a 1 e il ripiego per le partizioni mancanti, che segue la dipendenza dello standard invece di un decodificatore di riferimento | | 2026-11-18 | Il decodificatore H.264 gestisce i formati dei profili High: 4:2:2 (DC della crominanza 2×4 con qP + 3, tabelle CAVLC di nC −2, contesti CABAC per NumC8x8, predizione intra 8×16, compensazione con il vettore verticale a piena risoluzione, bordi orizzontali della crominanza alle righe 4, 8 e 12 anche con la trasformata 8×8 della luminanza), 4:4:4 con Cb e Cr codificati come la luminanza (solo CAVLC) e con `separate_colour_plane_flag` (tre immagini monocromatiche, una per `colour_plane_id`, ciascuna con i suoi dati di macroblocco e di moto e le matrici di quantizzazione del suo componente), 4:0:0, profondità da 8 a 14 bit (QP da −QpBdOffset, soglie del deblocking e scarti dei pesi scalati) e la codifica senza perdita (`qpprime_y_zero_transform_bypass_flag` a QP′Y 0, con la DPCM della predizione intra orizzontale e verticale). I campioni stanno in piani di byte, uno o due per campione: i nuclei di predizione, trasformata e filtro sono generici su `byte` e `ushort` e il JIT li specializza, così a 8 bit nulla rallenta (stessi tempi di prima sui flussi di conformità). Oltre gli 8 bit `H264Frame` ha due byte little-endian per campione, come i file di riferimento; un 4:0:0 esce con la crominanza 4:2:0 al valore medio, un 4:4:4 a piani separati come 4:4:4 con la profondità della luminanza; la conversione in RGB usa nero, ampiezza e centro della crominanza alla profondità del fotogramma e campiona la crominanza secondo il formato. Il CABAC in 4:4:4 con i piani insieme si rifiuta con un'`H264Exception`, come le slice SP e SI fuori da 4:2:0 a 8 bit | I dieci flussi 4:2:2 (8 e 10 bit, CABAC e CAVLC) e 4:0:0 della serie di conformità coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Per il CABAC in 4:4:4 servono i valori iniziali dei contesti 460–1023 (tabelle 9-24–9-33), non ancora trascritti dallo standard: rifiutare è meglio che decodificare male. Senza flussi ufficiali con ricostruzione per 4:4:4, piani separati, senza perdita e 11–14 bit, quelle parti si provano con flussi sintetici di I_PCM e di Intra_16x16 i cui campioni si conoscono. Scelte non verificate su un riferimento: nel 4:4:4 il bS 2 conta anche i coefficienti di Cb e Cr, nel bordo sinistro misto di MBAFF in 4:2:2 e 4:4:4 ogni riga di crominanza prende il bS della riga di luminanza omonima, un macroblocco senza perdita usa per il deblocking della crominanza il QPC di QPY 0 come gli I_PCM | | 2026-11-18 | Il decodificatore H.264 gestisce MVC (Annex H) e la parte di SVC (Annex G) delle qualità MGS. MVC: SPS di sottoinsieme, prefissi NAL 14, slice NAL 20, un decodificatore per vista con stato proprio, predizione fra viste (riferimenti della stessa unità di accesso aggiunti alle liste dopo quelli temporali, modifiche 4 e 5, né a breve né a lungo termine), tutte le viste in uscita con `H264Frame.ViewId`; `VideoFrameDecoder` chiede solo la vista base (`DecodeAllViews = false`), che è il video 2D, per le miniature. SVC: lo strato base sempre; sopra, gli strati di qualità della stessa risoluzione in CAVLC, decodificati uno sull'altro nello stesso fotogramma: un macroblocco intra con `base_mode_flag` non si predice di nuovo, ma somma il residuo accumulato nei coefficienti alla ricostruzione dello strato in cui era intra, e per i vicini conta come I_BL (modo DC); un macroblocco inter riprende il moto e somma i coefficienti dello strato sotto quando `residual_prediction_flag` lo dice. Ciò che non è scritto (spaziale, CGS, CABAC negli strati di miglioramento, immagini chiave, sottoinsiemi di coefficienti) lascia lo strato base e lo dice in `EnhancementLayersSkipped` | `SVCBMT-13` coincide ora con lo strato L2 ufficiale in tutti i 20 fotogrammi; la regola per i macroblocchi intra si è ricavata provando contro il riferimento. Per `SVCBST-19` e `SVCBCT-1` mancano la predizione fra risoluzioni e i contesti CABAC di SVC, non ancora trascritti: lasciare lo strato base esatto è meglio che dare uno strato alto sbagliato. MVC non ha ricostruzioni ufficiali nella serie ITU-T: le viste non base non sono verificate al bit, e la scelta di trattare i riferimenti fra viste come né a breve né a lungo termine (per la diretta temporale e il filtro) segue la lettura di §H.8 senza un riferimento | +| 2026-11-18 | Lettori in casa di ASF/WMV, FLV e flusso di programma MPEG, scritti dalle specifiche pubbliche (ASF 01.20.03, FLV 10.1 con AMF0, ISO/IEC 11172-1 e 13818-1, H.262 per l'intestazione di sequenza), dietro `ContainerReader` e quindi dietro la sonda dei metadati e `VideoFrameDecoder`. ASF: proprietà del file (data, durata meno il preroll, niente durata per le trasmissioni), proprietà dei flussi anche dentro l'estensione dell'intestazione, titolo, `WM/EncodingTime` se manca la data; nessun campione. FLV: `onMetaData`, dimensioni dall'SPS (che vince sui metadati) o dall'intestazione H.263 di Sorenson, durata dall'ultimo tag quando i metadati non la dicono, i tag H.264 come campioni (così anche gli FLV hanno la miniatura), il codec degli FLV «enhanced» dal FourCC. MPEG: si leggono solo i primi 2 MB e l'ultimo MB; codec e dimensioni dalla mappa del flusso di programma, dall'intestazione di sequenza MPEG-1/MPEG-2 (con l'estensione) o dall'SPS H.264; durata dal primo all'ultimo PTS del video più un'immagine, attraverso il giro dell'orologio a 33 bit; nessun campione, perché quelli di un MPEG stanno spezzati nei pacchetti PES. `MediaSniffer` non tratta più come video un WMA o un FLV di solo audio quando l'intestazione intera nei primi byte lo dimostra | Prima questi formati si riconoscevano ma la sonda non ne sapeva nulla: data, durata e dimensioni venivano solo dal nome e dalla data di modifica. Leggere solo le intestazioni (e per MPEG due finestre fisse) costa poco anche su librerie grandi; elencare i campioni di WMV e MPEG non servirebbe, perché VC-1 e MPEG-2 non si decodificano, e un elenco di pezzi PES chiederebbe un altro modello di campione. Un WMA o un FLV di solo audio non è un video, come l'M4A; nel dubbio (intestazione non intera) il file resta un video | diff --git a/src/Febe.Core/Codecs/Containers/AsfReader.cs b/src/Febe.Core/Codecs/Containers/AsfReader.cs new file mode 100644 index 0000000..08eabdd --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/AsfReader.cs @@ -0,0 +1,438 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// 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 (WM/EncodingTime 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. +/// +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); + + /// Bytes of an object header: its GUID and its 64-bit size. + private const int ObjectHeader = 24; + + /// Header objects looked at, in all: a real header has a few dozen. + private const int MaxObjects = 4096; + + /// The largest header object read into memory; the extended content description may hold a cover picture, cut here. + private const int MaxObjectBytes = 4 * 1024 * 1024; + + /// True when the stream starts with the GUID of the ASF header object. + public static bool Looks(ReadOnlySpan start) => start.Length >= 16 && new Guid(start[..16]) == HeaderObject; + + /// + /// 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. + /// + public static bool IsAudioOnly(ReadOnlySpan 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; + } + + /// Reads a seekable stream from its start. + 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 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 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(); + } + + /// The objects in , one after the other, up to its end or the first damaged one. + private static void Objects(ReadOnlySpan 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 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 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); + } + } + + /// + /// 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. + /// + private static void ExtendedStreamProperties(ReadOnlySpan 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 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; + } + } + + /// Name and value pairs (§3.11); only WM/EncodingTime is used, for the date. + private static void ExtendedContentDescription(ReadOnlySpan 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; + } + } + + /// True when a null-terminated UTF-16LE name is . + private static bool IsName(ReadOnlySpan 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); + } + + /// A FILETIME (100-nanosecond units from 1601, UTC) from 1995 to a day past now; null otherwise. + 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, + }; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/AviReader.cs b/src/Febe.Core/Codecs/Containers/AviReader.cs index f4d2fb5..1f7a7b9 100644 --- a/src/Febe.Core/Codecs/Containers/AviReader.cs +++ b/src/Febe.Core/Codecs/Containers/AviReader.cs @@ -228,7 +228,7 @@ public static class AviReader } /// The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021». - 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" }) diff --git a/src/Febe.Core/Codecs/Containers/BitReader.cs b/src/Febe.Core/Codecs/Containers/BitReader.cs new file mode 100644 index 0000000..1b7c6f2 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/BitReader.cs @@ -0,0 +1,22 @@ +namespace Febe.Core.Codecs.Containers; + +/// A big-endian bit reader over the few bytes of a codec header; past the end it gives zeros. +internal ref struct BitReader(ReadOnlySpan data, int position) +{ + private readonly ReadOnlySpan data = data; + private int position = position; + + /// The next bits (at most 31) as an unsigned number. + 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; + } +} diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs index c24e805..6aa585d 100644 --- a/src/Febe.Core/Codecs/Containers/ContainerReader.cs +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -1,6 +1,9 @@ namespace Febe.Core.Codecs.Containers; -/// Recognises the container of a video by its first bytes and reads it with the matching reader. +/// +/// 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. +/// public static class ContainerReader { /// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below. @@ -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, }; diff --git a/src/Febe.Core/Codecs/Containers/FlvReader.cs b/src/Febe.Core/Codecs/Containers/FlvReader.cs new file mode 100644 index 0000000..489b372 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/FlvReader.cs @@ -0,0 +1,693 @@ +using System.Buffers.Binary; +using System.Text; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of FLV files, written from the Adobe Flash Video File Format Specification (version 10.1, annex E): the header, +/// the onMetaData script tag (AMF0), the first audio and video tags, and for H.264 the AVC sequence header and every +/// NAL unit tag as a sample. HEVC, AV1 and VP9 stored with the enhanced video tag header are recognised by their FourCC. +/// Width and height come from the SPS when there is one, then from the metadata, then from a Sorenson H.263 picture header. +/// +public static class FlvReader +{ + private const int MaxSamples = IsoBmffReader.MaxSamples; + + /// The largest script tag read: metadata with a keyframe index of a long video stays far below. + private const int MaxScriptBytes = 4 * 1024 * 1024; + + /// The largest AVC sequence header or AAC configuration read. + private const int MaxConfigurationBytes = 64 * 1024; + + /// For the metadata alone, the tags looked at from the start (and their bytes) before giving up on the rest. + private const int HeadTags = 4096; + + private const long HeadBytes = 32L * 1024 * 1024; + + /// Tags looked at back from the end of the file for its last time. + private const int TailTags = 64; + + private const int AmfMaxDepth = 16; + + private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + + /// True when the stream starts like an FLV file: «FLV», version 1 and a header of at least nine bytes. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9; + + /// + /// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, and no + /// video tag is among the tags in . + /// + public static bool IsAudioOnly(ReadOnlySpan head) + { + if (!Looks(head) || (head[4] & 0x01) != 0 || (head[4] & 0x04) == 0) + { + return false; + } + + var position = (long)BinaryPrimitives.ReadUInt32BigEndian(head[5..]) + 4; + 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; + } + + /// Reads a seekable stream from its start. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + var length = stream.Length; + Span header = stackalloc byte[16]; + stream.Position = 0; + stream.ReadExactly(header[..9]); + if (!Looks(header[..9])) + { + throw new ContainerException("Non è un file FLV."); + } + + var flags = header[4]; + var dataOffset = BinaryPrimitives.ReadUInt32BigEndian(header[5..]); + var state = new State { HasAudioFlag = (flags & 0x04) != 0, HasVideoFlag = (flags & 0x01) != 0 }; + var position = dataOffset + 4L; // after PreviousTagSize0 + var tags = 0; + while (position + 11 <= length) + { + if ((tags & 1023) == 0) + { + ct.ThrowIfCancellationRequested(); + } + + stream.Position = position; + var got = stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false); + if (got < 11) + { + break; + } + + var size = (header[1] << 16) | (header[2] << 8) | header[3]; + var body = position + 11; + if ((header[0] & 0xC0) != 0 || (header[0] & 0x1F) is not (8 or 9 or 18) || header[8] != 0 || header[9] != 0 || header[10] != 0) + { + break; // reserved bits, an unknown tag or a stream ID other than 0: what follows is not a tag + } + + if (body + size > length) + { + break; // a tag cut short: the ones before it stand + } + + var time = (long)(int)((uint)(header[7] << 24) | (uint)(header[4] << 16) | (uint)(header[5] << 8) | header[6]); + var data = header[11..Math.Min(got, 16)]; + if (size < data.Length) + { + data = data[..size]; + } + + if ((header[0] & 0x20) == 0) + { + switch (header[0] & 0x1F) + { + case 8: + Audio(stream, body, size, time, data, state); + break; + case 9: + Video(stream, body, size, time, data, state, samples); + break; + case 18 when !state.HaveScript && size is >= 13 and <= MaxScriptBytes && IsMetadata(stream, body): + state.HaveScript = Script(Read(stream, body, size), state, now); + break; + } + } + + tags++; + position = body + size + 4; + if (!samples && (state.HaveEverything || tags >= HeadTags || position > HeadBytes)) + { + break; + } + } + + if (state.MetadataSeconds is null && state.FirstTime is { } first && LastTime(stream, dataOffset + 4L) is { } last && last > first) + { + state.LastSeconds = (last - first) / 1000.0; + } + + return state.Build(); + } + + /// True when a script tag starts with the AMF0 string «onMetaData»: other script tags (cue points) are not read. + private static bool IsMetadata(Stream stream, long body) + { + Span start = stackalloc byte[13]; + stream.Position = body; + stream.ReadExactly(start); + return start[..3].SequenceEqual((ReadOnlySpan)[2, 0, 10]) && start[3..].SequenceEqual("onMetaData"u8); + } + + private static void Audio(Stream stream, long body, int size, long time, ReadOnlySpan data, State state) + { + if (data.Length < 1) + { + return; + } + + state.FirstTime ??= time; + var format = data[0] >> 4; + if (!state.HaveAudio) + { + state.HaveAudio = true; + state.AudioFormat = format; + state.SampleRate = format == 10 ? 44100 : ((data[0] >> 2) & 3) switch { 0 => 5512, 1 => 11025, 2 => 22050, _ => 44100 }; + state.Channels = (data[0] & 1) + 1; + if (format is 4 or 14) + { + state.SampleRate = format == 4 ? 16000 : 8000; // Nellymoser 16 kHz, MP3 8 kHz: fixed rates + } + } + + if (format == 10 && state.AacConfiguration is null && data.Length >= 2 && data[1] == 0 && size - 2 is > 0 and <= MaxConfigurationBytes) + { + var config = Read(stream, body + 2, size - 2); + state.AacConfiguration = config; + if (AacRateAndChannels(config) is { } aac) + { + state.SampleRate = aac.Rate; + state.Channels = aac.Channels > 0 ? aac.Channels : state.Channels; + } + } + } + + private static void Video(Stream stream, long body, int size, long time, ReadOnlySpan data, State state, bool samples) + { + if (data.Length < 1) + { + return; + } + + if ((data[0] & 0x80) != 0) + { + // Enhanced video tag header: frame type, packet type and a FourCC. Only the codec is taken. + if (data.Length >= 5 && state.Codec is null) + { + state.FirstTime ??= time; + state.CodecTag = Encoding.Latin1.GetString(data[1..5]); + state.Codec = state.CodecTag switch + { + "avc1" => VideoCodec.H264, + "hvc1" => VideoCodec.Hevc, + "av01" => VideoCodec.Av1, + "vp09" => VideoCodec.Vp9, + _ => VideoCodec.Unknown, + }; + } + + return; + } + + var frameType = data[0] >> 4; + var codecId = data[0] & 0x0F; + if (frameType == 5) + { + return; // video info or command frame: no picture + } + + state.FirstTime ??= time; + if (state.Codec is null) + { + state.CodecId = codecId; + state.CodecTag = codecId.ToString(System.Globalization.CultureInfo.InvariantCulture); + state.Codec = codecId switch + { + 2 => VideoCodec.H263, + 4 or 5 => VideoCodec.Vp6, + 7 => VideoCodec.H264, + 12 => VideoCodec.Hevc, // the codec ID that HEVC writers outside the specification use + _ => VideoCodec.Unknown, + }; + } + + if (codecId != state.CodecId) + { + return; // a second codec in the same file: only the first is followed + } + + if (codecId == 2 && state.PictureWidth == 0 && size >= 10) + { + (state.PictureWidth, state.PictureHeight) = SorensonSize(Read(stream, body + 1, Math.Min(size - 1, 16))); + } + + if (codecId != 7 || data.Length < 5) + { + return; + } + + var packetType = data[1]; + if (packetType == 0) + { + if (state.AvcConfiguration is null && size - 5 is > 0 and <= MaxConfigurationBytes) + { + var config = Read(stream, body + 5, size - 5); + if (config.Length >= 7 && config[0] == 1) + { + state.AvcConfiguration = config; + if (H264StreamInfo.TryPictureSizeFromConfiguration(config, out var w, out var h)) + { + (state.PictureWidth, state.PictureHeight) = (w, h); + } + } + } + } + else if (packetType == 1 && samples && size > 5) + { + if (state.Samples.Count >= MaxSamples) + { + throw new ContainerException("Troppi campioni."); + } + + var composition = (data[2] << 16) | (data[3] << 8) | data[4]; + composition = (composition << 8) >> 8; // SI24 + state.Samples.Add(new MediaSample(body + 5, size - 5, time, time + composition, frameType == 1)); + } + } + + /// The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields. + private static long? LastTime(Stream stream, long firstTag) + { + Span 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; + } + + /// + /// Width and height of a Sorenson H.263 picture header (FLV specification, «H.263 video packet»): the 17-bit start + /// code, version, temporal reference, then a picture size code or the size itself. + /// + private static (int Width, int Height) SorensonSize(ReadOnlySpan data) + { + if (data.Length < 9 || data[0] != 0 || data[1] != 0 || (data[2] & 0x80) == 0) + { + return (0, 0); + } + + var bits = new BitReader(data, 17 + 5 + 8); + var code = bits.Read(3); + return code switch + { + 0 => (bits.Read(8), bits.Read(8)), + 1 => (bits.Read(16), bits.Read(16)), + 2 => (352, 288), + 3 => (176, 144), + 4 => (128, 96), + 5 => (320, 240), + 6 => (160, 120), + _ => (0, 0), + }; + } + + /// Sample rate and channels of an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1); null when damaged. + internal static (int Rate, int Channels)? AacRateAndChannels(ReadOnlySpan config) + { + if (config.Length < 2) + { + return null; + } + + var bits = new BitReader(config, 0); + if (bits.Read(5) == 31) + { + bits.Read(6); + } + + var index = bits.Read(4); + int rate; + if (index == 15) + { + if (config.Length < 5) + { + return null; + } + + rate = bits.Read(24); + } + else if (index < AacRates.Length) + { + rate = AacRates[index]; + } + else + { + return null; + } + + var channels = bits.Read(4); + return (rate, channels switch { 7 => 8, > 7 => 0, _ => channels }); + } + + /// Reads the onMetaData script tag; true when it was one (another script tag leaves the next to be read). + private static bool Script(ReadOnlySpan data, State state, DateTimeOffset now) + { + var p = 0; + if (!Byte(data, ref p, out var type) || type != 2 || !ShortString(data, ref p, out var name) || !name.SequenceEqual("onMetaData"u8)) + { + return false; + } + + if (!Byte(data, ref p, out type)) + { + return true; + } + + if (type == 8) + { + p += 4; // approximate count of an ECMA array: the end marker closes it + } + else if (type != 3) + { + return true; + } + + var metadata = new Metadata(now); + _ = Properties(data, ref p, 0, metadata); + state.MetadataSeconds = metadata.Duration is > 0 and < 1e9 ? metadata.Duration : null; + state.MetadataWidth = metadata.Width is > 0 and <= 65535 ? (int)metadata.Width : 0; + state.MetadataHeight = metadata.Height is > 0 and <= 65535 ? (int)metadata.Height : 0; + state.Created = metadata.Created; + return true; + } + + /// The properties of an AMF0 object up to its end marker; only the top level is kept. + private static bool Properties(ReadOnlySpan data, ref int p, int depth, Metadata? metadata) + { + while (p < data.Length) + { + if (p + 3 <= data.Length && data[p] == 0 && data[p + 1] == 0 && data[p + 2] == 9) + { + p += 3; + return true; + } + + if (!ShortString(data, ref p, out var name) || !Value(data, ref p, depth, metadata, name)) + { + return false; + } + } + + return true; // an ECMA array may end with the tag, without its marker + } + + /// One AMF0 value (Action Message Format AMF0, §2); false when the data is not AMF0 or runs out. + private static bool Value(ReadOnlySpan data, ref int p, int depth, Metadata? metadata, ReadOnlySpan name) + { + if (!Byte(data, ref p, out var type)) + { + return false; + } + + switch (type) + { + case 0: // number + if (p + 8 > data.Length) + { + return false; + } + + metadata?.Number(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); + p += 8; + return true; + case 1: // boolean + return Skip(data, ref p, 1); + case 2: // string + if (!ShortString(data, ref p, out var text)) + { + return false; + } + + metadata?.Text(name, text); + return true; + case 3: // object + return depth < AmfMaxDepth && Properties(data, ref p, depth + 1, null); + case 5 or 6 or 13: // null, undefined, unsupported + return true; + case 7: // reference + return Skip(data, ref p, 2); + case 8: // ECMA array + return depth < AmfMaxDepth && Skip(data, ref p, 4) && Properties(data, ref p, depth + 1, null); + case 10: // strict array + { + if (depth >= AmfMaxDepth || p + 4 > data.Length) + { + return false; + } + + var count = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); + p += 4; + if (count > (uint)(data.Length - p)) + { + return false; // every value takes at least a byte + } + + for (var i = 0u; i < count; i++) + { + if (!Value(data, ref p, depth + 1, null, default)) + { + return false; + } + } + + return true; + } + + case 11: // date: milliseconds from 1970 and a time zone that the specification says to ignore + if (p + 10 > data.Length) + { + return false; + } + + metadata?.Date(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); + p += 10; + return true; + case 12 or 15: // long string, XML document + { + if (p + 4 > data.Length) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); + p += 4; + return length <= (uint)(data.Length - p) && Skip(data, ref p, (int)length); + } + + case 16: // typed object: a class name, then the properties + return depth < AmfMaxDepth && ShortString(data, ref p, out _) && Properties(data, ref p, depth + 1, null); + default: + return false; // movie clip and record set are reserved; anything else is not AMF0 + } + } + + private static bool Byte(ReadOnlySpan data, ref int p, out byte value) + { + value = p < data.Length ? data[p] : (byte)0; + p++; + return p <= data.Length; + } + + private static bool Skip(ReadOnlySpan data, ref int p, int count) + { + p += count; + return p <= data.Length; + } + + private static bool ShortString(ReadOnlySpan data, ref int p, out ReadOnlySpan text) + { + text = default; + if (p + 2 > data.Length) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(data[p..]); + p += 2; + if (p + length > data.Length) + { + return false; + } + + text = data.Slice(p, length); + p += length; + return true; + } + + /// The onMetaData properties Febe uses. + private sealed class Metadata(DateTimeOffset now) + { + internal double? Duration; + internal double? Width; + internal double? Height; + internal DateTimeOffset? Created; + + internal void Number(ReadOnlySpan name, double value) + { + if (!double.IsFinite(value)) + { + return; + } + + if (name.SequenceEqual("duration"u8)) + { + Duration = value; + } + else if (name.SequenceEqual("width"u8)) + { + Width = value; + } + else if (name.SequenceEqual("height"u8)) + { + Height = value; + } + } + + internal void Text(ReadOnlySpan name, ReadOnlySpan value) + { + if (name.SequenceEqual("creationdate"u8) && value.Length is > 0 and < 128) + { + Created = AviReader.ParseDate(Encoding.UTF8.GetString(value), now) ?? Created; + } + } + + internal void Date(ReadOnlySpan name, double milliseconds) + { + // From 1995 to a day past now, as the other readers. + if (name.SequenceEqual("creationdate"u8) && double.IsFinite(milliseconds) && milliseconds >= 788_918_400_000d + && milliseconds <= now.AddDays(1).ToUnixTimeMilliseconds()) + { + Created = DateTimeOffset.FromUnixTimeMilliseconds((long)milliseconds); + } + } + } + + private sealed class State + { + internal bool HasAudioFlag; + internal bool HasVideoFlag; + internal bool HaveScript; + internal bool HaveAudio; + internal int AudioFormat; + internal int SampleRate; + internal int Channels; + internal byte[]? AacConfiguration; + internal VideoCodec? Codec; + internal int CodecId = -1; + internal string CodecTag = string.Empty; + internal byte[]? AvcConfiguration; + internal int PictureWidth; + internal int PictureHeight; + internal double? MetadataSeconds; + internal int MetadataWidth; + internal int MetadataHeight; + internal double? LastSeconds; + internal DateTimeOffset? Created; + internal long? FirstTime; + internal readonly List Samples = []; + + /// For the metadata alone: the script, the video codec (with its sequence header for H.264) and the audio are known. + internal bool HaveEverything => + HaveScript + && (!HasVideoFlag || (Codec is not null && (Codec != VideoCodec.H264 || CodecId != 7 || AvcConfiguration is not null))) + && (!HasAudioFlag || HaveAudio); + + internal MediaContainer Build() + { + var seconds = MetadataSeconds ?? LastSeconds; + TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds.Value) : null; + VideoTrack? video = null; + if (Codec is { } codec) + { + var (width, height) = PictureWidth > 0 && PictureHeight > 0 ? (PictureWidth, PictureHeight) : (MetadataWidth, MetadataHeight); + video = new VideoTrack + { + Codec = codec, + CodecTag = CodecTag, + Width = width, + Height = height, + AvcConfiguration = CodecId == 7 ? AvcConfiguration : null, + Timescale = 1000, + Duration = duration is { } d ? (long)d.TotalMilliseconds : 0, + Samples = Samples, + }; + } + else if (MetadataWidth > 0 && MetadataHeight > 0) + { + video = new VideoTrack { Width = MetadataWidth, Height = MetadataHeight, Timescale = 1000 }; // only the metadata knows it + } + + AudioTrack? audio = HaveAudio + ? new AudioTrack + { + Codec = AudioFormat switch + { + 10 => AudioCodec.Aac, + 2 or 14 => AudioCodec.Mp3, + 0 or 3 => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = AudioFormat.ToString(System.Globalization.CultureInfo.InvariantCulture), + SampleRate = SampleRate, + Channels = Channels, + AacConfiguration = AudioFormat == 10 ? AacConfiguration : null, + Timescale = 1000, + } + : null; + return new MediaContainer { Format = ContainerFormat.Flv, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs index 79b98a6..442d177 100644 --- a/src/Febe.Core/Codecs/Containers/MediaContainer.cs +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -11,6 +11,15 @@ public enum ContainerFormat /// RIFF AVI (also OpenDML). Avi, + + /// Advanced Systems Format: WMV, WMA and ASF files (metadata only). + Asf, + + /// Flash Video (FLV). + Flv, + + /// MPEG program stream (ISO/IEC 11172-1 and 13818-1): MPG, MPEG, VOB (metadata only). + MpegPs, } /// Video codecs recognised in a container; only can be decoded. @@ -24,6 +33,24 @@ public enum VideoCodec Av1, Mpeg4Part2, Mjpeg, + + /// MPEG-1 video (ISO/IEC 11172-2). + Mpeg1, + + /// MPEG-2 video (ITU-T H.262). + Mpeg2, + + /// Windows Media Video 7 and 8 (WMV1, WMV2). + Wmv, + + /// Windows Media Video 9 and VC-1 (WMV3, WMVA, WVC1). + Vc1, + + /// H.263 and its Sorenson Spark variant of FLV. + H263, + + /// On2 VP6 of FLV. + Vp6, } /// Audio codecs recognised in a container. @@ -35,6 +62,15 @@ public enum AudioCodec Opus, Vorbis, Pcm, + + /// MPEG audio layer I or II. + Mp2, + + /// AC-3 (Dolby Digital). + Ac3, + + /// Windows Media Audio (all versions). + Wma, } /// @@ -113,6 +149,9 @@ public sealed class MediaContainer /// Duration of the whole presentation. public TimeSpan? Duration { get; init; } + /// The title written in the container (ASF content description), when there is one. + public string? Title { get; init; } + public VideoTrack? Video { get; init; } public AudioTrack? Audio { get; init; } diff --git a/src/Febe.Core/Codecs/Containers/MpegPsReader.cs b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs new file mode 100644 index 0000000..736a015 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs @@ -0,0 +1,696 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of MPEG program streams (MPG, MPEG, VOB), written from ISO/IEC 13818-1 §2.5 and, for the MPEG-1 system layer, +/// ISO/IEC 11172-1: pack headers (MPEG-1 and MPEG-2), the system header, the program stream map and the PES packets. Only +/// the first megabytes and the last megabyte of the file are read. The duration runs from the first presentation time of +/// the video (or the audio, or the clock of the packs) to the last one, plus a frame; codec and size come from the +/// program stream map and the start of the video stream: the sequence header of MPEG-1 and MPEG-2 video (ISO/IEC +/// 11172-2 §2.4.2.3, ITU-T H.262 §6.2.2), the SPS of H.264. The samples of a program stream are cut into PES packets and +/// are not listed: the tracks have no samples. +/// +public static class MpegPsReader +{ + /// Bytes read from the start of the file. + private const int HeadWindow = 2 * 1024 * 1024; + + /// Bytes read from the end of the file, for the last time. + private const int TailWindow = 1024 * 1024; + + /// Bytes of the video stream gathered to find its headers. + private const int MaxVideoProbe = 1024 * 1024; + + /// Presentation times are 33-bit numbers of a 90 kHz clock. + private const long TimeWrap = 1L << 33; + + private const int ClockRate = 90_000; + + /// Ticks of 90 kHz per frame for each frame_rate_code of MPEG-1 and MPEG-2 video (0 = forbidden or reserved). + private static readonly int[] FrameTicks = [0, 3754, 3750, 3600, 3003, 3000, 1800, 1502, 1500]; + + private static readonly int[] MpegAudioRates = [44100, 48000, 32000]; + + private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + + /// True when the stream starts with an MPEG-1 or MPEG-2 pack header. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 5 && start[0] == 0 && start[1] == 0 && start[2] == 1 && start[3] == 0xBA + && ((start[4] & 0xC0) == 0x40 || (start[4] & 0xF0) == 0x20); + + /// Reads a seekable stream: its first megabytes and its last. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + _ = now; // a program stream carries no date + _ = samples; // nor samples that sit whole in the file + var length = stream.Length; + var headLength = (int)Math.Min(length, HeadWindow); + var state = new State(); + var buffer = ArrayPool.Shared.Rent(Math.Max(1, headLength)); + try + { + stream.Position = 0; + stream.ReadExactly(buffer, 0, headLength); + if (!Looks(buffer.AsSpan(0, headLength))) + { + throw new ContainerException("Non è un flusso di programma MPEG."); + } + + Scan(buffer.AsSpan(0, headLength), state, head: true, ct); + state.FinishVideo(final: true, whole: headLength == length); + if (length > headLength) + { + var tailStart = Math.Max(headLength, length - TailWindow); + var tailLength = (int)(length - tailStart); + stream.Position = tailStart; + stream.ReadExactly(buffer, 0, tailLength); + Scan(buffer.AsSpan(0, tailLength), state, head: false, ct); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + state.Release(); + } + + return state.Build(); + } + + /// The packs and packets of a window of the file; anything else is skipped up to the next start code. + private static void Scan(ReadOnlySpan data, State state, bool head, CancellationToken ct) + { + ReadOnlySpan startCode = [0, 0, 1]; + var p = 0; + var count = 0; + while (p + 4 <= data.Length) + { + if ((++count & 1023) == 0) + { + ct.ThrowIfCancellationRequested(); + } + + if (data[p] != 0 || data[p + 1] != 0 || data[p + 2] != 1) + { + var next = data[(p + 1)..].IndexOf(startCode); + if (next < 0) + { + return; + } + + p += 1 + next; + continue; + } + + var id = data[p + 3]; + if (id == 0xBA) + { + if (p + 12 > data.Length) + { + return; + } + + if ((data[p + 4] & 0xC0) == 0x40) + { + if (p + 14 > data.Length) + { + return; + } + + state.Mpeg2System = true; + state.Clocks.Add(Scr(data.Slice(p + 4, 6)), head); + p += 14 + (data[p + 13] & 7); + } + else if ((data[p + 4] & 0xF0) == 0x20) + { + state.Clocks.Add(Timestamp(data.Slice(p + 4, 5)), head); + p += 12; + } + else + { + p += 4; + } + + continue; + } + + if (id < 0xBB) + { + p += 3; // the end code, or a start code of an elementary stream met while looking for a packet + continue; + } + + if (p + 6 > data.Length) + { + return; + } + + var size = BinaryPrimitives.ReadUInt16BigEndian(data[(p + 4)..]); + var available = Math.Min(size, data.Length - p - 6); + var body = data.Slice(p + 6, available); + var whole = available == size; + if (id == 0xBC) + { + if (whole) + { + StreamMap(body, state); + } + } + else if (id is >= 0xC0 and <= 0xEF or 0xBD) + { + Packet(id, body, state, head); + } + + if (!whole) + { + return; + } + + p += 6 + size; + } + } + + /// A PES packet of an audio or video stream: its presentation time and, at the start of the file, its payload. + private static void Packet(int id, ReadOnlySpan body, State state, bool head) + { + if (!PesHeader(body, out var pts, out var payloadStart)) + { + return; + } + + var payload = body[payloadStart..]; + var key = id; + if (id == 0xBD) + { + if (payload.Length < 1) + { + return; + } + + key = 0x100 | payload[0]; // private stream 1: the sub-stream number (DVD: AC-3, DTS, LPCM) + if (payload[0] is not (>= 0x80 and <= 0x8F or >= 0xA0 and <= 0xA7)) + { + return; // subtitles and the like + } + } + + if (head) + { + if (id is >= 0xE0 and <= 0xEF && state.VideoId < 0) + { + state.VideoId = id; + } + else if (id is >= 0xC0 and <= 0xDF or 0xBD && state.AudioId < 0) + { + state.AudioId = key; + Audio(id, payload, state); + } + } + + if (key == state.VideoId) + { + state.VideoTimes.Add(pts, head); + if (head) + { + state.AddVideo(payload); + } + } + else if (key == state.AudioId) + { + state.AudioTimes.Add(pts, head); + } + } + + /// + /// The header of a PES packet, MPEG-2 (§2.4.3.7, «10» first) or MPEG-1 (stuffing, buffer size, then the times): + /// its presentation time (-1 without one) and where its payload starts; false when it is not a header. + /// + private static bool PesHeader(ReadOnlySpan b, out long pts, out int payload) + { + pts = -1; + payload = 0; + if (b.Length < 1) + { + return false; + } + + if ((b[0] & 0xC0) == 0x80) + { + if (b.Length < 3 || 3 + b[2] > b.Length) + { + return false; + } + + payload = 3 + b[2]; + if ((b[1] & 0x80) != 0) + { + if (b[2] < 5) + { + return false; + } + + pts = Timestamp(b.Slice(3, 5)); + return pts >= 0; + } + + return true; + } + + var i = 0; + while (i < b.Length && i < 16 && b[i] == 0xFF) + { + i++; + } + + if (i < b.Length && (b[i] & 0xC0) == 0x40) + { + i += 2; // STD buffer scale and size + } + + if (i >= b.Length) + { + return false; + } + + if ((b[i] & 0xF0) is 0x20 or 0x30) + { + var fields = (b[i] & 0xF0) == 0x20 ? 5 : 10; + if (i + fields > b.Length) + { + return false; + } + + pts = Timestamp(b.Slice(i, 5)); + payload = i + fields; + return pts >= 0; + } + + if (b[i] != 0x0F) + { + return false; + } + + payload = i + 1; + return true; + } + + /// A 33-bit time in five bytes with three marker bits (PTS, DTS, SCR of MPEG-1); -1 when a marker is wrong. + private static long Timestamp(ReadOnlySpan b) + { + if ((b[0] & 1) == 0 || (b[2] & 1) == 0 || (b[4] & 1) == 0) + { + return -1; + } + + return ((long)((b[0] >> 1) & 7) << 30) | ((long)b[1] << 22) | ((long)(b[2] >> 1) << 15) | ((long)b[3] << 7) | ((long)b[4] >> 1); + } + + /// The base of the system clock reference of an MPEG-2 pack header (§2.5.3.4); -1 when a marker is wrong. + private static long Scr(ReadOnlySpan b) + { + if ((b[0] & 4) == 0 || (b[2] & 4) == 0 || (b[4] & 4) == 0 || (b[5] & 1) == 0) + { + return -1; + } + + return ((long)((b[0] >> 3) & 7) << 30) | ((long)(b[0] & 3) << 28) | ((long)b[1] << 20) | ((long)(b[2] >> 3) << 15) + | ((long)(b[2] & 3) << 13) | ((long)b[3] << 5) | ((long)b[4] >> 3); + } + + /// The stream types of the program stream map (§2.5.4), by elementary stream ID. + private static void StreamMap(ReadOnlySpan body, State state) + { + if (body.Length < 6) + { + return; + } + + var info = BinaryPrimitives.ReadUInt16BigEndian(body[2..]); + var p = 4 + info; + if (p + 2 > body.Length) + { + return; + } + + var end = Math.Min(body.Length, p + 2 + BinaryPrimitives.ReadUInt16BigEndian(body[p..])); + p += 2; + while (p + 4 <= end) + { + state.StreamTypes[body[p + 1]] = body[p]; + p += 4 + BinaryPrimitives.ReadUInt16BigEndian(body[(p + 2)..]); + } + } + + /// Codec, sample rate and channels of the first payload of the audio stream. + private static void Audio(int id, ReadOnlySpan payload, State state) + { + if (id == 0xBD) + { + var sub = payload[0]; + if (sub is >= 0xA0 and <= 0xA7) + { + state.AudioCodec = AudioCodec.Pcm; // DVD LPCM: frequency and channels in its sixth byte + state.AudioTag = "LPCM"; + if (payload.Length >= 6) + { + state.SampleRate = ((payload[5] >> 4) & 3) == 1 ? 96000 : 48000; + state.Channels = (payload[5] & 7) + 1; + } + } + else if (sub <= 0x87) + { + state.AudioCodec = AudioCodec.Ac3; + state.AudioTag = "AC-3"; + if (payload.Length > 4) + { + Ac3(payload[4..], state); + } + } + else + { + state.AudioTag = "DTS"; + } + + return; + } + + state.AudioTag = "MPEG"; + for (var i = 0; i + 4 <= payload.Length; i++) + { + var b = payload.Slice(i, 4); + if (b[0] != 0xFF || (b[1] & 0xE0) != 0xE0) + { + continue; + } + + if ((b[1] & 0xF6) == 0xF0) + { + // ADTS (ISO/IEC 13818-7): AAC in an MPEG-2 audio stream. + var index = (b[2] >> 2) & 0xF; + if (index < AacRates.Length) + { + state.AudioCodec = AudioCodec.Aac; + state.SampleRate = AacRates[index]; + var channels = ((b[2] & 1) << 2) | (b[3] >> 6); + state.Channels = channels == 7 ? 8 : channels; + return; + } + + continue; + } + + var version = (b[1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5 + var layer = (b[1] >> 1) & 3; // 3 layer I, 2 layer II, 1 layer III + var rate = (b[2] >> 2) & 3; + if (version == 1 || layer == 0 || rate == 3 || (b[2] >> 4) == 15) + { + continue; + } + + state.AudioCodec = layer == 1 ? AudioCodec.Mp3 : AudioCodec.Mp2; + state.SampleRate = MpegAudioRates[rate] >> (version == 3 ? 0 : version == 2 ? 1 : 2); + state.Channels = (b[3] >> 6) == 3 ? 1 : 2; + return; + } + } + + /// Sample rate and channels of an AC-3 sync frame (ATSC A/52 §5.3): fscod, acmod and lfeon. + private static void Ac3(ReadOnlySpan data, State state) + { + var sync = data.IndexOf((ReadOnlySpan)[0x0B, 0x77]); + if (sync < 0 || sync + 8 > data.Length) + { + return; + } + + var frame = data[sync..]; + var fscod = frame[4] >> 6; + if (fscod == 3) + { + return; + } + + state.SampleRate = fscod switch { 0 => 48000, 1 => 44100, _ => 32000 }; + var bits = new BitReader(frame, (5 * 8) + 8); // after syncword, crc1, fscod and frmsizecod, bsid and bsmod + var acmod = bits.Read(3); + if ((acmod & 1) != 0 && acmod != 1) + { + bits.Read(2); // cmixlev + } + + if ((acmod & 4) != 0) + { + bits.Read(2); // surmixlev + } + + if (acmod == 2) + { + bits.Read(2); // dsurmod + } + + state.Channels = (acmod switch { 0 => 2, 1 => 1, 2 => 2, 3 or 4 => 3, 5 or 6 => 4, _ => 5 }) + bits.Read(1); + } + + private sealed class State + { + internal readonly byte[] StreamTypes = new byte[256]; + internal bool Mpeg2System; + internal int VideoId = -1; + internal int AudioId = -1; + + internal readonly Timeline Clocks = new(); + internal readonly Timeline VideoTimes = new(); + internal readonly Timeline AudioTimes = new(); + + internal VideoCodec Codec = VideoCodec.Unknown; + internal int Width; + internal int Height; + internal int FrameDuration; + internal bool VideoDone; + private byte[]? probe; + private int probed; + private int nextLook = 16 * 1024; + + internal AudioCodec AudioCodec = AudioCodec.Unknown; + internal string AudioTag = string.Empty; + internal int SampleRate; + internal int Channels; + + /// Gathers the start of the video stream and looks at it now and then, until its headers are found. + internal void AddVideo(ReadOnlySpan payload) + { + if (VideoDone || payload.IsEmpty) + { + return; + } + + probe ??= ArrayPool.Shared.Rent(MaxVideoProbe); + var take = Math.Min(payload.Length, MaxVideoProbe - probed); + payload[..take].CopyTo(probe.AsSpan(probed)); + probed += take; + if (probed >= nextLook || probed == MaxVideoProbe) + { + nextLook = probed * 4; + FinishVideo(final: probed == MaxVideoProbe, whole: false); + } + } + + /// + /// Codec and size from what was gathered; with nothing more will come, and with + /// the stream ends there. + /// + internal void FinishVideo(bool final, bool whole) + { + if (VideoDone || VideoId < 0) + { + return; + } + + var data = probe is null ? ReadOnlySpan.Empty : probe.AsSpan(0, probed); + var type = StreamTypes[VideoId]; + if (type is 0 or 1 or 2 && MpegVideo(data, type, final)) + { + VideoDone = true; + return; + } + + if (type is 0 or 0x1B && H264StreamInfo.TryPictureSizeFromAnnexB(data, whole, out var width, out var height)) + { + (Codec, Width, Height, VideoDone) = (VideoCodec.H264, width, height, true); + return; + } + + if (final) + { + Codec = type switch + { + 1 => VideoCodec.Mpeg1, + 2 => VideoCodec.Mpeg2, + 0x10 => VideoCodec.Mpeg4Part2, + 0x1B => VideoCodec.H264, + 0x24 => VideoCodec.Hevc, + 0xEA => VideoCodec.Vc1, + _ => VideoCodec.Unknown, + }; + VideoDone = true; + } + } + + /// The sequence header of MPEG-1 or MPEG-2 video and, for MPEG-2, its sequence extension right after it. + private bool MpegVideo(ReadOnlySpan data, byte type, bool final) + { + ReadOnlySpan sequence = [0, 0, 1, 0xB3]; + ReadOnlySpan startCode = [0, 0, 1]; + var at = data.IndexOf(sequence); + if (at < 0 || at + 12 > data.Length) + { + return false; + } + + var width = (data[at + 4] << 4) | (data[at + 5] >> 4); + var height = ((data[at + 5] & 0xF) << 8) | data[at + 6]; + var rate = data[at + 7] & 0xF; + var next = data[(at + 12)..].IndexOf(startCode); + bool mpeg2; + if (next >= 0 && at + 12 + next + 7 <= data.Length) + { + // Sequence extension (H.262 §6.2.2.3): extension ID 1, then the two high bits of each size. + var e = data[(at + 12 + next)..]; + mpeg2 = e[3] == 0xB5 && (e[4] >> 4) == 1; + if (mpeg2) + { + width |= (((e[5] & 1) << 1) | (e[6] >> 7)) << 12; + height |= ((e[6] >> 5) & 3) << 12; + } + } + else if (final) + { + mpeg2 = type == 2 || (type == 0 && Mpeg2System); + } + else + { + return false; + } + + if (width == 0 || height == 0) + { + return false; + } + + (Codec, Width, Height) = (mpeg2 ? VideoCodec.Mpeg2 : VideoCodec.Mpeg1, width, height); + FrameDuration = rate < FrameTicks.Length ? FrameTicks[rate] : 0; + return true; + } + + internal void Release() + { + if (probe is not null) + { + ArrayPool.Shared.Return(probe); + probe = null; + } + } + + internal MediaContainer Build() + { + long? ticks = null; + if (VideoTimes.Elapsed() is { } video) + { + ticks = video + FrameDuration; + } + else if (AudioTimes.Elapsed() is { } audio) + { + ticks = audio; + } + else if (Clocks.Elapsed() is { } clock) + { + ticks = clock; + } + + TimeSpan? duration = ticks is > 0 ? TimeSpan.FromSeconds((double)ticks.Value / ClockRate) : null; + var videoTrack = VideoId < 0 ? null : new VideoTrack + { + Codec = Codec, + CodecTag = StreamTypes[VideoId] != 0 + ? "0x" + StreamTypes[VideoId].ToString("X2", CultureInfo.InvariantCulture) + : Codec.ToString(), + Width = Width, + Height = Height, + AnnexB = Codec == 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 }; + } + } + + /// + /// The times of one stream, as distances from the first one seen, across the wrap of the 33-bit clock: at the start of + /// the file a time up to half the clock (13 hours) away either way, at the end any time up to ten seconds before. + /// + private sealed class Timeline + { + private const long Mask = TimeWrap - 1; + private const long TailSlack = 10L * ClockRate; + private long reference = -1; + private long headFirst; + private long headLast; + private long tailLast = long.MinValue; + + internal void Add(long time, bool head) + { + if (time < 0) + { + return; + } + + if (reference < 0) + { + if (!head) + { + return; // nothing seen at the start: the end alone tells no length + } + + reference = time; + return; + } + + var distance = (time - reference) & Mask; + if (head) + { + distance = distance >= TimeWrap / 2 ? distance - TimeWrap : distance; + headFirst = Math.Min(headFirst, distance); + headLast = Math.Max(headLast, distance); + } + else + { + distance = distance > TimeWrap - TailSlack ? distance - TimeWrap : distance; + tailLast = Math.Max(tailLast, distance); + } + } + + /// Ticks from the earliest time at the start to the latest at the end; null without two times. + internal long? Elapsed() + { + if (reference < 0) + { + return null; + } + + var last = tailLast != long.MinValue ? tailLast : headLast; + return last > headFirst ? last - headFirst : null; + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264StreamInfo.cs b/src/Febe.Core/Codecs/H264/H264StreamInfo.cs new file mode 100644 index 0000000..bc69cf0 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264StreamInfo.cs @@ -0,0 +1,92 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.H264; + +/// +/// What the sequence parameter set of an H.264 stream says without decoding it: the size of the pictures shown, after +/// the cropping of §7.4.2.1.1. Used by the container readers whose headers do not carry the size (FLV without +/// metadata, MPEG program streams). +/// +public static class H264StreamInfo +{ + /// The picture size of an SPS NAL unit (header byte included); false when it is not an SPS or is damaged. + public static bool TryPictureSize(ReadOnlySpan nal, out int width, out int height) + { + width = height = 0; + if (nal.Length < 4 || (nal[0] & 0x9F) != 7 || nal[1] is not (44 or 66 or 77 or 83 or 86 or 88 or 100 or 110 or 118 or 122 + or 128 or 134 or 135 or 138 or 139 or 144 or 244)) + { + return false; // forbidden_zero_bit set, not nal_unit_type 7, or a profile_idc no profile of Annex A has + } + + try + { + var sps = Sps.Parse(NalUnits.Parse(nal).Reader()); + var w = (sps.WidthInMbs * 16) - (sps.CropUnitX * (sps.CropLeft + sps.CropRight)); + var h = (sps.HeightInMbs * 16) - (sps.CropUnitY * (sps.CropTop + sps.CropBottom)); + if (w <= 0 || h <= 0) + { + return false; + } + + (width, height) = (w, h); + return true; + } + catch (Exception ex) when (ex is H264Exception or IndexOutOfRangeException or ArgumentException or OverflowException) + { + return false; + } + } + + /// + /// The picture size of the first SPS of an AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3.1), as FLV and MP4 + /// carry it. + /// + public static bool TryPictureSizeFromConfiguration(ReadOnlySpan avcC, out int width, out int height) + { + width = height = 0; + if (avcC.Length < 8 || avcC[0] != 1 || (avcC[5] & 0x1F) == 0) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(avcC[6..]); + return 8 + length <= avcC.Length && TryPictureSize(avcC.Slice(8, length), out width, out height); + } + + /// + /// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of + /// cuts counts only when says nothing follows. + /// + public static bool TryPictureSizeFromAnnexB(ReadOnlySpan stream, bool complete, out int width, out int height) + { + width = height = 0; + ReadOnlySpan startCode = [0, 0, 1]; + var found = stream.IndexOf(startCode); + while (found >= 0) + { + var start = found + 3; + var next = stream[start..].IndexOf(startCode); + if (next < 0 && !complete) + { + return false; // the last unit may be cut short + } + + var end = next < 0 ? stream.Length : start + next; + var nal = stream[start..end]; + while (nal.Length > 0 && nal[^1] == 0) + { + nal = nal[..^1]; // the zero byte of a four-byte start code belongs to the next unit + } + + if (nal.Length > 0 && (nal[0] & 0x1F) == 7 && TryPictureSize(nal, out width, out height)) + { + return true; + } + + found = next < 0 ? -1 : end; + } + + return false; + } +} diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index eb9745c..9fcc707 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -18,7 +18,8 @@ internal sealed record ContentFacts( /// /// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for -/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, the in-house container readers for WebM, Matroska and AVI). +/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, the in-house container readers for WebM, Matroska, AVI, +/// WMV/ASF, FLV and MPEG program streams). /// internal static class ContentAnalysis { diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index 553c94f..606b0ab 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -22,7 +22,7 @@ var import = new ImportService(new ImportEnvironment Thumbnails = new ThumbnailStore(data.Thumbnails), HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa - VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita) + VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska, AVI, WMV, FLV e MPEG (null: la stessa, predefinita) SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, DataFolder = data.Root, @@ -64,12 +64,12 @@ partenza (`DuplicateDecision.Pending`); «Fai lo stesso per gli altri» è `Deci Per ogni file, senza scrivere nulla nella sorgente: tipo dal contenuto (`MediaSniffer`: JPEG, PNG, GIF, WebP, HEIC/HEIF, AVIF, BMP, TIFF e raw, MP4, MOV anche senza `ftyp`, 3GP, WebM/Matroska, AVI, WMV, FLV, MPEG; l'audio M4A non è un -video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account +video, e nemmeno un WMA o un FLV di solo audio quando i primi 512 kB lo dimostrano), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account probabile, tipo probabile e titolo della raccolta. - **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di - contenitori scritti in casa per WebM, Matroska e AVI), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora + contenitori scritti in casa per WebM, Matroska, AVI, WMV/ASF, FLV e MPEG), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora dello stesso giorno, vince l'ora dei metadati. Le ore senza fuso sono quelle di Alberto (`IClock.LocalZone`). - **Cartelle** (`SourceLayout`): se la cartella scelta contiene solo cartelle di tipo (post, storie, evidenza, taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a @@ -159,6 +159,15 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per ## Limiti noti +- WMV/ASF, FLV e MPEG (lettori `AsfReader`, `FlvReader`, `MpegPsReader` in `Codecs/Containers`, scritti dalle + specifiche): di un WMV si leggono le proprietà del file (data, durata senza il preroll; niente durata se è una + trasmissione), dei flussi (codec, dimensioni, audio, anche dentro l'estensione dell'intestazione), il titolo e + `WM/EncodingTime` quando manca la data; di un FLV `onMetaData` (durata, dimensioni, `creationdate`), le dimensioni + dall'SPS dell'H.264 o dall'intestazione dell'H.263 di Sorenson, e senza metadati la durata dall'ultimo tag; di un MPEG + (MPEG-1 e MPEG-2, anche VOB) codec e dimensioni dall'intestazione di sequenza o dall'SPS dell'H.264 e la durata dal + primo all'ultimo tempo di presentazione, leggendo solo i primi 2 MB e l'ultimo MB. Un MPEG non ha data. La + miniatura viene solo dagli FLV H.264: WMV (VC-1) e MPEG-2 non si decodificano, e i campioni di un MPEG, spezzati nei + pacchetti PES, non si elencano, nemmeno se H.264. - HEIC/HEIF: si riconoscono, ma SkiaSharp (pacchetto Linux senza dipendenze) non li decodifica: niente dimensioni, impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica. - La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella diff --git a/src/Febe.Core/Import/MediaSniffer.cs b/src/Febe.Core/Import/MediaSniffer.cs index d7fb2d3..17f620c 100644 --- a/src/Febe.Core/Import/MediaSniffer.cs +++ b/src/Febe.Core/Import/MediaSniffer.cs @@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.Text; +using Febe.Core.Codecs.Containers; using Febe.Core.Domain; namespace Febe.Core.Import; @@ -17,7 +18,7 @@ public sealed record DetectedType(MediaKind Kind, string ContentType, string Ext /// /// Recognizes photos and videos from their first bytes, not from the extension (spec §9.2). Anything else is «Non -/// riconosciuto». Audio-only containers (M4A) are not videos. +/// riconosciuto». Audio-only containers (M4A, WMA, an FLV of audio alone) are not videos. /// public static class MediaSniffer { @@ -133,12 +134,13 @@ public static class MediaSniffer if (head.Length >= 16 && head.StartsWith(AsfSignature)) { - return new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV"); + // A WMA file is ASF too: only a whole header that lists audio and no video says so. + return AsfReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV"); } if (head.StartsWith("FLV"u8) && head[3] == 0x01) { - return new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV"); + return FlvReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV"); } if (head[0] == 0x00 && head[1] == 0x00 && head[2] == 0x01 && head[3] == 0xBA) diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index b14c631..c01ad97 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -6,7 +6,7 @@ namespace Febe.Core.Import; /// Metadata of a video read from its container. public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); -/// Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI). +/// Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI, WMV/ASF, FLV, MPEG program stream). public interface IVideoMetadataProbe { /// Metadata of a video file, read-only; null when it cannot be read. diff --git a/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs new file mode 100644 index 0000000..fc4e284 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs @@ -0,0 +1,332 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// The readers of the older containers — ASF (WMV), FLV and MPEG program streams — on files the tests build from the +/// specifications: what each header says must come out, and an FLV of H.264 must decode to the official frames. +/// +[TestClass] +public sealed class LegacyContainerTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + // ----- ASF ----- + + [TestMethod] + public void AnAsfHeaderGivesDurationSizeCodecDateAndTitle() + { + var created = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero); + var file = LegacyTestVideos.Asf(new AsfOptions { Created = created, Title = "Vacanze al mare" }); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Asf, container.Format); + Assert.AreEqual(created, container.CreatedAt); + Assert.AreEqual(TimeSpan.FromSeconds(12.5), container.Duration, "la durata di riproduzione senza il preroll"); + Assert.AreEqual("Vacanze al mare", container.Title); + Assert.AreEqual(VideoCodec.Vc1, container.Video!.Codec); + Assert.AreEqual("WMV3", container.Video.CodecTag); + Assert.AreEqual((640, 480), (container.Video.Width, container.Video.Height)); + Assert.IsEmpty(container.Video.Samples); + Assert.AreEqual(AudioCodec.Wma, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + + using var temp = new TempFolder("asf"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.wmv", file), Now); + Assert.AreEqual(new VideoMetadata(created, TimeSpan.FromSeconds(12.5), 640, 480), meta); + } + + [TestMethod] + public void AVideoStreamInsideTheHeaderExtensionIsFound() + { + var container = Read(LegacyTestVideos.Asf(new AsfOptions { VideoInExtension = true, Width = 1280, Height = 720, Compression = "WMV2" })); + Assert.AreEqual(VideoCodec.Wmv, container.Video!.Codec); + Assert.AreEqual((1280, 720), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(AudioCodec.Wma, container.Audio!.Codec); + } + + [TestMethod] + public void ABroadcastAsfHasNoDurationAndTheEncodingTimeGivesTheDate() + { + var encoded = new DateTimeOffset(2012, 1, 2, 3, 4, 5, TimeSpan.Zero); + var container = Read(LegacyTestVideos.Asf(new AsfOptions { Broadcast = true, EncodingTime = encoded })); + Assert.IsNull(container.Duration, "in una trasmissione i campi della durata non valgono"); + Assert.AreEqual(encoded, container.CreatedAt, "senza data nelle proprietà del file vale WM/EncodingTime"); + + // A date after now is not believed, wherever it comes from. + container = Read(LegacyTestVideos.Asf(new AsfOptions { Created = Now.AddDays(3), EncodingTime = Now.AddDays(5) })); + Assert.IsNull(container.CreatedAt); + } + + [TestMethod] + public void TheSnifferTellsAWmvFromAWma() + { + var wmv = LegacyTestVideos.Asf(new AsfOptions()); + var wma = LegacyTestVideos.Asf(new AsfOptions { Video = false }); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(Head(wmv))?.Kind); + Assert.IsNull(MediaSniffer.Detect(Head(wma)), "solo audio: né foto né video"); + + // A head that does not hold the whole header proves nothing: the file stays a video. + Assert.AreEqual("WMV", MediaSniffer.Detect(wma.AsSpan(0, 200))?.Format); + Assert.IsFalse(AsfReader.IsAudioOnly(wmv)); + Assert.IsTrue(AsfReader.IsAudioOnly(Head(wma))); + } + + // ----- FLV ----- + + [TestMethod] + [DataRow("BA1_Sony_D")] + [DataRow("CABA3_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("HCAFR1_HHI_C")] + public void AnFlvOfH264DecodesToTheReferenceFrames(string name) + { + var es = ElementaryStream.Load(name); + var file = LegacyTestVideos.Flv(es, audio: true); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Flv, container.Format); + var video = container.Video!; + Assert.AreEqual(VideoCodec.H264, video.Codec); + Assert.AreEqual((es.Width, es.Height), (video.Width, video.Height)); + Assert.HasCount(es.Count, video.Samples); + CollectionAssert.AreEqual(es.Key, video.Samples.Select(s => s.Key).ToArray()); + var shown = video.Samples.Select((s, i) => (s.PresentationTime, i)).OrderBy(p => p.PresentationTime).Select(p => p.i).ToArray(); + CollectionAssert.AreEqual(Enumerable.Range(0, es.Count).OrderBy(i => es.Rank[i]).ToArray(), shown, "ordine di presentazione"); + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, video)); + Assert.AreEqual(AudioCodec.Aac, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + CollectionAssert.AreEqual(new byte[] { 0x12, 0x10 }, container.Audio.AacConfiguration); + } + + [TestMethod] + public void TheMetadataGivesDurationAndDateAndTheSpsGivesTheSize() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var file = LegacyTestVideos.Flv(es, creationDate: "Sat Jul 08 09:10:11 2023\n", metadataSize: (999, 777)); + var container = Read(file, samples: false); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual(new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.Zero), container.CreatedAt); + Assert.AreEqual((es.Width, es.Height), (container.Video!.Width, container.Video.Height), "l'SPS vince sui metadati"); + Assert.IsEmpty(container.Video.Samples, "solo i metadati"); + Assert.IsNotNull(container.Video.AvcConfiguration); + + // A date as an AMF date (milliseconds from 1970). + var instant = new DateTimeOffset(2020, 2, 3, 4, 5, 6, TimeSpan.Zero); + container = Read(LegacyTestVideos.Flv(es, creationMilliseconds: instant.ToUnixTimeMilliseconds()), samples: false); + Assert.AreEqual(instant, container.CreatedAt); + } + + [TestMethod] + public void WithoutMetadataTheLastTagGivesTheDurationAndTheSpsTheSize() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var file = LegacyTestVideos.Flv(es, metadata: false, audio: true); + var expected = Math.Round((es.Count - 1) * 1000.0 / 30) / 1000; + foreach (var samples in new[] { false, true }) + { + var container = Read(file, samples); + Assert.AreEqual(expected, container.Duration!.Value.TotalSeconds, 1e-6, $"campioni: {samples}"); + Assert.AreEqual((es.Width, es.Height), (container.Video!.Width, container.Video.Height)); + Assert.IsNull(container.CreatedAt); + } + + using var temp = new TempFolder("flv-senza-metadati"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.flv", file), Now); + Assert.AreEqual(new VideoMetadata(null, TimeSpan.FromSeconds(expected), es.Width, es.Height), meta); + } + + [TestMethod] + public async Task TheFrameDecoderMakesTheSameThumbnailOfAnFlvAsOfAnMp4() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("flv-fotogramma"); + var flv = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "video.flv", LegacyTestVideos.Flv(es)), TimeSpan.FromSeconds(1)); + var mp4 = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)), TimeSpan.FromSeconds(1)); + Assert.IsNotNull(flv); + Assert.IsNotNull(mp4); + Assert.AreEqual((mp4.Width, mp4.Height), (flv.Width, flv.Height)); + CollectionAssert.AreEqual(mp4.Rgb, flv.Rgb); + } + + [TestMethod] + [DataRow(0, 200, 150)] + [DataRow(1, 1024, 576)] + [DataRow(5, 320, 240)] + [DataRow(3, 176, 144)] + public void ASorensonH263FlvTakesTheSizeOfItsPictureHeader(int code, int width, int height) + { + var container = Read(LegacyTestVideos.SorensonFlv(code, width, height)); + Assert.AreEqual(VideoCodec.H263, container.Video!.Codec); + Assert.AreEqual((width, height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(0.36, container.Duration!.Value.TotalSeconds, 1e-6, "dal primo all'ultimo tag"); + Assert.IsEmpty(container.Video.Samples, "solo H.264 si decodifica"); + } + + [TestMethod] + public void AnEnhancedFlvTellsItsCodecAndAnAudioFlvIsNoVideo() + { + var hevc = LegacyTestVideos.EnhancedOrAudioFlv("hvc1", audioFlag: true, videoFlag: true); + Assert.AreEqual(VideoCodec.Hevc, Read(hevc).Video!.Codec); + Assert.AreEqual(VideoCodec.Av1, Read(LegacyTestVideos.EnhancedOrAudioFlv("av01", audioFlag: true, videoFlag: true)).Video!.Codec); + + var audio = LegacyTestVideos.EnhancedOrAudioFlv(null, audioFlag: true, videoFlag: false); + var container = Read(audio); + Assert.IsNull(container.Video); + Assert.AreEqual(AudioCodec.Mp3, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + Assert.IsNull(MediaSniffer.Detect(audio), "solo audio: né foto né video"); + + // A header that forgets its video flag, with video tags after it, is still a video. + var forgetful = LegacyTestVideos.EnhancedOrAudioFlv("hvc1", audioFlag: true, videoFlag: false); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(forgetful)?.Kind); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(hevc)?.Kind); + } + + // ----- MPEG program stream ----- + + [TestMethod] + [DataRow(720, 576, false)] + [DataRow(4096, 2160, false)] + [DataRow(720, 480, true)] + public void AnMpeg2ProgramStreamGivesCodecSizeDurationAndAudio(int width, int height, bool streamMap) + { + // 4096 needs the size extension: its twelve low bits are zero. + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Width = width, Height = height, StreamMap = streamMap })); + Assert.AreEqual(ContainerFormat.MpegPs, container.Format); + Assert.AreEqual(VideoCodec.Mpeg2, container.Video!.Codec); + Assert.AreEqual((width, height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(2.0, container.Duration!.Value.TotalSeconds, 1e-6, "50 immagini a 25 al secondo"); + Assert.IsEmpty(container.Video.Samples); + Assert.IsNull(container.CreatedAt); + Assert.AreEqual(AudioCodec.Mp2, container.Audio!.Codec); + Assert.AreEqual((48_000, 2), (container.Audio.SampleRate, container.Audio.Channels)); + } + + [TestMethod] + public void AnMpeg1SystemStreamOfMpeg1Video() + { + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "mpeg1", Mpeg1System = true, Width = 352, Height = 288, Frames = 75 })); + Assert.AreEqual(VideoCodec.Mpeg1, container.Video!.Codec); + Assert.AreEqual((352, 288), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(3.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual(AudioCodec.Mp2, container.Audio!.Codec); + } + + [TestMethod] + [DataRow("CABA3_SVA_B", true)] + [DataRow("CABA3_SVA_B", false)] + [DataRow("FRExt1_Panasonic_D", false)] + public void H264InAProgramStreamTakesItsSizeFromTheSps(string name, bool streamMap) + { + var es = ElementaryStream.Load(name); + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "h264", Stream = es, StreamMap = streamMap, Audio = null })); + Assert.AreEqual(VideoCodec.H264, container.Video!.Codec); + Assert.AreEqual((es.Width, es.Height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual((es.Count - 1) / 30.0, container.Duration!.Value.TotalSeconds, 1e-6, "senza frequenza delle immagini: dal primo all'ultimo tempo"); + Assert.IsNull(container.Audio); + } + + [TestMethod] + public void TheEndOfALongProgramStreamGivesItsDuration() + { + // About 6 MB: the reader looks at the first 2 MB and the last 1 MB only. + var file = LegacyTestVideos.MpegPs(new PsOptions { Frames = 300, PictureBytes = 20_000 }); + Assert.IsGreaterThan(5_000_000, file.Length); + var container = Read(file); + Assert.AreEqual(12.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual((720, 576), (container.Video!.Width, container.Video.Height)); + + using var temp = new TempFolder("mpeg-lungo"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mpg", file), Now); + Assert.AreEqual(new VideoMetadata(null, TimeSpan.FromSeconds(12), 720, 576), meta); + } + + [TestMethod] + [DataRow(50)] + [DataRow(300)] + public void TheDurationCrossesTheWrapOfTheClock(int frames) + { + // The times start one second before the 33-bit clock wraps to zero, in a short file and in a long one. + var first = (1L << 33) - 90_000; + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { FirstPts = first, Frames = frames, PictureBytes = frames > 100 ? 20_000 : 1500 })); + Assert.AreEqual(frames / 25.0, container.Duration!.Value.TotalSeconds, 1e-6); + } + + [TestMethod] + public void Ac3InPrivateStreamOneIsRecognised() + { + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Audio = "ac3" })); + Assert.AreEqual(AudioCodec.Ac3, container.Audio!.Codec); + Assert.AreEqual((48_000, 6), (container.Audio.SampleRate, container.Audio.Channels)); + } + + [TestMethod] + public void TheNewFormatsAreRecognisedByTheirFirstBytes() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + Assert.AreEqual(ContainerFormat.Asf, ContainerReader.Detect(LegacyTestVideos.Asf(new AsfOptions()))); + Assert.AreEqual(ContainerFormat.Flv, ContainerReader.Detect(LegacyTestVideos.Flv(es))); + Assert.AreEqual(ContainerFormat.MpegPs, ContainerReader.Detect(LegacyTestVideos.MpegPs(new PsOptions()))); + Assert.AreEqual(ContainerFormat.MpegPs, ContainerReader.Detect(LegacyTestVideos.MpegPs(new PsOptions { Mpeg1System = true }))); + Assert.AreEqual("MPEG", MediaSniffer.Detect(LegacyTestVideos.MpegPs(new PsOptions()).AsSpan(0, 512))?.Format); + Assert.AreEqual("FLV", MediaSniffer.Detect(LegacyTestVideos.Flv(es).AsSpan(0, 512))?.Format); + } + + [TestMethod] + public void TheSizeOfAnSpsIsTheCroppedSize() + { + foreach (var name in new[] { "BA1_Sony_D", "FRExt1_Panasonic_D" }) + { + var es = ElementaryStream.Load(name); + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromConfiguration(es.AvcC, out var w, out var h), name); + Assert.AreEqual((es.Width, es.Height), (w, h), name); + } + + // Fields, 4:2:2 and 4:0:0: the size the official reconstruction has, from the first line of its MD5 file. + foreach (var name in new[] { "BA1_Sony_D", "FRExt1_Panasonic_D", "CVFI1_SVA_C", "Hi422FR10_SONY_A", "HPCAMOLQ_BRCM_B", "CAPAMA3_Sand_F" }) + { + var header = File.ReadLines(Path.Combine(ElementaryStream.Folder(name), "riferimento.md5")).First().Split(' '); + var size = header[2].Split('x').Select(int.Parse).ToArray(); + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromAnnexB(ElementaryStream.AnnexB(name), complete: true, out var w, out var h), name); + Assert.AreEqual((size[0], size[1]), (w, h), name); + } + + // Not an SPS, or one cut short at the end of what was gathered. + Assert.IsFalse(H264StreamInfo.TryPictureSize([0x68, 0xCE, 0x3C, 0x80], out _, out _)); + var annexB = ElementaryStream.AnnexB("BA1_Sony_D"); + var next = annexB.AsSpan(4).IndexOf((ReadOnlySpan)[0, 0, 1]) + 4; // the start code after the first SPS + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromAnnexB(annexB.AsSpan(0, next - 1), complete: true, out _, out _)); + Assert.IsFalse(H264StreamInfo.TryPictureSizeFromAnnexB(annexB.AsSpan(0, next - 1), complete: false, out _, out _)); + } + + private static byte[] Head(byte[] file) => file[..Math.Min(file.Length, 512 * 1024)]; + + private static MediaContainer Read(byte[] file, bool samples = true) + { + using var stream = new MemoryStream(file, writable: false); + var container = ContainerReader.Read(stream, Now, samples); + Assert.IsNotNull(container); + return container; + } + + private static List DecodeAll(byte[] file, VideoTrack video) + { + using var stream = new MemoryStream(file); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + var lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); + var buffer = Array.Empty(); + foreach (var sample in video.Samples) + { + decoder.DecodeSample(ContainerReader.ReadSample(stream, sample, ref buffer), lengthSize); + } + + decoder.Flush(); + return ElementaryStream.Md5InOutputOrder(frames); + } +} diff --git a/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs new file mode 100644 index 0000000..3c055bf --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs @@ -0,0 +1,544 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Tests.Codecs.Containers; + +/// What a test ASF file holds. +internal sealed record AsfOptions +{ + public int Width { get; init; } = 640; + public int Height { get; init; } = 480; + public string Compression { get; init; } = "WMV3"; + public bool Video { get; init; } = true; + public bool Audio { get; init; } = true; + public TimeSpan Duration { get; init; } = TimeSpan.FromSeconds(12.5); + public ulong PrerollMilliseconds { get; init; } = 3000; + public bool Broadcast { get; init; } + public DateTimeOffset? Created { get; init; } + public DateTimeOffset? EncodingTime { get; init; } + public string? Title { get; init; } + + /// The video stream properties sit in an extended stream properties object of the header extension. + public bool VideoInExtension { get; init; } +} + +/// What a test MPEG program stream holds. +internal sealed record PsOptions +{ + /// «mpeg2», «mpeg1» or «h264» (then gives the pictures). + public string Video { get; init; } = "mpeg2"; + public int Width { get; init; } = 720; + public int Height { get; init; } = 576; + public int Frames { get; init; } = 50; + + /// Bytes of slice data per picture: large values make a file longer than the windows the reader looks at. + public int PictureBytes { get; init; } = 1500; + public bool Mpeg1System { get; init; } + public bool StreamMap { get; init; } + + /// «mp2», «ac3» or null. + public string? Audio { get; init; } = "mp2"; + public long FirstPts { get; init; } = 90_000; + public ElementaryStream? Stream { get; init; } + public int Seed { get; init; } = 7301; +} + +/// +/// Builders of ASF, FLV and MPEG program stream files from their specifications, for the readers' tests: no real sample +/// file is needed, and the filler bytes come from a fixed seed. +/// +internal static class LegacyTestVideos +{ + public static readonly Guid AsfHeader = new("75B22630-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid AsfFileProperties = new("8CABDCA1-A947-11CF-8EE4-00C00C205365"); + private static readonly Guid AsfStreamProperties = new("B7DC0791-A9B7-11CF-8EE6-00C00C205365"); + private static readonly Guid AsfHeaderExtension = new("5FBF03B5-A92E-11CF-8EE3-00C00C205365"); + private static readonly Guid AsfReserved1 = new("ABD3D211-A9BA-11CF-8EE6-00C00C205365"); + private static readonly Guid AsfContentDescription = new("75B22633-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid AsfExtendedContentDescription = new("D2D0A440-E307-11D2-97F0-00A0C95EA850"); + private static readonly Guid AsfExtendedStreamProperties = new("14E6A5CB-C672-4332-8399-A96952065B5A"); + private static readonly Guid AsfVideoMedia = new("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfAudioMedia = new("F8699E40-5B4D-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfNoErrorCorrection = new("20FB5700-5B55-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfData = new("75B22636-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly DateTimeOffset Epoch1601 = new(1601, 1, 1, 0, 0, 0, TimeSpan.Zero); + + // ----- ASF ----- + + /// An ASF file: header object with the objects of , then a data object of filler packets. + public static byte[] Asf(AsfOptions o) + { + var random = new Random(4101); + var children = new List(); + var fileId = new byte[16]; + random.NextBytes(fileId); + + var play = (ulong)o.Duration.Ticks + (o.PrerollMilliseconds * 10_000); + children.Add(AsfObject(AsfFileProperties, [.. fileId, .. Le64(0), .. Le64(o.Created is { } c ? FileTime(c) : 0), .. Le64(10), + .. Le64(play), .. Le64(play), .. Le64(o.PrerollMilliseconds), .. Le32(o.Broadcast ? 1u : 2u), .. Le32(3200), .. Le32(3200), .. Le32(512_000)])); + if (o.Video && !o.VideoInExtension) + { + children.Add(VideoStream(o, 1)); + } + + if (o.Audio) + { + children.Add(AudioStream(2)); + } + + if (o.Title is not null) + { + var title = Encoding.Unicode.GetBytes(o.Title + "\0"); + var author = Encoding.Unicode.GetBytes("Febe\0"); + children.Add(AsfObject(AsfContentDescription, + [.. Le16((ushort)title.Length), .. Le16((ushort)author.Length), .. Le16(0), .. Le16(0), .. Le16(0), .. title, .. author])); + } + + var descriptors = new List { Descriptor("WM/ToolName", 0, Encoding.Unicode.GetBytes("Prove di Febe\0")) }; + if (o.EncodingTime is { } e) + { + descriptors.Add(Descriptor("WM/EncodingTime", 4, Le64(FileTime(e)))); + } + + descriptors.Add(Descriptor("IsVBR", 2, Le32(1))); + children.Add(AsfObject(AsfExtendedContentDescription, [.. Le16((ushort)descriptors.Count), .. descriptors.SelectMany(d => d)])); + + var extension = new List(); + if (o.Video && o.VideoInExtension) + { + var name = Encoding.Unicode.GetBytes("Video\0"); + extension.Add(AsfObject(AsfExtendedStreamProperties, + [.. Le64(0), .. Le64(0), .. Le32(500_000), .. Le32(3000), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(65_536), + .. Le32(0), .. Le16(1), .. Le16(0), .. Le64(400_000), .. Le16(1), .. Le16(1), + .. Le16(0), .. Le16((ushort)name.Length), .. name, + .. Enumerable.Repeat((byte)0x11, 16),.. Le16(4), .. Le32(4), 1, 2, 3, 4, + .. VideoStream(o, 1)])); + } + + var extensionData = extension.SelectMany(x => x).ToArray(); + children.Add(AsfObject(AsfHeaderExtension, [.. AsfReserved1.ToByteArray(), .. Le16(6), .. Le32((uint)extensionData.Length), .. extensionData])); + + var body = children.SelectMany(x => x).ToArray(); + byte[] header = [.. AsfHeader.ToByteArray(), .. Le64((ulong)(30 + body.Length)), .. Le32((uint)children.Count), 1, 2, .. body]; + var packets = new byte[10 * 3200]; + random.NextBytes(packets); + var data = AsfObject(AsfData, [.. fileId, .. Le64(10), 1, 1, .. packets]); + return [.. header, .. data]; + } + + private static byte[] VideoStream(AsfOptions o, int number) + { + var bitmap = new List(); + bitmap.AddRange(Le32(40)); + bitmap.AddRange(Le32((uint)o.Width)); + bitmap.AddRange(Le32((uint)o.Height)); + bitmap.AddRange(Le16(1)); + bitmap.AddRange(Le16(24)); + bitmap.AddRange(Encoding.ASCII.GetBytes(o.Compression)); + bitmap.AddRange(new byte[20]); + byte[] specific = [.. Le32((uint)o.Width), .. Le32((uint)o.Height), 2, .. Le16((ushort)bitmap.Count), .. bitmap]; + return StreamObject(AsfVideoMedia, number, specific); + } + + private static byte[] AudioStream(int number) + { + // WAVEFORMATEX of WMA 2: 44.1 kHz stereo, with ten bytes of codec data. + byte[] specific = [.. Le16(0x161), .. Le16(2), .. Le32(44_100), .. Le32(16_000), .. Le16(2_973), .. Le16(16), .. Le16(10), .. new byte[10]]; + return StreamObject(AsfAudioMedia, number, specific); + } + + private static byte[] StreamObject(Guid type, int number, byte[] specific) => AsfObject(AsfStreamProperties, + [.. type.ToByteArray(), .. AsfNoErrorCorrection.ToByteArray(), .. Le64(0), .. Le32((uint)specific.Length), .. Le32(0), + .. Le16((ushort)number), .. Le32(0), .. specific]); + + private static byte[] Descriptor(string name, ushort type, byte[] value) + { + var n = Encoding.Unicode.GetBytes(name + "\0"); + return [.. Le16((ushort)n.Length), .. n, .. Le16(type), .. Le16((ushort)value.Length), .. value]; + } + + private static byte[] AsfObject(Guid id, byte[] body) => [.. id.ToByteArray(), .. Le64((ulong)(24 + body.Length)), .. body]; + + private static ulong FileTime(DateTimeOffset instant) => (ulong)(instant - Epoch1601).Ticks; + + // ----- FLV ----- + + /// + /// An FLV file of an H.264 stream at 30 frames per second: onMetaData (unless is false), + /// the AVC sequence header, one tag per access unit with its composition time and, with , an + /// AAC sequence header and AAC tags between the frames. + /// + public static byte[] Flv(ElementaryStream es, bool metadata = true, string? creationDate = null, bool audio = false, + (int Width, int Height)? metadataSize = null, double? creationMilliseconds = null) + { + var shift = 0; + for (var i = 0; i < es.Count; i++) + { + shift = Math.Max(shift, i - es.Rank[i]); + } + + using var output = new MemoryStream(); + FlvHeader(output, audio, video: true); + if (metadata) + { + var size = metadataSize ?? (es.Width, es.Height); + var properties = new List + { + AmfProperty("duration", AmfNumber(es.Count / 30.0)), + AmfProperty("width", AmfNumber(size.Width)), + AmfProperty("height", AmfNumber(size.Height)), + AmfProperty("framerate", AmfNumber(30)), + AmfProperty("videocodecid", AmfNumber(7)), + AmfProperty("stereo", [1, 1]), + AmfProperty("encoder", AmfString("Prove di Febe")), + AmfProperty("keyframes", [3, .. AmfProperty("times", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i / 30.0))), + .. AmfProperty("filepositions", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i * 1000.0))), 0, 0, 9]), + }; + if (creationDate is not null) + { + properties.Add(AmfProperty("creationdate", AmfString(creationDate))); + } + + if (creationMilliseconds is { } ms) + { + properties.Add(AmfProperty("creationdate", [11, .. F64(ms), 0, 0])); + } + + FlvTag(output, 18, 0, [.. AmfString("onMetaData"), 8, .. U32((uint)properties.Count), .. properties.SelectMany(p => p), 0, 0, 9]); + } + + FlvTag(output, 9, 0, [0x17, 0, 0, 0, 0, .. es.AvcC]); + if (audio) + { + FlvTag(output, 8, 0, [0xAF, 0, 0x12, 0x10]); // AAC LC, 44.1 kHz, stereo + } + + for (var i = 0; i < es.Count; i++) + { + var dts = (int)Math.Round(i * 1000.0 / 30); + var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30); + var cts = pts - dts; + FlvTag(output, 9, dts, [es.Key[i] ? (byte)0x17 : (byte)0x27, 1, (byte)(cts >> 16), (byte)(cts >> 8), (byte)cts, .. es.LengthPrefixed(i)]); + if (audio && i % 2 == 0) + { + FlvTag(output, 8, dts, [0xAF, 1, 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C]); + } + } + + return output.ToArray(); + } + + /// An FLV with one script tag of the given AMF0 body and one H.263 video tag. + public static byte[] FlvWithScript(byte[] script) + { + using var output = new MemoryStream(); + FlvHeader(output, audio: false, video: true); + FlvTag(output, 18, 0, script); + FlvTag(output, 9, 0, [0x12, 0, 0, 0x80, 0, 0x0A, 0x00, 0x00, 0x00, 0x00]); + return output.ToArray(); + } + + /// An FLV of Sorenson H.263 tags whose picture headers give the size (code 0, 1 or a fixed size code). + public static byte[] SorensonFlv(int sizeCode, int width, int height, int frames = 10) + { + using var output = new MemoryStream(); + FlvHeader(output, audio: false, video: true); + var random = new Random(4102); + for (var i = 0; i < frames; i++) + { + var bits = new BitWriterForTests(); + bits.Write(1, 17); // picture start code + bits.Write(0, 5); // version + bits.Write(i & 0xFF, 8); // temporal reference + bits.Write(sizeCode, 3); + if (sizeCode == 0) + { + bits.Write(width, 8); + bits.Write(height, 8); + } + else if (sizeCode == 1) + { + bits.Write(width, 16); + bits.Write(height, 16); + } + + bits.Write(i == 0 ? 0 : 1, 2); // picture type: intra, then inter + var filler = new byte[200]; + random.NextBytes(filler); + FlvTag(output, 9, i * 40, [(byte)((i == 0 ? 0x10 : 0x20) | 2), .. bits.ToArray(), .. filler]); + } + + return output.ToArray(); + } + + /// An FLV whose video tags use the enhanced header with , or only audio tags. + public static byte[] EnhancedOrAudioFlv(string? fourCc, bool audioFlag, bool videoFlag) + { + using var output = new MemoryStream(); + FlvHeader(output, audioFlag, videoFlag); + for (var i = 0; i < 20; i++) + { + if (fourCc is not null) + { + FlvTag(output, 9, i * 40, [(byte)(0x80 | (i == 0 ? 0x10 : 0x20) | 1), .. Encoding.ASCII.GetBytes(fourCc), 0, 0, 0, 0x55, 0x66]); + } + + FlvTag(output, 8, i * 40, [0x2F, 0xFF, 0xFB, 0x90, 0x64, 0, 0, 0]); // MP3, 44 kHz, stereo + } + + return output.ToArray(); + } + + private static void FlvHeader(MemoryStream output, bool audio, bool video) + { + output.Write("FLV"u8); + output.WriteByte(1); + output.WriteByte((byte)((audio ? 4 : 0) | (video ? 1 : 0))); + output.Write(U32(9)); + output.Write(U32(0)); + } + + private static void FlvTag(MemoryStream output, int type, int time, byte[] data) + { + output.Write([(byte)type, (byte)(data.Length >> 16), (byte)(data.Length >> 8), (byte)data.Length, + (byte)(time >> 16), (byte)(time >> 8), (byte)time, (byte)(time >> 24), 0, 0, 0]); + output.Write(data); + output.Write(U32((uint)(11 + data.Length))); + } + + private static byte[] AmfString(string text) + { + var bytes = Encoding.UTF8.GetBytes(text); + return [2, .. U16((ushort)bytes.Length), .. bytes]; + } + + private static byte[] AmfNumber(double value) => [0, .. F64(value)]; + + private static byte[] AmfArray(IEnumerable values) + { + var items = values.ToList(); + return [10, .. U32((uint)items.Count), .. items.SelectMany(AmfNumber)]; + } + + private static byte[] AmfProperty(string name, byte[] value) + { + var bytes = Encoding.UTF8.GetBytes(name); + return [.. U16((ushort)bytes.Length), .. bytes, .. value]; + } + + // ----- MPEG program stream ----- + + /// + /// An MPEG program stream: a pack header before each picture, a system header, optionally a program stream map, the + /// pictures as PES packets of at most 2,000 bytes (the first with its presentation time), and audio frames between. + /// MPEG-1 and MPEG-2 pictures are a sequence header (with its extension in MPEG-2), a GOP header, a picture header + /// and filler slice bytes; H.264 pictures are the access units of . + /// + public static byte[] MpegPs(PsOptions o) + { + var random = new Random(o.Seed); + var frameTicks = o.Video == "h264" ? 3000 : 3600; // 30 or 25 pictures a second + var frames = o.Video == "h264" ? o.Stream!.Count : o.Frames; + using var output = new MemoryStream(); + var audioTime = o.FirstPts; + for (var i = 0; i < frames; i++) + { + var pts = (o.FirstPts + ((long)i * frameTicks)) & ((1L << 33) - 1); + Pack(output, o, pts > 9000 ? pts - 9000 : 0); + if (i == 0) + { + output.Write([0, 0, 1, 0xBB, 0, 12, 0x80, 0x00, 0x01, 0x04, 0xE1, 0xFF, 0xE0, 0xE0, 0xE8, 0xC0, 0xC0, 0x20]); + if (o.StreamMap) + { + var videoType = o.Video switch { "h264" => (byte)0x1B, "mpeg1" => (byte)0x01, _ => (byte)0x02 }; + byte[] map = [videoType, 0xE0, 0, 0, 0x04, 0xC0, 0, 0]; + byte[] body = [0x80, 0x01, 0, 0, .. U16((ushort)map.Length), .. map, 0, 0, 0, 0]; + output.Write([0, 0, 1, 0xBC, .. U16((ushort)body.Length), .. body]); + } + } + + var picture = o.Video == "h264" ? o.Stream!.WithStartCodes(i) : MpegPicture(o, i, random); + for (var offset = 0; offset < picture.Length; offset += 2000) + { + var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray(); + Pes(output, 0xE0, offset == 0 ? pts : -1, chunk, o.Mpeg1System); + } + + while (o.Audio is not null && audioTime <= o.FirstPts + ((long)i * frameTicks)) + { + var t = audioTime & ((1L << 33) - 1); + if (o.Audio == "ac3") + { + // Private stream 1, sub-stream 0x80: one AC-3 frame at 48 kHz, 3/2 channels with LFE (5.1). + var frame = new byte[768]; + frame[0] = 0x0B; + frame[1] = 0x77; + frame[4] = 0x00 | 0x0E; // fscod 0 (48 kHz), frmsizecod + frame[5] = 0x08 << 3; // bsid 8, bsmod 0 + var bits = new BitWriterForTests(); + bits.Write(7, 3); // acmod 3/2 + bits.Write(1, 2); // cmixlev + bits.Write(1, 2); // surmixlev + bits.Write(1, 1); // lfeon + bits.ToArray().CopyTo(frame, 6); + Pes(output, 0xBD, t, [0x80, 1, 0, 1, .. frame], o.Mpeg1System); + audioTime += 2880; // 1,536 samples + } + else + { + var frame = new byte[576]; + frame[0] = 0xFF; + frame[1] = 0xFD; // MPEG-1 layer II, no CRC + frame[2] = 0xA4; // 192 kbit/s, 48 kHz + frame[3] = 0x04; // stereo + Pes(output, 0xC0, t, frame, o.Mpeg1System); + audioTime += 2160; // 1,152 samples + } + } + } + + output.Write([0, 0, 1, 0xB9]); + return output.ToArray(); + } + + private static byte[] MpegPicture(PsOptions o, int index, Random random) + { + var data = new List(); + if (index % 12 == 0) + { + var bits = new BitWriterForTests(); + bits.Write(o.Width & 0xFFF, 12); + bits.Write(o.Height & 0xFFF, 12); + bits.Write(1, 4); // square pixels + bits.Write(3, 4); // 25 pictures a second + bits.Write(0x3FFFF, 18); + bits.Write(1, 1); + bits.Write(112, 10); + bits.Write(0, 3); + data.AddRange([0, 0, 1, 0xB3, .. bits.ToArray()]); + if (o.Video == "mpeg2") + { + var ext = new BitWriterForTests(); + ext.Write(1, 4); // sequence extension + ext.Write(0x48, 8); // main profile, main level + ext.Write(1, 1); // progressive + ext.Write(1, 2); // 4:2:0 + ext.Write(o.Width >> 12, 2); + ext.Write(o.Height >> 12, 2); + ext.Write(0, 12); + ext.Write(1, 1); + ext.Write(0, 8); + ext.Write(0, 8); + data.AddRange([0, 0, 1, 0xB5, .. ext.ToArray()]); + } + + data.AddRange([0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); + } + + data.AddRange([0, 0, 1, 0x00, (byte)(index >> 2), (byte)((index << 6) | 0x08), 0xFF, 0xF8]); + var slice = new byte[o.PictureBytes]; + random.NextBytes(slice); + for (var k = 0; k < slice.Length; k++) + { + slice[k] |= 0x01; // no zero bytes: no start code inside the filler + } + + data.AddRange([0, 0, 1, 0x01, .. slice]); + return [.. data]; + } + + private static void Pack(MemoryStream output, PsOptions o, long scr) + { + if (o.Mpeg1System) + { + // '0010', SCR in the layout of a time stamp, then the mux rate between two marker bits. + output.Write([0, 0, 1, 0xBA, .. Timestamp(0x2, scr), 0x80, 0x1B, 0x83]); + return; + } + + var b = new byte[] { 0, 0, 1, 0xBA, + (byte)(0x44 | ((scr >> 27) & 0x38) | ((scr >> 28) & 3)), + (byte)(scr >> 20), + (byte)(((scr >> 12) & 0xF8) | 0x04 | ((scr >> 13) & 3)), + (byte)(scr >> 5), + (byte)(((scr << 3) & 0xF8) | 0x04), + 0x01, 0x01, 0x89, 0xC3, 0xF8 }; + output.Write(b); + } + + private static void Pes(MemoryStream output, int id, long pts, byte[] payload, bool mpeg1) + { + byte[] header = mpeg1 + ? pts >= 0 ? Timestamp(0x2, pts) : [0x0F] + : pts >= 0 ? [0x81, 0x80, 5, .. Timestamp(0x2, pts)] : [0x81, 0x00, 0]; + var length = header.Length + payload.Length; + output.Write([0, 0, 1, (byte)id, (byte)(length >> 8), (byte)length, .. header, .. payload]); + } + + /// A 33-bit time in five bytes with a four-bit prefix and three marker bits. + private static byte[] Timestamp(int prefix, long t) => + [ + (byte)((prefix << 4) | (int)((t >> 29) & 0x0E) | 1), + (byte)(t >> 22), + (byte)(((t >> 14) & 0xFE) | 1), + (byte)(t >> 7), + (byte)(((t << 1) & 0xFE) | 1), + ]; + + // ----- bytes ----- + + private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v]; + + private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v]; + + private static byte[] F64(double v) + { + var b = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(b, v); + return b; + } + + private static byte[] Le16(ushort v) => [(byte)v, (byte)(v >> 8)]; + + private static byte[] Le32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, v); + return b; + } + + private static byte[] Le64(ulong v) + { + var b = new byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(b, v); + return b; + } + + /// Writes bits from the most significant one, as the codec headers want them. + private sealed class BitWriterForTests + { + private readonly List bytes = []; + private int used = 8; + + public void Write(int value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + if (used == 8) + { + bytes.Add(0); + used = 0; + } + + if (((value >> i) & 1) != 0) + { + bytes[^1] |= (byte)(0x80 >> used); + } + + used++; + } + } + + public byte[] ToArray() => [.. bytes]; + } +} diff --git a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs index 40c46e9..d283c7e 100644 --- a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs +++ b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs @@ -21,6 +21,10 @@ public sealed class MalformedInputTests [DataRow("frammentato.mp4")] [DataRow("mkv")] [DataRow("avi")] + [DataRow("wmv")] + [DataRow("flv")] + [DataRow("mpg")] + [DataRow("h264.mpg")] public void TruncatedFilesNeverBreakTheReaders(string kind) { var file = Build(kind); @@ -36,6 +40,10 @@ public sealed class MalformedInputTests [DataRow("frammentato.mp4", 5802)] [DataRow("mkv", 5803)] [DataRow("avi", 5804)] + [DataRow("wmv", 5805)] + [DataRow("flv", 5806)] + [DataRow("mpg", 5807)] + [DataRow("h264.mpg", 5808)] public void GarbledFilesNeverBreakTheReaders(string kind, int seed) { var file = Build(kind); @@ -51,6 +59,9 @@ public sealed class MalformedInputTests [DataRow("frammentato.mp4", 5812)] [DataRow("mkv", 5813)] [DataRow("avi", 5814)] + [DataRow("wmv", 5815)] + [DataRow("flv", 5816)] + [DataRow("mpg", 5817)] public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed) { var file = Build(kind); @@ -67,8 +78,16 @@ public sealed class MalformedInputTests _ = stillness; } - // Most damage hits frame data, not headers: many variants still give a frame. - Assert.IsGreaterThan(0, decoded, "nessuna variante ha dato un fotogramma"); + // Most damage hits frame data, not headers: many variants still give a frame. WMV and MPEG program streams have + // no samples Febe decodes, so no frame ever. + if (kind is "wmv" or "mpg") + { + Assert.AreEqual(0, decoded); + } + else + { + Assert.IsGreaterThan(0, decoded, "nessuna variante ha dato un fotogramma"); + } } [TestMethod] @@ -189,6 +208,54 @@ public sealed class MalformedInputTests Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); } + [TestMethod] + public void DeepOrEndlessFlvMetadataKeepsWhatCameBefore() + { + // onMetaData: a duration, then objects nested a hundred thousand deep (a stack overflow if followed blindly). + var deep = new List { 2, 0, 10 }; + deep.AddRange("onMetaData"u8.ToArray()); + deep.Add(3); + deep.AddRange([0, 8, .. "duration"u8, 0, .. Be64(5.0)]); + for (var i = 0; i < 100_000; i++) + { + deep.AddRange([0, 1, (byte)'a', 3]); + } + + var container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. deep]), out var allocated); + Assert.AreEqual(TimeSpan.FromSeconds(5), container!.Duration); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + + // A strict array that claims four billion values, then a width: the array ends the reading, the duration stays. + List endless = [2, 0, 10, .. "onMetaData"u8, 8, 0, 0, 0, 2, 0, 8, .. "duration"u8, 0, .. Be64(7.0), + 0, 4, .. "list"u8, 10, 0xFF, 0xFF, 0xFF, 0xFF, 0, .. Be64(1), 0, 5, .. "width"u8, 0, .. Be64(640)]; + container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. endless]), out _); + Assert.AreEqual(TimeSpan.FromSeconds(7), container!.Duration); + } + + [TestMethod] + public void AnAsfObjectLargerThanItsFileAllocatesNothing() + { + var file = LegacyTestVideos.Asf(new AsfOptions { Title = "Prova" }); + + // The file properties object (the first after the 30 bytes of the header) claims a gigabyte. + BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(30 + 16), 1L << 30); + var container = ReadMeasured(file, out var allocated); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + Assert.IsNull(container!.Duration, "nulla dopo l'oggetto rovinato"); + + // A header object smaller than its own fields. + file = LegacyTestVideos.Asf(new AsfOptions()); + BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(16), 12); + Assert.ThrowsExactly(() => ReadMeasured(file, out _)); + } + + private static byte[] Be64(double value) + { + var bytes = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(bytes, value); + return bytes; + } + private static void AssertReadersSurvive(byte[] data, string what) { foreach (var samples in new[] { false, true }) @@ -252,6 +319,16 @@ public sealed class MalformedInputTests "frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true), "mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), "avi" => TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021"), + "wmv" => LegacyTestVideos.Asf(new AsfOptions + { + Created = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero), + EncodingTime = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero), + Title = "Prova", + VideoInExtension = true, + }), + "flv" => LegacyTestVideos.Flv(es, creationDate: "Thu Mar 04 05:06:07 2021", audio: true), + "mpg" => LegacyTestVideos.MpegPs(new PsOptions { Frames = 30, PictureBytes = 300, StreamMap = true }), + "h264.mpg" => LegacyTestVideos.MpegPs(new PsOptions { Video = "h264", Stream = es, Audio = "ac3" }), _ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero), rotation: 90, audio: true), }; } diff --git a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs index 9717895..fb3908e 100644 --- a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs +++ b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs @@ -18,6 +18,7 @@ public sealed class VideoFrameDecoderTests [DataRow("frammentato.mp4")] [DataRow("senza-indice.avi")] [DataRow("senza-indice-con-parametri.avi")] + [DataRow("flv")] public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind) { var es = ElementaryStream.Load("CABA3_SVA_B"); @@ -33,6 +34,7 @@ public sealed class VideoFrameDecoderTests "senza-indice.avi" => TestVideos.Avi(es, index: false), "senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false), "frammentato.mp4" => TestVideos.FragmentedMp4(es), + "flv" => LegacyTestVideos.Flv(es, audio: true), _ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone }; var path = TestVideos.Write(temp, "video." + kind, data); diff --git a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md index 659f2fb..57569bd 100644 --- a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md +++ b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md @@ -1,7 +1,8 @@ # Flussi di conformità H.264 Questi flussi provano il decodificatore H.264 scritto in casa (`src/Febe.Core/Codecs/H264`) e, ricomposti in MP4, -Matroska e AVI dalle prove di `tests/Febe.Tests/Media/Containers`, anche i lettori dei contenitori e lo scrittore MP4. +Matroska, AVI, FLV e MPEG dalle prove di `tests/Febe.Tests/Media/Containers`, anche i lettori dei contenitori e lo +scrittore MP4. ## Provenienza