Files
Chronos/tests/Chronos.Core.Windows.Tests/Wic/DesktopConversionTests.cs
T
Alby96andClaude Opus 5.5 efa87f68ce
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
feat: owner review 2 phase 4b: mass conversion after import (#13)
Convert photos already in the archive to JPEG, TIFF-16 or Linear DNG, from the panel's Library and the desktop's Archive and Library. Each run asks Replace (same frames, originals to the trash, recoverable) or New sequence. A dry run lists what converts, what is skipped and why, size before and after, and free space; the job converts exactly the confirmed photos, resumes, and commits all or nothing per sequence. A conversion never changes what Chronos reads from a photo. Replaced originals are erased only on the archive's own word that their conversion is gone. Desktop TIFFs that WIC showed black or as noise now go to the managed reader; the Edit picker no longer spins a core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-03 10:41:50 +01:00

170 lines
8.9 KiB
C#

using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Windows.Wic;
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests.Wic;
/// <summary>
/// Conversions on the desktop (owner review 2, R7), read back through the desktop's own decoders, WIC first: what Chronos
/// shows of a photo there never changes with its conversion, whatever the photo's colour space and samples.
/// </summary>
[WindowsOnly]
public sealed class DesktopConversionTests(TestContext context)
{
private static readonly Lazy<ImageDecoder> Desktop = new(() => DecoderFactory.CreateClient(new WicDecoderProvider()));
/// <summary>
/// The desktop decodes the converted file (WIC for a JPEG or TIFF, the managed reader for a DNG) to the values it decodes
/// the original to, within what the target holds, for sRGB, Adobe RGB, ProPhoto and linear-curve sources of 8-bit,
/// 16-bit and float samples; the file carries a profile that says what its codes are. A DNG takes only values that are
/// sRGB's as the decoders read them, and refuses the others.
/// </summary>
[Test]
public void TheDesktopReadsTheConvertedFileAsItReadsTheOriginal()
{
var folder = context.CreateTempDirectory();
using var scene = WicDecoderProviderTests.Scene(48, 32);
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 = IccProfile.Synthesize("sRGB IEC61966-2.1", new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), IccCurve.Srgb);
var g10 = IccProfile.Synthesize("sRGB-elle-V4-g10", new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), IccCurve.Gamma(1));
var prophoto = IccProfile.Synthesize("ProPhoto RGB", new(0.7347, 0.2653), new(0.1596, 0.8404), new(0.0366, 0.0001), IccCurve.Gamma(1.8));
(string Name, byte[] File, bool DngKeeps)[] sources =
[
("untagged.jpg", Jpeg(scene, null), true),
("srgb.jpg", Jpeg(scene, srgb), true),
("gray22.jpg", JpegCarrying(grays, Gray(IccCurve.Gamma(2.2))), false),
("sgray.jpg", JpegCarrying(grays, Gray(IccCurve.Srgb)), true),
("adobe.jpg", Jpeg(scene, IccProfile.AdobeRgb), false),
("g10.jpg", Jpeg(scene, g10), false),
("prophoto16.tif", TiffWriter.Write(scene, new TiffWriteOptions { BitsPerSample = 16, IccProfile = prophoto.Data }), false),
("adobe16.tif", TiffWriter.Write(scene, new TiffWriteOptions { BitsPerSample = 16, IccProfile = IccProfile.AdobeRgb.Data }), false),
("float.tif", TestTiffs.FloatRgb(scene), true),
("float-adobe.tif", TestTiffs.FloatRgb(scene, IccProfile.AdobeRgb.Data), false),
("float-prophoto.tif", TestTiffs.FloatRgb(scene, prophoto.Data), false),
("float-g10.tif", TestTiffs.FloatRgb(scene, g10.Data), true),
("float-adobe-predicted.tif", TestTiffs.FloatRgb(scene, IccProfile.AdobeRgb.Data, predicted: true), false),
];
var desktop = Desktop.Value;
foreach (var (name, bytes, 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, scene.Width, scene.Height));
using var original = Assert.NotNull(desktop.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, desktop, Target(options), cancellationToken: context.Cancellation);
using var converted = Assert.NotNull(desktop.Decode(new DecodeRequest(file.Path, AllowPreview: false)));
Assert.Equal("wic", converted.Decoder, name);
var (max, mean) = CodeDifference(original.Pixels, converted.Pixels);
var what = $"{name} ({original.Decoder}) → {target}";
context.Log($"{what}: max {max * 255:0.00}/255, mean {mean * 255:0.000}/255");
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);
// What the file says its codes are: the original's profile with the original's codes, else its colorants with the sRGB curve.
var carried = SourceColor.Read(file.Path, file.Format).Profile;
if (color.Profile is not { } profile)
{
Assert.Null(carried, what);
}
else if (profile.IsGray)
{
// A gray profile's codes, kept, with its curve on three channels.
Assert.True(Assert.NotNull(carried, what).IsMatrixShaper, what);
for (var code = 0.0; code <= 1; code += 0.125) Assert.Approximately(profile.Curves![0].Evaluate(code), carried.Curves![1].Evaluate(code), 1e-3, what);
}
else if (!color.IsLinear)
{
Assert.BytesEqual(profile.Data, Assert.NotNull(carried, what).Data);
}
else
{
Assert.Equal(profile.Colorants, Assert.NotNull(carried, what).Colorants);
Assert.True(carried.Curves!.All(c => c.IsSrgb), what);
}
}
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var output = Target(dng);
if (!dngKeeps)
{
Assert.Equal(ConversionFailure.ColorProfile,
Assert.Throws<ConversionException>(() => FrameConverter.Convert(source, dng, desktop, output, cancellationToken: context.Cancellation)).Reason, name);
Assert.FileMissing(output);
continue;
}
FrameConverter.Convert(source, dng, desktop, output, cancellationToken: context.Cancellation);
using var developed = Assert.NotNull(desktop.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");
}
}
}
private static byte[] Jpeg(ImageBuffer scene, IccProfile? profile) => JpegCarrying(scene, profile?.Data);
private static byte[] JpegCarrying(ImageBuffer scene, byte[]? icc) => JpegEncoder.Encode(scene, new JpegEncodeOptions
{
Quality = 98,
Subsampling = JpegSubsampling.Yuv444,
IccProfile = icc,
});
/// <summary>A gray profile (GRAY, a kTRC of <paramref name="curve"/>): a synthesized RGB one, its red curve renamed.</summary>
private static byte[] Gray(IccCurve curve)
{
var data = (byte[])IccProfile.Synthesize("Gray", new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), curve).Data.Clone();
"GRAY"u8.CopyTo(data.AsSpan(16));
var count = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(128));
for (var i = 0; i < count; i++)
{
var entry = data.AsSpan(132 + 12 * i, 4);
if (entry.SequenceEqual("rTRC"u8)) "kTRC"u8.CopyTo(entry);
}
return data;
}
private static SidecarFrame Frame(string file, ImageFileFormat format, int width, int height) => new()
{
Id = Guid.NewGuid(),
File = "originals/" + file,
Sha256 = new string('a', 64),
CapturedAt = new DateTime(2026, 9, 28, 18, 0, 5),
W = width,
H = height,
Format = format,
};
private string Target(ConvertOptions options) => Path.Combine(context.CreateTempDirectory(), "converted" + options.Extension);
/// <summary>The largest and the mean difference between two decodes, 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), (b.Width, b.Height));
double max = 0, sum = 0;
for (var c = 0; c < 3; 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 / (3.0 * a.PlaneLength));
}
}