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
@@ -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<OperationCanceledException>(() => 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));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string?> GetAsync(string key, CancellationToken ct = default) => inner.Settings.GetAsync(key, ct);
|
||||
|
||||
public Task<IReadOnlyDictionary<string, string>> 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<string, string?> 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<ExportSettings> TurnOnAsync(TestLibrary library, ExportFormat photo)
|
||||
{
|
||||
var settings = ExportSettings.Default with { LibraryPhotoFormat = photo };
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>A segment read back from the movie timescale (milliseconds, rounded up) is within a millisecond.</summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>The duration of the first <c>mvhd</c> or <c>tkhd</c> of a file (movie units), of either version.</summary>
|
||||
private static long HeaderDuration(byte[] file, ReadOnlySpan<byte> 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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// A response body on a slow link: asynchronous writes only, each taking <c>perPiece</c> 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
|
||||
/// <see cref="LinkTime"/> a write moves that time instead of waiting for the real one.
|
||||
/// </summary>
|
||||
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<byte> 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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A time that moves only when <see cref="Advance"/> is called: its timers fire then, in order, on the caller's
|
||||
/// thread. Only one-shot timers (those of a <see cref="CancellationTokenSource"/>) are supported.
|
||||
/// </summary>
|
||||
private sealed class LinkTime : TimeProvider
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<LinkTimer> _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<LinkTimer> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A response body: asynchronous writes only.</summary>
|
||||
private sealed class AsyncOnlyStream(Stream inner) : Stream
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user