Files
Febe/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs
T
Alby96andClaude Opus 5.5 2efb408957
verifica / controlli (push) Canceled after 0s
verifica / prove (push) Canceled after 0s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
E3: seconda revisione di rimuxaggio, spazio, impostazioni e zip
Le quattro osservazioni confermate della seconda revisione, ognuna con
la sua prova (ciascuna cade sul codice di prima):

- Rimuxaggio con fotogrammi B: l'MP4 misura la fine della presentazione
  in tempo di composizione, non con la somma delle durate di decodifica.
  Prima nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone) e
  durava altrettanto meno in elst, tkhd e mvhd. Per le tracce senza
  scarti di composizione i byte restano gli stessi.
- Conversione della libreria: il lavoro ricorda il file che l'ha messo
  in pausa per spazio e quanto serve al suo convertito. Finché il disco
  non ha posto anche per quello, non rilegge l'originale a ogni
  risveglio (anche quando lo spazio libero sta appena sopra la soglia).
- Impostazioni dell'esportazione: formati, chiavi «dal» e coda del
  formato sostituito si salvano in una transazione sola; «Anche i N»
  dopo il salvataggio non dipende più dalla richiesta. Il gancio della
  libreria legge formati e chiavi «dal» in una lettura. Una scheda
  chiusa o un arresto non lasciano più un formato senza la sua chiave
  né «Non riuscito» che «Riprova» non tocca.
- Zip dei fotogrammi: i tempi del blocco passano da un TimeProvider
  della BCL, e la prova del lettore lento non dipende più dal carico
  della macchina.

Decisioni in docs/decisioni.md (28/11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:29:00 +01:00

243 lines
11 KiB
C#

using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library.Conversion;
/// <summary>What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17).</summary>
public sealed record LibraryConversionPreview(int Files, long Bytes);
/// <summary>
/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after
/// its line of <c>_febe.jsonl</c> (<see cref="LibraryIngest.AppendJournalAsync"/>); the files already in the library
/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29);
/// a format turned off or changed empties its queue, the converted files stay where they are.
/// </summary>
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 Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
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» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
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();
}
return added;
}
/// <summary>
/// Saves the settings <paramref name="after"/> (they were <paramref name="before"/>) with what a change of a library
/// format brings, in one transaction: the format, since when it is set (<see cref="PhotoSinceKey"/>) and the
/// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees
/// the new format without its «dal» key, nor the old failures left behind (D17, Q29).
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
/// «Anche i N già in libreria».
/// </summary>
public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var values = after.Values();
var (since, formats) = Changes(before, after);
foreach (var (key, value) in since)
{
values[key] = value;
}
return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct);
}
/// <summary>
/// The settings were saved by another way: a library format turned off or changed loses its queue and its failures
/// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction.
/// <see cref="SaveSettingsAsync"/> stores the settings with them.
/// </summary>
public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var (since, formats) = Changes(before, after);
return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct);
}
/// <summary>
/// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and
/// the format replaced, whose queue goes.
/// </summary>
private (Dictionary<string, string?> Since, List<ExportFormat> Formats) Changes(ExportSettings before, ExportSettings after)
{
var since = new Dictionary<string, string?>(StringComparer.Ordinal);
var formats = new List<ExportFormat>();
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{
var old = LibraryConversionRules.FormatFor(kind, before);
var now = LibraryConversionRules.FormatFor(kind, after);
if (old == now)
{
continue;
}
if (old is { } format)
{
formats.Add(format);
}
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
}
return (since, formats);
}
/// <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 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();
}
return reset;
}
/// <summary>«In pausa» or not.</summary>
public static async Task<bool> IsPausedAsync(ISettingsStore settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1";
}
/// <summary>«Sospendi» / «Riprendi» the conversion for the library.</summary>
public async Task SetPausedAsync(bool paused, CancellationToken ct = default)
{
await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false);
if (!paused)
{
Signal();
}
}
/// <summary>
/// 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)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(media);
// One read: the formats and their «dal» keys as one change stored them, never a format with an older key.
var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false);
var settings = ExportSettings.From(values);
if (!settings.ConvertsLibrary)
{
return 0;
}
var photoSince = Since(values, MediaKind.Photo);
var videoSince = Since(values, MediaKind.Video);
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;
}
var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
}
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 long? Since(IReadOnlyDictionary<string, string> values, MediaKind kind) =>
long.TryParse(values.GetValueOrDefault(SinceKey(kind)), 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()
{
TaskCompletionSource fired;
lock (SignalGate)
{
fired = _signal;
_signal = NewSignal();
}
fired.TrySetResult();
}
/// <summary>A task that completes at the next <see cref="Signal"/>.</summary>
internal static Task NextSignal()
{
lock (SignalGate)
{
return _signal.Task;
}
}
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}