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>
This commit is contained in:
1 parent
958cb71cd6
commit
2efb408957
13 files changed
+459
-49
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore
|
||||
},
|
||||
ct);
|
||||
|
||||
private static void Set(WriteContext w, string key, string? value)
|
||||
/// <summary>Stores one value inside a write (null removes the key): also for stores that save settings with their rows.</summary>
|
||||
internal static void Set(WriteContext w, string key, string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
|
||||
@@ -188,12 +188,41 @@ internal sealed partial class MediaConversionStore
|
||||
}
|
||||
|
||||
public Task<int> 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<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> 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<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,9 @@ public sealed class FrameService(IClock clock)
|
||||
/// </summary>
|
||||
public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>The timers of <see cref="WriteStall"/> (a seam: a test moves their time only as its link sends).</summary>
|
||||
public TimeProvider StallTime { get; init; } = TimeProvider.System;
|
||||
|
||||
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
|
||||
public async Task<VideoFrameInfo> 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<string>(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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user