fix(convert): a conversion never changes what Chronos reads from a photo

Owner review 2, phase 4b, fix round 3 (codecs).

Chronos's decoders never read an ICC profile: they take code values through
the sRGB curve and float samples as they are. Round 2 wrote a float TIFF's
values with its profile's own curves, so after a Replace the renders,
thumbnails, analyses and deflicker of an Adobe RGB, ProPhoto or gamma-1.0
float TIFF saw other pixels (up to 2.7 EV darker, shadows lifted). Every
converted file now holds the values the decoders read from the original, as
they read them back, and says truthfully what they are:

- A JPEG or TIFF-16 keeps the codes of code values and carries the original's
  profile. Float values are written as sRGB codes with a profile made for
  them: the original's colorants and media white with the sRGB curve. A gray
  profile's codes are kept, its curve carried as an RGB profile (they were
  converted to sRGB before, which changed them too).
- A Linear DNG, whose matrices Chronos develops it with as well, takes only
  values that are sRGB's as the decoders read them; any other profile is
  refused as color_profile instead of converted to colours Chronos would then
  show differently.
- A profile with colorant tags that convert nothing is never sRGB by its name.
- A float file with NaN or infinite samples fails as damaged data instead of
  being written black (and spending a DNG's headroom).

The plan and the decoders behind it:

- TooLarge and WorstBytes answer any size, int.MaxValue sides included,
  without a product that wraps around; the worst case saturates.
- A frame another host flagged unreadable (the server, for a CMYK or CIELab
  TIFF its reader refuses) is asked again with a small decode where the
  conversion has other decoders (WIC on a PC), so a PC still converts it.
  The too_large sentences say "or Chronos reads back" (en, it).
- WIC's TIFF decoder decodes an unknown compression as zeros, does not undo
  the floating-point predictor of Photoshop's 32-bit files and reads 32-bit
  integers as floats, all without an error: such TIFFs are left to the
  managed reader, on the desktop as in conversions, never black or noise.
- A conversion's WIC probe reads the headers (decoder, first frame's oriented
  size, pixel format), so the size bound applies to what only WIC reads; a
  read error stays a read error (inaccessible), never a verdict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 09:36:00 +01:00
1 parent 4dd3050334
commit b471a33bfc
16 files changed
+1341 -330

No files matched your search

@@ -91,8 +91,9 @@ public sealed class IccProfileTests(TestContext context)
/// <summary>
/// A damaged profile never fails a conversion's colour work midway (owner review 2, R7): bytes flipped in matrix/TRC
/// profiles, as in a damaged file, give a profile that does not parse, one only to carry, or one whose matrix is finite
/// and invertible, and whose conversion of a JPEG's code values or a float TIFF's linear values, wherever the treatment
/// asks for one, runs to finite values; anything else the treatment refuses before any pixel is decoded.
/// and invertible; wherever the treatment asks for a profile made for the codes written (a float TIFF's linear values
/// into a JPEG or TIFF), that profile is made and parses, its matrix finite and invertible; a DNG takes the values as
/// they are or refuses them. Anything else the treatment refuses before any pixel is decoded.
/// </summary>
[Test]
public void DamagedProfilesConvertOrAreRefusedNeverFailMidway()
@@ -102,7 +103,7 @@ public sealed class IccProfileTests(TestContext context)
float[] values = [0, 0.18f, 0.5f, 1, 3, -0.2f, 0.02f, 0.9f];
var data = pixels.Data;
for (var i = 0; i < data.Length; i++) data[i] = values[i % values.Length];
int parsed = 0, worked = 0;
int parsed = 0, described = 0;
foreach (var original in (byte[][])[IccProfile.AdobeRgb.Data, IccProfile.DisplayP3.Data, ColorFixtures.Profile("Wide gamma 1.8", IccCurve.Gamma(1.8), wide: true).Data])
{
for (var n = 0; n < 1000; n++)
@@ -126,24 +127,21 @@ public sealed class IccProfileTests(TestContext context)
{
foreach (var target in Enum.GetValues<ConvertTarget>())
{
using var image = pixels.Clone();
var treatment = FrameConverter.Treatment(color, target);
if (treatment == ColorTreatment.Convert) FrameConverter.ToLinearRec709(image, color.Profile!, color.IsLinear, 1, CancellationToken.None);
else if (treatment == ColorTreatment.Encode) FrameConverter.EncodeWithCurves(image, color.Profile!, 1, CancellationToken.None);
else continue;
worked++;
// Code values convert within the matrix's reach; linear ones as large as the file holds may overflow.
if (treatment == ColorTreatment.Encode || !color.IsLinear)
{
foreach (var v in image.Data) Assert.True(float.IsFinite(v), $"{treatment} of {target} gives finite values");
}
if (target == ConvertTarget.LinearDng) Assert.True(treatment is ColorTreatment.None or ColorTreatment.Refuse, $"a DNG of {treatment}");
if (treatment != ColorTreatment.Describe) continue;
var made = IccProfile.Parse(FrameConverter.Described(color.Profile!).Data);
Assert.True(made is { IsMatrixShaper: true }, "the profile made for the codes parses as a matrix/TRC one");
var m = made!.ToLinearRec709();
Assert.True(Finite(m) && m.TryInvert(out var inverse) && Finite(inverse), "and converts with finite numbers");
described++;
}
}
}
}
context.Log($"{parsed} damaged profiles parsed, {worked} conversions run");
context.Log($"{parsed} damaged profiles parsed, {described} described");
Assert.Greater(parsed, 1000);
Assert.Greater(worked, 1000);
Assert.Greater(described, 1000);
static bool Finite(Matrix3 m) => new[] { m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33 }.All(double.IsFinite);
@@ -155,7 +153,11 @@ public sealed class IccProfileTests(TestContext context)
}
}
/// <summary>A matrix/TRC profile is sRGB when its numbers are sRGB's, whatever its name says; one without them by its name.</summary>
/// <summary>
/// A matrix/TRC profile is sRGB when its numbers are sRGB's, whatever its name says; one without colorant tags at all (a
/// lookup-table profile) by its name. One whose colorants convert nothing, or whose curves are missing, is not, whatever
/// its name (owner review 2, R7).
/// </summary>
[Test]
public void SrgbIsWhatTheNumbersSay()
{
@@ -166,28 +168,77 @@ public sealed class IccProfileTests(TestContext context)
Assert.False(ColorFixtures.Profile("sRGB gamma 2.2", IccCurve.Gamma(2.2)).IsSrgb);
Assert.False(ColorFixtures.Profile("sRGB wide", IccCurve.Srgb, wide: true).IsSrgb);
Assert.False(IccProfile.DisplayP3.IsSrgb);
// Without colorant tags, the name decides; with colorants that convert nothing, or no curves, nothing says sRGB.
Assert.True(IccProfile.Parse(ColorFixtures.WithoutColorants(ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Gamma(1)).Data))!.IsSrgb);
Assert.False(IccProfile.Parse(ColorFixtures.WithoutColorants(IccProfile.AdobeRgb.Data))!.IsSrgb);
var degenerate = IccProfile.Parse(ColorFixtures.Degenerate(ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Srgb).Data))!;
Assert.True(degenerate is { IsRgb: true, Colorants: null, IsSrgb: false });
var curveless = ColorFixtures.Renamed(ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Srgb).Data, "rTRC", "xTRC");
Assert.True(IccProfile.Parse(curveless) is { IsMatrixShaper: false, IsSrgb: false });
// The curves themselves.
Assert.True(IccCurve.Srgb.IsSrgb && IccProfile.DisplayP3.Curves![0].IsSrgb);
Assert.False(IccCurve.Gamma(2.2).IsSrgb || IccCurve.Gamma(1).IsSrgb);
}
/// <summary>Curves invert: exactly for a power law and a table, within a 16-bit step for a parametric function.</summary>
/// <summary>
/// Values are sRGB's as Chronos's decoders take them (owner review 2, R7) when they are in sRGB's primaries and, for code
/// values, through sRGB's curve: a linear-curve profile in sRGB's primaries holds sRGB's linear values but not its code
/// values; a gray profile's linear values are linear gray, its code values need the sRGB curve.
/// </summary>
[Test]
public void CurvesInvert()
public void ValuesAreSrgbsWhereThePrimariesAndTheCurveSaySo()
{
var gamma = IccCurve.Gamma(2.2);
var table = ColorFixtures.Profile("Gamma 1.8", IccCurve.Gamma(1.8)).Curves![0];
var srgb = IccCurve.Srgb;
foreach (var curve in (IccCurve[])[gamma, table, srgb]) Assert.True(curve.IsInvertible);
for (var code = 0.0; code <= 1; code += 1 / 128.0)
(IccProfile Profile, bool Linear, bool Codes)[] cases =
[
(ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Srgb), true, true),
(ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Gamma(1)), true, false),
(ColorFixtures.Profile("sRGB gamma 2.2", IccCurve.Gamma(2.2)), true, false),
(IccProfile.AdobeRgb, false, false),
(IccProfile.DisplayP3, false, false),
(ColorFixtures.ProPhoto(), false, false),
(IccProfile.Parse(ColorFixtures.Gray("Gray Gamma 2.2", IccCurve.Gamma(2.2)))!, true, false),
(IccProfile.Parse(ColorFixtures.Gray("sGray", IccCurve.Srgb))!, true, true),
(IccProfile.Parse(ColorFixtures.Cmyk())!, false, false),
(IccProfile.Parse(ColorFixtures.Degenerate())!, false, false),
];
foreach (var (profile, linear, codes) in cases)
Assert.Equal((linear, codes), (profile.IsSrgbFor(linear: true), profile.IsSrgbFor(linear: false)), $"{profile.Description} ({profile.ColorSpace:X8})");
}
/// <summary>
/// The profiles a converted file carries for codes that are not the original's (owner review 2, R7): a matrix/TRC
/// profile's colorants and media white with the sRGB curve, to the bit; a gray profile's curve on three channels whose
/// equal values are neutral.
/// </summary>
[Test]
public void ProfilesMadeForTheCodesKeepWhatTheyDescribe()
{
foreach (var source in (IccProfile[])[IccProfile.AdobeRgb, ColorFixtures.ProPhoto(), ColorFixtures.Profile("Wide gamma 1.0", IccCurve.Gamma(1), wide: true)])
{
Assert.Approximately(code, gamma.Invert(gamma.Evaluate(code)), 1e-9);
Assert.Approximately(code, table.Invert(table.Evaluate(code)), 1e-6);
Assert.Approximately(code, srgb.Invert(ColorSpace.SrgbToLinear(code)), 1 / 65536.0);
var made = IccProfile.Parse(source.WithSrgbCurve().Data)!;
Assert.True(made.IsMatrixShaper && made.IsRgb, source.Description);
Assert.Equal(source.Colorants, made.Colorants);
Assert.Equal(source.MediaWhite, made.MediaWhite);
Assert.True(made.Curves!.All(c => c.IsSrgb), source.Description);
Assert.Equal($"{source.Description} (sRGB curve)", made.Description);
}
// Linear values beyond the curve's range take its ends.
Assert.Equal((0.0, 1.0), (gamma.Invert(-0.5), gamma.Invert(3)));
Assert.Equal((0.0, 1.0), (table.Invert(-0.5), table.Invert(3)));
// A curve that falls somewhere maps two codes to one value: no encoding undoes it.
Assert.False(IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0xFF, 0xFF, 0x80, 0])!.IsInvertible);
Assert.False(IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 2, 0x80, 0, 0x80, 0])!.IsInvertible);
var gray = IccProfile.Parse(ColorFixtures.Gray("Gray Gamma 2.2", IccCurve.Gamma(2.2)))!;
var rgb = IccProfile.Parse(gray.GrayAsRgb().Data)!;
Assert.True(rgb is { IsMatrixShaper: true, IsRgb: true });
Assert.Equal("Gray Gamma 2.2 (RGB)", rgb.Description);
for (var code = 0.0; code <= 1; code += 0.125)
{
var light = rgb.ToLinearRec709() * new Vector3D(rgb.Curves![0].Evaluate(code), rgb.Curves[1].Evaluate(code), rgb.Curves[2].Evaluate(code));
var expected = gray.Curves![0].Evaluate(code);
Assert.Approximately(expected, light.X, 1e-3);
Assert.Approximately(expected, light.Y, 1e-3);
Assert.Approximately(expected, light.Z, 1e-3);
}
Assert.Throws<InvalidOperationException>(() => gray.WithSrgbCurve());
Assert.Throws<InvalidOperationException>(() => IccProfile.AdobeRgb.GrayAsRgb());
// A damaged profile's endless description is cut.
var long1 = IccProfile.Synthesize(new string('x', 5000), new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), IccCurve.Srgb);
Assert.Less(long1.Description!.Length, 300);
}
/// <summary>A TIFF of floating-point samples or linear RAW holds linear values; integer samples are code values.</summary>