Quale video sia fermo dipende dall'ora: i passi lo cercano in tutta la libreria e dicono se manca. La dimostrazione chiude la ricerca prima dell'archivio. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
314 lines
17 KiB
C#
314 lines
17 KiB
C#
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;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
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)
|
|
{
|
|
// Bounded by the test's own timeout, whatever else the machine does.
|
|
while ((await OkAsync(HttpMethod.Get, path)).Bool("running"))
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(100, ct);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
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");
|
|
|
|
|
|
var selection = new { accountId = marta };
|
|
var search = await OkAsync(HttpMethod.Post, "/api/still-videos/plan", selection);
|
|
Assert.IsGreaterThanOrEqualTo(3, 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");
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow(9)]
|
|
[DataRow(20)]
|
|
[Timeout(600_000, CooperativeCancellation = true)]
|
|
public async Task WhateverTheHourTheDemoHasItsStillVideos(int hour)
|
|
{
|
|
// The demo is built around its local time (posts of «oggi» are there or not yet): the still videos never depend
|
|
// on it. The hour is the zone's, so the test asks for the same thing whenever it runs.
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder("demo-fermi-ore");
|
|
var offset = TimeSpan.FromMinutes(Math.Round(((hour + 0.5) * 60) - DateTimeOffset.UtcNow.TimeOfDay.TotalMinutes));
|
|
offset = offset > TimeSpan.FromHours(12) ? offset - TimeSpan.FromHours(24) : offset < TimeSpan.FromHours(-12) ? offset + TimeSpan.FromHours(24) : offset;
|
|
var zone = TimeZoneInfo.CreateCustomTimeZone("prova", offset, "prova", "prova");
|
|
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, zone, temp.Path), ct);
|
|
|
|
Assert.HasCount(2, demo.World.StillVideoFiles);
|
|
var tiles = (await demo.Storage.Entries.QueryLibraryAsync(
|
|
new Febe.Core.Storage.LibraryQuery { Filter = new Febe.Core.Storage.LibraryFilter { Kind = Febe.Core.Storage.LibraryKindFilter.StillVideos }, Limit = 100 },
|
|
ct)).Tiles;
|
|
Assert.HasCount(2, tiles, "one post and one story");
|
|
var accounts = await demo.Storage.Accounts.ListAsync(ct);
|
|
var marta = accounts.Single(a => a.Username == DemoStillVideos.StillAccount).Id;
|
|
Assert.AreEqual(1, tiles.Count(t => t.AccountId == marta));
|
|
var entries = await Task.WhenAll(tiles.Select(async t => (await demo.Storage.Entries.GetAsync(t.EntryId, ct))!));
|
|
Assert.AreEqual(1, entries.Count(e => e.Kind == EntryKind.Story && e.AccountId != marta));
|
|
Assert.IsTrue(entries.All(e => e.PublishedAt <= demo.App.Services.GetRequiredService<Febe.Core.Abstractions.IClock>().Now), "published, not to come");
|
|
|
|
var outcomes = new List<(VideoAnalysisOutcome, string?)>();
|
|
var unanalysed = 0;
|
|
foreach (var video in await VideosAsync(demo, marta, ct))
|
|
{
|
|
if (await demo.Storage.VideoAnalyses.GetAsync(video.Sha256!, ct) is { } analysis)
|
|
{
|
|
outcomes.Add((analysis.Outcome, analysis.Note));
|
|
}
|
|
else
|
|
{
|
|
unanalysed++;
|
|
}
|
|
}
|
|
|
|
CollectionAssert.AreEquivalent(
|
|
new (VideoAnalysisOutcome, string?)[]
|
|
{
|
|
(VideoAnalysisOutcome.Still, null), (VideoAnalysisOutcome.Moving, null), (VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.TooSlow),
|
|
},
|
|
outcomes.Distinct().ToArray(),
|
|
string.Join(", ", outcomes));
|
|
Assert.IsGreaterThan(0, unanalysed, "«È un video fermo?» has a video to be tried on");
|
|
}
|
|
|
|
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)
|
|
{
|
|
// Every page: @marta.demo has more than a thousand files, and the videos the demo analysed can be among the oldest
|
|
// (the pictures that no copy uses depend on the hour).
|
|
var videos = new List<Media>();
|
|
Febe.Core.Storage.LibraryCursor? cursor = null;
|
|
do
|
|
{
|
|
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, Cursor = cursor, Limit = 500 },
|
|
ct);
|
|
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);
|
|
}
|
|
}
|
|
|
|
cursor = page.Older;
|
|
}
|
|
while (cursor is not null);
|
|
|
|
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];
|
|
}
|
|
}
|