Files
Febe/src/Febe.Core/Codecs/Images/ImageConverter.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

540 lines
23 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.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>Options of <see cref="ImageConverter"/>.</summary>
public sealed record ImageConversionOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static ImageConversionOptions Default { get; } = new();
/// <summary>Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026).</summary>
public int JpegQuality { get; init; } = 92;
/// <summary>Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible.</summary>
public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444;
/// <summary>What transparent areas become in a JPEG target, which has no alpha.</summary>
public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White;
/// <summary>Limits of the decoding of the source.</summary>
public ImageLimits Limits { get; init; } = ImageLimits.Default;
}
/// <summary>What <see cref="ImageConverter.Convert"/> made.</summary>
/// <param name="Data">The converted file.</param>
/// <param name="Source">The format of the source.</param>
/// <param name="Target">The format written.</param>
/// <param name="Width">Width as stored (the orientation is not applied: the tag is copied).</param>
/// <param name="Height">Height as stored.</param>
/// <param name="Lossy">
/// Whether pixels may differ from the source's: a JPEG target, or a source with more than 8 bits per sample (the
/// decoders keep 8).
/// </param>
/// <param name="Metadata">The metadata written.</param>
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
/// <param name="Losses">
/// The same as note codes (tappa E3, <see cref="ImageConversionLosses"/>), once each, in a fixed order: what the export
/// and the library conversion record.
/// </param>
public sealed record ImageConversionResult(
byte[] Data,
ImageFormat Source,
ImageFormat Target,
int Width,
int Height,
bool Lossy,
ImageMetadata Metadata,
IReadOnlyList<string> NotCarried,
IReadOnlyList<string> Losses);
/// <summary>What a conversion does with a source (tappa E3, decisions D5 and D6).</summary>
public enum ImageConversionAction
{
/// <summary>The source is already in the target format: it is copied byte for byte, without a note.</summary>
CopyAsIs,
/// <summary>The source is decoded and written in the target format.</summary>
Convert,
/// <summary>The source cannot be converted without losing what matters: it is copied as it is, with a note.</summary>
CopyOriginal,
}
/// <summary>The outcome of <see cref="ImageConverter.Check"/>.</summary>
/// <param name="Action">What to do.</param>
/// <param name="Source">The format of the source by its bytes; null when it is not recognised.</param>
/// <param name="NoteCode">For <see cref="ImageConversionAction.CopyOriginal"/>, why (<c>AsIsHeif</c>, <c>AsIsAnimated</c>...).</param>
public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode);
/// <summary>The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3).</summary>
public static class ImageConversionLosses
{
public const string AsIsHeif = "AsIsHeif";
public const string AsIsAvif = "AsIsAvif";
public const string AsIsRaw = "AsIsRaw";
public const string AsIsAnimated = "AsIsAnimated";
public const string AsIsNotDecodable = "AsIsNotDecodable";
public const string AsIsDeepColor = "AsIsDeepColor";
public const string AsIsCmyk = "AsIsCmyk";
public const string AsIsTooLarge = "AsIsTooLarge";
public const string LostTexts = "LostTexts";
public const string LostColorChunks = "LostColorChunks";
public const string LostIcc = "LostIcc";
public const string LostIccTooLarge = "LostIccTooLarge";
public const string LostExifTooLarge = "LostExifTooLarge";
public const string LostXmpTooLarge = "LostXmpTooLarge";
public const string LostExtendedXmp = "LostExtendedXmp";
public const string LostExifUnreadable = "LostExifUnreadable";
public const string LostIptc = "LostIptc";
public const string LostOtherSegments = "LostOtherSegments";
public const string LostCommentTooLarge = "LostCommentTooLarge";
public const string TransparencyWhite = "TransparencyWhite";
/// <summary>The order in which the codes are listed, so that the same source always gives the same note.</summary>
internal static readonly string[] Order =
[
TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp,
LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments,
];
}
/// <summary>
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP without further loss,
/// JPEG at the quality of the options. The pixels written are always 8-bit RGB(A): a source with more bits per
/// sample (16-bit PNG, 12-bit or lossless JPEG) loses that precision, which the result reports as lossy. The EXIF
/// block (dates, camera, the orientation tag) and the XMP packet are copied as they are, the ICC profile only when it
/// describes RGB data (a CMYK or grey profile would no longer fit the RGB pixels); the pixels stay as stored, not
/// turned by the orientation, which the copied tag still describes. Texts go where the target can hold them: PNG
/// text chunks, JPEG comments; WebP has none. The PNG colour chunks (gAMA, cHRM, sRGB) are not written. Whatever
/// cannot be carried is listed in <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first frame
/// only, and say so.
/// </summary>
public static class ImageConverter
{
/// <summary>The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB).</summary>
public const long MaxSourceBytes = 512L * 1024 * 1024;
/// <summary>The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory).</summary>
public const long MaxWebPPixels = 40_000_000;
/// <summary>The formats a conversion can write.</summary>
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
/// <summary>
/// What a conversion of <paramref name="data"/> to <paramref name="target"/> does, from its bytes and its header
/// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF
/// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures
/// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file.
/// </summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
public static ImageConversionCheck Check(ReadOnlyMemory<byte> data, ImageFormat target, ImageConversionOptions? options = null)
{
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
var source = ImageFormatSniffer.Detect(data.Span);
if (source == target)
{
return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null);
}
string? asIs = source switch
{
ImageFormat.Heif => ImageConversionLosses.AsIsHeif,
ImageFormat.Avif => ImageConversionLosses.AsIsAvif,
ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...)
ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable,
_ => null,
};
if (asIs is null && data.Length > MaxSourceBytes)
{
asIs = ImageConversionLosses.AsIsTooLarge;
}
if (asIs is null)
{
asIs = IdentifyOutcome(data, target, options.Limits);
}
return asIs is null
? new ImageConversionCheck(ImageConversionAction.Convert, source, null)
: new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs);
}
private static string? IdentifyOutcome(ReadOnlyMemory<byte> data, ImageFormat target, ImageLimits limits)
{
ImageInfo info;
try
{
info = ImageDecoder.Identify(data, limits);
}
catch (ImageLimitException)
{
return ImageConversionLosses.AsIsTooLarge;
}
catch (ImageDecodeException)
{
return ImageConversionLosses.AsIsNotDecodable;
}
if (info.IsAnimated)
{
return ImageConversionLosses.AsIsAnimated;
}
if (target != ImageFormat.Jpeg && info.IsCmyk)
{
return ImageConversionLosses.AsIsCmyk;
}
if (target != ImageFormat.Jpeg && info.BitsPerSample > 8)
{
return ImageConversionLosses.AsIsDeepColor;
}
var pixels = (long)info.Width * info.Height;
var tooLarge = target == ImageFormat.WebP
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
: pixels > ImageLimits.Default.MaxPixels;
// What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder
// would refuse is too large for the conversion, never «not readable» (§4.10).
tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes;
return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
}
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
public static ImageConversionResult Convert(ReadOnlyMemory<byte> source, ImageFormat target, ImageConversionOptions? options = null)
{
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
using var image = ImageDecoder.Decode(source, out var info, options.Limits, pooled: true);
var notCarried = new List<string>();
if (info.FrameCount > 1)
{
notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}");
}
var lossy = target == ImageFormat.Jpeg;
if (info.BitsPerSample > 8)
{
notCarried.Add($"la profondità di {info.BitsPerSample} bit per campione (i pixel sono scritti a 8 bit)");
lossy = true;
}
var losses = new HashSet<string>(StringComparer.Ordinal);
var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written);
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses));
}
/// <summary>
/// Writes <paramref name="image"/> (straight RGBA) as <paramref name="target"/> with what of
/// <paramref name="metadata"/> the target can carry (none when null: the frames of tappa E3). A transparent image
/// to JPEG is first flattened over the background of the options, on a copy: <paramref name="image"/> is never
/// changed.
/// </summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP, or a WebP side is over 16384.</exception>
public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null)
{
ArgumentNullException.ThrowIfNull(image);
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
if (target == ImageFormat.Jpeg && !image.IsOpaque())
{
using var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
}
return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
}
/// <summary>The codes of <paramref name="losses"/> in the order of <see cref="ImageConversionLosses.Order"/>.</summary>
private static string[] Ordered(HashSet<string> losses) =>
[.. ImageConversionLosses.Order.Where(losses.Contains)];
/// <summary>Encodes; flattens <paramref name="image"/> in place for a JPEG target that is not opaque.</summary>
private static byte[] EncodeCore(
RgbaImage image,
ImageFormat target,
ImageMetadata metadata,
ImageConversionOptions options,
List<string> notCarried,
HashSet<string> losses,
out ImageMetadata written)
{
var exif = metadata.Exif;
if (exif is not null && !ExifOrientation.IsTiff(exif))
{
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
losses.Add(ImageConversionLosses.LostExifUnreadable);
exif = OrientationOnly(metadata);
}
var icc = metadata.IccProfile;
var iccName = metadata.IccProfileName;
if (icc is not null && IccColorSpace(icc) != "RGB ")
{
notCarried.Add(IccColorSpace(icc) switch
{
"CMYK" => "il profilo colore CMYK (i pixel sono stati convertiti in RGB)",
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
_ => "il profilo colore (non descrive pixel RGB)",
});
losses.Add(ImageConversionLosses.LostIcc);
icc = null;
iccName = null;
}
foreach (var chunk in metadata.ColorChunks)
{
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
losses.Add(ImageConversionLosses.LostColorChunks);
}
foreach (var block in metadata.Unread)
{
switch (block)
{
case "APP13":
notCarried.Add("i dati IPTC (segmento APP13)");
losses.Add(ImageConversionLosses.LostIptc);
break;
case "ExtendedXmp":
notCarried.Add("l'XMP esteso");
losses.Add(ImageConversionLosses.LostExtendedXmp);
break;
default:
notCarried.Add($"il blocco {block}");
losses.Add(ImageConversionLosses.LostOtherSegments);
break;
}
}
var xmp = metadata.Xmp;
var texts = metadata.Texts;
IReadOnlyList<ImageText> writtenTexts = texts;
byte[] data;
switch (target)
{
case ImageFormat.Png:
{
var pngTexts = PngTexts(texts, notCarried, losses);
writtenTexts = pngTexts;
data = PngEncoder.Encode(image, new PngEncoderOptions
{
Exif = exif,
IccProfile = icc,
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
Xmp = xmp,
Texts = pngTexts,
});
break;
}
case ImageFormat.WebP:
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
{
throw new ImageLimitException($"Un'immagine WebP non supera {WebPEncoder.MaxDimension} pixel per lato ({image.Width}×{image.Height}).");
}
if (texts.Count > 0)
{
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
losses.Add(ImageConversionLosses.LostTexts);
}
writtenTexts = [];
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
break;
default:
{
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
{
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostExifTooLarge);
exif = OrientationOnly(metadata);
}
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
{
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostXmpTooLarge);
xmp = null;
}
if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255)
{
notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)");
losses.Add(ImageConversionLosses.LostIccTooLarge);
icc = null;
iccName = null;
}
var comments = new List<string>();
var kept = new List<ImageText>();
foreach (var text in texts)
{
var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}";
if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload)
{
notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostCommentTooLarge);
continue;
}
comments.Add(comment);
kept.Add(text);
}
writtenTexts = kept;
if (!image.IsOpaque())
{
ImageBackground.Flatten(image, options.JpegBackground);
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
losses.Add(ImageConversionLosses.TransparencyWhite);
}
data = JpegEncoder.Encode(image, new JpegEncoderOptions
{
Quality = options.JpegQuality,
Subsampling = options.JpegSubsampling,
Exif = exif,
IccProfile = icc,
Xmp = xmp,
Comments = comments,
});
break;
}
}
written = new ImageMetadata
{
Exif = exif,
Orientation = exif is null ? 1 : metadata.Orientation,
IccProfile = icc,
IccProfileName = icc is null ? null : iccName,
Xmp = xmp,
Texts = writtenTexts,
};
return data;
}
/// <summary>
/// In place of an EXIF block left behind, the smallest one that keeps its orientation (in the source's byte order),
/// or null when the orientation is 1: the pixels are never turned (§4.10), so without the tag the picture would
/// show turned. The loss stays in the notes.
/// </summary>
private static byte[]? OrientationOnly(ImageMetadata metadata) =>
metadata.Orientation is > 1 and <= 8
? ExifOrientation.Minimal(metadata.Orientation, metadata.Exif is not { Length: > 0 } e || e[0] != (byte)'M')
: null;
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
{
if (profile.Length < 20)
{
return null;
}
Span<char> name = stackalloc char[4];
for (var i = 0; i < 4; i++)
{
var b = profile[16 + i];
if (b is < 32 or > 126)
{
return null;
}
name[i] = (char)b;
}
return new string(name);
}
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
private const int JpegMaxSegmentPayload = 65533;
/// <summary>Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters).</summary>
private const int JpegIccChunk = 65519;
private static string? ValidIccName(string? name)
{
if (string.IsNullOrEmpty(name) || name.Length > 79)
{
return null;
}
foreach (var c in name)
{
if (c < 32 || c > 255 || (c > 126 && c < 161))
{
return null;
}
}
return name.Trim().Length == name.Length ? name : null;
}
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried, HashSet<string> losses)
{
var result = new List<ImageText>(texts.Count);
foreach (var text in texts)
{
var keyword = text.Keyword.Length == 0 ? "Comment" : text.Keyword;
if (!PngEncoder.IsValidKeyword(keyword))
{
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
losses.Add(ImageConversionLosses.LostTexts);
continue;
}
result.Add(text with { Keyword = keyword });
}
return result;
}
}
/// <summary>Composites an image over a plain colour.</summary>
public static class ImageBackground
{
/// <summary>Every pixel of <paramref name="image"/> seen over <paramref name="background"/>, opaque, in place.</summary>
public static void Flatten(RgbaImage image, Drawing.Color background)
{
ArgumentNullException.ThrowIfNull(image);
var pixels = image.Pixels;
for (var i = 0; i < pixels.Length; i += 4)
{
int a = pixels[i + 3];
if (a == 255)
{
continue;
}
var keep = 255 - a;
pixels[i] = (byte)(((pixels[i] * a) + (background.R * keep) + 127) / 255);
pixels[i + 1] = (byte)(((pixels[i + 1] * a) + (background.G * keep) + 127) / 255);
pixels[i + 2] = (byte)(((pixels[i + 2] * a) + (background.B * keep) + 127) / 255);
pixels[i + 3] = 255;
}
}
}