Files
Febe/tests/Febe.Tests/Web/FrameServiceTests.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 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>
2026-11-28 13:30:33 +01:00

196 lines
9.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO.Compression;
using Febe.Core.Codecs.H264;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Tests.Support;
using Febe.Web.Export;
namespace Febe.Tests.Web;
/// <summary>
/// The zip of «Scarica» of frames (tappa E3, D14): written while it is sent, through asynchronous writes only (a
/// response body refuses synchronous ones), one entry per frame under the account folder, names made unique.
/// </summary>
[TestClass]
public sealed class FrameServiceTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheZipIsWrittenThroughAsynchronousWritesOnly()
{
using var temp = new TempFolder("fotogrammi-zip");
var path = temp.Combine("video.mp4");
await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), TestContext.CancellationToken);
var clock = new ManualClock(Make.T0);
var service = new FrameService(clock);
var instants = new[] { TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.5) };
var plan = new FrameDownloadPlan(FrameMode.Count, ExportFormat.Png, [
new FrameDownloadVideo("marta.demo", path, "post", instants, Make.T0.AddDays(-3)),
new FrameDownloadVideo("marta.demo", path, "post", instants[..1], Make.T0.AddDays(-3)),
]);
using var sent = new MemoryStream();
await service.WriteZipAsync(new AsyncOnlyStream(sent), plan, publicationTime: true, TestContext.CancellationToken);
using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
CollectionAssert.AreEqual(
new[] { "marta.demo/post_f001.png", "marta.demo/post_f002.png", "marta.demo/post_f003.png", "marta.demo/post_f001 (2).png" },
archive.Entries.Select(e => e.FullName).ToArray());
var published = TimeZoneInfo.ConvertTime(Make.T0.AddDays(-3), clock.LocalZone).DateTime;
foreach (var entry in archive.Entries)
{
Assert.AreEqual(entry.Length, entry.CompressedLength, "frames are stored, not compressed");
// The zip keeps local date and time fields at 2 s steps: the time of publication where Febe runs (D18).
Assert.IsLessThanOrEqualTo(2.0, Math.Abs((entry.LastWriteTime.DateTime - published).TotalSeconds), $"{entry.LastWriteTime} vs {published}");
}
}
[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
{
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) =>
inner.WriteAsync(buffer, offset, count, cancellationToken);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
inner.WriteAsync(buffer, cancellationToken);
}
}