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

@@ -436,6 +436,135 @@ public sealed class FrameConverterTests(TestContext context)
}
}
/// <summary>
/// A CMYK TIFF without a profile is decoded by what reads CMYK (WIC on a PC), never by the managed reader as the gray of
/// its first ink; where nothing reads it (the server), it is not converted, and nothing is written.
/// </summary>
[Test]
public void ACmykTiffIsDecodedByWhatReadsItNeverAsGray()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "cmyk.tif");
File.WriteAllBytes(path, ColorFixtures.Tiff(6, 4, 5, [0, 255, 255, 0]));
var frame = Frame("cmyk.tif", ImageFileFormat.Tiff, 6, 4);
using var red = new ImageBuffer(6, 4);
red.Plane(0).Fill(0.6f);
red.Plane(1).Fill(0.003f);
red.Plane(2).Fill(0.002f);
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
var file = FrameConverter.Convert(new ConvertSource(path, frame), jpeg, new ImageDecoder([new Developed(red, ImageFileFormat.Tiff), new ManagedDecoderProvider()]),
Target(jpeg), cancellationToken: context.Cancellation);
using var converted = DecoderFactory.CreateServer().Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
Assert.Greater(converted.Pixels[0, 3, 2], 0.5);
Assert.Less(converted.Pixels[1, 3, 2], 0.02);
var output = Target(jpeg);
var refused = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), jpeg, DecoderFactory.CreateServer(), output, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.NoDecoder, refused.Reason);
Assert.FileMissing(output);
}
/// <summary>
/// A float TIFF's values are linear light in its profile's primaries (owner review 2, R7): a JPEG or TIFF carries the
/// profile with codes its own curves give them, so a reader that applies the profile reads the original values; a DNG
/// gets them through the profile's matrix alone, no curve and no clip, so values above white stay.
/// </summary>
[Theory]
[Case(1.0)]
[Case(1.8)]
public void AFloatTiffKeepsItsLinearValuesInItsColourSpace(double gamma)
{
var profile = ColorFixtures.Profile($"Wide gamma {gamma}", IccCurve.Gamma(gamma), wide: true);
using var scene = new ImageBuffer(8, 4);
scene.Data.Fill(0.18f);
(scene[0, 1, 1], scene[1, 1, 1], scene[2, 1, 1]) = (0.5f, 0.1f, 0.05f);
(scene[0, 2, 1], scene[1, 2, 1], scene[2, 2, 1]) = (3f, 3f, 3f);
var path = Path.Combine(context.CreateTempDirectory("source"), "stack.tif");
File.WriteAllBytes(path, ColorFixtures.FloatTiff(scene, profile.Data));
var source = new ConvertSource(path, Frame("stack.tif", ImageFileFormat.Tiff, 8, 4));
var server = DecoderFactory.CreateServer();
Assert.Equal(ColorTreatment.Encode, FrameConverter.Treatment(SourceColor.Read(path, ImageFileFormat.Tiff), ConvertTarget.Tiff16));
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.Jpeg])
{
var options = new ConvertOptions(target, 100);
var file = FrameConverter.Convert(source, options, server, Target(options), cancellationToken: context.Cancellation);
Assert.BytesEqual(profile.Data, SourceColor.Read(file.Path, file.Format).Profile!.Data);
using var converted = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
// The codes written, read through the profile carried.
double Read(int c, int x, int y) => profile.Curves![c].Evaluate(ColorSpace.LinearToSrgb(converted.Pixels[c, x, y]));
var tolerance = target == ConvertTarget.Jpeg ? 0.012 : 1e-3;
Assert.Approximately(0.18, Read(1, 5, 2), tolerance, $"{target}, gamma {gamma}");
Assert.Approximately(0.5, Read(0, 1, 1), tolerance * 2, $"{target}, gamma {gamma}");
Assert.Approximately(0.05, Read(2, 1, 1), tolerance, $"{target}, gamma {gamma}");
// Above white is clipped there, as in any file of code values.
Assert.Approximately(1, Read(0, 2, 1), tolerance * 2);
}
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var linear = FrameConverter.Convert(source, dng, server, Target(dng), cancellationToken: context.Cancellation);
using var developed = server.Decode(new DecodeRequest(linear.Path, AllowPreview: false))!;
var matrix = profile.ToLinearRec709();
foreach (var (x, y) in ((int, int)[])[(5, 2), (1, 1), (2, 1)])
{
var expected = matrix * new Vector3D(scene[0, x, y], scene[1, x, y], scene[2, x, y]);
Assert.Approximately(expected.X, developed.Pixels[0, x, y], 2e-3 * Math.Max(1, expected.X));
Assert.Approximately(expected.Y, developed.Pixels[1, x, y], 2e-3 * Math.Max(1, expected.Y));
Assert.Approximately(expected.Z, developed.Pixels[2, x, y], 2e-3 * Math.Max(1, expected.Z));
}
Assert.Greater(developed.Pixels[1, 2, 1], 2.9);
}
/// <summary>
/// A DNG converts through any matrix/TRC profile that is not sRGB by its numbers, whatever its name: one named sRGB with
/// a linear curve gets its code values as linear light, not as sRGB codes.
/// </summary>
[Test]
public void AProfileNamedSrgbWithAnotherCurveIsConvertedIntoADng()
{
var folder = context.CreateTempDirectory("source");
using var scene = ColorFixtures.Scene();
var server = DecoderFactory.CreateServer();
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var linearCurve = ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Gamma(1));
var real = ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Srgb);
Assert.Equal(ColorTreatment.Convert, FrameConverter.Treatment(SourceColor.Read(new MemoryStream(ColorFixtures.Jpeg(scene, linearCurve.Data)), ImageFileFormat.Jpeg), ConvertTarget.LinearDng));
Assert.Equal(ColorTreatment.None, FrameConverter.Treatment(SourceColor.Read(new MemoryStream(ColorFixtures.Jpeg(scene, real.Data)), ImageFileFormat.Jpeg), ConvertTarget.LinearDng));
var path = Path.Combine(folder, "g10.jpg");
File.WriteAllBytes(path, ColorFixtures.Jpeg(scene, linearCurve.Data));
using var original = server.Decode(new DecodeRequest(path, AllowPreview: false))!;
var file = FrameConverter.Convert(new ConvertSource(path, Frame("g10.jpg", ImageFileFormat.Jpeg, 48, 32)), dng, server, Target(dng), cancellationToken: context.Cancellation);
using var developed = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
for (var i = 0; i < scene.PlaneLength; i += 5)
{
var code = ColorSpace.LinearToSrgb(original.Pixels.Plane(1)[i]);
Assert.Approximately(code, developed.Pixels.Plane(1)[i], 3e-3);
}
}
/// <summary>
/// A profile whose colorants convert nothing (a damaged one) refuses its photo for a DNG, which would convert through
/// them, at once and as a colour profile, and is carried unchanged into a JPEG or TIFF.
/// </summary>
[Test]
public void AProfileThatConvertsNothingIsRefusedForADngAndCarriedElsewhere()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "odd.jpg");
using var scene = ColorFixtures.Scene();
var degenerate = ColorFixtures.Degenerate();
File.WriteAllBytes(path, ColorFixtures.Jpeg(scene, degenerate));
var source = new ConvertSource(path, Frame("odd.jpg", ImageFileFormat.Jpeg, 48, 32));
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var output = Target(dng);
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(source, dng, DecoderFactory.CreateServer(), output, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.ColorProfile, refused.Reason);
Assert.FileMissing(output);
var tiff = new ConvertOptions(ConvertTarget.Tiff16);
var carried = FrameConverter.Convert(source, tiff, DecoderFactory.CreateServer(), Target(tiff), cancellationToken: context.Cancellation);
Assert.BytesEqual(degenerate, SourceColor.Read(carried.Path, carried.Format).Profile!.Data);
}
/// <summary>A photo larger than the target or one buffer holds fails as too large, not with the encoder's own exception.</summary>
[Test]
public void APhotoTooLargeForTheTargetFailsAsTooLarge()