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:
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>
|
||||
|
||||
@@ -102,13 +102,47 @@ internal static class ColorFixtures
|
||||
? IccProfile.Synthesize(description, new(0.64, 0.33), new(0.21, 0.71), new(0.15, 0.06), curve)
|
||||
: IccProfile.Synthesize(description, new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), curve);
|
||||
|
||||
/// <summary>
|
||||
/// The Adobe RGB profile with colorants that convert nothing: they add up to a white whose cone responses are not all
|
||||
/// positive, although the matrix they make can be inverted (as a damaged profile's can).
|
||||
/// </summary>
|
||||
public static byte[] Degenerate()
|
||||
/// <summary>ProPhoto (ROMM) primaries with its gamma 1.8 (and the D65 white the synthesized profiles have).</summary>
|
||||
public static IccProfile ProPhoto() =>
|
||||
IccProfile.Synthesize("ProPhoto RGB", new(0.7347, 0.2653), new(0.1596, 0.8404), new(0.0366, 0.0001), IccCurve.Gamma(1.8));
|
||||
|
||||
/// <summary>A gray profile (GRAY, a kTRC of <paramref name="curve"/>) named <paramref name="description"/>.</summary>
|
||||
public static byte[] Gray(string description, IccCurve curve)
|
||||
{
|
||||
var data = (byte[])IccProfile.AdobeRgb.Data.Clone();
|
||||
var data = Renamed(Profile(description, curve).Data, "rTRC", "kTRC");
|
||||
"GRAY"u8.CopyTo(data.AsSpan(16));
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="profile"/> with its rXYZ, gXYZ and bXYZ tags renamed: a profile without colorant tags, as a lookup-table one is.</summary>
|
||||
public static byte[] WithoutColorants(byte[] profile) => Renamed(Renamed(Renamed(profile, "rXYZ", "rLUT"), "gXYZ", "gLUT"), "bXYZ", "bLUT");
|
||||
|
||||
/// <summary>A copy of <paramref name="profile"/> whose tag <paramref name="from"/> is named <paramref name="to"/>: a reader no longer finds it.</summary>
|
||||
public static byte[] Renamed(byte[] profile, string from, string to)
|
||||
{
|
||||
var data = (byte[])profile.Clone();
|
||||
var count = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(128));
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var entry = data.AsSpan(132 + 12 * i, 12);
|
||||
if (entry[..4].SequenceEqual(System.Text.Encoding.ASCII.GetBytes(from))) System.Text.Encoding.ASCII.GetBytes(to).CopyTo(entry);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>A gray JPEG whose codes are the sRGB encoding of <paramref name="gray"/> (one channel), with an ICC profile.</summary>
|
||||
public static byte[] GrayJpeg(ImageBuffer gray, byte[]? icc = null) => JpegEncoder.Encode(gray, new JpegEncodeOptions { Quality = 98, IccProfile = icc });
|
||||
|
||||
/// <summary>A 16-bit TIFF whose codes are the sRGB encoding of <paramref name="scene"/>, with an ICC profile.</summary>
|
||||
public static byte[] Tiff16(ImageBuffer scene, byte[]? icc = null) => TiffWriter.Write(scene, new TiffWriteOptions { BitsPerSample = 16, IccProfile = icc });
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="profile"/> (the Adobe RGB one by default) with colorants that convert nothing: they add up to a white
|
||||
/// whose cone responses are not all positive, although the matrix they make can be inverted (as a damaged profile's can).
|
||||
/// </summary>
|
||||
public static byte[] Degenerate(byte[]? profile = null)
|
||||
{
|
||||
var data = (byte[])(profile ?? IccProfile.AdobeRgb.Data).Clone();
|
||||
var count = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(128));
|
||||
(string Tag, double X, double Y, double Z)[] colorants = [("rXYZ", -1.0, 0.2, 0.1), ("gXYZ", 0.1, 0.5, 0.1), ("bXYZ", 0.1, 0.3, 0.6)];
|
||||
for (var i = 0; i < count; i++)
|
||||
@@ -176,18 +210,22 @@ internal static class ColorFixtures
|
||||
0x12, 0x34, 0xFF, 0xD9,
|
||||
];
|
||||
|
||||
/// <summary>An uncompressed TIFF of 32-bit floating-point RGB (linear light), with an ICC profile when one is given.</summary>
|
||||
/// <summary>
|
||||
/// An uncompressed TIFF of 32-bit floating-point RGB, or gray for a one-channel image (linear light), with an ICC
|
||||
/// profile when one is given.
|
||||
/// </summary>
|
||||
public static byte[] FloatTiff(ImageBuffer image, byte[]? icc = null)
|
||||
{
|
||||
var strip = new byte[image.PlaneLength * 3 * 4];
|
||||
var channels = image.Channels == 1 ? 1 : 3;
|
||||
var strip = new byte[image.PlaneLength * channels * 4];
|
||||
for (var i = 0; i < image.PlaneLength; i++)
|
||||
{
|
||||
for (var c = 0; c < 3; c++) BinaryPrimitives.WriteSingleLittleEndian(strip.AsSpan((i * 3 + c) * 4), image.Plane(c)[i]);
|
||||
for (var c = 0; c < channels; c++) BinaryPrimitives.WriteSingleLittleEndian(strip.AsSpan((i * channels + c) * 4), image.Plane(c)[i]);
|
||||
}
|
||||
return TiffTestEncoders.Build(d =>
|
||||
{
|
||||
TiffTests.Layout(d, image.Width, image.Height, 3, 32, compression: 1);
|
||||
d.Short(TiffTags.SampleFormat, 3, 3, 3);
|
||||
TiffTests.Layout(d, image.Width, image.Height, channels, 32, compression: 1);
|
||||
d.Short(TiffTags.SampleFormat, [.. Enumerable.Repeat((ushort)3, channels)]);
|
||||
if (icc is not null) d.Add(TiffTags.InterColorProfile, TiffType.Undefined, icc.Length, icc);
|
||||
}, [strip], tiled: false);
|
||||
}
|
||||
|
||||
@@ -205,13 +205,14 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
var present = frames.Select(f => f.File).ToList();
|
||||
var decoder = DecoderFactory.CreateServer();
|
||||
|
||||
// A TIFF and a DNG keep the P3 photo (carried, or converted), not the unknown and CMYK ones, nor 2.5 G samples.
|
||||
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
|
||||
{
|
||||
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(target), decoder, "Roof");
|
||||
Assert.SequenceEqual([0, 1, 4], plan.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.ColorProfile, 2), (ConvertSkip.TooLarge, 1)], plan.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
}
|
||||
// A TIFF carries the P3 photo's profile; a DNG, which holds sRGB as Chronos reads it, does not take it. Neither takes
|
||||
// the unknown and CMYK ones, nor 2.5 G samples.
|
||||
var tiff = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Tiff16), decoder, "Roof");
|
||||
Assert.SequenceEqual([0, 1, 4], tiff.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.ColorProfile, 2), (ConvertSkip.TooLarge, 1)], tiff.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
var dng = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.LinearDng), decoder, "Roof");
|
||||
Assert.SequenceEqual([0, 4], dng.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.ColorProfile, 3), (ConvertSkip.TooLarge, 1)], dng.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
// A JPEG side holds 65535 pixels.
|
||||
var jpeg = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Jpeg), decoder, "Roof");
|
||||
Assert.SequenceEqual([(ConvertSkip.SameFormat, 4), (ConvertSkip.TooLarge, 2)], jpeg.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
@@ -271,6 +272,88 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Any size is answered, a damaged header's included (owner review 2, R7): sides up to <see cref="int.MaxValue"/> are too
|
||||
/// large for every target, never let through by a product that wrapped around, and the worst case saturates instead of
|
||||
/// turning negative.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AnySizeIsAnsweredWithoutOverflow()
|
||||
{
|
||||
(int W, int H)[] absurd =
|
||||
[
|
||||
(int.MaxValue, int.MaxValue), (2_000_000_000, 2_000_000_000), (1_800_000_000, 1_800_000_000), (1_000_000_000, 1_000_000_000),
|
||||
(int.MaxValue, 1), (1, int.MaxValue),
|
||||
];
|
||||
foreach (var target in Enum.GetValues<ConvertTarget>())
|
||||
{
|
||||
foreach (var (w, h) in absurd) Assert.True(ConvertPlanner.TooLarge(new ConvertOptions(target), w, h), $"{target} at {w}×{h}");
|
||||
Assert.Greater(ConvertPlanner.EstimateBytes(new ConvertOptions(target), int.MaxValue, int.MaxValue), 0L);
|
||||
}
|
||||
Assert.Equal(long.MaxValue, ConvertPlanner.WorstBytes(int.MaxValue, int.MaxValue));
|
||||
Assert.Greater(ConvertPlanner.WorstBytes(1_800_000_000, 1_800_000_000), Array.MaxLength);
|
||||
Assert.Greater(ConvertPlanner.WorstBytes(65_535, 65_535), 0L);
|
||||
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Tiff16), -5, 10));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame flagged unreadable by the host that analysed it (the server, whose decoders refuse a CMYK TIFF) is asked again
|
||||
/// where the conversion's decoders have others for its format (WIC on a PC), with a small decode (owner review 2, R7):
|
||||
/// converted where they read it, unreadable where they do not. A corrupt frame stays unreadable, and so does a flagged one
|
||||
/// where only the managed decoders read the format. A file that cannot be read while it is asked is inaccessible, nothing
|
||||
/// concluded of its content.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AFrameFlaggedUnreadableElsewhereIsAskedWhereOtherDecodersReadIt()
|
||||
{
|
||||
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
|
||||
SidecarFrame[] frames =
|
||||
[
|
||||
Frame(0, "cmyk.tif", ImageFileFormat.Tiff, flags: FrameFlags.Undecodable) with { W = 6, H = 4 },
|
||||
Frame(1, "corrupt.tif", ImageFileFormat.Tiff, flags: FrameFlags.Corrupt) with { W = 6, H = 4 },
|
||||
];
|
||||
File.WriteAllBytes(folder.File(frames[0].File), ColorFixtures.Tiff(6, 4, 5, [0, 255, 255, 0]));
|
||||
File.WriteAllBytes(folder.File(frames[1].File), ColorFixtures.Tiff(6, 4, 2, [1, 2, 3]));
|
||||
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
|
||||
var present = frames.Select(f => f.File).ToList();
|
||||
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
|
||||
IEnumerable<(ConvertSkip, int)> Skipped(ConvertSequencePlan plan) => plan.Skipped.Select(s => (s.Reason, s.Frames));
|
||||
|
||||
var server = ConvertPlanner.Plan(manifest, folder, present, jpeg, DecoderFactory.CreateServer(), "Roof");
|
||||
Assert.Empty(server.Frames);
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 2)], Skipped(server));
|
||||
var reads = ConvertPlanner.Plan(manifest, folder, present, jpeg, new ImageDecoder([new DecodesTiffs(decodes: true), new ManagedDecoderProvider()]), "Roof");
|
||||
Assert.SequenceEqual([0], reads.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 1)], Skipped(reads));
|
||||
var fails = ConvertPlanner.Plan(manifest, folder, present, jpeg, new ImageDecoder([new DecodesTiffs(decodes: false), new ManagedDecoderProvider()]), "Roof");
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 2)], Skipped(fails));
|
||||
var held = ConvertPlanner.Plan(manifest, folder, present, jpeg,
|
||||
new ImageDecoder([new DecodesTiffs(decodes: true, failure: new IOException("held by another process")), new ManagedDecoderProvider()]), "Roof");
|
||||
Assert.Empty(held.Frames);
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 1), (ConvertSkip.Inaccessible, 1)], Skipped(held));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WIC as a PC has it, for TIFFs: native by format (its probe trusts it), and a decode that reads a CMYK TIFF, finds
|
||||
/// nothing in it, or fails as <paramref name="failure"/> says.
|
||||
/// </summary>
|
||||
private sealed class DecodesTiffs(bool decodes, Exception? failure = null) : IImageDecoderProvider
|
||||
{
|
||||
public string Name => "wic";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Tiff ? DecodeTier.Native : null;
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (failure is not null) throw failure;
|
||||
if (!decodes) return null;
|
||||
var red = new ImageBuffer(6, 4);
|
||||
red.Plane(0).Fill(0.6f);
|
||||
return new DecodedImage(red, DecodeTier.Native, Name, 6, 4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run reads the headers of TIFF, PNG and JPEG files before it promises them (owner review 2, R7): on the server,
|
||||
/// a CMYK, CIELab, palette or ZSTD TIFF, one with more samples than its decoder takes and an arithmetic-coded JPEG are
|
||||
|
||||
@@ -351,7 +351,8 @@ public sealed class FrameConverterTests(TestContext context)
|
||||
|
||||
/// <summary>
|
||||
/// The colour space the original's values are in is kept: a JPEG or TIFF carries its ICC profile (or the Adobe RGB one
|
||||
/// its Exif names) with the values unchanged; a linear DNG gets the values converted through the profile.
|
||||
/// its Exif names) with the values unchanged. A linear DNG, whose matrices Chronos develops it with, cannot hold P3 codes
|
||||
/// as Chronos reads them and say they are P3: it refuses the photo, which converting would show otherwise.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void TheOriginalsColourSpaceIsKept()
|
||||
@@ -380,22 +381,10 @@ public sealed class FrameConverterTests(TestContext context)
|
||||
}
|
||||
|
||||
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 = p3.ToLinearRec709();
|
||||
for (var i = 0; i < scene.PlaneLength; i += 7)
|
||||
{
|
||||
var code = new Vector3D(
|
||||
p3.Curves![0].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(0)[i])),
|
||||
p3.Curves[1].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(1)[i])),
|
||||
p3.Curves[2].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(2)[i])));
|
||||
var expected = matrix * code;
|
||||
Assert.Approximately(expected.X, developed.Pixels.Plane(0)[i], 5e-4);
|
||||
Assert.Approximately(expected.Y, developed.Pixels.Plane(1)[i], 5e-4);
|
||||
Assert.Approximately(expected.Z, developed.Pixels.Plane(2)[i], 5e-4);
|
||||
}
|
||||
// The P3 green patch is outside sRGB: its red is negative in the DNG, not clipped to 0.
|
||||
Assert.Less(developed.Pixels[0, 2, 2], -0.05);
|
||||
var output = Target(dng);
|
||||
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(source, dng, server, output, cancellationToken: context.Cancellation));
|
||||
Assert.Equal(ConversionFailure.ColorProfile, refused.Reason);
|
||||
Assert.FileMissing(output);
|
||||
|
||||
// A camera JPEG in Adobe RGB (Exif uncalibrated, Interop R03) carries the Adobe RGB profile; a PNG its iCCP.
|
||||
var adobePath = Path.Combine(folder, "adobe.jpg");
|
||||
@@ -465,87 +454,235 @@ public sealed class FrameConverterTests(TestContext context)
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// What Chronos reads from a photo never changes with its conversion (owner review 2, R7): Chronos's decoders, which
|
||||
/// never read a profile, read the converted file as they read the original, within what the target holds, whatever the
|
||||
/// original's colour space (sRGB, Adobe RGB, ProPhoto, a linear-curve profile, gray) and samples (8-bit, 16-bit, float).
|
||||
/// The file says truthfully what the values are: the original's profile where its codes are the original's, else one
|
||||
/// made for them (the original's colorants with the sRGB curve, or a gray curve as RGB). A DNG takes only values that are
|
||||
/// sRGB's as the decoders read them, and reads back the same; it refuses the others, which its matrices would show
|
||||
/// otherwise.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void WhatChronosReadsIsWhatTheConvertedFileReadsBack()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("source");
|
||||
using var scene = ColorFixtures.Scene();
|
||||
using var grays = new ImageBuffer(48, 32, 1);
|
||||
for (var i = 0; i < grays.PlaneLength; i++) grays.Plane(0)[i] = 0.002f + 0.95f * i / grays.PlaneLength;
|
||||
var srgb = ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Srgb);
|
||||
var g10 = ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Gamma(1));
|
||||
var wideG10 = ColorFixtures.Profile("Wide gamma 1.0", IccCurve.Gamma(1), wide: true);
|
||||
var prophoto = ColorFixtures.ProPhoto();
|
||||
var gamma22 = ColorFixtures.Gray("Gray Gamma 2.2", IccCurve.Gamma(2.2));
|
||||
var sGray = ColorFixtures.Gray("sGray", IccCurve.Srgb);
|
||||
(string Name, byte[] File, IccProfile? Profile, bool DngKeeps)[] sources =
|
||||
[
|
||||
("untagged.jpg", ColorFixtures.Jpeg(scene), null, true),
|
||||
("srgb.jpg", ColorFixtures.Jpeg(scene, srgb.Data), srgb, true),
|
||||
("adobe.jpg", ColorFixtures.Jpeg(scene, IccProfile.AdobeRgb.Data), IccProfile.AdobeRgb, false),
|
||||
("g10.jpg", ColorFixtures.Jpeg(scene, g10.Data), g10, false),
|
||||
("adobe16.tif", ColorFixtures.Tiff16(scene, IccProfile.AdobeRgb.Data), IccProfile.AdobeRgb, false),
|
||||
("prophoto16.tif", ColorFixtures.Tiff16(scene, prophoto.Data), prophoto, false),
|
||||
("float.tif", ColorFixtures.FloatTiff(scene), null, true),
|
||||
("float-srgb.tif", ColorFixtures.FloatTiff(scene, srgb.Data), srgb, true),
|
||||
("float-adobe.tif", ColorFixtures.FloatTiff(scene, IccProfile.AdobeRgb.Data), IccProfile.AdobeRgb, false),
|
||||
("float-prophoto.tif", ColorFixtures.FloatTiff(scene, prophoto.Data), prophoto, false),
|
||||
("float-g10.tif", ColorFixtures.FloatTiff(scene, g10.Data), g10, true),
|
||||
("float-wide-g10.tif", ColorFixtures.FloatTiff(scene, wideG10.Data), wideG10, false),
|
||||
("gray22.jpg", ColorFixtures.GrayJpeg(grays, gamma22), IccProfile.Parse(gamma22), false),
|
||||
("sgray.jpg", ColorFixtures.GrayJpeg(grays, sGray), IccProfile.Parse(sGray), true),
|
||||
("float-gray22.tif", ColorFixtures.FloatTiff(grays, gamma22), IccProfile.Parse(gamma22), true),
|
||||
];
|
||||
var server = DecoderFactory.CreateServer();
|
||||
foreach (var (name, bytes, profile, dngKeeps) in sources)
|
||||
{
|
||||
var path = Path.Combine(folder, name);
|
||||
File.WriteAllBytes(path, bytes);
|
||||
var format = name.EndsWith(".jpg", StringComparison.Ordinal) ? ImageFileFormat.Jpeg : ImageFileFormat.Tiff;
|
||||
var color = SourceColor.Read(path, format);
|
||||
var source = new ConvertSource(path, Frame(name, format, 48, 32));
|
||||
using var original = server.Decode(new DecodeRequest(path, AllowPreview: false))!;
|
||||
foreach (var target in (ConvertTarget[])[ConvertTarget.Jpeg, ConvertTarget.Tiff16])
|
||||
{
|
||||
var options = new ConvertOptions(target, 100);
|
||||
var file = FrameConverter.Convert(source, options, server, Target(options), cancellationToken: context.Cancellation);
|
||||
using var converted = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
|
||||
var (max, mean) = CodeDifference(original.Pixels, converted.Pixels);
|
||||
var what = $"{name} → {target}";
|
||||
Assert.LessOrEqual(max, target == ConvertTarget.Jpeg ? 4 / 255.0 : 2 / 65535.0, what);
|
||||
Assert.Less(mean, target == ConvertTarget.Jpeg ? 1 / 255.0 : 1 / 65535.0, what);
|
||||
AssertTruthful(color, SourceColor.Read(file.Path, file.Format), original.Pixels, converted.Pixels, target == ConvertTarget.Jpeg ? 0.05 : 2e-4, what);
|
||||
}
|
||||
|
||||
var dng = new ConvertOptions(ConvertTarget.LinearDng);
|
||||
var output = Target(dng);
|
||||
Assert.Equal(dngKeeps ? ColorTreatment.None : ColorTreatment.Refuse, FrameConverter.Treatment(color, ConvertTarget.LinearDng), name);
|
||||
if (!dngKeeps)
|
||||
{
|
||||
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(source, dng, server, output, cancellationToken: context.Cancellation));
|
||||
Assert.Equal(ConversionFailure.ColorProfile, refused.Reason, name);
|
||||
Assert.FileMissing(output);
|
||||
continue;
|
||||
}
|
||||
FrameConverter.Convert(source, dng, server, output, cancellationToken: context.Cancellation);
|
||||
using var developed = server.Decode(new DecodeRequest(output, AllowPreview: false))!;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
for (var i = 0; i < scene.PlaneLength; i++) Assert.Approximately(original.Pixels.Plane(c)[i], developed.Pixels.Plane(c)[i], 3e-4, $"{name} → DNG");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The largest and the mean difference between two decodes of the same size, in sRGB code values (what the files hold).</summary>
|
||||
private static (double Max, double Mean) CodeDifference(ImageBuffer a, ImageBuffer b)
|
||||
{
|
||||
Assert.Equal((a.Width, a.Height, a.Channels), (b.Width, b.Height, b.Channels));
|
||||
double max = 0, sum = 0;
|
||||
for (var c = 0; c < a.Channels; c++)
|
||||
{
|
||||
var pa = a.Plane(c);
|
||||
var pb = b.Plane(c);
|
||||
for (var i = 0; i < pa.Length; i++)
|
||||
{
|
||||
var d = Math.Abs(ColorSpace.LinearToSrgb(pa[i]) - ColorSpace.LinearToSrgb(pb[i]));
|
||||
max = Math.Max(max, d);
|
||||
sum += d;
|
||||
}
|
||||
}
|
||||
return (max, sum / ((double)a.Channels * a.PlaneLength));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The converted file's profile says what its values are: read through it, its codes give the light the original's
|
||||
/// profile gives the original's values (linear Rec.709, to <paramref name="tolerance"/>); no profile where the original
|
||||
/// had none, or where its values are linear gray.
|
||||
/// </summary>
|
||||
private static void AssertTruthful(SourceColor original, SourceColor converted, ImageBuffer originalPixels, ImageBuffer convertedPixels, double tolerance,
|
||||
string what)
|
||||
{
|
||||
Assert.False(converted.IsLinear || converted.IsUnknown, what);
|
||||
if (original.Profile is not { } source || (source.IsGray && original.IsLinear))
|
||||
{
|
||||
Assert.Null(converted.Profile, what);
|
||||
return;
|
||||
}
|
||||
var carried = Assert.NotNull(converted.Profile, what);
|
||||
if (!original.IsLinear && source.IsRgb)
|
||||
{
|
||||
Assert.BytesEqual(source.Data, carried.Data);
|
||||
return;
|
||||
}
|
||||
Assert.True(carried.IsMatrixShaper, what);
|
||||
var to709 = carried.ToLinearRec709();
|
||||
for (var i = 0; i < originalPixels.PlaneLength; i += 11)
|
||||
{
|
||||
var (x, y) = (i % originalPixels.Width, i / originalPixels.Width);
|
||||
Vector3D light;
|
||||
if (source.IsGray)
|
||||
{
|
||||
// A gray profile's code: its curve's light, neutral.
|
||||
var gray = source.Curves![0].Evaluate(ColorSpace.LinearToSrgb(originalPixels[0, x, y]));
|
||||
light = new Vector3D(gray, gray, gray);
|
||||
}
|
||||
else
|
||||
{
|
||||
light = source.ToLinearRec709() * new Vector3D(originalPixels[0, x, y], originalPixels[1, x, y], originalPixels[2, x, y]);
|
||||
}
|
||||
var read = to709 * new Vector3D(
|
||||
carried.Curves![0].Evaluate(ColorSpace.LinearToSrgb(convertedPixels[0, x, y])),
|
||||
carried.Curves[1].Evaluate(ColorSpace.LinearToSrgb(convertedPixels[1, x, y])),
|
||||
carried.Curves[2].Evaluate(ColorSpace.LinearToSrgb(convertedPixels[2, x, y])));
|
||||
Assert.Approximately(light.X, read.X, tolerance, what);
|
||||
Assert.Approximately(light.Y, read.Y, tolerance, what);
|
||||
Assert.Approximately(light.Z, read.Z, tolerance, what);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A float TIFF's values are linear light in its profile's primaries (owner review 2, R7): a JPEG or TIFF holds them as
|
||||
/// the decoders read them back, sRGB codes, and carries the profile's colorants with the sRGB curve, so colour-managed
|
||||
/// programs read the same light; above white is clipped there, as in any file of code values. A DNG keeps above white,
|
||||
/// for values in sRGB's primaries only: in other primaries it refuses them.
|
||||
/// </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])
|
||||
foreach (var wide in (bool[])[true, false])
|
||||
{
|
||||
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 profile = ColorFixtures.Profile($"Gamma {gamma}", IccCurve.Gamma(gamma), wide);
|
||||
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);
|
||||
(scene[0, 3, 1], scene[1, 3, 1], scene[2, 3, 1]) = (0.001f, 0.01f, 0.0005f);
|
||||
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.Describe, FrameConverter.Treatment(SourceColor.Read(path, ImageFileFormat.Tiff), ConvertTarget.Tiff16));
|
||||
|
||||
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));
|
||||
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);
|
||||
var carried = SourceColor.Read(file.Path, file.Format).Profile!;
|
||||
Assert.Equal(profile.Colorants, carried.Colorants);
|
||||
Assert.True(carried.Curves!.All(c => c.IsSrgb), "the codes are sRGB's");
|
||||
using var converted = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
|
||||
var tolerance = target == ConvertTarget.Jpeg ? 0.012 : 1e-4;
|
||||
foreach (var (x, y) in ((int, int)[])[(5, 2), (1, 1), (3, 1)])
|
||||
{
|
||||
for (var c = 0; c < 3; c++)
|
||||
Assert.Approximately(ColorSpace.LinearToSrgb(scene[c, x, y]), ColorSpace.LinearToSrgb(converted.Pixels[c, x, y]), tolerance, $"{target}, gamma {gamma}");
|
||||
}
|
||||
Assert.Approximately(1, converted.Pixels[0, 2, 1], target == ConvertTarget.Jpeg ? 0.02 : 1e-3, "above white is clipped");
|
||||
}
|
||||
|
||||
var dng = new ConvertOptions(ConvertTarget.LinearDng);
|
||||
var output = Target(dng);
|
||||
if (wide)
|
||||
{
|
||||
Assert.Equal(ConversionFailure.ColorProfile,
|
||||
Assert.Throws<ConversionException>(() => FrameConverter.Convert(source, dng, server, output, cancellationToken: context.Cancellation)).Reason);
|
||||
continue;
|
||||
}
|
||||
FrameConverter.Convert(source, dng, server, output, cancellationToken: context.Cancellation);
|
||||
using var developed = server.Decode(new DecodeRequest(output, AllowPreview: false))!;
|
||||
foreach (var (x, y) in ((int, int)[])[(5, 2), (1, 1), (2, 1), (3, 1)])
|
||||
{
|
||||
for (var c = 0; c < 3; c++) Assert.Approximately(scene[c, x, y], developed.Pixels[c, x, y], 2e-3 * Math.Max(1, scene[c, x, y]));
|
||||
}
|
||||
Assert.Greater(developed.Pixels[1, 2, 1], 2.9);
|
||||
}
|
||||
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.
|
||||
/// A DNG takes values only where they are sRGB's as the decoders read them, whatever the profile's name: codes in one
|
||||
/// named sRGB with a linear curve are not (the decoders read them through the sRGB curve), the same profile's linear
|
||||
/// values are (sRGB's primaries), a real sRGB profile's codes are.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AProfileNamedSrgbWithAnotherCurveIsConvertedIntoADng()
|
||||
public void ADngTakesOnlyValuesThatAreSrgbsAsTheDecodersReadThem()
|
||||
{
|
||||
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);
|
||||
}
|
||||
ColorTreatment Dng(byte[] file, ImageFileFormat format) => FrameConverter.Treatment(SourceColor.Read(new MemoryStream(file), format), ConvertTarget.LinearDng);
|
||||
Assert.Equal(ColorTreatment.Refuse, Dng(ColorFixtures.Jpeg(scene, linearCurve.Data), ImageFileFormat.Jpeg));
|
||||
Assert.Equal(ColorTreatment.None, Dng(ColorFixtures.FloatTiff(scene, linearCurve.Data), ImageFileFormat.Tiff));
|
||||
Assert.Equal(ColorTreatment.None, Dng(ColorFixtures.Jpeg(scene, real.Data), ImageFileFormat.Jpeg));
|
||||
Assert.Equal(ColorTreatment.None, Dng(ColorFixtures.Jpeg(scene), ImageFileFormat.Jpeg));
|
||||
Assert.Equal(ColorTreatment.Refuse, Dng(ColorFixtures.Jpeg(scene, IccProfile.AdobeRgb.Data), ImageFileFormat.Jpeg));
|
||||
// Into a JPEG or TIFF the same codes are carried with their profile.
|
||||
Assert.Equal(ColorTreatment.Carry, FrameConverter.Treatment(SourceColor.Read(new MemoryStream(ColorFixtures.Jpeg(scene, linearCurve.Data)), ImageFileFormat.Jpeg), ConvertTarget.Tiff16));
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// A profile whose colorants convert nothing (a damaged one) refuses its photo for a DNG, at once and as a colour
|
||||
/// profile, and is carried unchanged into a JPEG or TIFF with the codes it came with. One named sRGB is no sRGB: a float
|
||||
/// TIFF's linear values in it, which a JPEG or TIFF would need its colorants to describe, are refused there too.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AProfileThatConvertsNothingIsRefusedForADngAndCarriedElsewhere()
|
||||
@@ -563,6 +700,71 @@ public sealed class FrameConverterTests(TestContext context)
|
||||
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);
|
||||
|
||||
var namedSrgb = ColorFixtures.Degenerate(ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Gamma(1)).Data);
|
||||
var floatPath = Path.Combine(context.CreateTempDirectory("source"), "stack.tif");
|
||||
File.WriteAllBytes(floatPath, ColorFixtures.FloatTiff(scene, namedSrgb));
|
||||
foreach (var target in Enum.GetValues<ConvertTarget>())
|
||||
{
|
||||
var options = new ConvertOptions(target);
|
||||
var floatOutput = Target(options);
|
||||
Assert.Equal(ConversionFailure.ColorProfile, Assert.Throws<ConversionException>(() =>
|
||||
FrameConverter.Convert(new ConvertSource(floatPath, Frame("stack.tif", ImageFileFormat.Tiff, 48, 32)), options, DecoderFactory.CreateServer(), floatOutput,
|
||||
cancellationToken: context.Cancellation)).Reason, target.ToString());
|
||||
Assert.FileMissing(floatOutput);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A float file whose samples are not numbers (NaN, ±infinity: damaged data) fails its conversion as damaged in every
|
||||
/// target, nothing written, rather than written black (with a DNG's headroom spent on it).
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void SamplesThatAreNotNumbersFailAsDamagedData()
|
||||
{
|
||||
foreach (var bad in (float[])[float.NaN, float.PositiveInfinity, float.NegativeInfinity])
|
||||
{
|
||||
using var scene = new ImageBuffer(8, 4);
|
||||
scene.Data.Fill(0.18f);
|
||||
scene[1, 6, 3] = bad;
|
||||
var path = Path.Combine(context.CreateTempDirectory("source"), "stack.tif");
|
||||
File.WriteAllBytes(path, ColorFixtures.FloatTiff(scene, IccProfile.AdobeRgb.Data));
|
||||
File.WriteAllBytes(Path.ChangeExtension(path, ".untagged.tif"), ColorFixtures.FloatTiff(scene));
|
||||
foreach (var file in (string[])[path, Path.ChangeExtension(path, ".untagged.tif")])
|
||||
{
|
||||
foreach (var target in Enum.GetValues<ConvertTarget>())
|
||||
{
|
||||
var options = new ConvertOptions(target);
|
||||
if (FrameConverter.Treatment(SourceColor.Read(file, ImageFileFormat.Tiff), target) == ColorTreatment.Refuse) continue;
|
||||
var output = Target(options);
|
||||
var failed = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(file, Frame("stack.tif", ImageFileFormat.Tiff, 8, 4)), options,
|
||||
DecoderFactory.CreateServer(), output, cancellationToken: context.Cancellation));
|
||||
Assert.Equal(ConversionFailure.Damaged, failed.Reason, $"{bad} → {target}");
|
||||
Assert.FileMissing(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every NaN and infinity is found, wherever it is (in a vector or in the tail), and finite values pass, however large.</summary>
|
||||
[Test]
|
||||
public void NumbersAreToldFromWhatIsNot()
|
||||
{
|
||||
foreach (var length in (int[])[0, 1, 7, 8, 9, 31, 64, 1001])
|
||||
{
|
||||
var values = new float[length];
|
||||
for (var i = 0; i < length; i++) values[i] = (i % 3 - 1) * (i % 2 == 0 ? float.MaxValue : float.Epsilon);
|
||||
Assert.True(FrameConverter.AllFinite(values), $"{length} finite values");
|
||||
for (var at = 0; at < length; at += Math.Max(1, length / 5))
|
||||
{
|
||||
foreach (var bad in (float[])[float.NaN, float.PositiveInfinity, float.NegativeInfinity])
|
||||
{
|
||||
var copy = (float[])values.Clone();
|
||||
copy[at] = bad;
|
||||
Assert.False(FrameConverter.AllFinite(copy), $"{bad} at {at} of {length}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo larger than the target or one buffer holds fails as too large, not with the encoder's own exception.</summary>
|
||||
|
||||
Reference in new issue
Block a user