using System.Buffers.Binary; using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.H264; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Tests.Support; namespace Febe.Tests.Codecs.Containers; /// /// «È un video fermo?» (spec §4.10, tappa E4, algorithm 1) on videos the tests build () and on the /// ITU conformance streams: still pictures with grain, audio, fades, a small animated sticker or caption (answer 47), /// motion, very short clips, black and single-colour videos (answer 42), rotation, unreadable files and the time limit. /// [TestClass] public sealed class StillVideoAnalyzerTests { /// The time of picture i of a video in whole milliseconds, as FrameAt carries it. private static long Ms(int picture) => ExportFrames.ActualMs(TimeSpan.FromTicks(picture * TimeSpan.TicksPerSecond / PcmVideos.Fps)); [TestMethod] [DataRow(false)] [DataRow(true)] public void AFixedPictureIsStillWithOrWithoutAudio(bool audio) { var photo = PcmVideos.Photo(); var result = Analyse(PcmVideos.Mp4(30, _ => photo, audio: audio)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(audio, result.HasAudio); Assert.IsNull(result.Note); Assert.AreEqual(0, result.Difference); Assert.AreEqual(StillVideoAnalyzer.Samples, result.Sampled); Assert.AreEqual(1, result.Algorithm); // Seven equal parts of one second: the first one looked at is picture 2 (the nearest to 72 ms), never the very // first. Assert.AreEqual(Ms(2), result.FrameAtMs, "a parità di nitidezza il primo mostrato fra quelli guardati"); Assert.AreEqual(new VideoAnalysis("abc", 1, VideoAnalysisOutcome.Still, Make.T0, result.FrameAt, null), result.ToAnalysis("abc", Make.T0)); } [TestMethod] public void GrainIsNotMotion() { var photo = PcmVideos.Photo(2); var result = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 3, i))); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.IsNull(result.Note, "la grana non è una parte che si muove"); } [TestMethod] public void AFadeFromBlackIsStillAndTheFrameComesAfterIt() { // The first nine pictures fade in from black (picture 2, the first one looked at, at 22 %; picture 6 at 67 %); // the third one looked at is picture 11, the one nearest to 358 ms. var photo = PcmVideos.Photo(3); var result = Analyse(PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(photo, i / 9.0) : photo)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(Ms(11), result.FrameAtMs, "il più nitido: il primo a piena luce, non uno della dissolvenza"); } [TestMethod] public void AFadeToBlackAndBlackFramesAtBothEndsLeaveItStill() { var photo = PcmVideos.Photo(4); var fadeOut = Analyse(PcmVideos.Mp4(30, i => i >= 21 ? PcmVideos.Fade(photo, (29 - i) / 9.0) : photo)); Assert.AreEqual(VideoAnalysisOutcome.Still, fadeOut.Outcome, Describe(fadeOut)); Assert.IsLessThan(Ms(21), fadeOut.FrameAtMs!.Value); var black = Analyse(PcmVideos.Mp4(42, i => i is < 8 or >= 34 ? PcmVideos.Black() : photo)); Assert.AreEqual(VideoAnalysisOutcome.Still, black.Outcome, Describe(black)); Assert.IsGreaterThanOrEqualTo(Ms(8), black.FrameAtMs!.Value); Assert.IsLessThan(Ms(34), black.FrameAtMs.Value); } [TestMethod] public void BlackBetweenTwoPicturesIsMotion() { var photo = PcmVideos.Photo(5); var result = Analyse(PcmVideos.Mp4(30, i => i is >= 12 and < 18 ? PcmVideos.Black() : photo)); Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); Assert.IsNull(result.FrameAt); } [TestMethod] public void MotionIsMotion() { // The demo's moving gradient, a slow pan of a photo (2 pixels a picture) and a slideshow of two photos. using (var demo = new MemoryStream(H264PcmWriter.DemoVideo())) { var gradient = StillVideoAnalyzer.Analyse(demo, CancellationToken.None); Assert.AreEqual(VideoAnalysisOutcome.Moving, gradient.Outcome, Describe(gradient)); } var photo = PcmVideos.Photo(6); var pan = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Shift(photo, 2 * i))); Assert.AreEqual(VideoAnalysisOutcome.Moving, pan.Outcome, Describe(pan)); Assert.IsLessThan(StillVideoAnalyzer.Samples, pan.Sampled, "la prima coppia che si muove basta"); var other = PcmVideos.Photo(7); var slideshow = Analyse(PcmVideos.Mp4(30, i => i < 15 ? photo : other)); Assert.AreEqual(VideoAnalysisOutcome.Moving, slideshow.Outcome, Describe(slideshow)); } [TestMethod] public void ASmallStickerThatMovesLeavesTheVideoStill() { // 16 × 24 and 24 × 40 pixels (1 % and 2,6 % of the picture) crossing the photo, and 28 × 48 (3,6 %) animated in // place. var photo = PcmVideos.Photo(8); var crossing = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 4 * i, 100, 16, 24))); Assert.AreEqual(VideoAnalysisOutcome.Still, crossing.Outcome, Describe(crossing)); Assert.AreEqual(VideoAnalysisNotes.SmallMotion, crossing.Note); Assert.IsGreaterThan(0, crossing.MovingArea); Assert.IsLessThanOrEqualTo(StillVideoAnalyzer.AreaThreshold, crossing.MovingArea); var larger = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 4 * i, 100, 24, 40))); Assert.AreEqual(VideoAnalysisOutcome.Still, larger.Outcome, Describe(larger)); var animated = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 90, 20, 28, 48, i))); Assert.AreEqual(VideoAnalysisOutcome.Still, animated.Outcome, Describe(animated)); Assert.AreEqual(VideoAnalysisNotes.SmallMotion, animated.Note); } [TestMethod] public void ALargeStickerThatMovesIsMotion() { // 48 × 80 pixels: 10 % of the picture. var photo = PcmVideos.Photo(9); var result = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 3 * i, 90, 48, 80))); Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); } [TestMethod] public void AThinMovingCaptionLeavesTheVideoStillAndAWideOneMoves() { // One row of blocks (8 pixels of 256, 3 %) of scrolling letters; then a band of a quarter of the picture. var photo = PcmVideos.Photo(10); var thin = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Caption(photo, 232, 8, 5 * i))); Assert.AreEqual(VideoAnalysisOutcome.Still, thin.Outcome, Describe(thin)); Assert.AreEqual(VideoAnalysisNotes.SmallMotion, thin.Note); var wide = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Caption(photo, 160, 64, 5 * i))); Assert.AreEqual(VideoAnalysisOutcome.Moving, wide.Outcome, Describe(wide)); } [TestMethod] public void VeryShortClipsAreAnalysedFrameByFrame() { // 0,4 seconds: 12 pictures. var photo = PcmVideos.Photo(11); var same = Analyse(PcmVideos.Mp4(12, _ => photo)); Assert.AreEqual(VideoAnalysisOutcome.Still, same.Outcome, Describe(same)); Assert.AreEqual(StillVideoAnalyzer.Samples, same.Sampled); var other = PcmVideos.Photo(12); var changing = Analyse(PcmVideos.Mp4(12, i => i < 6 ? photo : other)); Assert.AreEqual(VideoAnalysisOutcome.Moving, changing.Outcome, Describe(changing)); // Two pictures in all: both are looked at. var two = Analyse(PcmVideos.Mp4(2, i => i == 0 ? photo : other)); Assert.AreEqual(VideoAnalysisOutcome.Moving, two.Outcome, Describe(two)); Assert.AreEqual(2, two.Sampled); } [TestMethod] public void AVideoOfOnePictureIsThatPicture() { var result = Analyse(PcmVideos.Mp4(1, _ => PcmVideos.Photo(13), audio: true)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(0L, result.FrameAtMs); Assert.AreEqual(1, result.Sampled); } [TestMethod] public void AllBlackAndAllOneColourAreNotAnalysable() { var black = Analyse(PcmVideos.Mp4(30, _ => PcmVideos.Black(), audio: true)); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, black.Outcome, Describe(black)); Assert.AreEqual(VideoAnalysisNotes.AllDark, black.Note); Assert.IsNull(black.FrameAt); var nearlyBlack = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(PcmVideos.Flat(24), 4, i))); Assert.AreEqual(VideoAnalysisNotes.AllDark, nearlyBlack.Note, Describe(nearlyBlack)); var oneBlack = Analyse(PcmVideos.Mp4(1, _ => PcmVideos.Black())); Assert.AreEqual(VideoAnalysisNotes.AllDark, oneBlack.Note, Describe(oneBlack)); var red = PcmVideos.Flat(81, 90, 240); var single = Analyse(PcmVideos.Mp4(30, _ => red)); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, single.Outcome, Describe(single)); Assert.AreEqual(VideoAnalysisNotes.SingleColor, single.Note); // Fading too, from black and to black: a muted colour, and white, near white, red, blue, green and yellow, which // clip or are too dark for a fade to be undone block by block. var brick = PcmVideos.Flat(110, 110, 170); var fading = Analyse(PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(brick, i / 9.0) : PcmVideos.Noise(brick, 2, i))); Assert.AreEqual(VideoAnalysisNotes.SingleColor, fading.Note, Describe(fading)); foreach (var (y, cb, cr) in new (byte, byte, byte)[] { (235, 128, 128), (235, 120, 136), (81, 90, 240), (41, 240, 110), (145, 54, 34), (210, 16, 146) }) { var colour = PcmVideos.Flat(y, cb, cr); foreach (var light in new Func[] { i => Math.Min(1, i / 9.0), i => Math.Min(1, i / 20.0), i => Math.Min(1, (29 - i) / 9.0) }) { var faded = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(colour, light(i)))); Assert.AreEqual(VideoAnalysisNotes.SingleColor, faded.Note, $"{y},{cb},{cr}: {Describe(faded)}"); } } // One colour after another: the picture changes. var blue = PcmVideos.Flat(41, 240, 110); var changing = Analyse(PcmVideos.Mp4(30, i => i < 15 ? red : blue)); Assert.AreEqual(VideoAnalysisOutcome.Moving, changing.Outcome, Describe(changing)); } [TestMethod] public void TheSharpestFrameIsChosen() { // Every picture softened but picture 15 (the fourth looked at): the cells are the same, the detail is not. var photo = PcmVideos.Photo(14); var soft = PcmVideos.Blur(photo); var result = Analyse(PcmVideos.Mp4(30, i => i == 15 ? photo : soft)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(Ms(15), result.FrameAtMs); Assert.IsGreaterThan(0, result.Sharpness); } [TestMethod] [DataRow(90)] [DataRow(270)] public void RotatedVideosAreAnalysedUpright(int rotation) { var photo = PcmVideos.Photo(15); var data = PcmVideos.Mp4(30, _ => photo, rotation: rotation); var still = Analyse(data); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); Assert.AreEqual(rotation, still.Rotation); // The chosen instant gives the frame upright, as «Salva il fotogramma» will save it. using var stream = new MemoryStream(data); using var reader = VideoFrameReader.Open(stream, out _); using var frame = reader.Decode(reader.Locate([still.FrameAt!.Value]), CancellationToken.None).Single(); Assert.AreEqual((PcmVideos.Height, PcmVideos.Width), (frame.Image.Width, frame.Image.Height)); Assert.AreEqual(still.FrameAtMs, ExportFrames.ActualMs(frame.Actual)); var moving = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Shift(photo, 3 * i), rotation: rotation)); Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, Describe(moving)); } [TestMethod] public void TheSameVideoGivesTheSameResult() { var photo = PcmVideos.Photo(16); var data = PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 3, i)); Assert.AreEqual(Analyse(data), Analyse(data)); } [TestMethod] public void TheInstantIsTheShownTimeAfterAnEmptyEdit() { // A QuickTime file whose video starts half a second late (an empty edit), as some phones write it. var photo = PcmVideos.Photo(17); var es = PcmVideos.Stream("pcm", 30, _ => photo); var result = Analyse(TestVideos.Mov(es, new MovOptions(VideoEmptyEdit: TestVideos.Timescale / 2))); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.IsGreaterThanOrEqualTo(500L, result.FrameAtMs!.Value); } [TestMethod] public void ConformanceStreamsOfAStillPictureAndOfMotion() { var still = Analyse(TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D").FirstPictureRepeated(90))); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); Assert.AreEqual(0, still.Difference); foreach (var name in new[] { "CABA3_SVA_B", "FRExt1_Panasonic_D" }) { var moving = Analyse(TestVideos.Mp4(ElementaryStream.Load(name))); Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}"); } } [TestMethod] public void HevcVideosOfAStillPictureAndOfMotion() { var still = Analyse(TestVideos.Mp4(ElementaryStream.LoadHevc("INITQP_A_Sony_1").FirstPictureRepeated(90))); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); Assert.AreEqual(0, still.Difference); var moving = Analyse(TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4"))); Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, Describe(moving)); } [TestMethod] public async Task UnreadableVideosAreNotAnalysableAndNeverThrow() { Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, Analyse(new byte[4096]).Note); byte[] junk = [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1]; Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, Analyse(junk).Note); // A codec Febe does not decode. var vp9 = Analyse(TestVideos.Matroska(ElementaryStream.Load("BA1_Sony_D"), codecId: "V_VP9")); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, vp9.Outcome); Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, vp9.Note); // Cut short anywhere: never an exception, and never «Fermo» from frames that are not there. Past the last frame // looked at nothing is missing. var whole = PcmVideos.Mp4(30, _ => PcmVideos.Photo(18)); foreach (var tenths in new[] { 1, 3, 5, 9 }) { var cut = Analyse(whole[..(whole.Length * tenths / 10)]); Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.Unreadable), (cut.Outcome, cut.Note), $"{tenths}/10: {Describe(cut)}"); Assert.IsNull(cut.FrameAt); } var nearlyWhole = Analyse(whole[..^1000]); Assert.AreEqual(VideoAnalysisOutcome.Still, nearlyWhole.Outcome, Describe(nearlyWhole)); // A video that changes at picture 14: «Fermo» from its first part would be false. Motion already seen stands. var before = PcmVideos.Photo(18); var after = PcmVideos.Photo(27); var changing = PcmVideos.Stream("pcm", 30, i => i < 14 ? before : after); var full = TestVideos.Mp4(changing); Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(full).Outcome); var half = Analyse(full[..(full.Length * 4 / 10)]); Assert.AreEqual(VideoAnalysisNotes.Unreadable, half.Note, Describe(half)); Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(full[..(full.Length * 8 / 10)]).Outcome); for (var i = 12; i < changing.Count; i++) { changing.Units[i] = [.. changing.Units[i].Select(n => n[..Math.Min(n.Length, 6)])]; } var damaged = Analyse(TestVideos.Mp4(changing)); Assert.AreEqual(VideoAnalysisNotes.Unreadable, damaged.Note, Describe(damaged)); using var temp = new TempFolder("fermo-illeggibile"); var missing = await StillVideoAnalyzer.AnalyseAsync(temp.Combine("non-esiste.mp4"), TimeSpan.FromSeconds(30)); Assert.AreEqual(VideoAnalysisNotes.Unreadable, missing.Note); } [TestMethod] public async Task PastTheBudgetItIsTooSlowButTheCallerCanStillCancel() { var data = PcmVideos.Mp4(30, _ => PcmVideos.Photo(19)); using (var stream = new MemoryStream(data)) { var late = StillVideoAnalyzer.Analyse(stream, TimeSpan.Zero, CancellationToken.None); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, late.Outcome); Assert.AreEqual(VideoAnalysisNotes.TooSlow, late.Note); Assert.AreEqual(0, late.Sampled, "un tempo zero annulla subito"); } using var temp = new TempFolder("fermo-tempo"); var path = TestVideos.Write(temp, "video.mp4", data); Assert.AreEqual(VideoAnalysisOutcome.Still, (await StillVideoAnalyzer.AnalyseAsync(path, TimeSpan.FromMinutes(2))).Outcome); using var cancelled = new CancellationTokenSource(); await cancelled.CancelAsync(); await Assert.ThrowsAsync(() => StillVideoAnalyzer.AnalyseAsync(path, TimeSpan.FromSeconds(30), cancelled.Token)); using var again = new MemoryStream(data); Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(again, TimeSpan.FromSeconds(30), cancelled.Token)); } [TestMethod] [DataRow(2)] [DataRow(3)] public void AClipOfAFewEqualPicturesIsStill(int pictures) { // 0,07 and 0,1 seconds: every picture is looked at. var photo = PcmVideos.Photo(20); var result = Analyse(PcmVideos.Mp4(pictures, _ => photo, audio: true)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(pictures, result.Sampled); Assert.AreEqual(0L, result.FrameAtMs, "the first of equally sharp ones"); } [TestMethod] public void StrongGrainAndAPulsingLightAreNotMotion() { var photo = PcmVideos.Photo(21); var grain = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 8, 500 + i))); Assert.AreEqual(VideoAnalysisOutcome.Still, grain.Outcome, Describe(grain)); Assert.IsNull(grain.Note); // The light goes from full to 60 % and back, twice: the frame chosen is one at (nearly) full light. double Light(long i) => 0.8 + (0.2 * Math.Cos(i * 4 * Math.PI / 30)); var pulsing = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(photo, Light(i)))); Assert.AreEqual(VideoAnalysisOutcome.Still, pulsing.Outcome, Describe(pulsing)); Assert.IsGreaterThan(0.85, Light(pulsing.FrameAtMs!.Value * PcmVideos.Fps / 1000), Describe(pulsing)); } [TestMethod] public void ANightPhotoIsStillNotAllDark() { // Black all over but a lit sign of 16 × 16 pixels: a picture, not a black video (answer 42). var night = PcmVideos.Sticker(PcmVideos.Black(), 60, 100, 16, 16); var result = Analyse(PcmVideos.Mp4(30, _ => night)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.IsNull(result.Note); } [TestMethod] public void ADarkFrameIsNeverChosenEvenWhenItsGrainIsSharper() { // Nine nearly black pictures full of grain (a camera that starts in the dark), then a soft gradient with no // detail: the Laplacian of the grain is larger, yet «Salva il fotogramma» must never save black (answer 45). var soft = PcmVideos.Flat(120); for (var y = 0; y < PcmVideos.Height; y++) { for (var x = 0; x < PcmVideos.Width; x++) { soft.Y[(y * PcmVideos.Width) + x] = (byte)(60 + ((x + y) / 4)); } } H264PcmPicture Dark(int i) => PcmVideos.Noise(PcmVideos.Black(), 12, 900 + i); var result = Analyse(PcmVideos.Mp4(30, i => i < 9 ? Dark(i) : soft)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.IsGreaterThanOrEqualTo(Ms(9), result.FrameAtMs!.Value, Describe(result)); // The grain is a real trap (the same grain on a grey that is not dark is far sharper than the gradient), and a // video of it alone is all dark: no frame to save. var lit = Analyse(PcmVideos.Mp4(9, i => PcmVideos.Noise(PcmVideos.Sticker(PcmVideos.Flat(60), 60, 100, 16, 16), 6, 900 + i))); Assert.AreEqual(VideoAnalysisOutcome.Still, lit.Outcome, Describe(lit)); Assert.IsGreaterThan(result.Sharpness, lit.Sharpness); var dark = Analyse(PcmVideos.Mp4(9, Dark)); Assert.AreEqual(VideoAnalysisNotes.AllDark, dark.Note, Describe(dark)); Assert.IsNull(dark.FrameAt); } [TestMethod] public void AVideoHalfTurnedIsUprightToo() { var photo = PcmVideos.Photo(22); var result = Analyse(PcmVideos.Mp4(12, _ => photo, rotation: 180)); Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); Assert.AreEqual(180, result.Rotation); } [TestMethod] public void TheContainerDoesNotChangeTheOutcome() { var photo = PcmVideos.Photo(23); var still = PcmVideos.Stream("pcm", 30, _ => photo); var pan = PcmVideos.Stream("pcm", 30, i => PcmVideos.Shift(photo, 3 * i)); foreach (var (name, build) in new (string, Func)[] { ("MOV", es => TestVideos.Mov(es)), ("MP4 a frammenti", es => TestVideos.FragmentedMp4(es)), ("Matroska", es => TestVideos.Matroska(es)), ("AVI (i parametri in ogni fotogramma chiave, come si scrive un AVI)", es => TestVideos.Avi(es.WithParameterSetsEverywhere())), }) { var fixedPicture = Analyse(build(still)); Assert.AreEqual(VideoAnalysisOutcome.Still, fixedPicture.Outcome, $"{name}: {Describe(fixedPicture)}"); Assert.IsNotNull(fixedPicture.FrameAt, name); var moving = Analyse(build(pan)); Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}"); } } [TestMethod] public void AVideoWithNoDurationIsNotAnalysable() { // Two samples at the same time, and headers that say zero: nothing tells how long the video is. var es = PcmVideos.Stream("pcm", 2, i => PcmVideos.Photo(24 + i)); var track = new Mp4OutputTrack { IsVideo = true, Timescale = TestVideos.Timescale, Samples = [.. Enumerable.Range(0, 2).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, 0, 0, true))], WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), Width = es.Width, Height = es.Height, AvcConfiguration = es.AvcC, }; using var output = new MemoryStream(); Mp4Writer.Write(output, [track]); var result = Analyse(output.ToArray()); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, result.Outcome, Describe(result)); Assert.AreEqual(VideoAnalysisNotes.DurationUnknown, result.Note); } [TestMethod] public void ADamagedStreamIsUnreadableNeverStillFromOneFrame() { // The headers are whole, the pictures are cut to a few bytes, all but the first: one frame alone says nothing of // the video. var es = PcmVideos.Stream("pcm", 30, _ => PcmVideos.Photo(26)); for (var i = 3; i < es.Count; i++) { es.Units[i] = [.. es.Units[i].Select(n => n[..Math.Min(n.Length, 6)])]; } var result = Analyse(TestVideos.Mp4(es)); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, result.Outcome, Describe(result)); Assert.AreEqual(VideoAnalysisNotes.Unreadable, result.Note); } [TestMethod] public void EveryThresholdIsTheOneAgreed() { // Answer 44 of Alberto (29 November 2026) and docs/decisioni.md: a change raises Algorithm, so that the videos // already analysed are known as of the older rule. Assert.AreEqual( (1, 7, 32, 32.0, 2.0, 12.0, 3.0, 0.05), (StillVideoAnalyzer.Algorithm, StillVideoAnalyzer.Samples, StillVideoAnalyzer.GridSize, StillVideoAnalyzer.DarkLevel, StillVideoAnalyzer.UniformSpread, StillVideoAnalyzer.BlockThreshold, StillVideoAnalyzer.MeanThreshold, StillVideoAnalyzer.AreaThreshold)); Assert.AreEqual( (128, 4, 3.0, 16.0, 0.1, 8.0, 0.1), (StillVideoAnalyzer.FineGridSize, StillVideoAnalyzer.FineCell, StillVideoAnalyzer.EarlyAreaFactor, StillVideoAnalyzer.GainFloor, StillVideoAnalyzer.GainAgreement, StillVideoAnalyzer.GainRange, StillVideoAnalyzer.ClippedShare)); Assert.AreEqual( (250, 0.25, 96, 64.0, 32.0, 0.0002, TimeSpan.FromSeconds(1e9)), (StillVideoAnalyzer.White, StillVideoAnalyzer.ChromaWeight, StillVideoAnalyzer.BrightDetail, StillVideoAnalyzer.UniformVariance, StillVideoAnalyzer.UniformDetail, StillVideoAnalyzer.DetailShare, StillVideoAnalyzer.LatestInstant)); CollectionAssert.AreEqual(new[] { 0.4173, 0.3611, 0.6237, 0.5, 0.6619, 0.3307, 0.5521 }, StillVideoAnalyzer.Offsets); } [TestMethod] public void TheColourCountsToo() { // Half of the photo turns from bluish to reddish with the same luma. var photo = PcmVideos.Photo(28); var tinted = PcmVideos.Copy(photo); for (var i = 0; i < tinted.Cb.Length / 2; i++) { (tinted.Cb[i], tinted.Cr[i]) = (90, 190); } var result = Analyse(PcmVideos.Mp4(30, i => i < 15 ? photo : tinted)); Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); } [TestMethod] [DataRow(7)] [DataRow(14)] [DataRow(16)] public void AClipRepeatedManyTimesIsMotion(int times) { // A GIF or a boomerang repeated: its key frames come back at every repetition, and equal steps fall on the same // picture of it when the number of repetitions is a multiple of the frames looked at. var clip = ElementaryStream.AnnexB("CABA3_SVA_B"); var loop = Analyse(TestVideos.Mp4(ElementaryStream.FromAnnexB("ripetuto", [.. Enumerable.Repeat(clip, times).SelectMany(b => b)]))); Assert.AreEqual(VideoAnalysisOutcome.Moving, loop.Outcome, Describe(loop)); var photo = PcmVideos.Photo(29); var boomerang = Analyse(PcmVideos.Mp4(20 * times, i => PcmVideos.Shift(photo, 4 * (i % 20 < 10 ? i % 20 : 19 - (i % 20))))); Assert.AreEqual(VideoAnalysisOutcome.Moving, boomerang.Outcome, Describe(boomerang)); } [TestMethod] [DataRow(0.0)] [DataRow(0.015)] [DataRow(0.025)] public void MotionOverAWhiteAreaIsSeenWhileTheLightDrifts(double step) { // The upper half is burnt out (a sky, a wall), the ground below brightens a little at each frame as the exposure // adjusts itself: what moves over the white is still motion. byte[] Video(Func over, int luma) => PcmVideos.Large(256, 256, 7, k => PcmVideos.Grey(256, 256, (x, y) => y >= 120 ? 16 + ((1 + (step * k)) * (40 + (x * 60.0 / 256) + ((y - 120) * 60.0 / 256))) : over(k, x, y) ? luma : 235)); foreach (var luma in new[] { 40, 120 }) { var crossing = Analyse(Video((k, x, y) => x >= k * 20 && x < (k * 20) + 100 && y is >= 8 and < 108, luma)); Assert.AreEqual(VideoAnalysisOutcome.Moving, crossing.Outcome, Describe(crossing)); } var covered = Analyse(Video((k, x, _) => k == 3 && x < 220, 40)); Assert.AreEqual(VideoAnalysisOutcome.Moving, covered.Outcome, Describe(covered)); // Nothing moves over it: the drift alone is no motion. var still = Analyse(Video((_, x, y) => x is >= 60 and < 160 && y is >= 8 and < 108, 40)); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); } [TestMethod] public void AWhiteOrSaturatedCardWithAFadeIsStill() { foreach (var (y, cb, cr) in new (byte, byte, byte)[] { (235, 128, 128), (81, 90, 240), (225, 128, 128) }) { foreach (var share in new[] { 0.1, 0.15, 0.3 }) { var poster = PcmVideos.Poster(y, cb, cr, share); foreach (var pictures in new[] { 4.0, 9.0 }) { var faded = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(poster, Math.Min(1, i / pictures)))); Assert.AreEqual(VideoAnalysisOutcome.Still, faded.Outcome, $"{y},{cb},{cr}, {share}, {pictures}: {Describe(faded)}"); Assert.IsNull(faded.Note, Describe(faded)); } } } // A white card with black text, five seconds. var card = PcmVideos.Grey(PcmVideos.Width, PcmVideos.Height, (x, y) => y is > 80 and < 170 && y / 6 % 2 == 0 && x is > 20 and < 124 && x / 5 % 2 == 0 ? 20 : 235); var text = Analyse(PcmVideos.Mp4(150, i => PcmVideos.Fade(card, Math.Min(1, i / 30.0)))); Assert.AreEqual(VideoAnalysisOutcome.Still, text.Outcome, Describe(text)); } [TestMethod] public void OnePictureAmongDarkFramesSaysNothingOfTheVideo() { // Only one of the seven frames is not dark, but the lit part is full of different pictures. foreach (var (name, picture) in new (string, Func)[] { ("nero, poi foto", i => i < 60 ? PcmVideos.Black() : PcmVideos.Photo(i + 1)), ("foto, poi nero", i => i >= 10 ? PcmVideos.Black() : PcmVideos.Photo(i + 1)), ("notte, poi luce", i => PcmVideos.Fade(PcmVideos.Photo(i + 1), i < 60 ? 0.06 : 1)), }) { var moving = Analyse(PcmVideos.Mp4(70, picture)); Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}"); Assert.IsGreaterThan(StillVideoAnalyzer.Samples, moving.Sampled, "guardati anche quelli intorno"); } // The same lit part with one picture is still; one picture only, alone among black ones, is not. var photo = PcmVideos.Photo(30); var still = Analyse(PcmVideos.Mp4(70, i => i < 60 ? PcmVideos.Black() : photo)); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); Assert.IsGreaterThanOrEqualTo(Ms(60), still.FrameAtMs!.Value); var flash = Analyse(PcmVideos.Mp4(70, i => i == 35 ? photo : PcmVideos.Black())); Assert.AreEqual(VideoAnalysisNotes.AllDark, flash.Note, Describe(flash)); // Unless it is all the video shows there: a picture held for ten seconds between two black ones. var held = Analyse(Timed([(PcmVideos.Black(), 0.1), (photo, 10), (PcmVideos.Black(), 0.1)])); Assert.AreEqual(VideoAnalysisOutcome.Still, held.Outcome, Describe(held)); Assert.AreEqual(100L, held.FrameAtMs); } [TestMethod] public void PicturesShownForAMomentAfterAHeldOneAreLookedAtToo() { // A picture held for a minute, then 20 different ones in two thirds of a second: every instant falls on the first. var pictures = Enumerable.Range(0, 20).Select(i => (PcmVideos.Photo(40 + i), 1.0 / PcmVideos.Fps)); var result = Analyse(Timed([(PcmVideos.Photo(31), 60), .. pictures])); Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); } [TestMethod] public void TheInstantsAreSpreadOverWhatTheVideoTrackShows() { // Two seconds of motion in a file that says half a minute or more (a longer audio track, a wrong header). var two = TestVideos.Mp4(PcmVideos.Stream("pcm", 60, i => PcmVideos.Photo(i + 1)), audio: true); foreach (var seconds in new[] { 29, 40 }) { var longer = Analyse(WithMovieDuration(two, seconds)); Assert.AreEqual(VideoAnalysisOutcome.Moving, longer.Outcome, $"{seconds}: {Describe(longer)}"); } // And in one that says half a second only. var late = PcmVideos.Photo(32); var early = PcmVideos.Photo(33); var shorter = Analyse(WithMovieDuration(TestVideos.Mp4(PcmVideos.Stream("pcm", 60, i => i < 30 ? early : late)), 0.5)); Assert.AreEqual(VideoAnalysisOutcome.Moving, shorter.Outcome, Describe(shorter)); // Ten seconds of motion trimmed by the edit list to half a second, with ten seconds of audio. var ten = PcmVideos.Stream("pcm", 300, i => PcmVideos.Photo((i % 60) + 1)); var trimmed = Analyse(TestVideos.Mov(ten, new MovOptions(VideoTrim: TestVideos.Timescale / 2, Audio: true))); Assert.AreEqual(VideoAnalysisOutcome.Moving, trimmed.Outcome, Describe(trimmed)); } [TestMethod] public void AnErrorOfTheDiskIsThrownNeverAnOutcome() { // 25 equal pictures, then motion: whole it moves. Read past a point the disk (or the share) gives an error. var data = PcmVideos.Mp4(60, i => PcmVideos.Photo(i < 25 ? 1 : i)); Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(data).Outcome); foreach (var from in new[] { 100, data.Length / 5, data.Length * 3 / 10, data.Length * 4 / 10 }) { using var failing = new FailingStream(data, from); var error = Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(failing, CancellationToken.None), $"{from}"); Assert.AreEqual("rete", error.Message); using var denied = new FailingStream(data, from, new UnauthorizedAccessException("negato")); Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(denied, CancellationToken.None), $"{from}"); } } [TestMethod] public void FineMotionOverTheWholePictureIsMotion() { // At 720 × 1280 a block averages about 900 pixels: static and snow leave its mean as it is. const int w = 720, h = 1280; var noise = Analyse(PcmVideos.Large(w, h, 7, i => { var random = new Random(i); return PcmVideos.Grey(w, h, (_, _) => random.Next(16, 236)); })); Assert.AreEqual(VideoAnalysisOutcome.Moving, noise.Outcome, Describe(noise)); byte[] Snow(int flakes) => PcmVideos.Large(w, h, 7, i => { var random = new Random(i); var p = PcmVideos.Grey(w, h, (_, y) => 90 + (y * 60.0 / h)); for (var flake = 0; flake < flakes; flake++) { var at = (random.Next(h - 4) * w) + random.Next(w - 4); for (var row = 0; row < 4; row++) { p.Y.AsSpan(at + (row * w), 4).Fill(230); } } return p; }); var thick = Analyse(Snow(1000)); Assert.AreEqual(VideoAnalysisOutcome.Moving, thick.Outcome, Describe(thick)); // Sparse flakes change less than 5 % of the picture (answer 47): still, and the note says so. var sparse = Analyse(Snow(300)); Assert.AreEqual((VideoAnalysisOutcome.Still, VideoAnalysisNotes.SmallMotion), (sparse.Outcome, sparse.Note), Describe(sparse)); // Grain, even strong, is not motion at this size either. var grain = Analyse(PcmVideos.Large(w, h, 7, i => { var random = new Random(i); return PcmVideos.Grey(w, h, (x, y) => 60 + (x * 80.0 / w) + (y * 60.0 / h) + (((x / 40) + (y / 40)) % 2 * 20) + random.Next(-12, 13)); })); Assert.AreEqual((VideoAnalysisOutcome.Still, null), (grain.Outcome, grain.Note), Describe(grain)); } [TestMethod] public void ASmallTextOrAFineTextureIsAPicture() { const int w = 720, h = 1280, size = 14; H264PcmPicture Text(int ground, int ink) => PcmVideos.Grey(w, h, (x, y) => { var (line, column) = (y - (h / 2), x - 150); var letter = line is >= 0 and < size && column is >= 0 and < 160 && (column % 8 < 2 || (line < 2 && column % 8 < 6)); return letter ? ink : ground; }); foreach (var (name, picture) in new[] { ("bianca su nero", Text(16, 235)), ("nera su bianco", Text(235, 16)) }) { var writing = Analyse(PcmVideos.Large(w, h, 7, _ => picture)); Assert.AreEqual(VideoAnalysisOutcome.Still, writing.Outcome, $"{name}: {Describe(writing)}"); } // A texture of two pixels: fixed it is a picture, panning it moves. const int columns = (w + 300) / 2; var random = new Random(3); var grains = Enumerable.Range(0, columns * (h / 2)).Select(_ => random.Next(-40, 41)).ToArray(); H264PcmPicture Texture(int shift) => PcmVideos.Grey(w, h, (x, y) => 120 + grains[(y / 2 * columns) + ((x + shift) / 2)]); var texture = Texture(0); var still = Analyse(PcmVideos.Large(w, h, 7, _ => texture)); Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); var panning = Analyse(PcmVideos.Large(w, h, 7, i => Texture(37 * i))); Assert.AreEqual(VideoAnalysisOutcome.Moving, panning.Outcome, Describe(panning)); } [TestMethod] public void ACancellationIsSeenWhileTheStartOfDecodingIsLookedFor() { // Every sample says it is a key one and only the first is: each is read to find that out. var es = ElementaryStream.Load("HPCVMOLQ_BRCM_B"); Array.Fill(es.Key, true); var data = TestVideos.Mp4(es); using var source = new CancellationTokenSource(); using var stream = new FailingStream(data, data.Length + 1); using var reader = VideoFrameReader.Open(stream, out var info); Assert.IsTrue(info.Available); var target = reader.Locate([info.Duration]); var reads = 0; stream.OnRead = () => { if (++reads == 3) { source.Cancel(); } }; Assert.ThrowsExactly(() => reader.Decode(target, source.Token).ToList()); Assert.AreEqual(3, reads, "nessun altro campione letto dopo l'annullamento"); // And while the container is read. using var again = new MemoryStream(data); Assert.ThrowsExactly(() => VideoFrameReader.Open(again, out _, source.Token)); } [TestMethod] public void AHostileStartTimeIsNotAnInstant() { // One picture after an empty edit of 2^40 seconds: its shown time is past what a TimeSpan holds. var data = TestVideos.Mov(PcmVideos.Stream("pcm", 1, _ => PcmVideos.Photo()), new MovOptions(VideoEmptyEdit: TestVideos.Timescale)); var movie = data.AsSpan().IndexOf("mvhd"u8) + 4; BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(movie + (data[movie] == 1 ? 20 : 12)), 1); var edits = data.AsSpan().IndexOf("elst"u8) + 4; Assert.AreEqual(1, data[edits], "la versione a 64 bit, come la scrive TestVideos.Mov"); BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(edits + 8), 1UL << 40); var result = Analyse(data); Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.DurationUnknown), (result.Outcome, result.Note), Describe(result)); Assert.IsNull(result.FrameAt); Assert.AreEqual(TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond, ExportFrames.ActualMs(TimeSpan.MaxValue)); Assert.AreEqual(1L, ExportFrames.ActualMs(TimeSpan.FromTicks(1))); } /// An MP4 of pictures held for as long as each says, in seconds. private static byte[] Timed((H264PcmPicture Picture, double Seconds)[] pictures) { var es = PcmVideos.Stream("pcm", pictures.Length, i => pictures[i].Picture); var times = pictures.Select((_, i) => (long)Math.Round(pictures.Take(i).Sum(p => p.Seconds) * TestVideos.Timescale)).ToArray(); var track = new Mp4OutputTrack { IsVideo = true, Timescale = TestVideos.Timescale, Samples = [.. times.Select((at, i) => new Mp4OutputSample(es.LengthPrefixed(i).Length, at, at, true))], WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), Width = es.Width, Height = es.Height, AvcConfiguration = es.AvcC, }; using var output = new MemoryStream(); Mp4Writer.Write(output, [track]); return output.ToArray(); } /// The MP4 with the length its movie header says replaced. private static byte[] WithMovieDuration(byte[] mp4, double seconds) { var data = (byte[])mp4.Clone(); var body = data.AsSpan().IndexOf("mvhd"u8) + 4; var at = body + (data[body] == 1 ? 20 : 12); var length = (ulong)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(at)) * seconds); if (data[body] == 1) { BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(at + 4), length); } else { BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(at + 4), (uint)length); } return data; } /// A stream that cannot be read past a point, as a file on a share that went. private sealed class FailingStream(byte[] data, long from, Exception? error = null) : MemoryStream(data) { public Action? OnRead { get; set; } // A MemoryStream that is extended reads spans through here too. public override int Read(byte[] buffer, int offset, int count) { OnRead?.Invoke(); return Position + count > from ? throw error ?? new IOException("rete") : base.Read(buffer, offset, count); } } private static StillVideoResult Analyse(byte[] video) { using var stream = new MemoryStream(video); return StillVideoAnalyzer.Analyse(stream, CancellationToken.None); } private static string Describe(StillVideoResult r) => $"{r.Outcome} nota {r.Note ?? "-"} istante {r.FrameAtMs?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"} " + $"guardati {r.Sampled} differenza {r.Difference} area {r.MovingArea} nitidezza {r.Sharpness}"; }