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:
1 parent
e3cbe30b29
commit
5b5acaf307
15 files changed
+1160
-78
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using Chronos.Core.Codecs.Icc;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Mathematics;
|
||||
using Chronos.Core.Tests.Conversion;
|
||||
@@ -8,7 +9,7 @@ using Chronos.Testing;
|
||||
namespace Chronos.Core.Tests.Codecs;
|
||||
|
||||
/// <summary>ICC profiles (owner review 2, R7): parsed, synthesized for the spaces a marker names, and read from each container.</summary>
|
||||
public sealed class IccProfileTests
|
||||
public sealed class IccProfileTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheSynthesizedProfilesAreMatrixShapersOfTheirSpace()
|
||||
@@ -69,6 +70,142 @@ public sealed class IccProfileTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Colorants that convert nothing (their white has a cone response that is not positive, as a damaged profile's may) are
|
||||
/// dropped when the profile is parsed: it stays an RGB profile to carry, never one to convert through, and asking its
|
||||
/// matrix fails as for any profile without one, not inside the chromatic adaptation.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void ColorantsThatConvertNothingAreDroppedWhenParsed()
|
||||
{
|
||||
var degenerate = IccProfile.Parse(ColorFixtures.Degenerate())!;
|
||||
Assert.True(degenerate.IsRgb);
|
||||
Assert.Null(degenerate.Colorants);
|
||||
Assert.False(degenerate.IsMatrixShaper);
|
||||
Assert.False(degenerate.IsSrgb);
|
||||
Assert.Throws<InvalidOperationException>(() => degenerate.ToLinearRec709());
|
||||
// The same colorants inside a white with positive cone responses convert.
|
||||
Assert.NotNull(IccProfile.AdobeRgb.Colorants);
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void DamagedProfilesConvertOrAreRefusedNeverFailMidway()
|
||||
{
|
||||
var random = new Random(27);
|
||||
using var pixels = new ImageBuffer(4, 2);
|
||||
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;
|
||||
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++)
|
||||
{
|
||||
var damaged = (byte[])original.Clone();
|
||||
// The tag table and the tags: colorants, curves, description.
|
||||
for (var k = random.Next(1, 4); k > 0; k--) damaged[random.Next(128, damaged.Length)] ^= (byte)random.Next(1, 256);
|
||||
if (IccProfile.Parse(damaged) is not { } profile) continue;
|
||||
parsed++;
|
||||
if (profile.IsMatrixShaper)
|
||||
{
|
||||
var m = profile.ToLinearRec709();
|
||||
Assert.True(Finite(m) && m.TryInvert(out var inverse) && Finite(inverse), "a matrix to convert through is finite and invertible");
|
||||
}
|
||||
SourceColor[] carriers =
|
||||
[
|
||||
SourceColor.Read(new MemoryStream(JpegCarrying(damaged)), ImageFileFormat.Jpeg),
|
||||
SourceColor.Read(new MemoryStream(ColorFixtures.FloatTiff(pixels, damaged)), ImageFileFormat.Tiff),
|
||||
];
|
||||
foreach (var color in carriers)
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
context.Log($"{parsed} damaged profiles parsed, {worked} conversions run");
|
||||
Assert.Greater(parsed, 1000);
|
||||
Assert.Greater(worked, 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);
|
||||
|
||||
// The markers of a JPEG carrying the profile in one APP2 chunk, no image: all its colour is read from.
|
||||
static byte[] JpegCarrying(byte[] icc)
|
||||
{
|
||||
var length = 2 + 14 + icc.Length;
|
||||
return [0xFF, 0xD8, 0xFF, 0xE2, (byte)(length >> 8), (byte)length, .. "ICC_PROFILE\0"u8, 1, 1, .. icc, 0xFF, 0xD9];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A matrix/TRC profile is sRGB when its numbers are sRGB's, whatever its name says; one without them by its name.</summary>
|
||||
[Test]
|
||||
public void SrgbIsWhatTheNumbersSay()
|
||||
{
|
||||
Assert.True(ColorFixtures.Profile("sRGB IEC61966-2.1", IccCurve.Srgb).IsSrgb);
|
||||
Assert.True(ColorFixtures.Profile("Camera RGB", IccCurve.Srgb).IsSrgb);
|
||||
// sRGB's primaries with a linear curve, or a gamma 2.2 one, named sRGB.
|
||||
Assert.False(ColorFixtures.Profile("sRGB-elle-V4-g10", IccCurve.Gamma(1)).IsSrgb);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Curves invert: exactly for a power law and a table, within a 16-bit step for a parametric function.</summary>
|
||||
[Test]
|
||||
public void CurvesInvert()
|
||||
{
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// <summary>A TIFF of floating-point samples or linear RAW holds linear values; integer samples are code values.</summary>
|
||||
[Test]
|
||||
public void ATiffSaysWhetherItsSamplesAreLinear()
|
||||
{
|
||||
using var scene = ColorFixtures.Scene();
|
||||
SourceColor Read(byte[] file) => SourceColor.Read(new MemoryStream(file), ImageFileFormat.Tiff);
|
||||
var adobe = IccProfile.AdobeRgb.Data;
|
||||
var linear = Read(ColorFixtures.FloatTiff(scene, adobe));
|
||||
Assert.True(linear.IsLinear);
|
||||
Assert.BytesEqual(adobe, linear.Profile!.Data);
|
||||
Assert.True(Read(ColorFixtures.FloatTiff(scene)) is { IsLinear: true, Profile: null, IsUnknown: false });
|
||||
Assert.True(Read(Chronos.Core.Codecs.Dng.LinearDngWriter.Write(scene)).IsLinear);
|
||||
Assert.False(Read(TiffWriter.Write(scene, new TiffWriteOptions { BitsPerSample = 16, IccProfile = adobe })).IsLinear);
|
||||
Assert.False(Read(TiffWriter.Write(scene)).IsLinear);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EachContainerSaysItsColourSpace()
|
||||
{
|
||||
|
||||
@@ -194,6 +194,78 @@ public sealed class TiffTests(TestContext context)
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ToImageBuffer(raster));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Samples that are not gray, RGB or linear RAW are refused before their pixels are read, from the headers alone too,
|
||||
/// never decoded as gray from their first plane (a CMYK red read as black, owner review 2, R7).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[Case(5, 4)] // CMYK
|
||||
[Case(8, 3)] // CIELab
|
||||
[Case(3, 1)] // palette
|
||||
[Case(2, 1)] // RGB of one sample
|
||||
[Case(32844, 1)] // LogL
|
||||
public void SamplesItDoesNotRenderAreRefusedNotReadAsGray(int photometric, int samples)
|
||||
{
|
||||
// A CMYK red: no cyan, full magenta and yellow, no black.
|
||||
var pixel = Enumerable.Range(0, samples).Select(c => (byte)(c is 1 or 2 ? 255 : 0)).ToArray();
|
||||
var tiff = Conversion.ColorFixtures.Tiff(6, 4, (ushort)photometric, pixel);
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.Decode(tiff));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(tiff)));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ToImageBuffer(Raster(tiff)));
|
||||
}
|
||||
|
||||
/// <summary>The headers say what <see cref="TiffImageReader.Decode(Stream, TiffDecodeOptions?)"/> reads, and refuse what it refuses.</summary>
|
||||
[Test]
|
||||
public void ReadInfoSaysWhatDecodeReads()
|
||||
{
|
||||
foreach (var name in (string[])["tiff/lzw-pred.tif", "tiff/lzw-tiled.tif", "tiff/planar-zip.tif", "tiff/jpeg-ycbcr.tif", "tiff/float32-pred3.tif", "tiff/gray-miniswhite.tif"])
|
||||
{
|
||||
using var image = TiffImageReader.Decode(Fixture(name));
|
||||
Assert.Equal((image.Width, image.Height), TiffImageReader.ReadInfo(new MemoryStream(Fixture(name))), name);
|
||||
}
|
||||
var rgb = Conversion.ColorFixtures.Tiff(6, 4, 2, [10, 20, 30]);
|
||||
Assert.Equal((6, 4), TiffImageReader.ReadInfo(new MemoryStream(rgb)));
|
||||
// More samples than the decoder takes, a compression it lacks (ZSTD), float samples whose white is 0, no strips.
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(rgb), new TiffDecodeOptions { MaxSamples = 6 * 4 * 3 - 1 }));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(Conversion.ColorFixtures.Tiff(6, 4, 2, [1, 2, 3], d => d.Short(TiffTags.Compression, 50000)))));
|
||||
var floatWhiteIsZero = TiffTestEncoders.Build(d =>
|
||||
{
|
||||
Layout(d, 2, 2, 1, 32, compression: 1);
|
||||
d.Short(TiffTags.PhotometricInterpretation, 0);
|
||||
d.Short(TiffTags.SampleFormat, 3);
|
||||
}, [new byte[16]], tiled: false);
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(floatWhiteIsZero)));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.Decode(floatWhiteIsZero));
|
||||
using var noStrips = new MemoryStream();
|
||||
noStrips.Write("II*\0\0\0\0\0"u8);
|
||||
var directory = new TiffDirectory();
|
||||
Layout(directory, 6, 4, 3, 8, compression: 1);
|
||||
TiffWriter.WriteDirectory(noStrips, 0, directory);
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(noStrips.ToArray())));
|
||||
// Tiles that no count holds are a malformed file, not an arithmetic error, to a decode as to the headers: a chain
|
||||
// that finds them refused asks its next decoder.
|
||||
var tiles = Conversion.ColorFixtures.Tiff(6, 4, 2, [1, 2, 3], d =>
|
||||
{
|
||||
d.Long(TiffTags.ImageWidth, int.MaxValue);
|
||||
d.Long(TiffTags.ImageLength, int.MaxValue);
|
||||
d.Long(TiffTags.TileWidth, 1);
|
||||
d.Long(TiffTags.TileLength, 1);
|
||||
d.Long(TiffTags.TileOffsets, 8);
|
||||
});
|
||||
var unbounded = new TiffDecodeOptions { MaxSamples = long.MaxValue };
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(tiles), unbounded));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.Decode(tiles, unbounded));
|
||||
// More strips than the reader takes (one row each), refused before any is read.
|
||||
var strips = Conversion.ColorFixtures.Tiff(6, 4, 1, [1], d =>
|
||||
{
|
||||
d.Long(TiffTags.ImageWidth, 1);
|
||||
d.Long(TiffTags.ImageLength, (1 << 24) + 1);
|
||||
d.Long(TiffTags.RowsPerStrip, 1);
|
||||
});
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(strips)));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.Decode(strips));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(8, 1, TiffCompression.None, false)]
|
||||
[Case(8, 3, TiffCompression.Deflate, true)]
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO.Compression;
|
||||
using Chronos.Core.Codecs.Icc;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Tests.Codecs;
|
||||
using Chronos.Core.Tests.Metadata.Builders;
|
||||
|
||||
namespace Chronos.Core.Tests.Conversion;
|
||||
@@ -94,6 +97,101 @@ internal static class ColorFixtures
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>A matrix/TRC profile of <paramref name="description"/>, with sRGB's primaries or Adobe RGB's (D65) and <paramref name="curve"/>.</summary>
|
||||
public static IccProfile Profile(string description, IccCurve curve, bool wide = false) => wide
|
||||
? 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()
|
||||
{
|
||||
var data = (byte[])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++)
|
||||
{
|
||||
var entry = data.AsSpan(132 + 12 * i, 12);
|
||||
foreach (var (tag, x, y, z) in colorants)
|
||||
{
|
||||
if (!entry[..4].SequenceEqual(System.Text.Encoding.ASCII.GetBytes(tag))) continue;
|
||||
var at = BinaryPrimitives.ReadInt32BigEndian(entry[4..]) + 8;
|
||||
BinaryPrimitives.WriteInt32BigEndian(data.AsSpan(at), (int)Math.Round(x * 65536));
|
||||
BinaryPrimitives.WriteInt32BigEndian(data.AsSpan(at + 4), (int)Math.Round(y * 65536));
|
||||
BinaryPrimitives.WriteInt32BigEndian(data.AsSpan(at + 8), (int)Math.Round(z * 65536));
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An uncompressed TIFF of <paramref name="width"/> × <paramref name="height"/> 8-bit samples, <paramref name="samples"/>
|
||||
/// per pixel in <paramref name="photometric"/> interpretation, each pixel <paramref name="pixel"/>.
|
||||
/// </summary>
|
||||
public static byte[] Tiff(int width, int height, ushort photometric, byte[] pixel, Action<TiffDirectory>? tags = null)
|
||||
{
|
||||
var strip = new byte[width * height * pixel.Length];
|
||||
for (var i = 0; i < width * height; i++) pixel.CopyTo(strip, i * pixel.Length);
|
||||
return TiffTestEncoders.Build(d =>
|
||||
{
|
||||
TiffTests.Layout(d, width, height, pixel.Length, 8, compression: 1);
|
||||
d.Short(TiffTags.PhotometricInterpretation, photometric);
|
||||
tags?.Invoke(d);
|
||||
}, [strip], tiled: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The headers of a TIFF of <paramref name="width"/> × <paramref name="height"/> pixels of three 8-bit samples in
|
||||
/// <paramref name="photometric"/> interpretation, in strips of 16 rows, of which only the first is there: what a
|
||||
/// header read takes, without its pixels.
|
||||
/// </summary>
|
||||
public static byte[] TiffHeader(int width, int height, ushort photometric = 2) => Tiff(6, 4, photometric, [1, 2, 3], d =>
|
||||
{
|
||||
d.Long(TiffTags.ImageWidth, (uint)width);
|
||||
d.Long(TiffTags.ImageLength, (uint)height);
|
||||
d.Long(TiffTags.RowsPerStrip, 16);
|
||||
});
|
||||
|
||||
/// <summary>A PNG signature and header chunk of <paramref name="width"/> × <paramref name="height"/> 8-bit RGB, nothing after it.</summary>
|
||||
public static byte[] PngHeader(int width, int height)
|
||||
{
|
||||
var ihdr = new byte[13];
|
||||
BinaryPrimitives.WriteInt32BigEndian(ihdr, width);
|
||||
BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), height);
|
||||
(ihdr[8], ihdr[9]) = (8, 2);
|
||||
return [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, .. Box.Png("IHDR", ihdr)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The markers of a JPEG of <paramref name="width"/> × <paramref name="height"/> three-component pixels coded by
|
||||
/// <paramref name="sof"/> (0xC0 baseline, 0xC9 arithmetic…), up to its first scan.
|
||||
/// </summary>
|
||||
public static byte[] JpegHeader(int width, int height, byte sof = 0xC0) =>
|
||||
[
|
||||
0xFF, 0xD8,
|
||||
0xFF, sof, 0x00, 0x11, 0x08, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x00, 0x03, 0x11, 0x00,
|
||||
0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x3F, 0x00,
|
||||
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>
|
||||
public static byte[] FloatTiff(ImageBuffer image, byte[]? icc = null)
|
||||
{
|
||||
var strip = new byte[image.PlaneLength * 3 * 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]);
|
||||
}
|
||||
return TiffTestEncoders.Build(d =>
|
||||
{
|
||||
TiffTests.Layout(d, image.Width, image.Height, 3, 32, compression: 1);
|
||||
d.Short(TiffTags.SampleFormat, 3, 3, 3);
|
||||
if (icc is not null) d.Add(TiffTags.InterColorProfile, TiffType.Undefined, icc.Length, icc);
|
||||
}, [strip], tiled: false);
|
||||
}
|
||||
|
||||
/// <summary>A valid profile larger than one JPEG APP2 chunk holds (the Adobe RGB one padded with a private tag's room).</summary>
|
||||
public static byte[] Large()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Icc;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Codecs.Raw;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Tests.Raw;
|
||||
using Chronos.Testing;
|
||||
@@ -78,7 +81,8 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
|
||||
/// <summary>
|
||||
/// A frame whose tier is not known yet (imported, not analysed) or was recorded native by another host with other
|
||||
/// decoders is asked again: the dry run promises only what the file says here now.
|
||||
/// decoders is asked again: the dry run promises only what the file says here now. A file the decoders here do not read
|
||||
/// at all, although they read its format, is left to a PC; only a frame flagged unreadable is unreadable.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AFrameIsAskedWhateverTierWasRecorded()
|
||||
@@ -93,7 +97,7 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
Assert.Empty(preview.Frames);
|
||||
Assert.SequenceEqual([(ConvertSkip.PreviewOnly, 2)], preview.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
var unreadable = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.Unavailable)]), "Roof");
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 2)], unreadable.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
Assert.SequenceEqual([(ConvertSkip.NoNativeDecoder, 2)], unreadable.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
var native = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.Native)]), "Roof");
|
||||
Assert.SequenceEqual([0, 1], native.Frames.Select(f => f.Index));
|
||||
}
|
||||
@@ -151,14 +155,15 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
Frame(1, "p3.jpg", ImageFileFormat.Jpeg),
|
||||
Frame(2, "unknown.jpg", ImageFileFormat.Jpeg),
|
||||
Frame(3, "cmyk.jpg", ImageFileFormat.Jpeg),
|
||||
Frame(4, "panorama.png", ImageFileFormat.Png) with { W = 70_000, H = 3_800 },
|
||||
Frame(4, "panorama.png", ImageFileFormat.Png) with { W = 70_000, H = 2_500 },
|
||||
Frame(5, "huge.png", ImageFileFormat.Png) with { W = 70_000, H = 12_000 },
|
||||
];
|
||||
File.WriteAllBytes(folder.File(frames[0].File), ColorFixtures.Jpeg(scene));
|
||||
File.WriteAllBytes(folder.File(frames[1].File), ColorFixtures.Jpeg(scene, IccProfile.DisplayP3.Data));
|
||||
File.WriteAllBytes(folder.File(frames[2].File), ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)));
|
||||
File.WriteAllBytes(folder.File(frames[3].File), ColorFixtures.Jpeg(scene, ColorFixtures.Cmyk()));
|
||||
File.WriteAllBytes(folder.File(frames[4].File), [0]);
|
||||
// A panorama's header (the dry run reads no further), and a file the sidecar's size already rules out.
|
||||
File.WriteAllBytes(folder.File(frames[4].File), ColorFixtures.PngHeader(70_000, 2_500));
|
||||
File.WriteAllBytes(folder.File(frames[5].File), [0]);
|
||||
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
|
||||
var present = frames.Select(f => f.File).ToList();
|
||||
@@ -179,6 +184,118 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Tiff16), 0, 0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The size bound is what the server's decoders read back, which every converted file must (owner review 2, R7), never
|
||||
/// an estimate: a JPEG of 2^28 pixels, a TIFF-16 or DNG (whose raster the same TIFF reader reads) of 2^29 samples, whose
|
||||
/// headers are read while one row more is refused. A file that size stays within the array it is made in (2 GB) even
|
||||
/// when its pixels do not compress at all (16-bit noise takes 48 bits a pixel, up to 51 as lossless JPEG codes them),
|
||||
/// and noise encodes within that bound in every target.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void TheSizeBoundIsWhatTheServersDecodersReadBack()
|
||||
{
|
||||
var jpeg = new ConvertOptions(ConvertTarget.Jpeg, 100);
|
||||
Assert.False(ConvertPlanner.TooLarge(jpeg, 16_384, 16_384));
|
||||
Assert.True(ConvertPlanner.TooLarge(jpeg, 16_384, 16_385));
|
||||
Assert.False(ConvertPlanner.TooLarge(jpeg, 4_096, 65_535));
|
||||
Assert.True(ConvertPlanner.TooLarge(jpeg, 4_097, 65_535));
|
||||
var largest = JpegDecoder.ReadInfo(ColorFixtures.JpegHeader(16_384, 16_384));
|
||||
Assert.Equal((16_384, 16_384), (largest.Width, largest.Height));
|
||||
Assert.Throws<InvalidDataException>(() => JpegDecoder.ReadInfo(ColorFixtures.JpegHeader(16_384, 16_385)));
|
||||
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
|
||||
{
|
||||
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(target), 13_377, 13_377), $"{target} of 2^29 samples at most");
|
||||
Assert.True(ConvertPlanner.TooLarge(new ConvertOptions(target), 13_377, 13_378), $"{target} of one row more");
|
||||
}
|
||||
foreach (ushort photometric in (ushort[])[2, 34892])
|
||||
{
|
||||
Assert.Equal((13_377, 13_377), TiffImageReader.ReadInfo(new MemoryStream(ColorFixtures.TiffHeader(13_377, 13_377, photometric))));
|
||||
Assert.Throws<InvalidDataException>(() => TiffImageReader.ReadInfo(new MemoryStream(ColorFixtures.TiffHeader(13_377, 13_378, photometric))));
|
||||
}
|
||||
Assert.LessOrEqual(ConvertPlanner.WorstBytes(16_384, 16_384), Array.MaxLength);
|
||||
Assert.LessOrEqual(ConvertPlanner.WorstBytes(13_377, 13_377), Array.MaxLength);
|
||||
// 342 MP: its estimate (30 or 26 bits a pixel) would fit, the worst case would not, and nothing reads it back.
|
||||
foreach (var target in Enum.GetValues<ConvertTarget>())
|
||||
{
|
||||
Assert.True(ConvertPlanner.TooLarge(new ConvertOptions(target, 100), 18_500, 18_500), $"{target} at 342 MP");
|
||||
Assert.Less(ConvertPlanner.EstimateBytes(new ConvertOptions(target, 100), 18_500, 18_500), Array.MaxLength);
|
||||
}
|
||||
Assert.Greater(ConvertPlanner.WorstBytes(18_500, 18_500), Array.MaxLength);
|
||||
using var noise = new ImageBuffer(512, 512);
|
||||
var random = new Random(7);
|
||||
foreach (ref var v in noise.Data) v = random.NextSingle();
|
||||
var metadata = new Chronos.Core.Metadata.FrameMetadata { CapturedAt = new DateTime(2026, 10, 27, 12, 0, 0) };
|
||||
foreach (var target in Enum.GetValues<ConvertTarget>())
|
||||
{
|
||||
var bytes = FrameConverter.Encode(noise, metadata, new ConvertOptions(target, 100));
|
||||
var bits = bytes.Length * 8.0 / noise.PlaneLength;
|
||||
context.Log($"{target}: {bits:0.00} bits a pixel of noise");
|
||||
Assert.LessOrEqual(bits, ConvertPlanner.WorstBitsPerPixel, $"{target} encodes noise within the bound, its headers included");
|
||||
Assert.LessOrEqual(bytes.Length, ConvertPlanner.WorstBytes(512, 512));
|
||||
}
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// left to a PC, never planned to fail at every retry; where another decoder reads them (WIC on a PC), they convert. A
|
||||
/// photo larger than a converted file may be stays as it is everywhere.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void WhatTheServersDecodersRefuseIsLeftToAPc()
|
||||
{
|
||||
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
|
||||
(string File, ImageFileFormat Format, byte[] Bytes, int W, int H)[] files =
|
||||
[
|
||||
("rgb.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 2, [200, 30, 10]), 6, 4),
|
||||
("cmyk.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 5, [0, 255, 255, 0]), 6, 4),
|
||||
("lab.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 8, [50, 60, 70]), 6, 4),
|
||||
("palette.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 3, [1]), 6, 4),
|
||||
("zstd.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 2, [1, 2, 3], d => d.Short(TiffTags.Compression, 50000)), 6, 4),
|
||||
// RGBA of 576 M samples: beyond the managed reader, while its DNG (432 M) is not.
|
||||
("stitched.tif", ImageFileFormat.Tiff, ColorFixtures.Tiff(6, 4, 2, [1, 2, 3, 4], d =>
|
||||
{
|
||||
d.Long(TiffTags.ImageWidth, 12_000);
|
||||
d.Long(TiffTags.ImageLength, 12_000);
|
||||
}), 12_000, 12_000),
|
||||
("arithmetic.jpg", ImageFileFormat.Jpeg, ColorFixtures.JpegHeader(6, 4, sof: 0xC9), 6, 4),
|
||||
("stitched.png", ImageFileFormat.Png, ColorFixtures.PngHeader(17_000, 17_000), 17_000, 17_000),
|
||||
];
|
||||
var frames = files.Select((f, i) => Frame(i, f.File, f.Format) with { W = f.W, H = f.H }).ToArray();
|
||||
for (var i = 0; i < files.Length; i++) File.WriteAllBytes(folder.File(frames[i].File), files[i].Bytes);
|
||||
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
|
||||
var present = frames.Select(f => f.File).ToList();
|
||||
var dng = new ConvertOptions(ConvertTarget.LinearDng);
|
||||
|
||||
var server = ConvertPlanner.Plan(manifest, folder, present, dng, DecoderFactory.CreateServer(), "Roof");
|
||||
Assert.SequenceEqual([0], server.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.NoNativeDecoder, 6), (ConvertSkip.TooLarge, 1)], server.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
// A PC whose WIC reads them: the managed decoders first, WIC for what they refuse.
|
||||
var desktop = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ReadsEverything(), new ManagedDecoderProvider()]), "Roof");
|
||||
Assert.SequenceEqual(Enumerable.Range(0, 7), desktop.Frames.Select(f => f.Index));
|
||||
Assert.SequenceEqual([(ConvertSkip.TooLarge, 1)], desktop.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
// The managed provider of a conversion reads headers; the import's does not open the files.
|
||||
Assert.True(FrameConverter.Decoders(DecoderFactory.CreateServer(), dng, ImageFileFormat.Tiff).Providers.OfType<ManagedDecoderProvider>().Single().ReadsHeaders);
|
||||
Assert.Equal(DecodeTier.Native, DecoderFactory.CreateServer().Probe(folder.File(frames[1].File), ImageFileFormat.Tiff).Tier);
|
||||
}
|
||||
|
||||
/// <summary>A photo whose profile's colorants convert nothing is planned out of a DNG, which converts through them, and carried into a TIFF.</summary>
|
||||
[Test]
|
||||
public void AProfileThatConvertsNothingKeepsItsPhotoOutOfADng()
|
||||
{
|
||||
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
|
||||
using var scene = ColorFixtures.Scene();
|
||||
var frame = Frame(0, "odd.jpg", ImageFileFormat.Jpeg);
|
||||
File.WriteAllBytes(folder.File(frame.File), ColorFixtures.Jpeg(scene, ColorFixtures.Degenerate()));
|
||||
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = [frame] };
|
||||
var dng = ConvertPlanner.Plan(manifest, folder, [frame.File], new ConvertOptions(ConvertTarget.LinearDng), DecoderFactory.CreateServer(), "Roof");
|
||||
Assert.SequenceEqual([(ConvertSkip.ColorProfile, 1)], dng.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
var tiff = ConvertPlanner.Plan(manifest, folder, [frame.File], new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), "Roof");
|
||||
Assert.Count(1, tiff.Frames);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SizesAreEstimatedFromThePixels()
|
||||
{
|
||||
@@ -255,6 +372,16 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
|
||||
}
|
||||
|
||||
/// <summary>WIC as a PC with every codec has it: JPEG, PNG and TIFF native, whatever they hold.</summary>
|
||||
private sealed class ReadsEverything : IImageDecoderProvider
|
||||
{
|
||||
public string Name => "wic";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format is ImageFileFormat.Jpeg or ImageFileFormat.Png or ImageFileFormat.Tiff ? DecodeTier.Native : null;
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
|
||||
}
|
||||
|
||||
/// <summary>WIC with the Raw Image Extension, as a conversion sees it: every camera RAW native, developed at 8 bits.</summary>
|
||||
internal sealed class EightBitRaw : IImageDecoderProvider
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -232,6 +232,44 @@ public sealed class ManagedDecoderProviderTests(TestContext context)
|
||||
Assert.Equal(DecodeTier.Unavailable, client.Probe(Write("y.webp", Fixtures.WebP()), ImageFileFormat.WebP).Tier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A provider that reads headers (a conversion's) finds a JPEG, PNG or TIFF native, at its oriented size, only when its
|
||||
/// decoder takes what the headers describe; the others probe as before. Damage past the headers shows only when decoding.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void HeaderProbesSayWhatTheDecodersTake()
|
||||
{
|
||||
var headers = new ManagedDecoderProvider { ReadsHeaders = true };
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var jpeg = headers.Probe(Write("portrait.jpg", JpegFile(W, H, 6)), ImageFileFormat.Jpeg);
|
||||
Assert.Equal((DecodeTier.Native, "managed-jpeg", H, W), (jpeg.Tier, jpeg.Decoder, jpeg.Width, jpeg.Height));
|
||||
var png = headers.Probe(Write("a.png", PngEncoder.Encode(scene)), ImageFileFormat.Png);
|
||||
Assert.Equal((DecodeTier.Native, "managed-png", W, H), (png.Tier, png.Decoder, png.Width, png.Height));
|
||||
var tiff = headers.Probe(Write("a.tif", TiffWriter.Write(scene)), ImageFileFormat.Tiff);
|
||||
Assert.Equal((DecodeTier.Native, "managed-tiff", W, H), (tiff.Tier, tiff.Decoder, tiff.Width, tiff.Height));
|
||||
Assert.Equal(DecodeTier.Native, headers.Probe(Write("IMG_5.CR2", Cr2File("Canon EOS 5D Mark III")), ImageFileFormat.Cr2).Tier);
|
||||
// Headers alone: what follows them is not read.
|
||||
var header = headers.Probe(Write("header.jpg", Conversion.ColorFixtures.JpegHeader(4_000, 3_000)), ImageFileFormat.Jpeg);
|
||||
Assert.Equal((DecodeTier.Native, 4_000, 3_000), (header.Tier, header.Width, header.Height));
|
||||
|
||||
// A CMYK TIFF, a JPEG cut before its first scan, a file that is not what its format says, an arithmetic-coded JPEG,
|
||||
// and a JPEG, PNG or TIFF larger than its decoder takes: refused, like a decode.
|
||||
var cmyk = Write("cmyk.tif", Conversion.ColorFixtures.Tiff(6, 4, 5, [0, 255, 255, 0]));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(cmyk, ImageFileFormat.Tiff));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("cut.jpg", JpegFile(W, H, 1)[..200]), ImageFileFormat.Jpeg));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("short.png", [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), ImageFileFormat.Png));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("arithmetic.jpg", Conversion.ColorFixtures.JpegHeader(6, 4, sof: 0xC9)), ImageFileFormat.Jpeg));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("huge.jpg", Conversion.ColorFixtures.JpegHeader(16_384, 16_385)), ImageFileFormat.Jpeg));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("huge.png", Conversion.ColorFixtures.PngHeader(16_384, 16_385)), ImageFileFormat.Png));
|
||||
Assert.Throws<InvalidDataException>(() => headers.Probe(Write("huge.tif", Conversion.ColorFixtures.TiffHeader(13_377, 13_378)), ImageFileFormat.Tiff));
|
||||
// Through a chain: unavailable with the decoder's reason; a provider without header reads still finds it native.
|
||||
var chain = new ImageDecoder([headers]).Probe(cmyk, ImageFileFormat.Tiff);
|
||||
Assert.Equal(DecodeTier.Unavailable, chain.Tier);
|
||||
Assert.Contains("photometric 5", chain.Reason);
|
||||
Assert.Equal(DecodeTier.Native, new ManagedDecoderProvider().Probe(cmyk, ImageFileFormat.Tiff).Tier);
|
||||
Assert.Throws<InvalidDataException>(() => new ManagedDecoderProvider().Decode(new DecodeRequest(cmyk)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GoProRawDecodesThroughTheJpegBesideIt()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user