E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova: - JPEG: il controllo stima la memoria di lavoro del decodificatore (progressivo), così un file che non si decodifica esce «troppo grande» e non «illeggibile». - Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento, perché la foto convertita non esca girata. - Fotogrammi: istanti in millisecondi interi; la copia trova l'indice del nome dall'istante, non dall'ordine delle righe. - Video di durata sconosciuta misurati prima di registrare: contano nei limiti di 500 per richiesta e 5000 per video. - Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine tagliata resta nascosta (anche nei fotogrammi). - H.264: il punto di recupero vale come IDR solo con exact_match_flag. - MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre. - Conversione della libreria: il lavoro toglie le righe di un formato spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova» solo i formati di adesso; pausa per spazio prima di rileggere l'originale. - «Anche i N» conta e mette in coda solo il tipo che si cambia; le impostazioni dell'esportazione si salvano una per volta. - Eliminazione e «Tieni il più grande» scelgono i convertiti nella stessa transazione: nessun convertito orfano. - Un file arrivato tardi in un elemento vecchio mette in coda solo sé (file nuovo = salvato da quando il formato è scelto). - Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non si interrompe, uno fermo sì. Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eb79b05fda
commit
958cb71cd6
38 files changed
+1276
-222
No files matched your search
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library;
|
||||
@@ -234,6 +235,101 @@ public sealed class ExportFramesTests
|
||||
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NInAllOnAVideoShorterThanNMillisecondsNamesEachFrameByItsPosition()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var still = TestVideos.Mp4(Stream.FirstPictureRepeated(18)); // 0,6 s: 1.000 instants cannot all be a millisecond apart
|
||||
var video = (await SaveVideoAsync(bed, bed.Marta, "993", still, ".mp4")).Media[0];
|
||||
await bed.GeneralAsync(ct: ct);
|
||||
const int N = 1000;
|
||||
|
||||
// The instants are whole milliseconds (the item, the preview and the download locate the same one); the first of
|
||||
// those on one millisecond is the item, the others are counted as already there.
|
||||
var instants = ExportFrames.Spread(Duration(still), N);
|
||||
Assert.IsTrue(instants.All(t => t.Ticks % TimeSpan.TicksPerMillisecond == 0));
|
||||
var firsts = instants.Select((t, i) => (Ms: (long)t.TotalMilliseconds, Index: i)).GroupBy(x => x.Ms).Select(g => g.First()).ToList();
|
||||
Assert.IsLessThan(N, firsts.Count);
|
||||
|
||||
var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct);
|
||||
|
||||
Assert.AreEqual((firsts.Count, N - firsts.Count), (start.Plan.Frames, start.Plan.AlreadyCopied), "the plan says what is recorded");
|
||||
var items = await bed.ItemsAsync(start.Runs.Single().Id, ct);
|
||||
CollectionAssert.AreEqual(firsts.Select(f => (TimeSpan?)TimeSpan.FromMilliseconds(f.Ms)).ToArray(), items.Select(i => i.FrameAt).ToArray());
|
||||
|
||||
// Each frame written is named by its position among the N instants, as «Scarica» names it, not by its row.
|
||||
var targets = Locate(still, [.. firsts.Select(f => TimeSpan.FromMilliseconds(f.Ms))]);
|
||||
var stem = Path.ChangeExtension(video.RelativePath!, null);
|
||||
var leaders = targets.Select((t, k) => (t.Sample, k)).GroupBy(x => x.Sample).Select(g => g.First().k).ToList();
|
||||
Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb));
|
||||
foreach (var k in leaders)
|
||||
{
|
||||
Assert.AreEqual(ExportItemState.Copied, items[k].State);
|
||||
Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, firsts[k].Index, N) + ".png", items[k].RelativePath, $"frame {k}");
|
||||
}
|
||||
|
||||
Assert.AreNotEqual(leaders.Count - 1, firsts[leaders[^1]].Index, "the positions skip the instants on one millisecond");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VideosOfUnknownLengthCountAgainstTheCapsBeforeAnythingIsRecorded()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.GeneralAsync(ct: ct);
|
||||
|
||||
// One video of 200 s the library has no length for, one every 0,1 s: 2.000 frames, refused before any run.
|
||||
var long200 = (await SaveVideoAsync(bed, bed.Marta, "980", LongStill(200), ".mp4")).Media[0];
|
||||
var every = Frames(long200, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png));
|
||||
var overCap = await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(every, ct));
|
||||
StringAssert.StartsWith(overCap.Message, ExportFrames.OverCapMessage);
|
||||
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||
|
||||
// 21 videos of a second without a length, 1.000 each: 21.000 frames, over the 20.000 of a request.
|
||||
var still = Stream.FirstPictureRepeated(30);
|
||||
var ids = new List<long>();
|
||||
for (var i = 0; i < 21; i++)
|
||||
{
|
||||
ids.Add((await SaveVideoAsync(bed, bed.Marta, $"96{i:D2}", TestVideos.Mp4(still, Make.T0.AddDays(-i)), ".mp4")).Media[0].Id);
|
||||
}
|
||||
|
||||
var many = new ExportJobRequest(new ExportSelection.Media(ids), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 1000, ExportFormat.Png));
|
||||
var tooMany = await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(many, ct));
|
||||
StringAssert.StartsWith(tooMany.Message, ExportService.TooManyFramesText);
|
||||
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
|
||||
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
|
||||
|
||||
Assert.AreEqual(21, (await bed.Service.PlanAsync(many, ct)).Frames, "the dialog does not read the files: «circa» one a video");
|
||||
|
||||
// Two of them, 3 each: measured when the job is recorded, the plan of the start says what was recorded.
|
||||
var two = new ExportJobRequest(new ExportSelection.Media(ids.Take(2).ToList()), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png));
|
||||
var started = await bed.CopyAsync(two, ct);
|
||||
Assert.AreEqual((2, 6), (started.Plan.Videos, started.Plan.Frames));
|
||||
Assert.HasCount(6, await bed.ItemsAsync(started.Runs.Single().Id, ct));
|
||||
}
|
||||
|
||||
/// <summary>A video of one still picture shown for <paramref name="seconds"/>.</summary>
|
||||
private static byte[] LongStill(int seconds)
|
||||
{
|
||||
var es = Stream.FirstPictureRepeated(1);
|
||||
var bytes = es.LengthPrefixed(0);
|
||||
var track = new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = true,
|
||||
Timescale = TestVideos.Timescale,
|
||||
Samples = [new Mp4OutputSample(bytes.Length, 0, 0, true)],
|
||||
WriteSample = (_, s) => s.Write(bytes),
|
||||
Width = es.Width,
|
||||
Height = es.Height,
|
||||
AvcConfiguration = es.AvcC,
|
||||
LastSampleDuration = (long)seconds * TestVideos.Timescale,
|
||||
};
|
||||
using var output = new MemoryStream();
|
||||
Mp4Writer.Write(output, [track]);
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames);
|
||||
|
||||
/// <summary>A video whose length the library does not know (it is read when the job is recorded).</summary>
|
||||
|
||||
@@ -161,4 +161,57 @@ public sealed class ImageConversionCheckTests
|
||||
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.Jpeg).NoteCode);
|
||||
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.WebP).NoteCode);
|
||||
}
|
||||
|
||||
/// <summary>A JPEG of only its header (SOI, SOF, SOS, EOI): enough for the check, which never decodes.</summary>
|
||||
private static byte[] JpegHeader(int frameMarker, int width, int height, byte lumaSampling)
|
||||
{
|
||||
return
|
||||
[
|
||||
0xFF, 0xD8,
|
||||
0xFF, (byte)frameMarker, 0, 17, 8, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3,
|
||||
1, lumaSampling, 0, 2, 0x11, 1, 3, 0x11, 1,
|
||||
0xFF, 0xDA, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 0, 0,
|
||||
0xFF, 0xD9,
|
||||
];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AProgressiveJpegTheDecoderWouldRefuseIsTooLargeNotUnreadable()
|
||||
{
|
||||
// 8000 × 8000 = 64 MP, within the 100 MP of PNG and JPG. Baseline it needs 3 bytes a pixel besides the picture;
|
||||
// progressive 4:4:4 keeps its coefficients too, 9 bytes a pixel: 576 MB, over the decoder's 512 MiB.
|
||||
var baseline = JpegHeader(0xC0, 8000, 8000, 0x11);
|
||||
var progressive = JpegHeader(0xC2, 8000, 8000, 0x11);
|
||||
var progressive420 = JpegHeader(0xC2, 8000, 8000, 0x22);
|
||||
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png).Action);
|
||||
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive420, ImageFormat.Png).Action, "4:2:0: 4,5 byte a pixel");
|
||||
Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Jpeg, ImageConversionLosses.AsIsTooLarge),
|
||||
ImageConverter.Check(progressive, ImageFormat.Png));
|
||||
Assert.AreEqual(576_000_000L, ImageDecoder.Identify(progressive).DecodeWorkingBytes);
|
||||
|
||||
// The copy and the library conversion say «troppo grande», never «Febe non riesce a leggere l'immagine».
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(progressive));
|
||||
using var prepared = await MediaConverter.PrepareAsync(() => new MemoryStream(progressive), "post/grande.jpg", MediaKind.Photo,
|
||||
ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None);
|
||||
Assert.AreEqual(ExportVariant.Whole, prepared.Variant);
|
||||
CollectionAssert.AreEqual(new[] { ImageConversionLosses.AsIsTooLarge }, prepared.Notes.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WhatTheCheckLetsThroughTheDecoderConverts()
|
||||
{
|
||||
// A real progressive 4:4:4 JPEG of 64 × 64 under a working budget between the 3 bytes a pixel of a baseline
|
||||
// decode and the 9 of a progressive one: the check sends it as it is, so the conversion never throws.
|
||||
using var picture = Gradient(64, 64, seed: 3);
|
||||
var baseline = ImageConverter.Encode(picture, ImageFormat.Jpeg, null, new ImageConversionOptions { JpegSubsampling = JpegSubsampling.Ratio444 });
|
||||
var progressive = JpegTestEncoder.Write(JpegDecoder.DecodeCoefficients(baseline), new JpegTestOptions { Progressive = true });
|
||||
var options = new ImageConversionOptions { Limits = new ImageLimits { MaxWorkingBytes = 64 * 64 * 6 } };
|
||||
|
||||
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png, options).Action);
|
||||
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(baseline, ImageFormat.Png, options).Data));
|
||||
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(progressive, ImageFormat.Png, options).NoteCode);
|
||||
Assert.ThrowsExactly<ImageLimitException>(() => ImageConverter.Convert(progressive, ImageFormat.Png, options));
|
||||
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive, ImageFormat.Png).Action, "con i limiti di sempre");
|
||||
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(progressive, ImageFormat.Png).Data));
|
||||
}
|
||||
}
|
||||
@@ -87,4 +87,51 @@ public sealed class ImageConversionTests
|
||||
CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite);
|
||||
CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(true)]
|
||||
[DataRow(false)]
|
||||
public void AnExifTooLargeForJpgStillKeepsTheOrientation(bool littleEndian)
|
||||
{
|
||||
// 70 000 bytes of TIFF (a big maker note, say) with Orientation 6: more than one APP1 segment holds. The block is
|
||||
// left behind, but the pixels are never turned (§4.10): without the tag the JPG would show turned.
|
||||
var exif = new byte[70_000];
|
||||
var tiff = exif.AsSpan();
|
||||
tiff[0] = tiff[1] = littleEndian ? (byte)'I' : (byte)'M';
|
||||
void W16(int at, ushort v)
|
||||
{
|
||||
if (littleEndian)
|
||||
{
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(exif.AsSpan(at), v);
|
||||
}
|
||||
else
|
||||
{
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(exif.AsSpan(at), v);
|
||||
}
|
||||
}
|
||||
|
||||
W16(2, 42);
|
||||
W16(littleEndian ? 4 : 6, 8); // first IFD at 8
|
||||
W16(8, 1);
|
||||
W16(10, 0x0112);
|
||||
W16(12, 3);
|
||||
W16(littleEndian ? 14 : 16, 1);
|
||||
W16(18, 6);
|
||||
using var picture = Gradient(4, 4, seed: 5);
|
||||
var png = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif, Orientation = 6 });
|
||||
Assert.AreEqual(6, ImageDecoder.Identify(png).Metadata.Orientation);
|
||||
|
||||
var result = ImageConverter.Convert(png, ImageFormat.Jpeg);
|
||||
|
||||
CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.LostExifTooLarge);
|
||||
var written = ImageDecoder.Identify(result.Data).Metadata;
|
||||
Assert.AreEqual(6, written.Orientation);
|
||||
Assert.AreEqual(6, result.Metadata.Orientation);
|
||||
Assert.AreEqual(26, written.Exif!.Length);
|
||||
Assert.AreEqual(littleEndian ? (byte)'I' : (byte)'M', written.Exif[0], "l'ordine dei byte della sorgente");
|
||||
|
||||
// Orientation 1 needs no block at all.
|
||||
var upright = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif.AsSpan(0, 8).ToArray().Concat(new byte[70_000]).ToArray(), Orientation = 1 });
|
||||
Assert.IsNull(ImageDecoder.Identify(ImageConverter.Convert(upright, ImageFormat.Jpeg).Data).Metadata.Exif);
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,35 @@ public sealed class LibraryConversionTests
|
||||
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(jpg.Media[0].Id, ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ALateFileOfAnOldEntryQueuesItselfOnly()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
using var temp = new TempFolder();
|
||||
await using var library = await TestLibrary.CreateAsync(temp);
|
||||
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
var added = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Photo(2)], ct);
|
||||
var (first, second) = (added.Stored.Media[0], added.Stored.Media[1]);
|
||||
await StorePngAsync(library, account, added.Stored.Entry, first, 31);
|
||||
await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct);
|
||||
|
||||
// Photos to JPG with «Solo i nuovi»: the PNG already in the library is left alone...
|
||||
library.Clock.Now += TimeSpan.FromMinutes(5);
|
||||
var settings = await TurnOnAsync(library, ExportFormat.Jpg);
|
||||
await new LibraryConversionQueue(library.Db, library.Clock).OnSettingsChangedAsync(ExportSettings.Default, settings, ct);
|
||||
|
||||
// ...also when the second file of its series arrives later: only that one is new.
|
||||
library.Clock.Now += TimeSpan.FromMinutes(5);
|
||||
await StorePngAsync(library, account, added.Stored.Entry, second, 32);
|
||||
await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct);
|
||||
|
||||
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(first.Id, ct), "the old file had its answer");
|
||||
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(second.Id, ct)).Single().State);
|
||||
|
||||
// «Anche i N» still counts the old one.
|
||||
Assert.AreEqual(1, (await new LibraryConversionQueue(library.Db, library.Clock).PreviewExistingAsync(settings, ct)).Files);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TurningOffDropsThePendingRowsAndKeepsTheConvertedOnes()
|
||||
{
|
||||
@@ -278,6 +307,108 @@ public sealed class LibraryConversionTests
|
||||
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ALowDiskPausesBeforeTheOriginalIsReadAgain()
|
||||
{
|
||||
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", 23);
|
||||
var space = new FakeFreeSpaceProbe();
|
||||
space.Set(library.Layout.AccountFolder(account), 1024, 2 * FakeFreeSpaceProbe.GB);
|
||||
var throttle = new ConversionThrottle();
|
||||
var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with { FreeSpace = space });
|
||||
|
||||
// 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++)
|
||||
{
|
||||
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(library.Layout.AccountFolder(account), 50 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB);
|
||||
Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted()
|
||||
{
|
||||
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, entry) = await SavePngAsync(library, "1", 24);
|
||||
var media = entry.Media[0];
|
||||
var path = library.Layout.FullPath(account, media.RelativePath!);
|
||||
var bytes = await File.ReadAllBytesAsync(path, ct);
|
||||
File.Delete(path);
|
||||
await Worker(library).RunOnceAsync(ct);
|
||||
Assert.AreEqual(MediaConversionState.Failed, (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single().State);
|
||||
await File.WriteAllBytesAsync(path, bytes, ct);
|
||||
var queue = new LibraryConversionQueue(library.Db, library.Clock);
|
||||
|
||||
// Photos to PNG without the queue told (another way in): «Riprova» puts back only the formats set now.
|
||||
var png = jpg with { LibraryPhotoFormat = ExportFormat.Png };
|
||||
await png.SaveAsync(library.Db.Settings, ct);
|
||||
Assert.AreEqual(0, await queue.RetryFailedAsync(ct));
|
||||
|
||||
// Told: the failures of the format changed go with its queue, they are neither counted nor retried.
|
||||
await queue.OnSettingsChangedAsync(jpg, png, ct);
|
||||
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
|
||||
Assert.AreEqual(0, (await library.Db.Conversions.CountByStateAsync(ct)).Failed);
|
||||
|
||||
// A row left in the old format (put back by a supersession, say) is dropped by the worker, never written.
|
||||
await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Jpg, media.Sha256!)], library.Clock.Now, ct);
|
||||
var pass = await Worker(library).RunOnceAsync(ct);
|
||||
Assert.AreEqual(0, pass.Converted);
|
||||
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
|
||||
Assert.IsFalse(File.Exists(Path.ChangeExtension(path, ".jpg")), "no JPG while the photos are set to PNG");
|
||||
|
||||
// Turned off altogether: the same.
|
||||
var off = png with { LibraryPhotoFormat = ExportFormat.Original };
|
||||
await off.SaveAsync(library.Db.Settings, ct);
|
||||
await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Png, media.Sha256!)], library.Clock.Now, ct);
|
||||
Assert.AreEqual(0, (await Worker(library).RunOnceAsync(ct)).Converted);
|
||||
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
|
||||
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 AConversionRecordedWhileTheEntryIsDeletedGoesWithIt()
|
||||
{
|
||||
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 media = entry.Media[0];
|
||||
var worker = Worker(library);
|
||||
|
||||
// The worker records its conversion while the deletion writes its journal line (the file is still there).
|
||||
var clock = new HookClock(library.Clock.Now, () => worker.RunOnceAsync(ct));
|
||||
var deletion = new LibraryDeletion(library.Db, library.Layout, new AccountJournal(clock), library.Clock);
|
||||
var result = await deletion.DeleteAsync(entry.Entry.Id, DeletionMode.Remember, ct);
|
||||
|
||||
Assert.AreEqual(1, clock.Pass?.Converted, "converted during the deletion");
|
||||
var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single();
|
||||
Assert.AreEqual(MediaConversionState.Removed, row.State, "the row says the truth");
|
||||
Assert.IsFalse(File.Exists(library.Layout.FullPath(account, row.RelativePath!)), "the converted file goes with the entry");
|
||||
Assert.AreEqual(1, result.ConvertedFiles);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUnpluggedAccountFolderIsNotCreated()
|
||||
{
|
||||
@@ -532,6 +663,29 @@ public sealed class LibraryConversionTests
|
||||
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original");
|
||||
}
|
||||
|
||||
/// <summary>A clock that runs <c>work</c> once, the first time it is read (inside the journal append of a deletion).</summary>
|
||||
private sealed class HookClock(DateTimeOffset now, Func<Task<LibraryConversionPass>> work) : IClock
|
||||
{
|
||||
public LibraryConversionPass? Pass { get; private set; }
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Pass is null)
|
||||
{
|
||||
Pass = Task.Run(work).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
return now;
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TestZones.Rome;
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new()
|
||||
{
|
||||
Storage = library.Db,
|
||||
@@ -552,6 +706,12 @@ public sealed class LibraryConversionTests
|
||||
return settings;
|
||||
}
|
||||
|
||||
private static async Task StorePngAsync(TestLibrary library, Account account, Entry entry, Media media, int scene)
|
||||
{
|
||||
using var image = TestImages.Scene(scene, 64, 48);
|
||||
await library.Ingest.SaveMediaAsync(account, entry, media, new MediaContent { Content = new MemoryStream(TestImages.Png(image)), Extension = ".png" });
|
||||
}
|
||||
|
||||
private static Task<(Account Account, EntryWithMedia Entry)> SavePngAsync(TestLibrary library, string id, int scene)
|
||||
{
|
||||
using var image = TestImages.Scene(scene, 64, 48);
|
||||
|
||||
@@ -63,6 +63,69 @@ public sealed class Mp4RemuxerTests
|
||||
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ATrimmedEndStaysHiddenInTheMp4()
|
||||
{
|
||||
// A passthrough trim: the edits show 0,3 s of video and of audio, the rest of the media is hidden.
|
||||
var es = ElementaryStream.Load("BA1_Sony_D");
|
||||
const int ShownFrames = 9; // 0,3 s: a whole number of milliseconds, as the movie timescale keeps the edit
|
||||
Assert.IsGreaterThan(ShownFrames + 3, es.Count);
|
||||
var shownVideo = (long)ShownFrames * TestVideos.FrameTicks;
|
||||
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoTrim: shownVideo, AudioTrim: 13230));
|
||||
using var source = new MemoryStream(mov);
|
||||
var before = Read(source);
|
||||
Assert.AreEqual(shownVideo, before.Video!.EditSegmentDuration);
|
||||
Assert.AreEqual(13230L, before.Audio!.EditSegmentDuration);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), before.Duration);
|
||||
|
||||
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
|
||||
using var output = new MemoryStream(Remux(plan!, source));
|
||||
var after = Read(output);
|
||||
|
||||
Assert.AreEqual(shownVideo, after.Video!.EditSegmentDuration, "the edits are carried over");
|
||||
Assert.AreEqual(13230L, after.Audio!.EditSegmentDuration);
|
||||
Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EditMediaTime ?? 0), (after.Audio.EditMediaTime, after.Video.EditMediaTime ?? 0));
|
||||
Assert.AreEqual(before.Duration, after.Duration, "the MP4 lasts what the source shows");
|
||||
AssertSameSamples(before.Video, source, after.Video, output, "video");
|
||||
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
|
||||
|
||||
// A frame «oltre la fine» is the last one shown, never one the edit hides.
|
||||
using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info);
|
||||
Assert.IsTrue(info.Available);
|
||||
var last = reader.Locate([TimeSpan.FromHours(1)]).Single();
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), last.Actual);
|
||||
Assert.AreEqual(ShownFrames - 1, last.Sample);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(44100, 0x6B)]
|
||||
[DataRow(32000, 0x6B)]
|
||||
[DataRow(24000, 0x69)]
|
||||
[DataRow(22050, 0x69)]
|
||||
[DataRow(16000, 0x69)]
|
||||
public void Mp3IsLabelledMpeg1OrMpeg2AudioByItsRate(int rate, int objectType)
|
||||
{
|
||||
// ISO/IEC 14496-1 Table 5: 0x6B is ISO/IEC 11172-3 (MPEG-1, 32-48 kHz), 0x69 ISO/IEC 13818-3 (the lower rates).
|
||||
var mov = TestVideos.Mov(ElementaryStream.Load("BA1_Sony_D"), new MovOptions(Audio: true, Mp3: true, AudioRate: rate));
|
||||
using var source = new MemoryStream(mov);
|
||||
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
|
||||
var mp4 = Remux(plan!, source);
|
||||
|
||||
Assert.AreEqual(objectType, ObjectTypeIndication(mp4));
|
||||
using var output = new MemoryStream(mp4);
|
||||
Assert.AreEqual((AudioCodec.Mp3, rate), (Read(output).Audio!.Codec, Read(output).Audio!.SampleRate));
|
||||
}
|
||||
|
||||
/// <summary>The objectTypeIndication of the DecoderConfigDescriptor (tag 4) in the <c>esds</c> of a file.</summary>
|
||||
private static int ObjectTypeIndication(byte[] file)
|
||||
{
|
||||
var esds = file.AsSpan().IndexOf("esds"u8);
|
||||
Assert.IsGreaterThan(0, esds);
|
||||
var config = file.AsSpan(esds).IndexOf((ReadOnlySpan<byte>)[0x04, 0x80, 0x80, 0x80]);
|
||||
Assert.IsGreaterThan(0, config);
|
||||
return file[esds + config + 5];
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExtraTracksAreDroppedAndCountedAndMp3IsKept()
|
||||
{
|
||||
|
||||
@@ -340,24 +340,27 @@ internal static class TestVideos
|
||||
HevcConfiguration = es.Hevc ? es.AvcC : null,
|
||||
Language = o.Language,
|
||||
EmptyEditDuration = o.VideoEmptyEdit,
|
||||
EditMediaTime = o.VideoTrim > 0 ? 0 : null,
|
||||
EditSegmentDuration = o.VideoTrim > 0 ? o.VideoTrim : null,
|
||||
},
|
||||
};
|
||||
for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++)
|
||||
{
|
||||
var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024) + (o.AudioPriming > 0 ? 1 : 0);
|
||||
var frames = (int)Math.Ceiling(es.Count / 30.0 * o.AudioRate / 1024) + (o.AudioPriming > 0 ? 1 : 0);
|
||||
var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track };
|
||||
tracks.Add(new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = false,
|
||||
Timescale = 44100,
|
||||
Timescale = o.AudioRate,
|
||||
Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))],
|
||||
WriteSample = (_, s) => s.Write(payload),
|
||||
AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo
|
||||
IsMp3 = o.Mp3,
|
||||
SampleRate = 44100,
|
||||
SampleRate = o.AudioRate,
|
||||
Channels = 2,
|
||||
Language = o.Language,
|
||||
EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null,
|
||||
EditSegmentDuration = o.AudioTrim > 0 ? o.AudioTrim : null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -624,6 +627,9 @@ internal static class TestVideos
|
||||
/// <param name="ExtraAudioTracks">Further audio tracks (an MP4 of Febe keeps one).</param>
|
||||
/// <param name="AudioPriming">Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit.</param>
|
||||
/// <param name="VideoEmptyEdit">Ticks (of 30000 a second) before the video starts: an empty edit.</param>
|
||||
/// <param name="VideoTrim">Ticks (of 30000 a second) of video shown by its edit, the rest hidden (a trim); 0: all.</param>
|
||||
/// <param name="AudioRate">The sample rate (and timescale) of the audio; the AAC configuration always says 44,1 kHz.</param>
|
||||
/// <param name="AudioTrim">Samples (of 44100 a second) of audio shown by its edit after the priming; 0: all.</param>
|
||||
internal sealed record MovOptions(
|
||||
bool Audio = false,
|
||||
bool Mp3 = false,
|
||||
@@ -633,4 +639,7 @@ internal sealed record MovOptions(
|
||||
DateTimeOffset? Created = null,
|
||||
DateTimeOffset? Modified = null,
|
||||
long AudioPriming = 0,
|
||||
long VideoEmptyEdit = 0);
|
||||
long VideoEmptyEdit = 0,
|
||||
long VideoTrim = 0,
|
||||
long AudioTrim = 0,
|
||||
int AudioRate = 44100);
|
||||
@@ -0,0 +1,39 @@
|
||||
using Febe.Core.Codecs.H264;
|
||||
|
||||
namespace Febe.Tests.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// The recovery point SEI (H.264 §D.1.8, §D.2.8) that lets an exact frame start at an I picture (D12 of tappa E3): only
|
||||
/// with recovery_frame_cnt 0 and exact_match_flag 1. The access units are written by the test.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class H264RecoveryPointTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void OnlyAnExactMatchIsAnExactStart()
|
||||
{
|
||||
// payload: ue(recovery_frame_cnt) = 0 «1», exact_match_flag, broken_link_flag 0, changing_slice_group_idc 00,
|
||||
// then the stop bit of the payload: 1 1 0 00 1 00 (exact) and 1 0 0 00 1 00 (not exact).
|
||||
Assert.IsTrue(H264Decoder.HasExactRecoveryPoint(AccessUnit(0xC4), 4), "exact_match_flag 1");
|
||||
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x84), 4), "exact_match_flag 0: pictures may differ from the IDR's");
|
||||
|
||||
// recovery_frame_cnt 1 («010»), exact: the pictures are exact only one frame later.
|
||||
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x51), 4));
|
||||
|
||||
// Annex B carries the same.
|
||||
Assert.IsTrue(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0xC4), 0, 0, 0, 1, .. Slice], 0));
|
||||
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0x84), 0, 0, 0, 1, .. Slice], 0));
|
||||
}
|
||||
|
||||
/// <summary>A non-IDR slice NAL header and a byte of data: where the SEIs of an access unit end.</summary>
|
||||
private static readonly byte[] Slice = [0x41, 0x9A];
|
||||
|
||||
/// <summary>An SEI NAL unit with one recovery point message of one byte, and its RBSP trailing bits.</summary>
|
||||
private static byte[] Sei(byte payload) => [0x06, 0x06, 0x01, payload, 0x80];
|
||||
|
||||
private static byte[] AccessUnit(byte payload)
|
||||
{
|
||||
var sei = Sei(payload);
|
||||
return [0, 0, 0, (byte)sei.Length, .. sei, 0, 0, 0, (byte)Slice.Length, .. Slice];
|
||||
}
|
||||
}
|
||||
@@ -364,6 +364,58 @@ public sealed class ExportFormatsApiTests
|
||||
Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheQuestionOfOneKindNeitherCountsNorQueuesTheOther()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var server = await StartAsync();
|
||||
var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
||||
var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(8), ".png"));
|
||||
var video = WebLibrary.DemoVideo(3);
|
||||
var mov = await WebLibrary.AddPostAsync(server, marta, "mov", Make.T0.AddDays(-2), video with { Extension = ".mov" });
|
||||
|
||||
// Photos to JPG, «Solo i nuovi»: the PNG already in the library is left alone.
|
||||
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = false });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
|
||||
Assert.AreEqual(0, saved.Int("queued"));
|
||||
|
||||
// Then videos to MP4: the question counts the MOV only, and «Anche i N» queues it only.
|
||||
var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?video=mp4");
|
||||
Assert.AreEqual((1, (long)video.Bytes.Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString());
|
||||
(status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryVideoFormat = "mp4", convertExisting = true });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
|
||||
Assert.AreEqual(1, saved.Int("queued"));
|
||||
Assert.IsEmpty(await server.Db.Conversions.ListByMediaAsync(png.Media[0].Id, ct), "the photo refused with «Solo i nuovi» stays so");
|
||||
Assert.AreEqual(ExportFormat.Mp4, (await server.Db.Conversions.ListByMediaAsync(mov.Media[0].Id, ct)).Single().Format);
|
||||
|
||||
// Asked about both (no kind named), the preview counts what both formats would add.
|
||||
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion/preview")).Int("files"), "the PNG");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TwoQuickChangesOfTheSettingsAreBothKept()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
for (var round = 0; round < 10; round++)
|
||||
{
|
||||
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "jpg", videoFormat = "mp4" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
|
||||
|
||||
// Two clicks one after the other: two requests at once, each changing one format.
|
||||
var photo = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "original" });
|
||||
var video = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { videoFormat = "original" });
|
||||
foreach (var (code, body) in await Task.WhenAll(photo, video))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, code, body.ToString());
|
||||
}
|
||||
|
||||
var overview = await server.GetJsonAsync("/api/export");
|
||||
Assert.AreEqual(("original", "original"), (overview.Str("photoFormat"), overview.Str("videoFormat")), $"round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- support
|
||||
|
||||
/// <summary>A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it.</summary>
|
||||
|
||||
@@ -46,6 +46,119 @@ public sealed class FrameServiceTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task ASlowReaderThatKeepsReadingGetsTheWholeZip()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
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) };
|
||||
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));
|
||||
await service.WriteZipAsync(link, plan, publicationTime: false, ct);
|
||||
|
||||
using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
|
||||
var entry = archive.Entries.Single();
|
||||
Assert.IsGreaterThan(64L * 1024 * 3, entry.Length, "a frame that takes more than a stall to send");
|
||||
Assert.IsGreaterThan(TimeSpan.FromMilliseconds(400), link.Busy, "the link was slower than a stall for the frame");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AReaderThatStopsReadingAbortsTheZip()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
using var temp = new TempFolder("fotogrammi-fermo");
|
||||
var path = temp.Combine("video.mp4");
|
||||
await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), ct);
|
||||
var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(300) };
|
||||
var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [
|
||||
new FrameDownloadVideo("marta.demo", path, "post", [TimeSpan.Zero], Make.T0),
|
||||
]);
|
||||
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => service.WriteZipAsync(new SlowStream(Stream.Null, Timeout.InfiniteTimeSpan), plan, false, ct));
|
||||
Assert.IsFalse(ct.IsCancellationRequested);
|
||||
}
|
||||
|
||||
/// <summary>A video of one picture of noise (320 × 320): its PNG frame is several hundred KB.</summary>
|
||||
private static byte[] NoiseVideo()
|
||||
{
|
||||
var random = new Random(28);
|
||||
using var output = new MemoryStream();
|
||||
H264PcmWriter.WriteMp4(output, 320, 320, 1, 8, _ =>
|
||||
{
|
||||
var p = new H264PcmPicture(320, 320);
|
||||
for (var i = 0; i < p.Y.Length; i++)
|
||||
{
|
||||
p.Y[i] = (byte)random.Next(16, 236);
|
||||
}
|
||||
|
||||
for (var i = 0; i < p.Cb.Length; i++)
|
||||
{
|
||||
p.Cb[i] = (byte)random.Next(16, 241);
|
||||
p.Cr[i] = (byte)random.Next(16, 241);
|
||||
}
|
||||
|
||||
return p;
|
||||
});
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
private sealed class SlowStream(Stream inner, TimeSpan perPiece) : Stream
|
||||
{
|
||||
public TimeSpan Busy { get; private set; }
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override void Flush() => throw new InvalidOperationException("synchronous flush");
|
||||
|
||||
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write");
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer) => throw new InvalidOperationException("synchronous write");
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
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 (wait != Timeout.InfiniteTimeSpan)
|
||||
{
|
||||
Busy += wait;
|
||||
}
|
||||
|
||||
await inner.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A response body: asynchronous writes only.</summary>
|
||||
private sealed class AsyncOnlyStream(Stream inner) : Stream
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user