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

@@ -1,4 +1,5 @@
using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Codecs.H264; namespace Febe.Core.Codecs.H264;
@@ -213,6 +214,83 @@ public static class H264PcmWriter
return output.ToArray(); return output.ToArray();
} }
/// <summary>
/// The demo's still video (tappa E4): <paramref name="picture"/> alone for two seconds, <see cref="DemoFps"/> pictures per
/// second, after a short fade from black (the first picture nearly black, the second at half light), as a photo
/// shared as a video. «È un video fermo?» finds it «Fermo» and «Salva il fotogramma» takes a frame after the fade.
/// </summary>
/// <param name="picture">The picture, <see cref="DemoWidth"/>×<see cref="DemoHeight"/> (see <see cref="FromRgba"/>).</param>
public static byte[] DemoStillVideo(H264PcmPicture picture)
{
ArgumentNullException.ThrowIfNull(picture);
if (picture.Width != DemoWidth || picture.Height != DemoHeight)
{
throw new ArgumentException("Il fotogramma deve avere le dimensioni del video dimostrativo.", nameof(picture));
}
var dark = Faded(picture, 0.05);
var half = Faded(picture, 0.5);
using var output = new MemoryStream();
WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, i => i switch { 0 => dark, 1 => half, _ => picture }, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
return output.ToArray();
}
/// <summary>
/// A picture of the samples of <paramref name="image"/> (alpha ignored), with the coefficients the decoder uses for a
/// stream that says nothing about its colours under 720 lines: BT.601, limited range (luma 16-235, chroma 16-240).
/// The chroma of each 2×2 block is the mean of its four pixels. Width and height must be multiples of 16.
/// </summary>
public static H264PcmPicture FromRgba(RgbaImage image)
{
ArgumentNullException.ThrowIfNull(image);
var p = new H264PcmPicture(image.Width, image.Height);
var pixels = image.Pixels;
var chromaWidth = image.Width / 2;
for (var y = 0; y < image.Height; y += 2)
{
for (var x = 0; x < image.Width; x += 2)
{
double cb = 0, cr = 0;
for (var dy = 0; dy < 2; dy++)
{
for (var dx = 0; dx < 2; dx++)
{
var at = (((y + dy) * image.Width) + x + dx) * RgbaImage.BytesPerPixel;
double r = pixels[at], g = pixels[at + 1], b = pixels[at + 2];
p.Y[((y + dy) * image.Width) + x + dx] = Clamp(16 + (((65.481 * r) + (128.553 * g) + (24.966 * b)) / 255), 16, 235);
cb += 128 + (((-37.797 * r) - (74.203 * g) + (112.0 * b)) / 255);
cr += 128 + (((112.0 * r) - (93.786 * g) - (18.214 * b)) / 255);
}
}
p.Cb[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cb / 4, 16, 240);
p.Cr[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cr / 4, 16, 240);
}
}
return p;
}
/// <summary>The picture with its light scaled by <paramref name="factor"/> toward black (luma 16, chroma 128).</summary>
private static H264PcmPicture Faded(H264PcmPicture picture, double factor)
{
var p = new H264PcmPicture(picture.Width, picture.Height);
for (var i = 0; i < p.Y.Length; i++)
{
p.Y[i] = Clamp(16 + ((picture.Y[i] - 16) * factor), 16, 235);
}
for (var i = 0; i < p.Cb.Length; i++)
{
p.Cb[i] = Clamp(128 + ((picture.Cb[i] - 128) * factor), 16, 240);
p.Cr[i] = Clamp(128 + ((picture.Cr[i] - 128) * factor), 16, 240);
}
return p;
}
private static byte Clamp(double value, int low, int high) => (byte)Math.Clamp((int)Math.Round(value), low, high);
/// <summary>Picture <paramref name="index"/> of the demo video (luma 16-235, chroma 16-240: no zero byte).</summary> /// <summary>Picture <paramref name="index"/> of the demo video (luma 16-235, chroma 16-240: no zero byte).</summary>
public static H264PcmPicture DemoPicture(int index) public static H264PcmPicture DemoPicture(int index)
{ {
+5 -1
View File
@@ -390,7 +390,10 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask; public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
} }
/// <summary>Files of the demo: the shared sample pictures, and one short video for every video (tappa E3).</summary> /// <summary>
/// Files of the demo: the shared sample pictures, the still videos by their SHA-256 (tappa E4), and one short moving
/// video for every other video (tappa E3).
/// </summary>
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
{ {
public string? Resolve(Account account, Media media) public string? Resolve(Account account, Media media)
@@ -399,6 +402,7 @@ public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
return media.Kind switch return media.Kind switch
{ {
MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null, MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null,
MediaKind.Video when media.Sha256 is { } sha && world.StillVideoFiles.TryGetValue(sha, out var still) => File.Exists(still) ? still : null,
MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null, MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null,
_ => null, _ => null,
}; };
+1
View File
@@ -73,6 +73,7 @@ public sealed class DemoHost : IAsyncDisposable
var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false); var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false);
import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false);
await DemoExport.SeedAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); await DemoExport.SeedAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false);
await DemoStillVideos.SeedAsync(database, world, data, clock, ct).ConfigureAwait(false);
var exportRoot = DemoExport.Root(root); var exportRoot = DemoExport.Root(root);
var demoImport = import; var demoImport = import;
var library = new FebeLibrary(database, data, layout, clock); var library = new FebeLibrary(database, data, layout, clock);
+9 -2
View File
@@ -68,11 +68,18 @@ public sealed class DemoWorld
public IReadOnlyList<string> StoryPictures { get; init; } = []; public IReadOnlyList<string> StoryPictures { get; init; } = [];
/// <summary> /// <summary>
/// The demo's one video file (H.264, 2 s, tappa E3), served for every video of the demo so that «Fotogramma» works. /// The demo's one moving video file (H.264, 2 s, tappa E3), served for every video of the demo that is not in
/// Its bytes are not those recorded for the videos (they share the SHA-256 of their cover picture). /// <see cref="StillVideoFiles"/>, so that «Fotogramma» works. Its bytes are not those recorded for the videos (they
/// share the SHA-256 of their cover picture).
/// </summary> /// </summary>
public string? VideoFile { get; init; } public string? VideoFile { get; init; }
/// <summary>
/// The still videos of the demo (tappa E4), by SHA-256: each is its cover picture alone for two seconds, and its
/// videos are recorded with that file's own SHA-256 (written by <see cref="DemoStillVideos"/>).
/// </summary>
public ConcurrentDictionary<string, string> StillVideoFiles { get; } = new(StringComparer.Ordinal);
/// <summary>The files of the seeded conversions of the library, by row id (written by <see cref="DemoExport"/>).</summary> /// <summary>The files of the seeded conversions of the library, by row id (written by <see cref="DemoExport"/>).</summary>
public ConcurrentDictionary<long, string> ConversionFiles { get; } = new(); public ConcurrentDictionary<long, string> ConversionFiles { get; } = new();
} }
+163
View File
@@ -0,0 +1,163 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
namespace Febe.Web.Demo;
/// <summary>
/// The still videos of the demo (spec §4.10 «Video fermi», tappa E4): two videos (the newest of @marta.demo and the
/// newest story video of another account) become their cover picture alone for two seconds, each in its own file
/// recorded with its own SHA-256 (so «Salva il fotogramma» works both with «Scarica» and «Nella cartella delle copie»),
/// with a «Fermo» analysis that the real analyser gave on that file. Another video of @marta.demo has an «In movimento»
/// analysis (of the demo's moving file), a third «Non analizzabile» because it took too long («Analizza di nuovo»); the
/// rest is never analysed, so «È un video fermo?» and «Cerca i video fermi» work live. Analyses are only on request in
/// Febe: these rows stand for requests made in the days before. Every scene of the demo sees them.
/// </summary>
public static class DemoStillVideos
{
/// <summary>The account whose newest video is still (and whose next two are «In movimento» and «Non analizzabile»).</summary>
public const string StillAccount = DemoExport.CopiedAccount;
/// <summary>The file name of the still video of position <paramref name="n"/> (1 or 2).</summary>
public static string FileName(int n) => $"video-fermo-dimostrativo-{n}.mp4";
/// <summary>Writes the files, records them and seeds the analyses. Without videos to use, nothing.</summary>
public static async Task SeedAsync(FebeDatabase database, DemoWorld world, DataFolderLayout data, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(database);
ArgumentNullException.ThrowIfNull(world);
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(clock);
if (world.VideoFile is not { } movingFile || !File.Exists(movingFile)
|| (await database.Accounts.ListAsync(ct).ConfigureAwait(false)).FirstOrDefault(a => a.Username == StillAccount) is not { } marta)
{
return;
}
var now = clock.Now;
var folder = Path.GetDirectoryName(movingFile)!;
var own = await VideosAsync(database, world, new LibraryFilter { AccountIds = [marta.Id] }, 3, null, ct).ConfigureAwait(false);
var story = await VideosAsync(database, world, new LibraryFilter { Kind = LibraryKindFilter.Stories }, 1, marta.Id, ct).ConfigureAwait(false);
var stills = own.Take(1).Concat(story).ToList();
var thumbnails = new ThumbnailStore(data.Thumbnails);
var n = 0;
foreach (var media in stills)
{
n++;
var cover = world.Pictures[media.Sha256!];
var bytes = await Task.Run(() => StillVideo(cover), ct).ConfigureAwait(false);
StillVideoResult result;
using (var stream = new MemoryStream(bytes, writable: false))
{
result = StillVideoAnalyzer.Analyse(stream, ct);
}
// Never a row the analyser did not give: a video that would not be «Fermo» stays a moving one of the demo.
if (result.Outcome != VideoAnalysisOutcome.Still)
{
continue;
}
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
var file = Path.Combine(folder, FileName(n));
await File.WriteAllBytesAsync(file, bytes, ct).ConfigureAwait(false);
thumbnails.CreateFromFile(sha, cover);
await database.Media.UpdateAsync(
media with
{
Sha256 = sha,
Bytes = bytes.Length,
Width = H264PcmWriter.DemoWidth,
Height = H264PcmWriter.DemoHeight,
Duration = TimeSpan.FromSeconds((double)H264PcmWriter.DemoPictures / H264PcmWriter.DemoFps),
},
ct).ConfigureAwait(false);
world.StillVideoFiles[sha] = file;
await database.VideoAnalyses.SetAsync(result.ToAnalysis(sha, now.AddDays(-2 - n)), ct).ConfigureAwait(false);
}
// «In movimento» for the next video of the account (the demo's moving file, as «È un video fermo?» would find it),
// «Non analizzabile» (too slow) for the one after, on a different picture.
if (own.Skip(1).FirstOrDefault() is { Sha256: { } movingSha })
{
StillVideoResult moving;
await using (var stream = File.OpenRead(movingFile))
{
moving = StillVideoAnalyzer.Analyse(stream, ct);
}
await database.VideoAnalyses.SetAsync(moving.ToAnalysis(movingSha, now.AddDays(-1)), ct).ConfigureAwait(false);
if (own.Skip(2).FirstOrDefault() is { Sha256: { } slowSha } && !string.Equals(slowSha, movingSha, StringComparison.Ordinal))
{
await database.VideoAnalyses.SetAsync(
new VideoAnalysis(slowSha, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.NotAnalyzable, now.AddHours(-20), Note: VideoAnalysisNotes.TooSlow),
ct).ConfigureAwait(false);
}
}
}
/// <summary>
/// The still video of a cover picture: the middle of the picture in the proportions of the demo video, reduced to
/// its size, after a short fade from black (<see cref="H264PcmWriter.DemoStillVideo"/>).
/// </summary>
public static byte[] StillVideo(string coverPath)
{
using var decoded = ImageDecoder.Decode(File.ReadAllBytes(coverPath));
const int Width = H264PcmWriter.DemoWidth;
const int Height = H264PcmWriter.DemoHeight;
var (w, h) = decoded.Width * Height > decoded.Height * Width
? (decoded.Height * Width / Height, decoded.Height)
: (decoded.Width, decoded.Width * Height / Width);
using var cropped = new RgbaImage(w, h);
var left = (decoded.Width - w) / 2;
var top = (decoded.Height - h) / 2;
for (var y = 0; y < h; y++)
{
decoded.GetRow(top + y).Slice(left * RgbaImage.BytesPerPixel, w * RgbaImage.BytesPerPixel).CopyTo(cropped.GetRow(y));
}
using var small = ImageResampler.Resize(cropped, Width, Height);
return H264PcmWriter.DemoStillVideo(H264PcmWriter.FromRgba(small));
}
/// <summary>
/// Up to <paramref name="count"/> present videos of the filter, newest first, each on its own cover picture, that no
/// copy uses (the copies of the demo keep the SHA-256 they were made from) and not of <paramref name="exceptAccount"/>.
/// </summary>
private static async Task<List<Media>> VideosAsync(FebeDatabase database, DemoWorld world, LibraryFilter filter, int count, long? exceptAccount, CancellationToken ct)
{
var found = new List<Media>();
var shas = new HashSet<string>(StringComparer.Ordinal);
LibraryCursor? cursor = null;
do
{
var page = await database.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 }, ct).ConfigureAwait(false);
foreach (var tile in page.Tiles)
{
if (tile.CoverKind != MediaKind.Video || tile.CoverMediaId is not { } id || tile.AccountId == exceptAccount
|| await database.Media.GetAsync(id, ct).ConfigureAwait(false) is not { Sha256: { } sha, RelativePath: not null } media
|| !EntryStateRules.IsPresent(media.State) || !world.Pictures.ContainsKey(sha) || !shas.Add(sha)
|| (await database.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Count > 0)
{
continue;
}
found.Add(media);
if (found.Count == count)
{
return found;
}
}
cursor = page.Older;
}
while (cursor is not null);
return found;
}
}
+2
View File
@@ -121,6 +121,8 @@ public static class FebeWeb
Clock = clock, Clock = clock,
Gate = sp.GetRequiredService<LongWorkGate>(), Gate = sp.GetRequiredService<LongWorkGate>(),
Session = sp.GetRequiredService<IEngineSessionState>(), Session = sp.GetRequiredService<IEngineSessionState>(),
// The demo serves one moving file for the videos it has no still file for: their SHA-256 is never that file's.
VerifySource = !options.Demo,
Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")), Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")),
Log = logger is null ? null : message => logger.LogWarning("{Message}", message), Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
}); });
+8
View File
@@ -278,6 +278,14 @@ scrive mai nella libreria vera e non usa la rete.
fotogramma mostrato in quel momento) già nella cartella generale, una foto con il suo PNG in libreria e una che «non si fotogramma mostrato in quel momento) già nella cartella generale, una foto con il suo PNG in libreria e una che «non si
converte». La conversione della libreria non parte mai. «Nella cartella delle copie» dei fotogrammi di un video converte». La conversione della libreria non parte mai. «Nella cartella delle copie» dei fotogrammi di un video
finisce in errore («non corrisponde»): i video condividono l'impronta della loro copertina, non quella del file. finisce in errore («non corrisponde»): i video condividono l'impronta della loro copertina, non quella del file.
- Video fermi (tappa E4, `Demo/DemoStillVideos.cs`): 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
(`campioni/video-fermo-dimostrativo-1.mp4` e `-2.mp4`, da `H264PcmWriter.DemoStillVideo`), ciascuno registrato con
l'impronta del suo file: «Salva il fotogramma» funziona anche «Nella cartella delle copie». Hanno un'analisi «Fermo»
data dall'analizzatore vero (il filtro «Video fermi» li mostra); il video dopo di @marta.demo è «In movimento», quello
dopo ancora «Non analizzabile» (troppo lento, «Analizza di nuovo»); gli altri non sono mai stati analizzati, così «È un
video fermo?» e «Cerca i video fermi» lavorano davvero (sul video dimostrativo che si muove). Nella dimostrazione il
servizio non controlla l'impronta dei file prima di analizzarli (`VerifySource = false`).
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i - I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino. conti tornino.
+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];
}
}