E3: API di formati e fotogrammi, conversione della libreria e demo

Porta le funzioni della tappa E3 fino all'interfaccia web, così che WP4
possa costruire le schermate su indirizzi veri.

- Impostazioni, cartelle delle copie e «Copia in…» hanno i formati
  (nomi original, jpg, png, webplossless, mp4); il riepilogo dice cosa si
  converte, cosa resta com'è e se c'è perdita. «Copia di nuovo» rifà la
  copia nella sua forma esatta.
- Fotogrammi: informazioni di un video, un fotogramma (anteprima o
  scaricamento), gli istanti di una modalità, «Scarica» di uno o di uno
  zip scritto mentre parte, con il permesso dei lavori lunghi oltre 20.
  Kestrel non vede mai scritture sincrone: il piccolo descrittore che lo
  zip di .NET 10 scrive in modo sincrono parte con la scrittura seguente.
- Conversione della libreria: stato, la domanda «Converti anche i N già
  in libreria?», riprova, pausa e ripresa; il visualizzatore mostra i
  file convertiti, e le eliminazioni li contano.
- Demo: un video H.264 scritto in casa (solo macroblocchi I_PCM) per
  ogni video, una copia in PNG, un fotogramma e due conversioni; la
  conversione non parte mai.

Due prove cambiano con il comportamento: i video della demo ora si
aprono, e un file non copiato può avere il segno «solo fotogramma».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 01:02:37 +01:00
1 parent 724c5bda6f
commit ab0d717424
25 files changed
+2559 -95

No files matched your search

+177 -1
View File
@@ -1,4 +1,6 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
@@ -11,7 +13,8 @@ namespace Febe.Web.Demo;
/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder
/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its
/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore»,
/// and a job left «interrotto» for the Dashboard. Everything lives in the demo's temporary folder, whose «esporta» is
/// and a job left «interrotto» for the Dashboard; tappa E3 adds a copy converted to PNG, a frame of a video and two
/// conversions of the library («Convertito», «Non si converte»). Everything lives in the demo's temporary folder, whose «esporta» is
/// the demo's <c>/esporta</c>: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
/// </summary>
public static class DemoExport
@@ -117,6 +120,179 @@ public static class DemoExport
}
await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false);
// Tappa E3: a converted copy by the real engine (PNG, «Copia in…» → «Cambia»), a frame and two conversions.
if (rest.Skip(FormatsFrom).FirstOrDefault() is { } toConvert)
{
await service.StartAsync(
new ExportJobRequest(new ExportSelection.Media([toConvert.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)),
ct).ConfigureAwait(false);
await service.WaitAsync(ct).ConfigureAwait(false);
}
await FrameAsync(database, world, general, marta, clock, ct).ConfigureAwait(false);
await ConversionsAsync(root, database, world, [.. rest.Skip(FormatsFrom + 1).Take(2)], clock, ct).ConfigureAwait(false);
}
/// <summary>The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s).</summary>
public static readonly TimeSpan FrameAsked = TimeSpan.FromMilliseconds(1234);
// rest[0..2] are «Tolto», «Superato» and «Errore», rest[3..14] the interrupted job.
private const int FormatsFrom = 15;
/// <summary>
/// A frame of a video of @marta.demo in the general folder, as «Fotogrammi…» → «Nella cartella delle copie» writes it:
/// the demo shares one video file whose SHA-256 is not the one recorded, so the engine would refuse it (rule: the
/// frames are of the file recorded); the row and its PNG are written here.
/// </summary>
private static async Task FrameAsync(FebeDatabase database, DemoWorld world, ExportDestination general, Account marta, IClock clock, CancellationToken ct)
{
if (world.VideoFile is not { } videoFile || !File.Exists(videoFile)
|| await VideoAsync(database, marta, ct).ConfigureAwait(false) is not { } video
|| await database.Entries.GetAsync(video.EntryId, ct).ConfigureAwait(false) is not { } entry)
{
return;
}
byte[] png;
TimeSpan actual;
await using (var stream = File.OpenRead(videoFile))
{
using var reader = VideoFrameReader.Open(stream, out var info);
if (!info.Available)
{
return;
}
var target = reader.Locate([FrameAsked])[0];
using var frame = reader.Decode([target], ct).Single();
png = ImageConverter.Encode(frame.Image, ImageFormat.Png, null);
actual = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
}
var suffix = ExportFrames.Suffix(FrameMode.At, actual, 0, 1);
var segments = ExportPaths.Segments(general, LibraryNaming.Default, marta, entry, video, null, false, world.Zone, new ExportNameOptions(".png", suffix));
var relative = ExportPaths.RelativePathFor(general, segments, keepSuffix: suffix);
var framePath = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative));
Directory.CreateDirectory(Path.GetDirectoryName(framePath)!);
await using (var output = new FileStream(framePath, FileMode.CreateNew, FileAccess.Write))
{
await output.WriteAsync(png, ct).ConfigureAwait(false);
}
await database.Exports.AddCopyAsync(
new ExportCopy
{
DestinationId = general.Id,
AccountId = marta.Id,
MediaId = video.Id,
SourceSha256 = video.Sha256!,
Variant = ExportVariant.Frame,
Format = ExportFormat.Png,
FrameAt = actual,
State = ExportCopyState.Copied,
RelativePath = relative,
Bytes = png.Length,
CopySha256 = Convert.ToHexStringLower(SHA256.HashData(png)),
CopiedAt = clock.Now.AddDays(-1),
},
ct).ConfigureAwait(false);
}
/// <summary>
/// Two conversions of the library (spec §4.10): a PNG next to its original («Convertito», its file in the demo's
/// «convertiti» folder) and one that never converts («Non si converte»). The demo never runs the conversion.
/// </summary>
private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList<Media> photos, IClock clock, CancellationToken ct)
{
var now = clock.Now;
if (photos.Count > 0 && photos[0] is { Sha256: { } sha, RelativePath: { } original } converted
&& world.Pictures.TryGetValue(sha, out var source) && File.Exists(source))
{
var result = await Task.Run(() => ImageConverter.Convert(File.ReadAllBytes(source), ImageFormat.Png), ct).ConfigureAwait(false);
var folder = Path.Combine(root, "convertiti");
Directory.CreateDirectory(folder);
var file = Path.Combine(folder, sha + ".png");
await File.WriteAllBytesAsync(file, result.Data, ct).ConfigureAwait(false);
var row = await database.Conversions.AddAsync(
new MediaConversion
{
MediaId = converted.Id,
Format = ExportFormat.Png,
State = MediaConversionState.Converted,
SourceSha256 = sha,
RelativePath = Path.ChangeExtension(original, ".png"),
Bytes = result.Data.Length,
Sha256 = Convert.ToHexStringLower(SHA256.HashData(result.Data)),
CreatedAt = now.AddDays(-4),
ConvertedAt = now.AddDays(-4),
StateChangedAt = now.AddDays(-4),
LastError = ExportText.JoinNotes([.. result.NotCarried, .. result.Losses]),
},
ct).ConfigureAwait(false);
world.ConversionFiles[row.Id] = file;
}
if (photos.Count > 1 && photos[1].Sha256 is { } asIsSha)
{
await database.Conversions.AddAsync(
new MediaConversion
{
MediaId = photos[1].Id,
Format = ExportFormat.Png,
State = MediaConversionState.Failed,
SourceSha256 = asIsSha,
CreatedAt = now.AddDays(-4),
StateChangedAt = now.AddDays(-4),
LastError = ImageConversionLosses.AsIsAnimated,
},
ct).ConfigureAwait(false);
}
}
/// <summary>
/// A present video of an account whose SHA-256 the fewest files share (the demo's videos take the SHA-256 of their
/// cover picture, and the marks of the copies go by SHA-256): the newest among those.
/// </summary>
private static async Task<Media?> VideoAsync(FebeDatabase database, Account account, CancellationToken ct)
{
var files = new Dictionary<string, int>(StringComparer.Ordinal);
var videos = new List<long>();
LibraryCursor? cursor = null;
do
{
var page = await database.Entries.QueryLibraryAsync(
new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 },
ct).ConfigureAwait(false);
foreach (var tile in page.Tiles)
{
if (tile.CoverSha256 is { } sha)
{
files[sha] = files.GetValueOrDefault(sha) + 1;
}
if (tile.CoverKind == MediaKind.Video && tile.CoverMediaId is { } id)
{
videos.Add(id);
}
}
cursor = page.Older;
}
while (cursor is not null);
Media? best = null;
foreach (var id in videos)
{
if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha, RelativePath: not null } media
&& EntryStateRules.IsPresent(media.State)
&& (best is null || files.GetValueOrDefault(sha) < files.GetValueOrDefault(best.Sha256!)))
{
best = media;
}
}
return best;
}
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>