Correzioni della revisione della catena 0.3.0, ognuna con la sua prova
- Collegamento: corretta la SyntaxError di connection.js (una «let saved» dichiarata due
volte nello stesso blocco fermava tutta la pagina). Nuova prova ScriptSyntaxTests con un
controllo scritto in casa che legge ogni modulo di wwwroot: parentesi, dichiarazioni
doppie nello stesso blocco, importazioni che il modulo di arrivo non esporta.
- HEIF: il riconoscimento dei formati prende ogni marchio che HeifDecoder accetta (mif2,
MiHE, marchi solo compatibili), così rilevazione, decodifica, misure, miniatura e
impronta concordano.
- Docker, lasciare la pagina del browser: un nuovo contratto del browser cancella l'uscita
annotata (_leftAt) anche prima che la vista si riapra, e la copia della sessione aspetta
un altro comando del collegamento al più LetGoWait invece che senza limite.
- JPEG e PNG: senza EOI o IEND la decodifica fallisce («File danneggiato o incompleto»),
la sola lettura delle misure resta tollerante.
- Visualizzatore: IsDamaged legge prima l'intestazione e il file intero solo quando può
servire, in modo asincrono e con una piccola memoria per file, così una scheda con
molti file non blocca il server.
- Importazione (§9.3): le immagini danneggiate si importano come le altre ma si segnano
nella revisione, nel resoconto e nel CSV.
- Pulizia: le prove con il limite di 5 minuti non corrono più in parallelo fra loro.
- Pila dei caratteri come l'appendice B, senza Liberation; testo di Informazioni sulle
immagini fatte in casa; guida (Problemi comuni, Sicurezza) allineata all'uscita in
Docker dalla pagina del browser.
- docs/decisioni.md: le righe del 25 novembre 2026 con i motivi, compresa l'unione 537517b
tenuta così com'è.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3d234f8791
commit
2068dd28f3
35 files changed
+1366
-75
No files matched your search
@@ -23,7 +23,10 @@ public enum ImageFormat
|
||||
/// <summary>Recognises an image format from the first bytes of a file.</summary>
|
||||
public static class ImageFormatSniffer
|
||||
{
|
||||
/// <summary>Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats.</summary>
|
||||
/// <summary>
|
||||
/// Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats. A HEIF whose brand
|
||||
/// is only among the compatible brands needs the whole <c>ftyp</c> box.
|
||||
/// </summary>
|
||||
public const int HeaderLength = 32;
|
||||
|
||||
/// <summary>The format the bytes start with, or <see cref="ImageFormat.Unknown"/>.</summary>
|
||||
@@ -72,6 +75,13 @@ public static class ImageFormatSniffer
|
||||
{
|
||||
return ImageFormat.Heif;
|
||||
}
|
||||
|
||||
// Every file the HEIF decoder takes (mif2, MiHE, or a HEIF brand among the compatible ones) is a HEIF:
|
||||
// the decoder is chosen from this answer, so a narrower list would leave such a HEIC without a picture.
|
||||
if (Heif.HeifDecoder.Looks(header))
|
||||
{
|
||||
return ImageFormat.Heif;
|
||||
}
|
||||
}
|
||||
|
||||
return ImageFormat.Unknown;
|
||||
|
||||
@@ -10,8 +10,10 @@ namespace Febe.Core.Codecs.Images;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged
|
||||
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have; a missing EOI after complete
|
||||
/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
|
||||
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have, and a file that ends before its
|
||||
/// EOI is incomplete even after complete scans (spec §3: a progressive file cut between two scans is refused, not shown
|
||||
/// at a lower quality); <see cref="Identify"/> still reads the size of such a file. Bytes after EOI and stray restart
|
||||
/// markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
|
||||
/// with <see cref="ImageFormatNotSupportedException"/>.
|
||||
/// </remarks>
|
||||
public static class JpegDecoder
|
||||
|
||||
@@ -288,6 +288,13 @@ internal sealed partial class JpegFile : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
// Spec §3, §8.4: a JPEG that ends before its end marker is incomplete, even when its scans so far are complete
|
||||
// (a progressive file cut between two scans would otherwise give a picture of lower quality).
|
||||
if (!sawEoi)
|
||||
{
|
||||
throw new ImageDecodeException("JPEG troncato: manca il marcatore di fine (EOI).");
|
||||
}
|
||||
|
||||
if (_scanCount == 0)
|
||||
{
|
||||
throw new ImageDecodeException("JPEG senza dati d'immagine.");
|
||||
|
||||
@@ -48,6 +48,7 @@ public static class PngDecoder
|
||||
{
|
||||
limits ??= ImageLimits.Default;
|
||||
var file = Parse(data, limits, readMetadata: false);
|
||||
RequireEnd(file);
|
||||
return DecodePixels(data, file, limits, pooled);
|
||||
}
|
||||
|
||||
@@ -56,13 +57,27 @@ public static class PngDecoder
|
||||
{
|
||||
limits ??= ImageLimits.Default;
|
||||
var file = Parse(data, limits, readMetadata: true);
|
||||
RequireEnd(file);
|
||||
var image = DecodePixels(data, file, limits, pooled);
|
||||
info = file.ToInfo();
|
||||
return image;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spec §3, §8.4: a PNG that ends before its end marker is incomplete, even when its image data is complete, and is
|
||||
/// not decoded; <see cref="Identify"/> still reads its size.
|
||||
/// </summary>
|
||||
private static void RequireEnd(PngFile file)
|
||||
{
|
||||
if (!file.SeenEnd)
|
||||
{
|
||||
throw new ImageDecodeException("PNG troncato: manca il blocco di fine (IEND).");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PngFile
|
||||
{
|
||||
public bool SeenEnd;
|
||||
public int Width;
|
||||
public int Height;
|
||||
public int BitDepth;
|
||||
@@ -129,6 +144,7 @@ public static class PngDecoder
|
||||
var seenPalette = false;
|
||||
var seenTransparency = false;
|
||||
var idatState = 0; // 0 none yet, 1 inside the IDAT run, 2 after it
|
||||
var seenEnd = false;
|
||||
var metadataBudget = limits.MaxMetadataBytes;
|
||||
var pos = 8;
|
||||
while (pos < data.Length)
|
||||
@@ -227,6 +243,7 @@ public static class PngDecoder
|
||||
break;
|
||||
|
||||
case "IEND":
|
||||
seenEnd = true;
|
||||
pos = data.Length;
|
||||
break;
|
||||
|
||||
@@ -275,6 +292,7 @@ public static class PngDecoder
|
||||
throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT).");
|
||||
}
|
||||
|
||||
file.SeenEnd = seenEnd;
|
||||
return file;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ internal sealed record ContentFacts(
|
||||
TimeSpan? Duration,
|
||||
ulong? PerceptualHash,
|
||||
DateTimeOffset? MetadataDate,
|
||||
string? Error);
|
||||
string? Error,
|
||||
bool Damaged = false);
|
||||
|
||||
/// <summary>
|
||||
/// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for
|
||||
@@ -58,6 +59,7 @@ internal static class ContentAnalysis
|
||||
string sha;
|
||||
int? width = null, height = null;
|
||||
ulong? hash = null;
|
||||
var damaged = false;
|
||||
if (length <= InMemoryLimit)
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
@@ -69,16 +71,18 @@ internal static class ContentAnalysis
|
||||
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
ct.ThrowIfCancellationRequested();
|
||||
(width, height, hash) = Decode(bytes);
|
||||
damaged = hash is null && ImageDecoding.IsDamaged(bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
sha = await env.FileSystem.ComputeSha256Async(fullPath, ct).ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
(width, height, hash) = Decode(() => env.FileSystem.OpenRead(fullPath));
|
||||
(width, height, hash, damaged) = Decode(() => env.FileSystem.OpenRead(fullPath));
|
||||
}
|
||||
|
||||
// Spec §9.3: a truncated or damaged image is imported like the others, and the review and the report say so.
|
||||
var date = ExifDateReader.Read(head, env.Clock.LocalZone);
|
||||
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
|
||||
return new ContentFacts(type, length, sha, width, height, null, hash, date, null, damaged);
|
||||
}
|
||||
|
||||
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF).</summary>
|
||||
@@ -101,7 +105,7 @@ internal static class ContentAnalysis
|
||||
/// more, whole (up to <see cref="ImageDecoding.MaxFileBytes"/>; the codecs need the bytes in memory), and decoded
|
||||
/// once for both hash and size.
|
||||
/// </summary>
|
||||
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> open)
|
||||
private static (int? Width, int? Height, ulong? Hash, bool Damaged) Decode(Func<Stream> open)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -113,15 +117,15 @@ internal static class ContentAnalysis
|
||||
|
||||
if (data is null)
|
||||
{
|
||||
return (null, null, null);
|
||||
return (null, null, null, false);
|
||||
}
|
||||
|
||||
var (hash, size) = PerceptualHash.ComputeWithSize(data);
|
||||
return (size?.Width, size?.Height, hash);
|
||||
return (size?.Width, size?.Height, hash, hash is null && ImageDecoding.IsDamaged(data));
|
||||
}
|
||||
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
|
||||
{
|
||||
return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash
|
||||
return (null, null, null, false); // a format no decoder reads (e.g. AVIF): no size, no hash
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -265,6 +265,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var updates = new List<ImportFile>(batch.Count);
|
||||
var damaged = new List<long>();
|
||||
for (var i = 0; i < batch.Count; i++)
|
||||
{
|
||||
var file = batch[i];
|
||||
@@ -275,6 +276,11 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fact.Damaged)
|
||||
{
|
||||
damaged.Add(file.Id);
|
||||
}
|
||||
|
||||
var hints = recognizers.Recognize(new ImportFileContext(layout, file.RelativePath));
|
||||
var (takenAt, source) = ResolveDate(hints, fact.MetadataDate, file.ModifiedAt);
|
||||
var analysed = file with
|
||||
@@ -318,6 +324,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
|
||||
}
|
||||
|
||||
await env.Storage.Imports.UpdateFilesAsync(updates, ct).ConfigureAwait(false);
|
||||
await ImportRunSettings.AddDamagedAsync(env.Storage.Settings, run.Id, damaged, ct).ConfigureAwait(false);
|
||||
foreach (var update in updates)
|
||||
{
|
||||
done++;
|
||||
|
||||
@@ -115,6 +115,67 @@ internal static class ImportRunSettings
|
||||
|
||||
public static string NewAccountsKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.nuovi-account");
|
||||
|
||||
/// <summary>
|
||||
/// The files of the run the analysis found «File danneggiato o incompleto» (spec §9.3), as a JSON array of their ids:
|
||||
/// a setting of the run like the others, so that the schema (and the numbering of its migrations) stays as it is.
|
||||
/// </summary>
|
||||
public static string DamagedKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.danneggiati");
|
||||
|
||||
/// <summary>The ids of the files of the run that the analysis found damaged or truncated (spec §9.3).</summary>
|
||||
public static async Task<HashSet<long>> GetDamagedAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||
{
|
||||
var text = await store.GetAsync(DamagedKey(runId), ct).ConfigureAwait(false);
|
||||
var result = new HashSet<long>();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (JsonNode.Parse(text) is JsonArray ids)
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (id is JsonValue value && value.TryGetValue<long>(out var fileId))
|
||||
{
|
||||
result.Add(fileId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidOperationException or FormatException)
|
||||
{
|
||||
// An unreadable value: no file is marked.
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Adds <paramref name="fileIds"/> to the damaged files of the run (an analysis that starts again adds nothing twice).</summary>
|
||||
public static async Task AddDamagedAsync(ISettingsStore store, long runId, IReadOnlyCollection<long> fileIds, CancellationToken ct)
|
||||
{
|
||||
if (fileIds.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var all = await GetDamagedAsync(store, runId, ct).ConfigureAwait(false);
|
||||
if (all.IsSupersetOf(fileIds))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
all.UnionWith(fileIds);
|
||||
var json = new JsonArray();
|
||||
foreach (var id in all.Order())
|
||||
{
|
||||
json.Add(id);
|
||||
}
|
||||
|
||||
await store.SetAsync(DamagedKey(runId), json.ToJsonString(), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static Task<bool> GetStogramAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||
store.GetBoolAsync(StogramKey(runId), false, ct);
|
||||
|
||||
@@ -169,5 +230,5 @@ internal static class ImportRunSettings
|
||||
}
|
||||
|
||||
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||
store.SetManyAsync(new Dictionary<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null }, ct);
|
||||
store.SetManyAsync(new Dictionary<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null, [DamagedKey(runId)] = null }, ct);
|
||||
}
|
||||
@@ -124,6 +124,7 @@ public sealed record ImportFolderReview(
|
||||
/// <param name="AnalysisDuration">From the start of the import to the end of the analysis.</param>
|
||||
/// <param name="StogramHypothesis">The 4K Stogram hypothesis recognizer was used.</param>
|
||||
/// <param name="Copied">Files already copied or moved by this import.</param>
|
||||
/// <param name="Damaged">Images the analysis found «File danneggiato o incompleto» (spec §9.3): imported like the others.</param>
|
||||
public sealed record ImportReviewSummary(
|
||||
ImportRun Run,
|
||||
string DisplayPath,
|
||||
@@ -135,7 +136,8 @@ public sealed record ImportReviewSummary(
|
||||
IReadOnlyList<ImportFolderReview> Folders,
|
||||
TimeSpan? AnalysisDuration,
|
||||
bool StogramHypothesis,
|
||||
int Copied)
|
||||
int Copied,
|
||||
int Damaged = 0)
|
||||
{
|
||||
/// <summary>«Sposta» is offered only for writable sources.</summary>
|
||||
public bool CanMove => !Run.SourceReadOnly;
|
||||
|
||||
@@ -29,6 +29,8 @@ public sealed record ReportNote(string Path, string Note);
|
||||
/// <param name="AlreadyInLibraryByAccount">Where the «Già in libreria» files already are.</param>
|
||||
/// <param name="Unrecognized">The files that are neither photos nor videos (at most <see cref="ImportReports.MaxListed"/>).</param>
|
||||
/// <param name="Problems">Files that failed or need attention, with the reason (at most <see cref="ImportReports.MaxListed"/>).</param>
|
||||
/// <param name="DamagedCount">Images found «File danneggiato o incompleto» by the analysis (spec §9.3).</param>
|
||||
/// <param name="Damaged">Their paths (at most <see cref="ImportReports.MaxListed"/>).</param>
|
||||
public sealed record ImportReport(
|
||||
ImportRun Run,
|
||||
string DisplayPath,
|
||||
@@ -46,7 +48,9 @@ public sealed record ImportReport(
|
||||
IReadOnlyList<AccountCount> ImportedByAccount,
|
||||
IReadOnlyList<AccountCount> AlreadyInLibraryByAccount,
|
||||
IReadOnlyList<string> Unrecognized,
|
||||
IReadOnlyList<ReportNote> Problems);
|
||||
IReadOnlyList<ReportNote> Problems,
|
||||
int DamagedCount = 0,
|
||||
IReadOnlyList<string>? Damaged = null);
|
||||
|
||||
/// <summary>
|
||||
/// The report of an import and its CSV export (spec §9.4, §4.8): one row per file, ';' as separator, UTF-8 with BOM, so
|
||||
@@ -74,9 +78,16 @@ public sealed class ImportReports(ImportEnvironment env)
|
||||
var already = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
var unrecognized = new List<string>();
|
||||
var problems = new List<ReportNote>();
|
||||
var damagedIds = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
var damaged = new List<string>();
|
||||
await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false))
|
||||
{
|
||||
var file = row.File;
|
||||
if (damagedIds.Contains(file.Id) && damaged.Count < MaxListed)
|
||||
{
|
||||
damaged.Add(file.RelativePath);
|
||||
}
|
||||
|
||||
if (file.State is ImportFileState.Copied or ImportFileState.Moved)
|
||||
{
|
||||
bytesCopied += file.Bytes;
|
||||
@@ -120,7 +131,9 @@ public sealed class ImportReports(ImportEnvironment env)
|
||||
Sorted(imported),
|
||||
Sorted(already),
|
||||
unrecognized,
|
||||
problems);
|
||||
problems,
|
||||
damagedIds.Count,
|
||||
damaged);
|
||||
}
|
||||
|
||||
/// <summary>Suggested name of the CSV file: «importazione-2026-10-13-12.csv».</summary>
|
||||
@@ -138,9 +151,13 @@ public sealed class ImportReports(ImportEnvironment env)
|
||||
var zone = env.Clock.LocalZone;
|
||||
await using var writer = new StreamWriter(destination, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 64 * 1024, leaveOpen: true) { NewLine = "\r\n" };
|
||||
await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false);
|
||||
var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false))
|
||||
{
|
||||
var f = row.File;
|
||||
var note = damaged.Contains(f.Id)
|
||||
? f.LastError is { Length: > 0 } other ? $"{ImportText.NoteDamaged}. {other}" : ImportText.NoteDamaged
|
||||
: f.LastError ?? string.Empty;
|
||||
var replaced = f.LastError?.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal) == true;
|
||||
var destinationUser = replaced ? row.MatchedUsername : row.TargetUsername;
|
||||
await writer.WriteLineAsync(Line(
|
||||
@@ -163,7 +180,7 @@ public sealed class ImportReports(ImportEnvironment env)
|
||||
f.InstagramId ?? string.Empty,
|
||||
row.MatchedUsername is { } user ? $"{user}/{row.MatchedPath}" : string.Empty,
|
||||
f.DestinationPath is { } path && destinationUser is { } to ? $"{to}/{path}" : f.DestinationPath ?? string.Empty,
|
||||
f.LastError ?? string.Empty,
|
||||
note,
|
||||
])).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ public sealed class ImportReview(ImportEnvironment env)
|
||||
var folders = await ListFoldersAsync(run, ct).ConfigureAwait(false);
|
||||
var pending = await env.Storage.Imports.CountPairsAsync(runId, pendingOnly: true, ct).ConfigureAwait(false);
|
||||
var stogram = await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
return new ImportReviewSummary(
|
||||
run,
|
||||
env.CreateSources().DisplayPath(run.SourcePath),
|
||||
@@ -31,7 +32,8 @@ public sealed class ImportReview(ImportEnvironment env)
|
||||
folders,
|
||||
run.AnalyzedAt is { } analyzed ? analyzed - run.StartedAt : null,
|
||||
stogram,
|
||||
summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved]);
|
||||
summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved],
|
||||
damaged.Count);
|
||||
}
|
||||
|
||||
/// <summary>The rows of «Cartelle e account».</summary>
|
||||
|
||||
@@ -145,4 +145,7 @@ public static class ImportText
|
||||
internal const string NoteOriginalKept = "Copiato; l'originale non si è potuto eliminare e resta al suo posto.";
|
||||
internal const string NoteMovePending = "Copiato; l'originale si elimina dopo la verifica della copia.";
|
||||
internal const string NoteOldNotDeleted = "Il file sostituito non si è potuto eliminare dalla libreria: resta accanto al nuovo.";
|
||||
|
||||
/// <summary>Spec §9.3, §8.4: an image truncated or damaged, imported like the others, without visual fingerprint.</summary>
|
||||
internal const string NoteDamaged = "File danneggiato o incompleto";
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
@@ -7,11 +9,18 @@ namespace Febe.Core.Library;
|
||||
/// class only looks, it never deletes, replaces or downloads again.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The check decodes the picture, so it is meant for a single file at a time (the viewer) and only for photos that
|
||||
/// have no thumbnail: a photo with a thumbnail was decoded when it was stored.
|
||||
/// The check decodes the picture, so it is meant for a single file at a time (the viewer, the import of one file) and
|
||||
/// only for photos that have no thumbnail: a photo with a thumbnail was decoded when it was stored. The first bytes are
|
||||
/// looked at before the rest is read: a format Febe does not decode, a HEIC and a picture over the decoding limit are
|
||||
/// never damaged, so their file is not read whole for nothing.
|
||||
/// </remarks>
|
||||
public static class DamagedImage
|
||||
{
|
||||
/// <summary>How many answers <see cref="IsFileDamagedAsync"/> keeps; the whole memory is dropped when it is full.</summary>
|
||||
private const int RememberedAnswers = 512;
|
||||
|
||||
private static readonly ConcurrentDictionary<(string Path, long Length, DateTime Written), bool> Answers = new();
|
||||
|
||||
/// <summary>
|
||||
/// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or
|
||||
/// truncated; false for a photo that decodes, for a format Febe does not read (AVIF, an unknown one), for HEIC (see ImageDecoding.IsDamaged) and for a
|
||||
@@ -20,23 +29,120 @@ public static class DamagedImage
|
||||
public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk, read once; false when it cannot be read or is
|
||||
/// larger than <see cref="ImageDecoding.MaxFileBytes"/>.
|
||||
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk; false when it cannot be read or is larger than
|
||||
/// <see cref="ImageDecoding.MaxFileBytes"/>. Reads the first bytes and, only when the picture may be damaged, the rest.
|
||||
/// </summary>
|
||||
public static bool IsFileDamaged(string path)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
byte[]? data;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
data = ImageDecoding.ReadAll(stream);
|
||||
var length = stream.Length;
|
||||
if (length <= 0 || length > ImageDecoding.MaxFileBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var head = (int)Math.Min(length, ImageDecoding.HeaderBytes);
|
||||
var data = new byte[head];
|
||||
stream.ReadExactly(data);
|
||||
if (!ImageDecoding.MayBeDamaged(data))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (length > head)
|
||||
{
|
||||
var whole = new byte[length];
|
||||
data.CopyTo(whole, 0);
|
||||
stream.ReadExactly(whole.AsSpan(head));
|
||||
data = whole;
|
||||
}
|
||||
|
||||
return ImageDecoding.IsDamaged(data);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IsFileDamaged"/> with asynchronous reads, for a request: the answer is kept for the same file (path,
|
||||
/// length and time of the last write), so stepping back and forth in the viewer does not read and decode it again.
|
||||
/// </summary>
|
||||
public static async Task<bool> IsFileDamagedAsync(string path, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
(string, long, DateTime) key;
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
key = (info.FullName, info.Length, info.LastWriteTimeUtc);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return data is not null && ImageDecoding.IsDamaged(data);
|
||||
if (Answers.TryGetValue(key, out var known))
|
||||
{
|
||||
return known;
|
||||
}
|
||||
|
||||
var answer = await ReadAndCheckAsync(path, ct).ConfigureAwait(false);
|
||||
if (answer is not { } damaged)
|
||||
{
|
||||
return false; // not readable now: not remembered
|
||||
}
|
||||
|
||||
if (Answers.Count >= RememberedAnswers)
|
||||
{
|
||||
Answers.Clear();
|
||||
}
|
||||
|
||||
Answers[key] = damaged;
|
||||
return damaged;
|
||||
}
|
||||
|
||||
private static async Task<bool?> ReadAndCheckAsync(string path, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
var length = stream.Length;
|
||||
if (length <= 0 || length > ImageDecoding.MaxFileBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var head = (int)Math.Min(length, ImageDecoding.HeaderBytes);
|
||||
var data = new byte[head];
|
||||
await stream.ReadExactlyAsync(data, ct).ConfigureAwait(false);
|
||||
if (!ImageDecoding.MayBeDamaged(data))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (length > head)
|
||||
{
|
||||
var whole = new byte[length];
|
||||
data.CopyTo(whole, 0);
|
||||
await stream.ReadExactlyAsync(whole.AsMemory(head), ct).ConfigureAwait(false);
|
||||
data = whole;
|
||||
}
|
||||
|
||||
return ImageDecoding.IsDamaged(data);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Buffers.Binary;
|
||||
using Febe.Core.Codecs.Heif;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
@@ -112,6 +113,54 @@ internal static class ImageDecoding
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// From the first bytes of a file (at least the header of its format): false when <see cref="IsDamaged"/> would
|
||||
/// say false whatever follows — a format Febe does not decode, a HEIC, a PNG, GIF, BMP or WebP whose header gives
|
||||
/// more pixels than <see cref="MaxDecodedPixels"/> — so that such a file is not read whole only to be refused.
|
||||
/// JPEG decodes at a reduced size, so its header alone never rules it out.
|
||||
/// </summary>
|
||||
internal static bool MayBeDamaged(ReadOnlySpan<byte> head)
|
||||
{
|
||||
var format = head.IsEmpty ? ImageFormat.Unknown : ImageFormatSniffer.Detect(head);
|
||||
if (format == ImageFormat.Heif || !ImageDecoder.CanDecode(format))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return HeaderPixels(format, head) is not { } pixels || pixels <= MaxDecodedPixels;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Width × height as the header of a PNG (IHDR), GIF (logical screen), BMP (information header) or WebP (VP8X,
|
||||
/// VP8L or VP8 frame header) states it, from their public specifications; null when it is not there.
|
||||
/// </summary>
|
||||
internal static long? HeaderPixels(ImageFormat format, ReadOnlySpan<byte> h)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case ImageFormat.Png when h.Length >= 24 && h[12..16].SequenceEqual("IHDR"u8):
|
||||
return (long)BinaryPrimitives.ReadUInt32BigEndian(h[16..]) * BinaryPrimitives.ReadUInt32BigEndian(h[20..]);
|
||||
case ImageFormat.Gif when h.Length >= 10:
|
||||
return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[6..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[8..]);
|
||||
case ImageFormat.Bmp when h.Length >= 22 && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12:
|
||||
return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[18..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[20..]);
|
||||
case ImageFormat.Bmp when h.Length >= 26:
|
||||
return Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[18..])) * Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[22..]));
|
||||
case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8X"u8):
|
||||
return (1L + (h[24] | (h[25] << 8) | (h[26] << 16))) * (1L + (h[27] | (h[28] << 8) | (h[29] << 16)));
|
||||
case ImageFormat.WebP when h.Length >= 25 && h[12..16].SequenceEqual("VP8L"u8) && h[20] == 0x2F:
|
||||
{
|
||||
var bits = BinaryPrimitives.ReadUInt32LittleEndian(h[21..]);
|
||||
return (1L + (bits & 0x3FFF)) * (1L + ((bits >> 14) & 0x3FFF));
|
||||
}
|
||||
|
||||
case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8 "u8) && h[23] == 0x9D && h[24] == 0x01 && h[25] == 0x2A:
|
||||
return (long)(BinaryPrimitives.ReadUInt16LittleEndian(h[26..]) & 0x3FFF) * (BinaryPrimitives.ReadUInt16LittleEndian(h[28..]) & 0x3FFF);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The smallest long side <see cref="IsDamaged"/> lets a JPEG be decoded at: the cheapest reduction.</summary>
|
||||
private const int DamageCheckSide = 1;
|
||||
|
||||
|
||||
Reference in new issue
Block a user