E3: seconda revisione di rimuxaggio, spazio, impostazioni e zip
verifica / controlli (push) Canceled after 0s
verifica / prove (push) Canceled after 0s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 14:29:00 +01:00
1 parent 958cb71cd6
commit 2efb408957
13 files changed
+459 -49

No files matched your search

+15 -6
View File
@@ -271,13 +271,14 @@ public static class Mp4Writer
}
/// <summary>
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/> and <paramref name="Shown"/> (the media
/// the edit shows, from <paramref name="EditMediaTime"/>) are in track units.
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/>, <paramref name="Shown"/> (the media
/// the edit shows, from <paramref name="EditMediaTime"/>) and <paramref name="PresentationEnd"/> (where the last
/// sample stops being shown, in composition time) are in track units.
/// </summary>
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)
{
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
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);
}
}
+11 -10
View File
@@ -68,18 +68,19 @@ public sealed record ExportSettings(
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
return store.SetManyAsync(
new Dictionary<string, string?>
{
[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);
}
/// <summary>The five keys with their stored values (for a write that stores more with them).</summary>
public Dictionary<string, string?> Values() => new(StringComparer.Ordinal)
{
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
[ExportSettingKeys.SamePost] = SamePost.ToString(),
};
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
{
@@ -72,15 +72,48 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
}
/// <summary>
/// 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 <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 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);
}
/// <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);
@@ -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);
}
/// <summary>
@@ -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;
/// <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;
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()
@@ -78,6 +78,14 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
private volatile string? _waiting;
private long _current;
/// <summary>
/// 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).
/// </summary>
private volatile LowSpaceMark? _lowSpace;
private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed);
/// <summary>The counts of the store with what the worker is doing now.</summary>
public async Task<LibraryConversionStatus> 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);
}
}
@@ -71,6 +71,13 @@ public interface IMediaConversionStore
/// </summary>
Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default);
/// <summary>
/// A change of the library formats: stores <paramref name="settings"/> (null values remove their key) and empties
/// the queues of <paramref name="formats"/> as <see cref="DeleteQueueAsync"/> 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.
/// </summary>
Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default);
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);