E4: video fermi nella dimostrazione

La dimostrazione ha ora due video fermi veri: il video più recente di
@marta.demo e la storia video più recente di un altro account sono la
loro copertina ferma per 2 secondi dopo una breve dissolvenza dal nero
(H264PcmWriter.DemoStillVideo e FromRgba, scritti in casa). Ognuno ha il
suo file, registrato con la sua impronta vera, e un'analisi «Fermo» data
dall'analizzatore vero: così il filtro «Video fermi», «Salva il
fotogramma» con «Scarica» e «Nella cartella delle copie» (dal motore
vero) funzionano. Il video dopo di @marta.demo è «In movimento», quello
dopo ancora «Non analizzabile» (troppo lento); gli altri non sono mai
analizzati, così «È un video fermo?» e «Cerca i video fermi» lavorano
davvero. Nella sola dimostrazione il servizio non controlla l'impronta
prima di analizzare (VerifySource), perché gli altri video condividono
un file che si muove. Prove in DemoStillVideoTests; riga in LEGGIMI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-29 16:15:41 +01:00
1 parent 78502e9c14
commit 5eec9cc22a
8 files changed
+517 -3

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Library.StillVideos;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// The still videos of the demo (spec §4.10 «Video fermi», §10.6, tappa E4): two videos that are their cover picture
/// alone, each in its own file with its own SHA-256, found «Fermo» by the real analyser; one «In movimento», one
/// «Non analizzabile»; «È un video fermo?», the filter «Video fermi», «Salva il fotogramma» («Scarica» and «Nella
/// cartella delle copie») and «Cerca i video fermi» all work on the demo. Videos built here, never real ones.
/// </summary>
[TestClass]
public sealed class DemoStillVideoTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheDemoStillVideoIsItsPictureAfterAFade()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("demo-fermo-file");
var cover = Path.Combine(temp.Path, "copertina.jpg");
File.WriteAllBytes(cover, DemoImages.Render(DemoSubject.Sea, 7, 720, 1280));
var bytes = DemoStillVideos.StillVideo(cover);
CollectionAssert.AreEqual(bytes, DemoStillVideos.StillVideo(cover), "the same picture gives the same file");
using var stream = new MemoryStream(bytes, writable: false);
var result = StillVideoAnalyzer.Analyse(stream, ct);
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, result.ToString());
Assert.IsNull(result.Note, "nothing moves");
Assert.IsFalse(result.HasAudio);
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(2.0 / H264PcmWriter.DemoFps), result.FrameAt!.Value, "the frame comes after the fade");
// The first picture is nearly black, the chosen frame is the cover picture (its colours, on average).
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available);
Assert.AreEqual(TimeSpan.FromSeconds(2), info.Duration);
var frames = reader.Decode(reader.Locate([TimeSpan.Zero, result.FrameAt.Value]), ct).OrderBy(f => f.Index).ToList();
try
{
Assert.AreEqual((H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight), (frames[1].Image.Width, frames[1].Image.Height));
Assert.IsLessThan(20.0, Mean(frames[0].Image).Max(), "a dark picture first");
using var picture = ImageDecoder.Decode(File.ReadAllBytes(cover));
var expected = Mean(picture);
var actual = Mean(frames[1].Image);
for (var c = 0; c < 3; c++)
{
Assert.AreEqual(expected[c], actual[c], 8.0, $"channel {c}: {string.Join(", ", expected)} / {string.Join(", ", actual)}");
}
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheDemoFindsSavesAndSearchesStillVideos()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("demo-fermi");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) };
var origin = demo.Address.GetLeftPart(UriPartial.Authority);
async Task<(HttpStatusCode Status, JsonElement Body)> SendAsync(HttpMethod method, string path, object? body = null)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation("Origin", origin);
if (body is not null)
{
request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
}
using var response = await client.SendAsync(request, ct);
var text = await response.Content.ReadAsStringAsync(ct);
return (response.StatusCode, text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone());
}
async Task<JsonElement> OkAsync(HttpMethod method, string path, object? body = null)
{
var (status, answer) = await SendAsync(method, path, body);
Assert.AreEqual(HttpStatusCode.OK, status, $"{method} {path}: {answer}");
return answer;
}
async Task WaitAsync(string path, string what)
{
for (var i = 0; i < 600; i++)
{
if (!(await OkAsync(HttpMethod.Get, path)).Bool("running"))
{
return;
}
await Task.Delay(100, ct);
}
Assert.Fail(what);
}
// Two still files, each recorded with its own SHA-256 and served for its video.
Assert.HasCount(2, demo.World.StillVideoFiles);
foreach (var (sha, path) in demo.World.StillVideoFiles)
{
Assert.AreEqual(sha, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path, ct))));
StringAssert.StartsWith(Path.GetFileName(path), "video-fermo-dimostrativo-");
}
// «Video fermi»: the newest video of @marta.demo and a story of another account, from a «Fermo» analysis.
var accounts = (await OkAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").ToList();
var marta = accounts.Single(a => a.Str("username") == DemoStillVideos.StillAccount).Long("id");
var tiles = (await OkAsync(HttpMethod.Get, "/api/library?kind=stillvideos&limit=100")).Items("tiles").ToList();
Assert.HasCount(2, tiles, string.Join(", ", tiles));
Assert.AreEqual(1, tiles.Count(t => t.Long("accountId") == marta));
var stillEntries = new List<(long Entry, JsonElement Media)>();
foreach (var tile in tiles)
{
var entry = await OkAsync(HttpMethod.Get, $"/api/entries/{tile.Long("id")}");
var video = entry.Items("media").Single(m => m.GetProperty("still").ValueKind == JsonValueKind.Object);
var still = video.GetProperty("still");
Assert.AreEqual("still", still.Str("outcome"), still.ToString());
Assert.IsTrue(still.Bool("current"));
Assert.IsGreaterThanOrEqualTo(2_000L / H264PcmWriter.DemoFps, still.Long("frameAtMs"), "after the fade");
Assert.IsTrue(video.Bool("framesAvailable"), video.ToString());
stillEntries.Add((tile.Long("id"), video));
}
var stories = await Task.WhenAll(stillEntries.Select(async s => (await demo.Storage.Entries.GetAsync(s.Entry, ct))!));
Assert.AreEqual(1, stories.Count(e => e.Kind == EntryKind.Story && e.AccountId != marta), "a story of another account");
Assert.HasCount(1, (await OkAsync(HttpMethod.Get, $"/api/library?kind=stillvideos&mode=files&accounts={marta}&limit=100")).Items("tiles").ToList());
// «Salva il fotogramma» → «Scarica»: a PNG named «…_fotogramma.png», the frame the analysis chose, never a dark one.
var (_, stillMedia) = stillEntries.Single(s => stories.Single(e => e.Id == s.Entry).AccountId == marta);
var mediaId = stillMedia.Long("id");
using (var response = await client.GetAsync($"/api/media/{mediaId}/still/frame?format=png&download=1", ct))
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync(ct));
var name = response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName?.Trim('"');
Assert.IsTrue(name?.EndsWith("_fotogramma.png", StringComparison.Ordinal), name);
using var png = ImageDecoder.Decode(await response.Content.ReadAsByteArrayAsync(ct));
Assert.AreEqual((H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight), (png.Width, png.Height));
Assert.IsGreaterThan(40.0, Mean(png).Max(), "not a dark frame");
}
// «Nella cartella delle copie»: the real engine writes it in «Disco USB» (the file's SHA-256 is the one recorded).
var request = new { mediaIds = new[] { mediaId }, frames = new { mode = "fermo", format = "png" } };
var plan = await OkAsync(HttpMethod.Post, "/api/export/plan", request);
Assert.AreEqual((1, 1, 0), (plan.Int("videos"), plan.Int("frames"), plan.Int("notStill")), plan.ToString());
await OkAsync(HttpMethod.Post, "/api/export/start", request);
await WaitAsync("/api/export/progress", "the copy did not end");
var general = (await demo.Storage.Exports.GetGeneralDestinationAsync(ct))!;
var stillSha = (await demo.Storage.Media.GetAsync(mediaId, ct))!.Sha256!;
var copy = (await demo.Storage.Exports.ListCopiesBySha256Async(stillSha, ct)).Single();
Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Frame, ExportFormat.Png, stillMedia.GetProperty("still").Long("frameAtMs")), (copy.State, copy.Variant, copy.Format, (long)copy.FrameAt!.Value.TotalMilliseconds));
StringAssert.EndsWith(copy.RelativePath, "_fotogramma.png");
Assert.IsTrue(File.Exists(Path.Combine(general.RootPath, LibraryLayout.ToPlatform(copy.RelativePath!))), copy.RelativePath);
// The analyses seeded for @marta.demo: one «In movimento», one «Non analizzabile» (too slow).
var outcomes = new List<string>();
foreach (var video in await VideosAsync(demo, marta, ct))
{
if (await demo.Storage.VideoAnalyses.GetAsync(video.Sha256!, ct) is not null)
{
var still = (await OkAsync(HttpMethod.Get, $"/api/entries/{video.EntryId}")).Items("media").Single(m => m.Long("id") == video.Id).GetProperty("still");
outcomes.Add(still.Str("outcome") + "/" + (still.GetProperty("note").GetString() ?? "-"));
}
}
CollectionAssert.AreEquivalent(new[] { "still/-", "moving/-", "notAnalyzable/TooSlow" }, outcomes.Distinct().ToArray(), string.Join(", ", outcomes));
// «È un video fermo?» on a video never analysed: the demo's moving file, «In movimento», stored (no SHA-256 check
// in the demo, whose other videos share one file).
var unanalysed = await UnanalysedVideoAsync(demo, marta, ct);
var answer = await OkAsync(HttpMethod.Post, $"/api/media/{unanalysed.Id}/still");
Assert.AreEqual("moving", answer.Str("outcome"), answer.ToString());
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await demo.Storage.VideoAnalyses.GetAsync(unanalysed.Sha256!, ct))!.Outcome);
var again = await OkAsync(HttpMethod.Post, $"/api/media/{mediaId}/still");
Assert.AreEqual(("still", stillMedia.GetProperty("still").Long("frameAtMs")), (again.Str("outcome"), again.Long("frameAtMs")), "the still video again");
// «Cerca i video fermi» over the account: the already analysed are skipped, the rest is «In movimento».
var selection = new { accountId = marta };
var search = await OkAsync(HttpMethod.Post, "/api/still-videos/plan", selection);
Assert.IsGreaterThanOrEqualTo(4, search.Int("alreadyAnalysed"), search.ToString());
Assert.IsGreaterThan(0, search.Int("toAnalyse"), search.ToString());
Assert.IsNull(search.GetProperty("waiting").GetString(), "the demo is never in a session for the job");
await OkAsync(HttpMethod.Post, "/api/still-videos/start", selection);
await WaitAsync("/api/still-videos/progress", "the search did not end");
var done = await OkAsync(HttpMethod.Get, "/api/still-videos/progress");
Assert.AreEqual((search.Int("toAnalyse"), 0, search.Int("toAnalyse"), 0), (done.Int("done"), done.Int("still"), done.Int("moving"), done.Int("skipped")), done.ToString());
Assert.HasCount(2, (await OkAsync(HttpMethod.Get, "/api/library?kind=stillvideos&limit=100")).Items("tiles").ToList(), "the moving file is never still");
}
private static async Task<Media> UnanalysedVideoAsync(DemoHost demo, long accountId, CancellationToken ct)
{
foreach (var media in await VideosAsync(demo, accountId, ct))
{
if (await demo.Storage.VideoAnalyses.GetAsync(media.Sha256!, ct) is null)
{
return media;
}
}
throw new AssertFailedException("the demo has a video never analysed");
}
/// <summary>The present videos of an account in the library, newest first.</summary>
private static async Task<List<Media>> VideosAsync(DemoHost demo, long accountId, CancellationToken ct)
{
var page = await demo.Storage.Entries.QueryLibraryAsync(
new Febe.Core.Storage.LibraryQuery { Filter = new Febe.Core.Storage.LibraryFilter { AccountIds = [accountId] }, Mode = Febe.Core.Storage.MosaicMode.Files, Limit = 1000 },
ct);
var videos = new List<Media>();
foreach (var tile in page.Tiles.Where(t => t.CoverKind == MediaKind.Video))
{
if (await demo.Storage.Media.GetAsync(tile.CoverMediaId!.Value, ct) is { Sha256: not null } media && EntryStateRules.IsPresent(media.State))
{
videos.Add(media);
}
}
return videos;
}
/// <summary>The mean of R, G and B.</summary>
private static double[] Mean(RgbaImage image)
{
var sums = new double[3];
var pixels = image.Pixels;
for (var i = 0; i < pixels.Length; i += RgbaImage.BytesPerPixel)
{
sums[0] += pixels[i];
sums[1] += pixels[i + 1];
sums[2] += pixels[i + 2];
}
var count = pixels.Length / RgbaImage.BytesPerPixel;
return [sums[0] / count, sums[1] / count, sums[2] / count];
}
}