From 2efb4089579c9b5bbe64d41460b18d8d9a3604b9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sat, 28 Nov 2026 14:29:00 +0100 Subject: [PATCH] E3: seconda revisione di rimuxaggio, spazio, impostazioni e zip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 4 + src/Febe.Core/Codecs/Containers/Mp4Writer.cs | 21 ++- src/Febe.Core/Export/ExportSettings.cs | 21 +-- .../Conversion/LibraryConversionQueue.cs | 58 +++++-- .../Conversion/LibraryConversionWorker.cs | 20 ++- .../Storage/IMediaConversionStore.cs | 7 + src/Febe.Data/Stores/EngineStores.cs | 3 +- .../Stores/MediaConversionStore.Library.cs | 39 ++++- src/Febe.Web/Api/ExportApi.cs | 7 +- src/Febe.Web/Export/FrameService.cs | 11 +- .../Library/LibraryConversionTests.cs | 155 ++++++++++++++++++ .../Media/Containers/Mp4RemuxerTests.cs | 57 +++++++ tests/Febe.Tests/Web/FrameServiceTests.cs | 105 +++++++++++- 13 files changed, 459 insertions(+), 49 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index a43285e..d0d0ba4 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -653,3 +653,7 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro | | 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate | | 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola | +| 2026-11-28 | Seconda revisione della tappa E3, video: `Mp4Writer` misura la fine della presentazione in tempo di composizione (il massimo di decodifica + scarto di composizione + durata di ogni campione), non la somma delle durate di decodifica. Con i fotogrammi B l'edit comincia al primo scarto di composizione e con la somma l'MP4 nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone), e durava altrettanto meno in `mvhd`, `tkhd` ed `elst`; il segmento della sorgente resta il limite. Vale per ogni scrittura, non solo per le sorgenti con un segmento: per una traccia senza scarti la fine è la stessa di prima e i byte non cambiano, con gli scarti il risultato di prima era sbagliato anche senza segmento (Matroska, ISO senza `elst`). | Una MOV con fotogrammi B rimuxata in MP4 (conversione della libreria o copia) deve mostrare quello che mostrava la sorgente; i fotogrammi presi dal convertito ora leggono il segmento giusto. | +| 2026-11-28 | Seconda revisione della tappa E3, conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito (riga, SHA-256 dell'originale, byte), e finché il disco non ha posto anche per quello la pausa vale prima di rileggere l'originale (hash, decodifica, rimuxaggio). Non si sottraggono i byte dell'originale in anticipo: un PNG grande che diventa un JPG piccolo resterebbe fermo senza motivo. Il ricordo è del processo: dopo un riavvio l'originale si rilegge una volta. | La pausa per spazio (D17) non deve rileggere lo stesso video di 2 GB a ogni risveglio quando lo spazio libero sta fra la soglia e la soglia più il file. | +| 2026-11-28 | Seconda revisione della tappa E3: un cambio dei formati della libreria si salva in una transazione sola con le chiavi «dal» e la coda svuotata del formato sostituito (`LibraryConversionQueue.SaveSettingsAsync`, `IMediaConversionStore.SaveSettingsAndDeleteQueuesAsync`); «Anche i N» dopo il salvataggio non dipende più dalla richiesta (`CancellationToken.None`). Il gancio della libreria legge formati e chiavi «dal» con una lettura sola. | Una scheda chiusa, un arresto o un file salvato in quel momento non devono vedere il formato nuovo senza la sua chiave «dal» (che metterebbe in coda tutto l'elemento) né lasciare «Non riuscito» del formato vecchio che «Riprova» non tocca più. | +| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. | diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs index 9362290..145c5ae 100644 --- a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -271,13 +271,14 @@ public static class Mp4Writer } /// - /// Times of a track as the boxes need them; and (the media - /// the edit shows, from ) are in track units. + /// Times of a track as the boxes need them; , (the media + /// the edit shows, from ) and (where the last + /// sample stops being shown, in composition time) are in track units. /// - private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown) + private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown, long PresentationEnd) { /// Whether the edit hides the end of the media (it must then be written). - public bool TrimsEnd => Shown < MediaDuration - EditMediaTime; + public bool TrimsEnd => Shown < PresentationEnd - EditMediaTime; internal static Timing Of(Mp4OutputTrack track) { @@ -315,6 +316,14 @@ public static class Mp4Writer total += d; } + // The presentation ends where the sample shown last stops, in composition time: with B frames that is later + // than the decoding durations add up to (by the first composition offset), and the edit starts there too. + long presentationEnd = 0; + for (var i = 0; i < n; i++) + { + presentationEnd = Math.Max(presentationEnd, samples[i].DecodeTime - first + offsets[i] + durations[i]); + } + // The edit list starts the presentation at the first shown sample, or where the track says; a start before // the first sample becomes an empty edit. var editTime = (track.EditMediaTime ?? minPts) - first + shift; @@ -325,13 +334,13 @@ public static class Mp4Writer editTime = 0; } - var shown = Math.Max(0, total - editTime); + var shown = Math.Max(0, presentationEnd - editTime); if (track.EditSegmentDuration is { } segment && segment > 0) { shown = Math.Min(shown, segment); } - return new Timing(durations, offsets, total, editTime, allKey, empty, shown); + return new Timing(durations, offsets, total, editTime, allKey, empty, shown, presentationEnd); } } diff --git a/src/Febe.Core/Export/ExportSettings.cs b/src/Febe.Core/Export/ExportSettings.cs index 2e2d1b9..2e3ac4a 100644 --- a/src/Febe.Core/Export/ExportSettings.cs +++ b/src/Febe.Core/Export/ExportSettings.cs @@ -68,18 +68,19 @@ public sealed record ExportSettings( public Task SaveAsync(ISettingsStore store, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(store); - return store.SetManyAsync( - new Dictionary - { - [ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(), - [ExportSettingKeys.VideoFormat] = VideoFormat.ToString(), - [ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(), - [ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(), - [ExportSettingKeys.SamePost] = SamePost.ToString(), - }, - ct); + return store.SetManyAsync(Values(), ct); } + /// The five keys with their stored values (for a write that stores more with them). + public Dictionary Values() => new(StringComparer.Ordinal) + { + [ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(), + [ExportSettingKeys.VideoFormat] = VideoFormat.ToString(), + [ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(), + [ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(), + [ExportSettingKeys.SamePost] = SamePost.ToString(), + }; + /// The settings from stored values: exact, case-sensitive names; anything else gives the key's default. internal static ExportSettings From(IReadOnlyDictionary values) { diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs index 759aa5f..73374b2 100644 --- a/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs +++ b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs @@ -72,15 +72,48 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) } /// - /// 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). + /// Saves the settings (they were ) with what a change of a library + /// format brings, in one transaction: the format, since when it is set () 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 only for /// «Anche i N già in libreria». /// - public async Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default) + 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); + } + + /// + /// 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. + /// stores the settings with them. + /// + 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); + } + + /// + /// 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. + /// + private (Dictionary Since, List Formats) Changes(ExportSettings before, ExportSettings after) + { + var since = new Dictionary(StringComparer.Ordinal); + var formats = new List(); foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video }) { var old = LibraryConversionRules.FormatFor(kind, before); @@ -92,13 +125,14 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) if (old is { } format) { - await storage.Conversions.DeleteQueueAsync(format, ct).ConfigureAwait(false); + formats.Add(format); } // 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); + since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); } + + return (since, formats); } /// @@ -148,14 +182,16 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(media); - var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + // 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 = await SinceAsync(storage.Settings, MediaKind.Photo, ct).ConfigureAwait(false); - var videoSince = await SinceAsync(storage.Settings, MediaKind.Video, ct).ConfigureAwait(false); + 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)), @@ -177,8 +213,8 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey; /// Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new. - private static async Task 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; + private static long? Since(IReadOnlyDictionary values, MediaKind kind) => + long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null; /// Wakes the worker: something entered the queue (or the pause ended). public static void Signal() diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs index e309c0e..0424648 100644 --- a/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs +++ b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs @@ -78,6 +78,14 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env) private volatile string? _waiting; private long _current; + /// + /// The file that last paused the conversion for space, with the length its converted file needs: until the disk + /// has room for that too, the original is not read (hashed, decoded or remuxed) again at every wake-up (D17). + /// + private volatile LowSpaceMark? _lowSpace; + + private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed); + /// The counts of the store with what the worker is doing now. public async Task StatusAsync(CancellationToken ct = default) { @@ -278,14 +286,16 @@ 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)) + // A disk already below the threshold stays below it with the file, and the file that paused the conversion last + // needs as much again: the pause holds before the original is read (hashed, decoded or remuxed) again at every + // wake-up (D17). The exact check with the file's length follows. + var source = media.Sha256.ToLowerInvariant(); + var needed = _lowSpace is { } mark && mark.RowId == row.Id && string.Equals(mark.SourceSha256, source, StringComparison.Ordinal) ? mark.Needed : 0; + if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before with { AvailableBytes = before.AvailableBytes - needed })) { return Outcome.LowSpace; } - var source = media.Sha256.ToLowerInvariant(); if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal)) { row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now }; @@ -332,9 +342,11 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env) if (_env.FreeSpace.Measure(folder) is { } space && _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length })) { + _lowSpace = new LowSpaceMark(row.Id, source, result.Length); return Outcome.LowSpace; } + _lowSpace = null; return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false); } } diff --git a/src/Febe.Core/Storage/IMediaConversionStore.cs b/src/Febe.Core/Storage/IMediaConversionStore.cs index 9f50ac4..b65b335 100644 --- a/src/Febe.Core/Storage/IMediaConversionStore.cs +++ b/src/Febe.Core/Storage/IMediaConversionStore.cs @@ -71,6 +71,13 @@ public interface IMediaConversionStore /// Task DeleteQueueAsync(ExportFormat format, CancellationToken ct = default); + /// + /// A change of the library formats: stores (null values remove their key) and empties + /// the queues of as does, in one transaction, so that the + /// formats, the keys that go with them and the queues are stored whole or not at all. Returns how many rows went. + /// + Task SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary settings, IReadOnlyCollection formats, CancellationToken ct = default); + /// Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending. Task DeletePendingRowAsync(long id, CancellationToken ct = default); diff --git a/src/Febe.Data/Stores/EngineStores.cs b/src/Febe.Data/Stores/EngineStores.cs index eb92055..44add40 100644 --- a/src/Febe.Data/Stores/EngineStores.cs +++ b/src/Febe.Data/Stores/EngineStores.cs @@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore }, ct); - private static void Set(WriteContext w, string key, string? value) + /// Stores one value inside a write (null removes the key): also for stores that save settings with their rows. + internal static void Set(WriteContext w, string key, string? value) { if (value is null) { diff --git a/src/Febe.Data/Stores/MediaConversionStore.Library.cs b/src/Febe.Data/Stores/MediaConversionStore.Library.cs index 9b6ba3b..03b3b7c 100644 --- a/src/Febe.Data/Stores/MediaConversionStore.Library.cs +++ b/src/Febe.Data/Stores/MediaConversionStore.Library.cs @@ -188,12 +188,41 @@ internal sealed partial class MediaConversionStore } public Task DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) => - db.WriteAsync( - w => w.Command($""" - DELETE FROM media_conversion - WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})))) - """).With("@f", Sql.Enum(format)).ExecuteNonQuery(), + db.WriteAsync(w => DeleteQueue(w, format), ct); + + public Task SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary settings, IReadOnlyCollection formats, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(formats); + foreach (var key in settings.Keys) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + } + + return db.WriteAsync( + w => + { + foreach (var (key, value) in settings) + { + SettingsStore.Set(w, key, value); + } + + var deleted = 0; + foreach (var format in formats.Distinct()) + { + deleted += DeleteQueue(w, format); + } + + return deleted; + }, ct); + } + + private static int DeleteQueue(WriteContext w, ExportFormat format) => + w.Command($""" + DELETE FROM media_conversion + WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})))) + """).With("@f", Sql.Enum(format)).ExecuteNonQuery(); public Task DeletePendingRowAsync(long id, CancellationToken ct = default) => db.WriteAsync( diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs index ca52cb1..c1c4f83 100644 --- a/src/Febe.Web/Api/ExportApi.cs +++ b/src/Febe.Web/Api/ExportApi.cs @@ -689,8 +689,9 @@ public static class ExportApi 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); + // The formats, their «dal» keys and the queue of a format replaced in one transaction; once it is stored, what + // follows no longer depends on the request (a closed tab must not leave half of it). + await queue.SaveSettingsAsync(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 @@ -699,7 +700,7 @@ public static class ExportApi 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); + queued = await queue.EnqueueExistingAsync(photo, video, CancellationToken.None).ConfigureAwait(false); } } diff --git a/src/Febe.Web/Export/FrameService.cs b/src/Febe.Web/Export/FrameService.cs index 744bf66..c7d0e3f 100644 --- a/src/Febe.Web/Export/FrameService.cs +++ b/src/Febe.Web/Export/FrameService.cs @@ -77,6 +77,9 @@ public sealed class FrameService(IClock clock) /// public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60); + /// The timers of (a seam: a test moves their time only as its link sends). + public TimeProvider StallTime { get; init; } = TimeProvider.System; + /// What a video allows, from the cache by SHA-256 when known (the file is opened only the first time). public async Task InfoAsync(string path, string? sha256, CancellationToken ct) { @@ -203,7 +206,7 @@ public sealed class FrameService(IClock clock) 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 guarded = new StallGuardStream(output, WriteStall, StallTime); var names = new HashSet(StringComparer.OrdinalIgnoreCase); var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false); await using (zip.ConfigureAwait(false)) @@ -369,7 +372,7 @@ public sealed class FrameService(IClock clock) /// .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. /// - private sealed class StallGuardStream(Stream inner, TimeSpan stall) : Stream + private sealed class StallGuardStream(Stream inner, TimeSpan stall, TimeProvider time) : 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; @@ -459,8 +462,8 @@ public sealed class FrameService(IClock clock) { for (var offset = 0; offset < buffer.Length; offset += Piece) { - using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct); - guard.CancelAfter(stall); + using var timer = new CancellationTokenSource(stall, time); + using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct, timer.Token); await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false); } } diff --git a/tests/Febe.Tests/Library/LibraryConversionTests.cs b/tests/Febe.Tests/Library/LibraryConversionTests.cs index 007ff45..6ff6d18 100644 --- a/tests/Febe.Tests/Library/LibraryConversionTests.cs +++ b/tests/Febe.Tests/Library/LibraryConversionTests.cs @@ -1,9 +1,11 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; +using Febe.Core.Alerts; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Library.Conversion; +using Febe.Core.Storage; using Febe.Tests.Alerts.Support; using Febe.Tests.Export.Support; using Febe.Tests.Import.Support; @@ -343,6 +345,55 @@ public sealed class LibraryConversionTests Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts"); } + [TestMethod] + public async Task AFileThatWouldTakeTheDiskBelowTheThresholdIsNotReadAgainAtEveryWakeUp() + { + // Free space above the threshold, but not by the converted file's length: the first pass reads the original and + // pauses; the next ones pause before reading it again, until the disk has room for that file too. + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 25); + var folder = library.Layout.AccountFolder(account); + const long Threshold = 10 * FakeFreeSpaceProbe.GB; + var space = new FakeFreeSpaceProbe(); + space.Set(folder, Threshold + 1, 1000 * FakeFreeSpaceProbe.GB); + var throttle = new ConversionThrottle(); + var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with + { + FreeSpace = space, + Thresholds = new DiskThresholds(Threshold, 0), + }); + + var first = await worker.RunOnceAsync(ct); + Assert.AreEqual((0, false), (first.Done, first.Again)); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting, "the converted file does not fit"); + + // Another conversion holds the throttle: a pass that decoded the photo again would wait for it. + using var release = new ManualResetEventSlim(); + var other = throttle.RunAsync(_ => release.Wait(TimeSpan.FromMinutes(1)), ct); + try + { + for (var wakeUp = 0; wakeUp < 3; wakeUp++) + { + space.Set(folder, Threshold + 1 + wakeUp, 1000 * FakeFreeSpaceProbe.GB); // a little more, never enough + var pass = await worker.RunOnceAsync(ct).WaitAsync(TimeSpan.FromSeconds(30), ct); + Assert.AreEqual((0, false), (pass.Done, pass.Again)); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting); + } + } + finally + { + release.Set(); + await other; + } + + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + space.Set(folder, Threshold + FakeFreeSpaceProbe.GB, 1000 * FakeFreeSpaceProbe.GB); + Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "room for the file: it converts"); + } + [TestMethod] public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted() { @@ -386,6 +437,43 @@ public sealed class LibraryConversionTests Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal)), "only the original"); } + [TestMethod] + public async Task AChangeOfFormatIsStoredWithItsDalKeyAndQueueWholeOrNotAtAll() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var jpg = await TurnOnAsync(library, ExportFormat.Jpg); + var (account, failed) = await SavePngAsync(library, "1", 26); + File.Delete(library.Layout.FullPath(account, failed.Media[0].RelativePath!)); + await Worker(library).RunOnceAsync(ct); + await SavePngAsync(library, "2", 27); + Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed)); + var png = jpg with { LibraryPhotoFormat = ExportFormat.Png }; + + // A request aborted before its write stores nothing of the change. + using var aborted = new CancellationTokenSource(); + await aborted.CancelAsync(); + await Assert.ThrowsAsync(() => new LibraryConversionQueue(library.Db, library.Clock).SaveSettingsAsync(jpg, png, aborted.Token)); + Assert.AreEqual(ExportFormat.Jpg, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat); + Assert.IsNull(await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct)); + Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed)); + + // A request aborted once the format is written (the tab closed): the change is already whole, never a format + // without its «dal» key or with the old failures left behind. + using var request = new CancellationTokenSource(); + var storage = new AbortAfterSettingsWrite(library.Db, request); + library.Clock.Now += TimeSpan.FromMinutes(1); + await new LibraryConversionQueue(storage, library.Clock).SaveSettingsAsync(jpg, png, request.Token); + + Assert.AreEqual(0, storage.SettingsWrites, "nothing of the change is written on its own"); + Assert.AreEqual(ExportFormat.Png, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat); + Assert.AreEqual(library.Clock.Now.ToUnixTimeMilliseconds().ToString(System.Globalization.CultureInfo.InvariantCulture), await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct)); + var counts = await library.Db.Conversions.CountByStateAsync(ct); + Assert.AreEqual((0, 0), (counts.Pending, counts.Failed), "the queue and the failures of JPG went with it"); + Assert.AreEqual(0, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct)); + } + [TestMethod] public async Task AConversionRecordedWhileTheEntryIsDeletedGoesWithIt() { @@ -699,6 +787,73 @@ public sealed class LibraryConversionTests private static LibraryConversionWorker Worker(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new(Environment(library, gate, throttle)); + /// + /// The storage of a request whose client goes away as soon as a setting is written on its own (outside the + /// transaction of the conversion store): every later write that honours the request's token fails. + /// + private sealed class AbortAfterSettingsWrite(IFebeStorage inner, CancellationTokenSource request) : IFebeStorage, ISettingsStore + { + public int SettingsWrites { get; private set; } + + public IAccountStore Accounts => inner.Accounts; + + public IEntryStore Entries => inner.Entries; + + public IMediaStore Media => inner.Media; + + public IHighlightStore Highlights => inner.Highlights; + + public IDuplicateStore Duplicates => inner.Duplicates; + + public ITaskStore Tasks => inner.Tasks; + + public IActionLogStore ActionLog => inner.ActionLog; + + public ISessionStore Sessions => inner.Sessions; + + public IIncidentStore Incidents => inner.Incidents; + + public IEventStore Events => inner.Events; + + public IFollowingStore Following => inner.Following; + + public IImportStore Imports => inner.Imports; + + public IExportStore Exports => inner.Exports; + + public IVideoAnalysisStore VideoAnalyses => inner.VideoAnalyses; + + public IMediaConversionStore Conversions => inner.Conversions; + + public ISettingsStore Settings => this; + + public IDatabaseMaintenance Maintenance => inner.Maintenance; + + public Task GetAsync(string key, CancellationToken ct = default) => inner.Settings.GetAsync(key, ct); + + public Task> GetAllAsync(CancellationToken ct = default) => inner.Settings.GetAllAsync(ct); + + public async Task SetAsync(string key, string? value, CancellationToken ct = default) + { + await inner.Settings.SetAsync(key, value, ct); + Wrote(); + } + + public async Task SetManyAsync(IReadOnlyDictionary values, CancellationToken ct = default) + { + await inner.Settings.SetManyAsync(values, ct); + Wrote(); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; // the library owns the database + + private void Wrote() + { + SettingsWrites++; + request.Cancel(); + } + } + private static async Task TurnOnAsync(TestLibrary library, ExportFormat photo) { var settings = ExportSettings.Default with { LibraryPhotoFormat = photo }; diff --git a/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs index c2e168d..e63ae10 100644 --- a/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs +++ b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using System.Security.Cryptography; using Febe.Core.Codecs.Containers; @@ -97,6 +98,62 @@ public sealed class Mp4RemuxerTests Assert.AreEqual(ShownFrames - 1, last.Sample); } + [TestMethod] + public void TheLastReorderedFramesStayShownInTheMp4() + { + // B frames, as iPhones and High profile encoders write them: the edit starts at the first composition offset + // and shows the whole presentation (N frames). The MP4 must show as much, never 2 frames less. + var es = ElementaryStream.Load("CABA3_SVA_B"); + var n = es.Count; + Assert.IsTrue(Enumerable.Range(0, n).Any(i => es.Rank[i] < i), "the stream has reordered frames"); + var presentation = (long)n * TestVideos.FrameTicks; + var mov = TestVideos.Mov(es, new MovOptions(VideoTrim: presentation)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.IsGreaterThan(0L, before.Video!.EditMediaTime ?? 0, "the edit starts at the first composition offset"); + AssertAbout(presentation, before.Video.EditSegmentDuration, "the source shows all N frames"); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + var mp4 = Remux(plan!, source); + using var output = new MemoryStream(mp4); + var after = Read(output); + + Assert.AreEqual(before.Video.EditMediaTime, after.Video!.EditMediaTime); + Assert.AreEqual(before.Video.EditSegmentDuration, after.Video.EditSegmentDuration, "the segment is the source's"); + AssertAbout(presentation, after.Video.EditSegmentDuration, "the MP4 shows all N frames"); + Assert.AreEqual(before.Duration, after.Duration); + var shownMs = (long)Math.Ceiling(n * 1000.0 / 30); + Assert.AreEqual((shownMs, shownMs), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)), "mvhd and tkhd last N frames"); + Assert.AreEqual((HeaderDuration(mov, "mvhd"u8), HeaderDuration(mov, "tkhd"u8)), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8))); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + + // A frame «oltre la fine» is the one presented last, not one that decodes last. + var lastShown = Enumerable.Range(0, n).MaxBy(i => es.Rank[i]); + using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info); + Assert.IsTrue(info.Available); + Assert.AreEqual(lastShown, reader.Locate([TimeSpan.FromHours(1)]).Single().Sample); + } + + /// A segment read back from the movie timescale (milliseconds, rounded up) is within a millisecond. + private static void AssertAbout(long expected, long? actual, string what) + { + Assert.IsNotNull(actual, what); + Assert.IsLessThanOrEqualTo(TestVideos.Timescale / 1000, Math.Abs(actual.Value - expected), $"{what}: {actual} for {expected}"); + } + + /// The duration of the first mvhd or tkhd of a file (movie units), of either version. + private static long HeaderDuration(byte[] file, ReadOnlySpan type) + { + var at = file.AsSpan().IndexOf(type); + Assert.IsGreaterThan(0, at); + var body = file.AsSpan(at + 4); + var wide = body[0] == 1; + var isTrack = type[0] == (byte)'t'; + // version and flags, the dates, then the timescale (mvhd) or the track id and a reserved word (tkhd). + var offset = 4 + (wide ? 16 : 8) + (isTrack ? 8 : 4); + return wide ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[offset..]) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]); + } + [TestMethod] [DataRow(44100, 0x6B)] [DataRow(32000, 0x6B)] diff --git a/tests/Febe.Tests/Web/FrameServiceTests.cs b/tests/Febe.Tests/Web/FrameServiceTests.cs index 13c5e67..b2cae0f 100644 --- a/tests/Febe.Tests/Web/FrameServiceTests.cs +++ b/tests/Febe.Tests/Web/FrameServiceTests.cs @@ -54,14 +54,17 @@ public sealed class FrameServiceTests using var temp = new TempFolder("fotogrammi-lento"); var path = temp.Combine("rumore.mp4"); await File.WriteAllBytesAsync(path, NoiseVideo(), ct); - var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400) }; + + // The time of the stalls moves only as the link sends, never with the load of the machine. + var time = new LinkTime(); + var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400), StallTime = time }; var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0), ]); // 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes. using var sent = new MemoryStream(); - var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150)); + var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150), time); await service.WriteZipAsync(link, plan, publicationTime: false, ct); using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); @@ -113,9 +116,10 @@ public sealed class FrameServiceTests /// /// A response body on a slow link: asynchronous writes only, each taking perPiece for every 64 KB it holds - /// (a write completes once its bytes are sent); an infinite time is a reader that stopped. + /// (a write completes once its bytes are sent); an infinite time is a reader that stopped. With a + /// a write moves that time instead of waiting for the real one. /// - private sealed class SlowStream(Stream inner, TimeSpan perPiece) : Stream + private sealed class SlowStream(Stream inner, TimeSpan perPiece, LinkTime? time = null) : Stream { public TimeSpan Busy { get; private set; } @@ -149,7 +153,16 @@ public sealed class FrameServiceTests public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536); - await Task.Delay(wait, cancellationToken); + if (time is not null && wait != Timeout.InfiniteTimeSpan) + { + time.Advance(wait); // the stall timers due before this write is sent fire now + cancellationToken.ThrowIfCancellationRequested(); + } + else + { + await Task.Delay(wait, cancellationToken); + } + if (wait != Timeout.InfiniteTimeSpan) { Busy += wait; @@ -159,6 +172,88 @@ public sealed class FrameServiceTests } } + /// + /// A time that moves only when is called: its timers fire then, in order, on the caller's + /// thread. Only one-shot timers (those of a ) are supported. + /// + private sealed class LinkTime : TimeProvider + { + private readonly Lock _gate = new(); + private readonly List _timers = []; + private DateTimeOffset _now = Make.T0; + + public override DateTimeOffset GetUtcNow() + { + lock (_gate) + { + return _now; + } + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + Assert.AreEqual(Timeout.InfiniteTimeSpan, period, "one-shot timers only"); + var timer = new LinkTimer(this, callback, state); + timer.Change(dueTime, period); + return timer; + } + + public void Advance(TimeSpan by) + { + List due; + lock (_gate) + { + _now += by; + due = [.. _timers.Where(t => t.Due <= _now).OrderBy(t => t.Due)]; + foreach (var t in due) + { + _timers.Remove(t); + } + } + + foreach (var t in due) + { + t.Fire(); + } + } + + private sealed class LinkTimer(LinkTime owner, TimerCallback callback, object? state) : ITimer + { + public DateTimeOffset Due { get; private set; } + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + lock (owner._gate) + { + owner._timers.Remove(this); + if (dueTime != Timeout.InfiniteTimeSpan) + { + Due = owner._now + dueTime; + owner._timers.Add(this); + } + } + + return true; + } + + public void Fire() => callback(state); + + public void Dispose() + { + lock (owner._gate) + { + owner._timers.Remove(this); + } + } + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } + } + /// A response body: asynchronous writes only. private sealed class AsyncOnlyStream(Stream inner) : Stream {