Lettori in casa di WMV/ASF, FLV e MPEG: data, durata, dimensioni e codec anche per questi video (#58)

Finora MediaSniffer riconosceva WMV, FLV e MPEG ma la sonda dei metadati non ne sapeva nulla:
data, durata e dimensioni venivano solo dal nome e dalla data di modifica. Tre lettori nuovi,
scritti dalle specifiche pubbliche senza componenti esterni, stanno dietro ContainerReader e
quindi dietro ContainerVideoMetadataProbe e VideoFrameDecoder.

- AsfReader: proprietà del file (data FILETIME, durata meno il preroll, niente durata per le
  trasmissioni), proprietà dei flussi anche dentro l'estensione dell'intestazione, titolo della
  descrizione del contenuto, WM/EncodingTime quando manca la data. Nessun campione.
- FlvReader: onMetaData in AMF0 (durata, dimensioni, creationdate come testo o come data),
  dimensioni dall'SPS della sequenza AVC o dall'intestazione H.263 di Sorenson, durata
  dall'ultimo tag senza metadati, codec degli FLV «enhanced» dal FourCC; i tag H.264 sono
  campioni, così anche un FLV ha la miniatura.
- MpegPsReader: pacchetti MPEG-1 e MPEG-2, intestazione di sistema, mappa del flusso, PES; codec
  e dimensioni dall'intestazione di sequenza (con l'estensione di MPEG-2) o dall'SPS H.264, audio
  MPEG, ADTS, AC-3 e LPCM; durata dal primo all'ultimo PTS attraverso il giro dei 33 bit,
  leggendo solo i primi 2 MB e l'ultimo MB.
- H264StreamInfo: dimensioni ritagliate di un SPS, da un avcC o da un flusso Annex B.
- MediaSniffer: un WMA o un FLV di solo audio non è più un video, quando l'intestazione intera
  nei primi byte lo dimostra.

Prove con file costruiti dalle prove stesse (LegacyTestVideos, semi fissi): metadati, MD5
ufficiali dei fotogrammi da FLV, miniatura dell'FLV uguale a quella dell'MP4, file lunghi e giro
dell'orologio, file troncati e rovinati, AMF annidato senza fine e oggetti ASF più grandi del
file. LEGGIMI dell'importazione e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 18:50:44 +01:00
1 parent 898e9d60e7
commit 6c8b228333
18 files changed
+2983 -13

No files matched your search

@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<byte>)[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<string> DecodeAll(byte[] file, VideoTrack video)
{
using var stream = new MemoryStream(file);
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
var lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
var buffer = Array.Empty<byte>();
foreach (var sample in video.Samples)
{
decoder.DecodeSample(ContainerReader.ReadSample(stream, sample, ref buffer), lengthSize);
}
decoder.Flush();
return ElementaryStream.Md5InOutputOrder(frames);
}
}
@@ -0,0 +1,544 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Tests.Codecs.Containers;
/// <summary>What a test ASF file holds.</summary>
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; }
/// <summary>The video stream properties sit in an extended stream properties object of the header extension.</summary>
public bool VideoInExtension { get; init; }
}
/// <summary>What a test MPEG program stream holds.</summary>
internal sealed record PsOptions
{
/// <summary>«mpeg2», «mpeg1» or «h264» (then <see cref="Stream"/> gives the pictures).</summary>
public string Video { get; init; } = "mpeg2";
public int Width { get; init; } = 720;
public int Height { get; init; } = 576;
public int Frames { get; init; } = 50;
/// <summary>Bytes of slice data per picture: large values make a file longer than the windows the reader looks at.</summary>
public int PictureBytes { get; init; } = 1500;
public bool Mpeg1System { get; init; }
public bool StreamMap { get; init; }
/// <summary>«mp2», «ac3» or null.</summary>
public string? Audio { get; init; } = "mp2";
public long FirstPts { get; init; } = 90_000;
public ElementaryStream? Stream { get; init; }
public int Seed { get; init; } = 7301;
}
/// <summary>
/// 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.
/// </summary>
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 -----
/// <summary>An ASF file: header object with the objects of <paramref name="o"/>, then a data object of filler packets.</summary>
public static byte[] Asf(AsfOptions o)
{
var random = new Random(4101);
var children = new List<byte[]>();
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<byte[]> { 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<byte[]>();
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<byte>();
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 -----
/// <summary>
/// An FLV file of an H.264 stream at 30 frames per second: onMetaData (unless <paramref name="metadata"/> is false),
/// the AVC sequence header, one tag per access unit with its composition time and, with <paramref name="audio"/>, an
/// AAC sequence header and AAC tags between the frames.
/// </summary>
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<byte[]>
{
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();
}
/// <summary>An FLV with one script tag of the given AMF0 body and one H.263 video tag.</summary>
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();
}
/// <summary>An FLV of Sorenson H.263 tags whose picture headers give the size (code 0, 1 or a fixed size code).</summary>
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();
}
/// <summary>An FLV whose video tags use the enhanced header with <paramref name="fourCc"/>, or only audio tags.</summary>
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<double> 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 -----
/// <summary>
/// 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 <see cref="PsOptions.Stream"/>.
/// </summary>
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<byte>();
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]);
}
/// <summary>A 33-bit time in five bytes with a four-bit prefix and three marker bits.</summary>
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;
}
/// <summary>Writes bits from the most significant one, as the codec headers want them.</summary>
private sealed class BitWriterForTests
{
private readonly List<byte> 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];
}
}
@@ -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<byte> { 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<byte> 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<ContainerException>(() => 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),
};
}
@@ -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);