Files
Febe/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs
T
Alby96andClaude Opus 5.5 e61da9be23 E4: analizzatore dei video fermi scritto in casa (algoritmo 1)
StillVideoAnalyzer sostituisce VideoFrameDecoder.AnalyseStillness, che
confrontava solo con il primo fotogramma (una dissolvenza dal nero
risultava in movimento) e diluiva un adesivo nella media.

- Sette fotogrammi esatti, uno per settimo del video, spostati sul
  fotogramma chiave vicino (VideoFrameReader.LocateNearKey, nuovo).
- Griglia 32x32 di blocchi; dissolvenze annullate quando i rapporti dei
  blocchi concordano; fotogrammi neri messi da parte solo all'inizio o
  alla fine.
- Fermo se ogni fotogramma differisce dall'immagine ferma mediana per una
  media di al massimo 3 e per non più del 5 % dei blocchi (risposta 47:
  un piccolo adesivo o una scritta che si muove restano fermi; nota
  SmallMotion).
- Tutto nero o di un solo colore: Non analizzabile (risposta 42); anche
  codec non decodificato, file illeggibile, tempo oltre il limite.
- Il fotogramma scelto è il più nitido (varianza del laplaciano), mai
  uno scuro, con l'istante in millisecondi come le copie dei fotogrammi.

Prove su video costruiti dalle prove (PcmVideos) e sui flussi di
conformità; le prove della vecchia analisi sono spostate qui.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:44:32 +01:00

341 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <summary>
/// «È un video fermo?» (spec §4.10, tappa E4, algorithm 1) on videos the tests build (<see cref="PcmVideos"/>) 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.
/// </summary>
[TestClass]
public sealed class StillVideoAnalyzerTests
{
/// <summary>The time of picture <c>i</c> of a <see cref="PcmVideos"/> video in whole milliseconds, as FrameAt carries it.</summary>
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);
// A muted colour (a saturated one clips at white, and a fade of it cannot be undone).
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));
// 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.
var whole = PcmVideos.Mp4(30, _ => PcmVideos.Photo(18));
foreach (var length in new[] { whole.Length / 10, whole.Length / 2, whole.Length - 1000 })
{
var cut = Analyse(whole[..length]);
Assert.AreNotEqual(VideoAnalysisOutcome.Moving, cut.Outcome, $"{length}: {Describe(cut)}");
}
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<OperationCanceledException>(() => StillVideoAnalyzer.AnalyseAsync(path, TimeSpan.FromSeconds(30), cancelled.Token));
using var again = new MemoryStream(data);
Assert.ThrowsExactly<OperationCanceledException>(() => StillVideoAnalyzer.Analyse(again, TimeSpan.FromSeconds(30), cancelled.Token));
}
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}";
}