E3: conversione delle foto, rimux in MP4 e fotogrammi esatti nel nucleo
Prima parte della tappa E3 (formati e fotogrammi), solo nel nucleo: il pianificatore, il copiatore e l'archivio delle esportazioni restano alla parte successiva. - Foto: ImageConverter.Check dice prima che cosa succede (copia identica, conversione, copia così com'è con il motivo: HEIC, AVIF, raw, animazioni, file danneggiati, CMYK e oltre 8 bit verso PNG/WEBP, oltre il limite di pixel); la conversione riporta come note ciò che non può portare invece di fermarsi, e la trasparenza verso JPG diventa bianco. I lettori segnalano animazioni, CMYK e segmenti non letti. VP8L usa un logaritmo in virgola fissa, così lo stesso file dà gli stessi byte su ogni sistema. - Video: i lettori ISO e Matroska leggono elenco dei montaggi, lingue, tipo di AAC, MP3 e i vecchi codici AAC di Matroska; Mp4Writer prepara la disposizione e ne conosce la lunghezza prima di scrivere; il nuovo Mp4Remuxer porta in MP4 senza ricodificare, sempre con gli stessi byte. - Fotogrammi: VideoFrameReader trova il campione mostrato a un istante come lo mostra il lettore, lo decodifica esatto a piena risoluzione e lo raddrizza; ExportFrames calcola istanti, suffissi e etichette. - Nomi: il suffisso del fotogramma non si accorcia mai e la numerazione dei nomi liberi viene dopo di lui; SafeFileWriter scrive anche contenuti prodotti mentre li scrive. - MediaConverter e ConversionThrottle preparano una conversione senza sapere dove andrà, una alla volta in tutto il processo. Nuove prove per determinismo, istanti, rotazione, rimux e nomi; tutte le prove di Febe.Tests passano. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7faf92e667
commit
704c1ed9cf
28 files changed
+2830
-144
No files matched your search
@@ -33,6 +33,10 @@ public sealed record ImageConversionOptions
|
||||
/// </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,
|
||||
@@ -41,7 +45,60 @@ public sealed record ImageConversionResult(
|
||||
int Height,
|
||||
bool Lossy,
|
||||
ImageMetadata Metadata,
|
||||
IReadOnlyList<string> NotCarried);
|
||||
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
|
||||
@@ -57,9 +114,97 @@ public sealed record ImageConversionResult(
|
||||
/// </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;
|
||||
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>
|
||||
@@ -85,8 +230,58 @@ public static class ImageConverter
|
||||
lossy = true;
|
||||
}
|
||||
|
||||
var metadata = info.Metadata;
|
||||
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 = null;
|
||||
}
|
||||
|
||||
var icc = metadata.IccProfile;
|
||||
var iccName = metadata.IccProfileName;
|
||||
if (icc is not null && IccColorSpace(icc) != "RGB ")
|
||||
@@ -97,6 +292,7 @@ public static class ImageConverter
|
||||
"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;
|
||||
}
|
||||
@@ -104,23 +300,49 @@ public static class ImageConverter
|
||||
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:
|
||||
data = PngEncoder.Encode(image, new PngEncoderOptions
|
||||
{
|
||||
Exif = exif,
|
||||
IccProfile = icc,
|
||||
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
||||
Xmp = xmp,
|
||||
Texts = PngTexts(texts, notCarried),
|
||||
});
|
||||
break;
|
||||
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)
|
||||
{
|
||||
@@ -130,8 +352,10 @@ public static class ImageConverter
|
||||
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:
|
||||
@@ -139,25 +363,47 @@ public static class ImageConverter
|
||||
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 = null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
var comments = new List<string>();
|
||||
foreach (var text in texts)
|
||||
if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255)
|
||||
{
|
||||
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
|
||||
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
|
||||
@@ -173,16 +419,16 @@ public static class ImageConverter
|
||||
}
|
||||
}
|
||||
|
||||
var written = new ImageMetadata
|
||||
written = new ImageMetadata
|
||||
{
|
||||
Exif = exif,
|
||||
Orientation = metadata.Orientation,
|
||||
Orientation = exif is null ? 1 : metadata.Orientation,
|
||||
IccProfile = icc,
|
||||
IccProfileName = icc is null ? null : iccName,
|
||||
Xmp = xmp,
|
||||
Texts = target == ImageFormat.WebP ? [] : texts,
|
||||
Texts = writtenTexts,
|
||||
};
|
||||
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried);
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
|
||||
@@ -211,6 +457,9 @@ public static class ImageConverter
|
||||
/// <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)
|
||||
@@ -229,7 +478,7 @@ public static class ImageConverter
|
||||
return name.Trim().Length == name.Length ? name : null;
|
||||
}
|
||||
|
||||
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
|
||||
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)
|
||||
@@ -238,6 +487,7 @@ public static class ImageConverter
|
||||
if (!PngEncoder.IsValidKeyword(keyword))
|
||||
{
|
||||
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
|
||||
losses.Add(ImageConversionLosses.LostTexts);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -248,6 +498,7 @@ public static class ImageConverter
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Composites an image over a plain colour.</summary>
|
||||
public static class ImageBackground
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user