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

+454
View File
@@ -0,0 +1,454 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.IO.Compression;
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;
using Febe.Core.Library.Conversion;
using Febe.Web.Api;
namespace Febe.Web.Export;
/// <summary>A frame encoded for the page: its bytes, media type, extension and the instant really shown.</summary>
public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual);
/// <summary>The frames of one video in a download: where it is, its account and name, and the instants asked.</summary>
/// <param name="Username">The account (first segment of the zip entries).</param>
/// <param name="Path">The library file.</param>
/// <param name="Stem">The library file name without extension.</param>
/// <param name="Instants">The instants asked, in increasing order.</param>
/// <param name="PublishedAt">When the entry was published (the time of the zip entries, D18).</param>
public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList<TimeSpan> Instants, DateTimeOffset PublishedAt);
/// <summary>A «Scarica» of frames waiting for its address to be opened.</summary>
public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList<FrameDownloadVideo> Videos)
{
/// <summary>The frames in all.</summary>
public int Frames => Videos.Sum(v => v.Instants.Count);
}
/// <summary>
/// Frames of videos for the page (spec §4.10 «Fotogrammi», tappa E3, D14): what a video allows (kept for 64 files by
/// SHA-256), a single frame for the previews and «Scarica», and the zip of several. Previews and single frames go one at
/// a time (one decoder busy, never a queue of heavy work) within <see cref="Budget"/>; they are not long work and run at
/// any time. A zip of up to <see cref="MaxAnyTime"/> frames runs at any time too; from 21 to <see cref="MaxDownload"/>
/// it takes <see cref="LongWorkKind.FrameDownload"/> and never runs during an engine session. Nothing here writes a
/// file: the frames go to the page only.
/// </summary>
public sealed class FrameService(IClock clock)
{
/// <summary>The longest side of a preview.</summary>
public const int MaxPreview = 480;
/// <summary>The most frames of a zip at any time.</summary>
public const int MaxAnyTime = 20;
/// <summary>The most frames of «Scarica».</summary>
public const int MaxDownload = 500;
/// <summary>Video infos kept.</summary>
public const int CacheSize = 64;
public const string TimeoutText = "Il fotogramma richiede troppo tempo: scegli la cartella delle copie";
public const string SessionText = "Il motore è in sessione: per più di 20 fotogrammi riprova fra poco";
public const string TooManyText = "Per più di 500 fotogrammi scegli la cartella delle copie";
public const string NothingText = "Nessun fotogramma da scaricare: scegli dei video con i fotogrammi disponibili.";
private static readonly TimeSpan TokenLife = TimeSpan.FromMinutes(5);
private readonly SemaphoreSlim _one = new(1, 1);
private readonly Lock _cacheGate = new();
private readonly Dictionary<string, (VideoFrameInfo Info, long Used)> _cache = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, (FrameDownloadPlan Plan, DateTimeOffset Expires)> _tokens = new(StringComparer.Ordinal);
private long _uses;
/// <summary>The time a preview or a single frame may take, waiting included.</summary>
public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A write of the zip that makes no progress for this long aborts the download.</summary>
public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
public async Task<VideoFrameInfo> InfoAsync(string path, string? sha256, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(path);
if (sha256 is { Length: > 0 } && Cached(sha256) is { } cached)
{
return cached;
}
var info = await Task.Run(
() =>
{
using var stream = OpenRead(path);
using var reader = VideoFrameReader.Open(stream, out var found);
return found;
},
ct).ConfigureAwait(false);
if (sha256 is { Length: > 0 })
{
Remember(sha256, info);
}
return info;
}
/// <summary>
/// The instants of <paramref name="request"/> for the video at <paramref name="path"/> with the samples really shown;
/// empty when the video has no frames. <see cref="ArgumentException"/> over 1.000 frames.
/// </summary>
public Task<(VideoFrameInfo Info, IReadOnlyList<VideoFrameTarget> Targets)> LocateAsync(string path, string? sha256, ExportFramesRequest request, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(path);
ArgumentNullException.ThrowIfNull(request);
return Task.Run(
() =>
{
using var stream = OpenRead(path);
using var reader = VideoFrameReader.Open(stream, out var info);
if (sha256 is { Length: > 0 })
{
Remember(sha256, info);
}
if (!info.Available)
{
return (info, (IReadOnlyList<VideoFrameTarget>)[]);
}
var instants = ExportFrames.Instants(info.Duration, request);
return (info, reader.Locate(instants));
},
ct);
}
/// <summary>
/// The frame shown at <paramref name="at"/>, encoded in <paramref name="format"/>; with <paramref name="maxSide"/>
/// scaled down to fit it (a preview). One at a time, within <see cref="Budget"/>: past it
/// <see cref="ApiStatusException"/> 503. <see cref="NotFoundException"/> when the video has no frames.
/// </summary>
public async Task<EncodedFrame> FrameAsync(string path, string? sha256, TimeSpan at, ExportFormat format, int? maxSide, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(path);
var image = MediaConverter.ImageFormatOf(format) ?? throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.");
using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
budget.CancelAfter(Budget);
try
{
await _one.WaitAsync(budget.Token).ConfigureAwait(false);
try
{
return await Task.Run(() => Decode(path, sha256, at, image, maxSide, budget.Token), budget.Token).ConfigureAwait(false);
}
finally
{
_one.Release();
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new ApiStatusException(503, TimeoutText);
}
}
/// <summary>Keeps a download for <see cref="TokenLife"/>, for one use; returns its token.</summary>
public string Register(FrameDownloadPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var now = clock.Now;
foreach (var (key, value) in _tokens)
{
if (value.Expires <= now)
{
_tokens.TryRemove(key, out _);
}
}
var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
_tokens[token] = (plan, now + TokenLife);
return token;
}
/// <summary>The download of <paramref name="token"/>, taken once; null when unknown, used or expired.</summary>
public FrameDownloadPlan? Take(string token)
{
if (string.IsNullOrEmpty(token) || !_tokens.TryRemove(token, out var found))
{
return null;
}
return found.Expires > clock.Now ? found.Plan : null;
}
/// <summary>The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension.</summary>
public static string FileName(string stem, FrameMode mode, TimeSpan actual, int index, int count, ExportFormat format) =>
WindowsFileNames.SanitizeSegment(stem + ExportFrames.Suffix(mode, actual, index, count) + MediaConverter.ExtensionOf(format));
/// <summary>
/// Writes the zip of <paramref name="plan"/> into <paramref name="output"/> as it is made (not compressed: the
/// images are), entries <c>account/name</c> unique as the copies number them («x (2).png»), dated per
/// <paramref name="publicationTime"/> (the publication, else now), within the years a zip can hold.
/// </summary>
public async Task WriteZipAsync(Stream output, FrameDownloadPlan plan, bool publicationTime, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(plan);
var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan));
var guarded = new StallGuardStream(output, WriteStall);
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false);
await using (zip.ConfigureAwait(false))
{
foreach (var video in plan.Videos)
{
var folder = WindowsFileNames.SanitizeSegment(video.Username);
var time = EntryTime(publicationTime ? video.PublishedAt : clock.Now);
await foreach (var (index, frame) in FramesAsync(video, plan, image, ct).ConfigureAwait(false))
{
var name = FileName(video.Stem, plan.Mode, frame.Actual, index, video.Instants.Count, plan.Format);
var relative = folder + "/" + name;
var suffix = ExportFrames.Suffix(plan.Mode, frame.Actual, index, video.Instants.Count);
for (var attempt = 2; !names.Add(relative); attempt++)
{
relative = ExportPaths.NumberedName("febe", folder + "/" + name, attempt, keepSuffix: suffix);
}
var entry = zip.CreateEntry(relative, CompressionLevel.NoCompression);
entry.LastWriteTime = time;
var stream = await entry.OpenAsync(ct).ConfigureAwait(false);
await using (stream.ConfigureAwait(false))
{
await stream.WriteAsync(frame.Data, ct).ConfigureAwait(false);
}
}
}
}
await guarded.CompleteAsync(ct).ConfigureAwait(false);
}
/// <summary>The frames of one video of a download, encoded, in decoding order, with their index among its instants.</summary>
public async IAsyncEnumerable<(int Index, EncodedFrame Frame)> FramesAsync(FrameDownloadVideo video, FrameDownloadPlan plan, ImageFormat image, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(video);
ArgumentNullException.ThrowIfNull(plan);
Stream stream;
try
{
stream = OpenRead(video.Path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
yield break; // the file went since the plan: its frames are left out
}
await using (stream.ConfigureAwait(false))
{
var (reader, info) = await Task.Run(() => (VideoFrameReader.Open(stream, out var found), found), ct).ConfigureAwait(false);
using (reader)
{
if (!info.Available)
{
yield break;
}
var targets = reader.Locate(video.Instants);
using var frames = reader.Decode(targets, ct).GetEnumerator();
var shown = new HashSet<long>();
while (await Task.Run(() => frames.MoveNext(), ct).ConfigureAwait(false))
{
using var frame = frames.Current;
if (!shown.Add(frame.Actual.Ticks))
{
continue; // two instants on the same picture give it once, as the copies do
}
var data = await Task.Run(() => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false);
yield return (frame.Index, new EncodedFrame(data, ContentType(image), MediaConverter.ExtensionOf(plan.Format), frame.Actual));
}
}
}
}
/// <summary>The media type of an image format written by Febe.</summary>
public static string ContentType(ImageFormat format) => format switch
{
ImageFormat.Jpeg => "image/jpeg",
ImageFormat.Png => "image/png",
_ => "image/webp",
};
private EncodedFrame Decode(string path, string? sha256, TimeSpan at, ImageFormat image, int? maxSide, CancellationToken ct)
{
using var stream = OpenRead(path);
using var reader = VideoFrameReader.Open(stream, out var info);
if (sha256 is { Length: > 0 })
{
Remember(sha256, info);
}
if (!info.Available)
{
throw new NotFoundException(info.Unavailable ?? VideoFrameReader.NotAvailableMessage);
}
var targets = reader.Locate([at]);
using var frame = reader.Decode(targets, ct).FirstOrDefault() ?? throw new NotFoundException(VideoFrameReader.NotAvailableMessage);
ct.ThrowIfCancellationRequested();
var source = frame.Image;
if (maxSide is { } max && Math.Max(source.Width, source.Height) > max)
{
var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, max);
using var small = ImageResampler.Resize(source, width, height);
return new EncodedFrame(ImageConverter.Encode(small, image, null), ContentType(image), Extension(image), frame.Actual);
}
return new EncodedFrame(ImageConverter.Encode(source, image, null), ContentType(image), Extension(image), frame.Actual);
}
private static string Extension(ImageFormat image) => image switch
{
ImageFormat.Jpeg => ".jpg",
ImageFormat.Png => ".png",
_ => ".webp",
};
/// <summary>The time of a zip entry: within 1980-2107, the years a zip can hold.</summary>
private DateTimeOffset EntryTime(DateTimeOffset instant)
{
var local = TimeZoneInfo.ConvertTime(instant, clock.LocalZone);
var min = new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset);
var max = new DateTimeOffset(2107, 12, 31, 23, 59, 58, local.Offset);
return local < min ? min : local > max ? max : local;
}
private VideoFrameInfo? Cached(string sha256)
{
lock (_cacheGate)
{
if (_cache.TryGetValue(sha256, out var found))
{
_cache[sha256] = (found.Info, ++_uses);
return found.Info;
}
return null;
}
}
private void Remember(string sha256, VideoFrameInfo info)
{
lock (_cacheGate)
{
_cache[sha256] = (info, ++_uses);
if (_cache.Count > CacheSize)
{
var oldest = _cache.MinBy(p => p.Value.Used).Key;
_cache.Remove(oldest);
}
}
}
private static FileStream OpenRead(string path) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
internal static string Day(DateTimeOffset now, TimeZoneInfo zone) =>
LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
/// <summary>
/// A write-only stream that gives up a write making no progress for a while (the page stopped reading). The zip of
/// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those
/// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write.
/// </summary>
private sealed class StallGuardStream(Stream inner, TimeSpan stall) : Stream
{
// A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL.
private const int MaxPending = 64 * 1024;
private readonly MemoryStream _pending = new();
private long _position;
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => _position;
set => throw new NotSupportedException();
}
public override void Flush()
{
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await SendPendingAsync(cancellationToken).ConfigureAwait(false);
await inner.FlushAsync(cancellationToken).ConfigureAwait(false);
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
if (_pending.Length + buffer.Length > MaxPending)
{
throw new NotSupportedException("Lo zip dei fotogrammi si scrive solo in modo asincrono.");
}
_pending.Write(buffer);
_position += buffer.Length;
}
public override void WriteByte(byte value) => Write([value]);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
await SendPendingAsync(cancellationToken).ConfigureAwait(false);
await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false);
_position += buffer.Length;
}
/// <summary>Sends what was written synchronously and flushes: call it once the zip is complete.</summary>
public Task CompleteAsync(CancellationToken ct) => FlushAsync(ct);
private async Task SendPendingAsync(CancellationToken ct)
{
if (_pending.Length == 0)
{
return;
}
var bytes = _pending.ToArray();
_pending.SetLength(0);
await GuardedAsync(bytes, ct).ConfigureAwait(false);
}
private async Task GuardedAsync(ReadOnlyMemory<byte> buffer, CancellationToken ct)
{
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct);
guard.CancelAfter(stall);
await inner.WriteAsync(buffer, guard.Token).ConfigureAwait(false);
}
}
}