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);
// The last video tag plus one frame (the interval from the tag before it), as the MPEG reader counts the last
// frame and as the metadata of the same stream say: es.Count frames at 30 per second, to the millisecond of the
// tag times.
static double Dts(int i) => Math.Round(i * 1000.0 / 30);
var expected = ((2 * Dts(es.Count - 1)) - Dts(es.Count - 2)) / 1000;
Assert.AreEqual(expected, es.Count / 30.0, 0.002, "the metadata of the same stream");
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.4, container.Duration!.Value.TotalSeconds, 1e-6, "dal primo tag alla fine dell'ultimo fotogramma: dieci da 40 ms");
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);
}
[TestMethod]
public void AnFlvIsAudioOnlyOnlyWithProofInItsHead()
{
using var temp = new TempFolder("flv-solo-audio");
// A header that says audio without video, an onMetaData larger than the 512 bytes of MediaSniffer.HeadLength and
// video tags after it: the head ends inside the metadata, which proves nothing, so it stays a video.
var video = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 4000, seconds: 3, videoFromMs: 500);
Assert.IsGreaterThan(MediaSniffer.HeadLength, video.Length);
Assert.IsFalse(FlvReader.IsAudioOnly(video.AsSpan(0, MediaSniffer.HeadLength)));
Assert.AreEqual(MediaKind.Video, MediaSniffer.DetectFile(TestVideos.Write(temp, "video.flv", video))?.Kind);
Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(Head(video))?.Kind);
Assert.IsNotNull(Read(video).Video, "il video c'è");
// The same with audio only: a whole file, or a head with five seconds of audio and no video tag, proves it; the
// first 512 bytes, or a head that holds only a little audio after the metadata, do not.
var audio = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 4000, seconds: 8);
Assert.IsTrue(FlvReader.IsAudioOnly(audio));
Assert.IsNull(MediaSniffer.Detect(Head(audio)));
Assert.IsTrue(FlvReader.IsAudioOnly(audio.AsSpan(0, audio.Length - 100)), "più di cinque secondi di solo audio");
Assert.AreEqual(MediaKind.Video, MediaSniffer.DetectFile(TestVideos.Write(temp, "audio.flv", audio))?.Kind);
var audioStart = 13 + 11 + ((audio[14] << 16) | (audio[15] << 8) | audio[16]) + 4; // after onMetaData
Assert.IsFalse(FlvReader.IsAudioOnly(audio.AsSpan(0, audioStart + (20 * 23) + 7)), "venti tag d'audio, mezzo secondo");
Assert.IsFalse(FlvReader.IsAudioOnly(audio.AsSpan(0, 13 + 11 + 3000)), "la testa finisce dentro i metadati");
// Video after five seconds of audio alone: a head that holds it sees the video tag.
var late = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 100, seconds: 8, videoFromMs: 6000);
Assert.IsFalse(FlvReader.IsAudioOnly(late));
}
[TestMethod]
public void WithoutADurationAnAudioFlvLastsUntilItsLastFrameEnds()
{
// onMetaData without a duration and no video: the last audio tag plus the interval from the one before it.
var audio = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 0, seconds: 2);
var last = (2000 - 1) / 26 * 26;
Assert.AreEqual((last + 26) / 1000.0, Read(audio, samples: false).Duration!.Value.TotalSeconds, 1e-6);
}
// ----- 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);
}
}