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:
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.Images;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
@@ -213,6 +214,83 @@ public static class H264PcmWriter
|
||||
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>
|
||||
public static H264PcmPicture DemoPicture(int index)
|
||||
{
|
||||
|
||||
@@ -390,7 +390,10 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
|
||||
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 string? Resolve(Account account, Media media)
|
||||
@@ -399,6 +402,7 @@ public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
|
||||
return media.Kind switch
|
||||
{
|
||||
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,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -73,6 +73,7 @@ public sealed class DemoHost : IAsyncDisposable
|
||||
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);
|
||||
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 demoImport = import;
|
||||
var library = new FebeLibrary(database, data, layout, clock);
|
||||
|
||||
@@ -68,11 +68,18 @@ public sealed class DemoWorld
|
||||
public IReadOnlyList<string> StoryPictures { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The demo's one video file (H.264, 2 s, tappa E3), served for every video of the demo so that «Fotogramma» works.
|
||||
/// Its bytes are not those recorded for the videos (they share the SHA-256 of their cover picture).
|
||||
/// The demo's one moving video file (H.264, 2 s, tappa E3), served for every video of the demo that is not in
|
||||
/// <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>
|
||||
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>
|
||||
public ConcurrentDictionary<long, string> ConversionFiles { get; } = new();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,8 @@ public static class FebeWeb
|
||||
Clock = clock,
|
||||
Gate = sp.GetRequiredService<LongWorkGate>(),
|
||||
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")),
|
||||
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
|
||||
});
|
||||
|
||||
@@ -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
|
||||
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.
|
||||
- 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
|
||||
conti tornino.
|
||||
|
||||
|
||||
Reference in new issue
Block a user