fix(convert): plan, decode and colour only what a conversion really does

Round-2 fixes for the codecs part of owner review 2, phase 4b (mass
conversion), so the dry run never promises a conversion that then fails
or writes wrong pixels.

- The managed TIFF reader refuses samples it does not render (CMYK,
  CIELab, palette, LogL, RGB of fewer than three samples, float
  min-is-white) before reading pixels, instead of decoding them as the
  gray of their first plane. The conversion chain then asks WIC on a PC;
  the server leaves them to a PC. Impossible strip/tile counts are
  refused as data, not as an OverflowException that escaped the chain.
- A conversion's managed provider reads JPEG, PNG and TIFF headers in
  its probe (ReadsHeaders): what its decoders refuse there (compression,
  sample format, photometric, MaxSamples, MaxPixels, arithmetic coding)
  is not planned as convertible on the server, and is asked of WIC on a
  PC. The probe gives the real size, so TooLarge sees it.
- Float TIFFs are linear light (SourceColor.IsLinear): a JPEG or TIFF
  carrying their profile gets codes from the profile's own curves, a DNG
  gets them through the matrix only (no curve, no clip, highlights
  kept). IsSrgb is decided by the numbers for matrix/TRC profiles, so a
  linear profile named sRGB is converted, not taken as sRGB. The TIFF
  profile is read from the image the decoders read.
- TooLarge is a bound: the target's limits and what the server's
  decoders read back, which every converted file must (JPEG 2^28 pixels,
  TIFF-16 and DNG 2^29 samples), and the incompressible worst case
  against the 2 GB array. A MemoryStream overflow is TooLarge, never a
  generic file failure.
- Colorants that convert nothing (a white without positive cone
  responses, a non-finite or singular matrix) are dropped when a profile
  is parsed: the photo is carried into a JPEG or TIFF and planned out of
  a DNG as colour_profile, instead of throwing in BradfordAdaptation at
  every retry.

Tests: header probes, refused photometrics, the size bound against the
verifier's header reads, float TIFF colour, a fuzz of damaged profiles,
and a Windows test converting a CMYK TIFF through WIC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 18cf9133087aada2db06c8310d2c69ff804c0115)
This commit is contained in:
Alby96 committed 2026-11-02 10:33:33 +01:00
1 parent e3cbe30b29
commit 5b5acaf307
15 files changed
+1160 -78

No files matched your search

+54 -11
View File
@@ -3,6 +3,8 @@ using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
@@ -15,7 +17,11 @@ public enum ConvertSkip
/// <summary>The photo is in the target's format already (a TIFF of 8 bits included).</summary>
SameFormat,
/// <summary>This host has no full-resolution decoder for the photo's format (a server and a CR3 or HEIC): a PC may have one.</summary>
/// <summary>
/// This host has no full-resolution decoder for the photo's format (a server and a CR3 or HEIC), or its decoders do not
/// read this file at full resolution (a CMYK, CIELab or palette TIFF, a compression or size they do not take, a RAW body
/// they do not develop and without a preview): a PC may have one.
/// </summary>
NoNativeDecoder,
/// <summary>This host reads the photo only from its embedded preview (a camera body its RAW decoder does not support).</summary>
@@ -36,7 +42,10 @@ public enum ConvertSkip
/// <summary>The photo's colour profile can be neither carried into the target nor converted to it (CMYK, an unknown space…).</summary>
ColorProfile,
/// <summary>The photo is larger than the target holds (a JPEG side above 65535) or one image in memory can.</summary>
/// <summary>
/// The photo is larger than the target holds (a JPEG side above 65535) or than the server's decoders read back, which
/// every converted file must (<see cref="ConvertPlanner.TooLarge"/>).
/// </summary>
TooLarge,
}
@@ -149,10 +158,11 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert
/// <summary>
/// Plans the conversion of a sequence's frames (owner review 2, R7): a frame is converted when it is not in the target's
/// format already, its file is there, it was hashed, it is not flagged unreadable, the target holds its size, this host
/// decodes it at full resolution with the decoders the conversion uses (<see cref="FrameConverter.Decoders"/>: its format
/// has a native decoder here and the file itself probes native now, whatever tier another host or an earlier pass
/// recorded; for a 16-bit target, not through a RAW development at 8 bits), and its colour profile can be kept
/// format already, its file is there, it was hashed, it is not flagged unreadable, its size is one the target holds and the
/// server's decoders read back (<see cref="TooLarge"/>), this host decodes it at full resolution with the decoders the
/// conversion uses (<see cref="FrameConverter.Decoders"/>: its format has a native decoder here and the file itself probes
/// native now, whatever tier another host or an earlier pass recorded, its headers saying what those decoders take; for a
/// 16-bit target, not through a RAW development at 8 bits), and its colour profile can be kept
/// (<see cref="FrameConverter.Treatment"/>). The plan asks the files what the conversion will ask them, reading headers
/// only, several at once. Sizes after are estimated from the pixels (<see cref="EstimateBytes"/>).
/// </summary>
@@ -176,6 +186,22 @@ public static class ConvertPlanner
/// </summary>
private const double FullChroma = 1.25;
/// <summary>
/// Bits per pixel of pixels that do not compress at all (noise) in the costliest target: three 16-bit samples, 48 bits
/// as Deflate stores them, and less than a bit more each as lossless JPEG codes them (an optimal Huffman code exceeds
/// the entropy of what it codes by less than one bit); a 4:4:4 JPEG of noise at quality 100 takes about 22.
/// </summary>
public const int WorstBitsPerPixel = 51;
/// <summary>
/// Margin on <see cref="WorstBitsPerPixel"/>: Deflate's stored blocks and zlib framing per strip, lossless JPEG's byte
/// stuffing (a 0xFF byte in 256 of noise) and headers per tile stay below 1 %.
/// </summary>
private const double WorstMargin = 1.01;
/// <summary>What a converted file holds beyond its pixels at most: an ICC profile carried whole, the Exif block, the directory and its strip or tile tables.</summary>
private const long WorstOverhead = IccProfile.MaxBytes + (4L << 20);
/// <summary>The plan of one sequence from its sidecar.</summary>
/// <param name="present">Every file in the folders of the sequence's frames, relative to the sequence folder
/// (<see cref="FileRenames.ListPresent"/>): the frames whose file is not among them are missing.</param>
@@ -231,9 +257,11 @@ public static class ConvertPlanner
var path = folder.File(frame.File);
try
{
// Not read at full resolution here, although the format is: what the file holds (its encoding, its size, a RAW
// body) is beyond these decoders, and only a preview, or nothing, is left.
var probe = decoders.Probe(path, frame.Format);
if (probe.Tier != DecodeTier.Native)
return probe.Tier == DecodeTier.EmbeddedPreview ? eightBit ? ConvertSkip.EightBit : ConvertSkip.PreviewOnly : ConvertSkip.Undecodable;
return eightBit ? ConvertSkip.EightBit : probe.Tier == DecodeTier.EmbeddedPreview ? ConvertSkip.PreviewOnly : ConvertSkip.NoNativeDecoder;
if (TooLarge(options, probe.Width, probe.Height)) return ConvertSkip.TooLarge;
return FrameConverter.Treatment(SourceColor.Read(path, frame.Format), options.Target) == ColorTreatment.Refuse ? ConvertSkip.ColorProfile : null;
}
@@ -245,17 +273,32 @@ public static class ConvertPlanner
/// <summary>
/// Whether a frame of <paramref name="width"/> × <paramref name="height"/> (unknown: 0) cannot be converted to
/// <paramref name="options"/>: a JPEG side above <see cref="FrameConverter.MaxJpegSide"/>, more samples than one image
/// buffer indexes, or an estimated file larger than the array it is made in.
/// <paramref name="options"/>, a bound and never an estimate: the target does not hold it (a JPEG side above
/// <see cref="FrameConverter.MaxJpegSide"/>), the server's decoders, which every converted file must decode with
/// (<see cref="FrameConverter.Verify"/>), do not read it back (a JPEG of more pixels than
/// <see cref="JpegDecodeOptions.MaxPixels"/>, a TIFF-16 or DNG of more samples than <see cref="TiffDecodeOptions.MaxSamples"/>),
/// or its file could outgrow the array it is made in (<see cref="WorstBytes"/>, which those sizes keep below it). What it
/// lets through fits one image buffer, its file the array it is made in, and the server's decoders read it back.
/// </summary>
public static bool TooLarge(ConvertOptions options, int width, int height)
{
ArgumentNullException.ThrowIfNull(options);
if (width <= 0 || height <= 0) return false;
if (options.Target == ConvertTarget.Jpeg && Math.Max(width, height) > FrameConverter.MaxJpegSide) return true;
return (long)width * height * 3 > Array.MaxLength || EstimateBytes(options, width, height) > Array.MaxLength;
var pixels = (long)width * height;
var readBack = options.Target == ConvertTarget.Jpeg
? Math.Max(width, height) <= FrameConverter.MaxJpegSide && pixels <= JpegDecodeOptions.Default.MaxPixels
: pixels * 3 <= TiffDecodeOptions.Default.MaxSamples;
return !readBack || WorstBytes(width, height) > Array.MaxLength;
}
/// <summary>
/// The largest a converted file of <paramref name="width"/> × <paramref name="height"/> pixels can be when its pixels do
/// not compress at all, in any target: <see cref="WorstBitsPerPixel"/> with its margin, and the most a file holds beyond
/// its pixels.
/// </summary>
public static long WorstBytes(int width, int height) =>
(long)Math.Ceiling((double)Math.Max(0, width) * Math.Max(0, height) * WorstBitsPerPixel / 8 * WorstMargin) + WorstOverhead;
/// <summary>
/// Estimated size of a converted file of <paramref name="width"/> × <paramref name="height"/> pixels (unknown:
/// <see cref="UnknownPixels"/>), from the bits per pixel the Export tab estimates with (<see cref="ExportEstimator"/>):