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

@@ -1,3 +1,4 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
@@ -19,24 +20,49 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
public const string PausedKey = "esportazione.libreria-sospesa";
/// <summary>
/// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files
/// stored in the library from then on (<see cref="Media.DownloadedAt"/>), the others only with «Anche i N».
/// </summary>
public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal";
/// <summary>As <see cref="PhotoSinceKey"/>, for videos.</summary>
public const string VideoSinceKey = "esportazione.libreria-formato-video-dal";
private static readonly Lock SignalGate = new();
private static TaskCompletionSource _signal = NewSignal();
/// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
public Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
var (files, bytes) = await storage.Conversions.CountExistingAsync(
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct).ConfigureAwait(false);
return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
}
/// <summary>
/// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked
/// about, as when only the other one is being turned on).
/// </summary>
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
{
var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false);
return new LibraryConversionPreview(files, bytes);
}
/// <summary>«Anche i N già in libreria»: queues the present files that convert, in one statement per kind. Returns how many.</summary>
public async Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
/// <summary>«Anche i N già in libreria» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
var added = await storage.Conversions.EnqueueExistingAsync(
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), clock.Now, ct).ConfigureAwait(false);
return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
}
/// <summary>
/// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds
/// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many.
/// </summary>
public async Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
{
var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
@@ -46,7 +72,8 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
}
/// <summary>
/// The settings changed: a library format turned off or changed loses its queue (its converted files and rows stay).
/// The settings changed: a library format turned off or changed loses its queue and its failures that «Riprova»
/// would put back (its converted files and rows stay).
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
/// «Anche i N già in libreria».
/// </summary>
@@ -57,17 +84,35 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{
var old = LibraryConversionRules.FormatFor(kind, before);
if (old is { } format && old != LibraryConversionRules.FormatFor(kind, after))
var now = LibraryConversionRules.FormatFor(kind, after);
if (old == now)
{
await storage.Conversions.DeletePendingAsync(format, ct).ConfigureAwait(false);
continue;
}
if (old is { } format)
{
await storage.Conversions.DeleteQueueAsync(format, ct).ConfigureAwait(false);
}
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
var since = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
await storage.Settings.SetAsync(SinceKey(kind), since, ct).ConfigureAwait(false);
}
}
/// <summary>«Riprova»: the failed files go back to the queue, except those that never convert (<c>AsIs*</c>). Returns how many.</summary>
/// <summary>
/// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert
/// (<c>AsIs*</c>). Returns how many.
/// </summary>
public async Task<int> RetryFailedAsync(CancellationToken ct = default)
{
var reset = await storage.Conversions.ResetFailedAsync(clock.Now, ct).ConfigureAwait(false);
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var formats = new[] { MediaKind.Photo, MediaKind.Video }
.Select(kind => LibraryConversionRules.FormatFor(kind, settings))
.OfType<ExportFormat>()
.ToList();
var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false);
if (reset > 0)
{
Signal();
@@ -94,8 +139,10 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
}
/// <summary>
/// Queues the present files of an entry by the library formats set now, after its journal line (the hook of
/// <see cref="LibraryIngest"/>). Nothing when both formats are «Originale». Returns how many rows were added.
/// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
/// <see cref="LibraryIngest"/>): those stored in the library since the format was set (<see cref="PhotoSinceKey"/>),
/// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included).
/// Nothing when both formats are «Originale». Returns how many rows were added.
/// </summary>
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
{
@@ -107,7 +154,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
return 0;
}
var requests = LibraryConversionRules.RequestsFor(media, settings);
var photoSince = await SinceAsync(storage.Settings, MediaKind.Photo, ct).ConfigureAwait(false);
var videoSince = await SinceAsync(storage.Settings, MediaKind.Video, ct).ConfigureAwait(false);
var requests = LibraryConversionRules.RequestsFor(
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
settings);
if (requests.Count == 0)
{
return 0;
@@ -122,6 +174,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
return added;
}
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
/// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary>
private static async Task<long?> SinceAsync(ISettingsStore settings, MediaKind kind, CancellationToken ct) =>
long.TryParse(await settings.GetAsync(SinceKey(kind), ct).ConfigureAwait(false), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
public static void Signal()
{
@@ -245,6 +245,15 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
return Outcome.Skipped;
}
// Only in the library format set now (§4.10, Q29): a row left in a format turned off or changed (put back by a
// supersession, say) is dropped, never converted.
var settings = await ExportSettings.LoadAsync(storage.Settings, token).ConfigureAwait(false);
if (LibraryConversionRules.FormatFor(media.Kind, settings) != row.Format)
{
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
return Outcome.Skipped;
}
var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false);
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
if (entry is null || account is null)
@@ -269,6 +278,13 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
return Outcome.Settled;
}
// A disk already below the threshold stays below it with the file: the pause starts before the original is read
// (hashed, decoded or remuxed) again at every wake-up (D17). The exact check with the file's length follows.
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before))
{
return Outcome.LowSpace;
}
var source = media.Sha256.ToLowerInvariant();
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
{
@@ -136,25 +136,26 @@ public static class MediaConverter
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
}
var converted = await throttle.RunAsync(token =>
var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) =>
{
token.ThrowIfCancellationRequested();
try
{
return ImageConverter.Convert(bytes, format);
return (ImageConverter.Convert(bytes, format), null);
}
catch (ImageLimitException)
{
return null;
// Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge».
return (null, ImageConversionLosses.AsIsTooLarge);
}
catch (ImageDecodeException)
{
return null;
return (null, ImageConversionLosses.AsIsNotDecodable);
}
}, ct).ConfigureAwait(false);
if (converted is null)
{
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsNotDecodable]);
return Whole(bytes, extension, sha, [refusal!]);
}
var data = converted.Data;
@@ -283,14 +283,11 @@ public sealed class DownloadDuplicateReview(
var folder = layout.AccountFolder(account);
// Its converted files of the library (tappa E3) go with it: the queue and the failures are dropped, the rows
// with a file become «Tolto». No supersession for the loser.
var conversions = await storage.Conversions.ListByMediaAsync(media.Id, ct).ConfigureAwait(false);
var withFiles = conversions
.Where(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null)
.ToList();
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
// Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue
// and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the
// worker records meanwhile is among them). No supersession for the loser.
var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
var withFiles = removed.Where(LibraryDeletion.HasFile).ToList();
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
hashIndex?.Remove(media.Id);
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
+7 -14
View File
@@ -65,9 +65,6 @@ public sealed class LibraryDeletion(
var folder = layout.AccountFolder(account);
var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
// From here the deletion goes to the end: a half-done deletion is worse than a late one.
@@ -75,16 +72,12 @@ public sealed class LibraryDeletion(
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
.ConfigureAwait(false);
IReadOnlyList<MediaConversion> withFiles;
if (mode == DeletionMode.Remember)
{
withFiles = conversions.Where(HasFile).ToList();
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false);
}
else
{
withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList();
}
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
// Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them.
var removed = mode == DeletionMode.Remember
? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false)
: await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false);
IReadOnlyList<MediaConversion> withFiles = removed.Where(HasFile).ToList();
foreach (var media in stored.Media)
{
@@ -141,7 +134,7 @@ public sealed class LibraryDeletion(
}
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
private static bool HasFile(MediaConversion c) =>
internal static bool HasFile(MediaConversion c) =>
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
/// <summary>
+2 -1
View File
@@ -373,7 +373,8 @@ public sealed class LibraryIngest(
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
ct).ConfigureAwait(false);
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line.
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
}
+4 -2
View File
@@ -83,8 +83,10 @@ public sealed class VideoFrameReader : IDisposable
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
}
// Samples shown before the start (cut by the edit list) are not chosen, unless nothing else is.
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0).ToArray();
// Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless
// nothing else is.
var end = video.EditSegmentDuration is { } segment && segment > 0 ? video.EmptyEditDuration + segment : long.MaxValue;
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0 && shown[i] < end).ToArray();
order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)];
Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
}