E3: correzioni della revisione di formati e fotogrammi

Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 13:30:33 +01:00
1 parent eb79b05fda
commit 958cb71cd6
38 files changed
+1276 -222

No files matched your search

+94 -36
View File
@@ -32,6 +32,12 @@ public static class ExportApi
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the
/// library conversion compares before and after, so two quick changes must not both start from the same before.
/// </summary>
private static readonly SemaphoreSlim SettingsGate = new(1, 1);
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
@@ -42,41 +48,7 @@ public static class ExportApi
endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false);
var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var after = before;
if (body.SamePost is { } samePostText)
{
after = after with
{
SamePost = samePostText.Trim().ToLowerInvariant() switch
{
"oneperaccount" => SamePostCopies.OnePerAccount,
"oneonly" => SamePostCopies.OneOnly,
_ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
},
};
}
after = after with
{
PhotoFormat = ParseFormat(body.PhotoFormat, MediaKind.Photo) ?? after.PhotoFormat,
VideoFormat = ParseFormat(body.VideoFormat, MediaKind.Video) ?? after.VideoFormat,
LibraryPhotoFormat = ParseFormat(body.LibraryPhotoFormat, MediaKind.Photo) ?? after.LibraryPhotoFormat,
LibraryVideoFormat = ParseFormat(body.LibraryVideoFormat, MediaKind.Video) ?? after.LibraryVideoFormat,
};
if (body.SamePost is null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null && body.ConvertExisting is null)
{
throw new BadRequestException("Niente da salvare: scegli un'impostazione.");
}
await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false);
await queue.OnSettingsChangedAsync(before, after, ct).ConfigureAwait(false);
var queued = 0;
if (body.ConvertExisting == true && after.ConvertsLibrary)
{
queued = await queue.EnqueueExistingAsync(after, ct).ConfigureAwait(false);
}
var (before, after, queued) = await SaveSettingsAsync(body, storage, queue, ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false);
return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto);
@@ -93,7 +65,17 @@ public static class ExportApi
LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat,
LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat,
};
var preview = settings.ConvertsLibrary ? await queue.PreviewExistingAsync(settings, ct).ConfigureAwait(false) : new LibraryConversionPreview(0, 0);
// The question is about the kind being turned on or changed: the other one is not counted (it already had
// its answer). Without either, both formats set now.
var (photoAsked, videoAsked) = (!string.IsNullOrWhiteSpace(photo), !string.IsNullOrWhiteSpace(video));
var both = !photoAsked && !videoAsked;
var preview = settings.ConvertsLibrary
? await queue.PreviewExistingAsync(
both || photoAsked ? LibraryConversionRules.FormatFor(MediaKind.Photo, settings) : null,
both || videoAsked ? LibraryConversionRules.FormatFor(MediaKind.Video, settings) : null,
ct).ConfigureAwait(false)
: new LibraryConversionPreview(0, 0);
return ApiHttp.Json(new LibraryConversionPreviewDto(preview.Files, preview.Bytes, PreviewText(preview)), FebeJsonContext.Default.LibraryConversionPreviewDto);
});
@@ -658,6 +640,82 @@ public static class ExportApi
/// <summary>The wire name of a format (D21): <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>.</summary>
public static string FormatName(ExportFormat format) => format.ToString().ToLowerInvariant();
/// <summary>
/// PUT /api/export/settings under <see cref="SettingsGate"/>: loads the settings, applies the request, saves them
/// and tells the queue of the library conversion, all before the next change starts.
/// </summary>
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsAsync(
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
{
await SettingsGate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await SaveSettingsCoreAsync(body, storage, queue, ct).ConfigureAwait(false);
}
finally
{
SettingsGate.Release();
}
}
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsCoreAsync(
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
{
var queued = 0;
var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var after = before;
if (body.SamePost is { } samePostText)
{
after = after with
{
SamePost = samePostText.Trim().ToLowerInvariant() switch
{
"oneperaccount" => SamePostCopies.OnePerAccount,
"oneonly" => SamePostCopies.OneOnly,
_ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
},
};
}
after = after with
{
PhotoFormat = ParseFormat(body.PhotoFormat, MediaKind.Photo) ?? after.PhotoFormat,
VideoFormat = ParseFormat(body.VideoFormat, MediaKind.Video) ?? after.VideoFormat,
LibraryPhotoFormat = ParseFormat(body.LibraryPhotoFormat, MediaKind.Photo) ?? after.LibraryPhotoFormat,
LibraryVideoFormat = ParseFormat(body.LibraryVideoFormat, MediaKind.Video) ?? after.LibraryVideoFormat,
};
if (body.SamePost is null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null && body.ConvertExisting is null)
{
throw new BadRequestException("Niente da salvare: scegli un'impostazione.");
}
await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false);
await queue.OnSettingsChangedAsync(before, after, ct).ConfigureAwait(false);
if (body.ConvertExisting == true)
{
// «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps
// what was answered for it («Solo i nuovi» included, Q29).
var photo = Changed(MediaKind.Photo, body.LibraryPhotoFormat, before, after);
var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after);
if (photo is not null || video is not null)
{
queued = await queue.EnqueueExistingAsync(photo, video, ct).ConfigureAwait(false);
}
}
return (before, after, queued);
}
/// <summary>
/// The library format of <paramref name="kind"/> when this request set it and it changed (the kind the question
/// «Convertire anche i N file già in libreria?» was asked about); null otherwise, or when it is «Originale».
/// </summary>
private static ExportFormat? Changed(MediaKind kind, string? requested, ExportSettings before, ExportSettings after)
{
var now = LibraryConversionRules.FormatFor(kind, after);
return requested is not null && now != LibraryConversionRules.FormatFor(kind, before) ? now : null;
}
/// <summary>
/// A format of <paramref name="kind"/> from its wire name; null for null or empty (nothing chosen). 400 for a name
/// that is not a format of that kind.
+2 -1
View File
@@ -80,7 +80,8 @@ public sealed record LibraryConversionDto(int Pending, int Converted, int Failed
/// <summary>
/// <c>PUT /api/export/settings</c>, every field optional (null keeps it): «Lo stesso post in due account»
/// (<c>onePerAccount</c> or <c>oneOnly</c>), the formats of the copies and of the library (wire names).
/// <paramref name="ConvertExisting"/>: the answer «Anche i N già in libreria» when a library format is turned on.
/// <paramref name="ConvertExisting"/>: the answer «Anche i N già in libreria» when a library format is turned on or
/// changed; it queues the files of the kinds whose library format this request changes, never those of the other.
/// </summary>
public sealed record ExportSettingsRequest(
string? SamePost = null,
+18 -4
View File
@@ -71,7 +71,10 @@ public sealed class FrameService(IClock clock)
/// <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>
/// <summary>
/// A write of the zip that makes no progress for this long aborts the download: each piece of 64 KB sent restarts
/// the time, so a slow link that keeps reading is never cut.
/// </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>
@@ -371,6 +374,9 @@ public sealed class FrameService(IClock clock)
// 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;
// The bytes of one guarded write: the response buffer of Kestrel (64 KB).
private const int Piece = 64 * 1024;
private readonly MemoryStream _pending = new();
private long _position;
@@ -444,11 +450,19 @@ public sealed class FrameService(IClock clock)
await GuardedAsync(bytes, ct).ConfigureAwait(false);
}
/// <summary>
/// Sends <paramref name="buffer"/> in pieces of <see cref="Piece"/> bytes, each with its own time: a frame of
/// several megabytes on a slow link keeps going as long as every piece goes (a response write completes only once
/// the socket has taken nearly all of it), and stops after <c>stall</c> without one.
/// </summary>
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);
for (var offset = 0; offset < buffer.Length; offset += Piece)
{
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct);
guard.CancelAfter(stall);
await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false);
}
}
}
}