fix(convert): keep what the original holds and plan only what converts

Phase 4b review, codec findings. A Replace makes the converted file the
photo, so a conversion must not lose what the original held, and the dry
run must promise only what the job will do.

- Linear DNG from a conversion is scene-referred: the pixels are stored in
  linear ProPhoto primaries (colours outside sRGB stay positive) and
  divided by the power of two that brings their peak under the white
  level (at most 4 stops), with BaselineExposure giving it back and
  ColorMatrix1/ForwardMatrix1 describing that space. Highlights a RAW
  develops above 1 and its wide-gamut colours now read back as written.
  Exports keep the clipped linear-sRGB DNG.
- A conversion reads with the managed decoders first for every format they
  read natively (RAWs developed at float precision, as on the server) and
  with WIC only for what they cannot. A RAW only WIC's Raw Image Extension
  develops (8 bits) is refused for TIFF-16 and linear DNG and planned out
  as "eight_bit"; JPEG still converts it. Providers say so through
  IImageDecoderProvider.DevelopsRawAt8Bits.
- The original's colour space is kept: a JPEG (APP2) or TIFF (tag 34675)
  carries its ICC profile, with the values unchanged; a linear DNG gets the
  values converted through a matrix/TRC profile; a gray profile converts
  to sRGB. Exif Adobe RGB (uncalibrated + R03) and HEIF nclx P3 get an
  in-house profile. A space nothing here can keep (CMYK, a lookup-table
  profile into a DNG, uncalibrated without R03, HDR nclx) is planned out
  as "color_profile". New in-house ICC parser/writer and header reader
  for JPEG, PNG, TIFF, HEIF/AVIF and WebP.
- The planner asks every file, whatever tier was recorded (unknown before
  the light analysis, or by another host), with the conversion's decoders,
  headers only and eight at a time; a RAW the server cannot develop is
  "convert_on_pc" in the plan instead of failing its sequence. Photos a
  target cannot hold (a JPEG side above 65535, more samples than one
  buffer) are planned out as "too_large", and an overflow fails its photo
  rather than the job.
- A photo that fails reads in the job log as one catalog sentence by cause
  (Archive.Convert.Failed.*), the file named once; the exception's English
  text goes to the diagnostics log only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 0ca1e91ea09946d7a55f45695ee58e1a0ff5f779)
This commit is contained in:
Alby96 committed 2026-10-27 22:04:34 +01:00
1 parent 341fb77507
commit f86a151a5d
26 files changed
+1755 -82

No files matched your search

@@ -0,0 +1,103 @@
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Mathematics;
using Chronos.Core.Tests.Conversion;
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
{
[Test]
public void TheSynthesizedProfilesAreMatrixShapersOfTheirSpace()
{
var adobe = IccProfile.AdobeRgb;
Assert.True(adobe.IsMatrixShaper && adobe.IsRgb && !adobe.IsSrgb);
Assert.Equal("Compatible with Adobe RGB (1998)", adobe.Description);
// Colorants add up to the D50 PCS white.
var white = adobe.Colorants!.Value * new Vector3D(1, 1, 1);
Assert.Approximately(0.9642, white.X, 2e-4);
Assert.Approximately(1.0, white.Y, 2e-4);
Assert.Approximately(0.8249, white.Z, 2e-4);
// Adobe RGB → linear sRGB: red reaches 1.398 with green −0.398, blue stays put but borrows from green.
var m = adobe.ToLinearRec709();
Assert.Approximately(1.3982, m.M11, 2e-3);
Assert.Approximately(-0.3982, m.M12, 2e-3);
Assert.Approximately(1.0, m.M22, 2e-3);
Assert.Approximately(-0.0429, m.M32, 2e-3);
Assert.Approximately(1.0429, m.M33, 2e-3);
var neutral = m * new Vector3D(1, 1, 1);
Assert.Approximately(1, neutral.X, 1e-9);
Assert.Approximately(1, neutral.Y, 1e-9);
Assert.Approximately(1, neutral.Z, 1e-9);
// Its gamma 563/256, written as a u8Fixed8 curve.
Assert.Approximately(Math.Pow(0.5, 563 / 256.0), adobe.Curves![0].Evaluate(0.5), 1e-12);
var p3 = IccProfile.DisplayP3;
Assert.True(p3.IsMatrixShaper);
// The sRGB curve, tabulated in 1024 entries.
for (var v = 0.0; v <= 1; v += 0.05) Assert.Approximately(ColorSpace.SrgbToLinear(v), p3.Curves![1].Evaluate(v), 2e-5);
// P3's own green is outside sRGB: negative red and blue in Rec.709.
var green = p3.ToLinearRec709() * new Vector3D(0, 1, 0);
Assert.Approximately(-0.2246, green.X, 3e-3);
Assert.Approximately(1.0421, green.Y, 3e-3);
Assert.Approximately(-0.0786, green.Z, 3e-3);
Assert.Null(IccProfile.Parse(new byte[200]));
Assert.Null(IccProfile.Parse(adobe.Data[..131]));
}
[Test]
public void ParametricCurvesFollowTheirFunctions()
{
// para function 3 with the sRGB parameters (as Apple's Display P3 profile writes it).
byte[] tag = [.. "para"u8, 0, 0, 0, 0, 0, 3, 0, 0, .. Fixed(2.4), .. Fixed(1 / 1.055), .. Fixed(0.055 / 1.055), .. Fixed(1 / 12.92), .. Fixed(0.04045)];
var curve = IccCurve.Parse(tag)!;
foreach (var v in new[] { 0.0, 0.02, 0.04045, 0.3, 0.75, 1.0 }) Assert.Approximately(ColorSpace.SrgbToLinear(v), curve.Evaluate(v), 2e-5);
Assert.Approximately(Math.Pow(0.5, 1.8), IccCurve.Parse([.. "para"u8, 0, 0, 0, 0, 0, 0, 0, 0, .. Fixed(1.8)])!.Evaluate(0.5), 1e-4);
Assert.Approximately(0.25, IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 0])!.Evaluate(0.25), 1e-12);
Assert.Approximately(0.5, IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0x80, 0, 0xFF, 0xFF])!.Evaluate(0.5), 1e-4);
Assert.Null(IccCurve.Parse([.. "para"u8, 0, 0, 0, 0, 0, 9, 0, 0]));
static byte[] Fixed(double v)
{
var b = new byte[4];
System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(b, (int)Math.Round(v * 65536));
return b;
}
}
[Test]
public void EachContainerSaysItsColourSpace()
{
using var scene = ColorFixtures.Scene();
var p3 = IccProfile.DisplayP3.Data;
SourceColor Read(byte[] file, ImageFileFormat format) => SourceColor.Read(new MemoryStream(file), format);
// Untagged and sRGB files are sRGB.
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Jpeg(scene), ImageFileFormat.Jpeg));
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(1, "R98")), ImageFileFormat.Jpeg));
// An embedded profile, byte for byte: JPEG APP2 (one chunk, or several), PNG iCCP, TIFF tag 34675, HEIF prof.
Assert.BytesEqual(p3, Read(ColorFixtures.Jpeg(scene, p3), ImageFileFormat.Jpeg).Profile!.Data);
var large = ColorFixtures.Large();
Assert.BytesEqual(large, Read(ColorFixtures.Jpeg(scene, large), ImageFileFormat.Jpeg).Profile!.Data);
Assert.BytesEqual(p3, Read(ColorFixtures.Png(scene, p3), ImageFileFormat.Png).Profile!.Data);
Assert.BytesEqual(p3, Read(TiffWriter.Write(scene, new TiffWriteOptions { IccProfile = p3 }), ImageFileFormat.Tiff).Profile!.Data);
Assert.BytesEqual(p3, Read(ColorFixtures.Heif(ColorFixtures.Nclx(1, 13), ColorFixtures.Prof(p3)), ImageFileFormat.Heif).Profile!.Data);
// A grid whose tiles carry the profile, not the grid item.
Assert.BytesEqual(p3, Read(ColorFixtures.Heif(2, ColorFixtures.Prof(p3)), ImageFileFormat.Heif).Profile!.Data);
// A camera's Adobe RGB marker (uncalibrated, Interop R03) names Adobe RGB, in a JPEG and in a TIFF.
Assert.Same(IccProfile.AdobeRgb, Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF, "R03")), ImageFileFormat.Jpeg).Profile);
// nclx: BT.709 is sRGB, P3 primaries Display P3, BT.2020 or PQ unknown.
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Heif(ColorFixtures.Nclx(1, 13)), ImageFileFormat.Heif));
Assert.Same(IccProfile.DisplayP3, Read(ColorFixtures.Heif(ColorFixtures.Nclx(12, 13)), ImageFileFormat.Heif).Profile);
Assert.True(Read(ColorFixtures.Heif(ColorFixtures.Nclx(9, 16)), ImageFileFormat.Heif).IsUnknown);
// Uncalibrated without R03, or a profile that does not parse: a space nothing here describes.
Assert.True(Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)), ImageFileFormat.Jpeg).IsUnknown);
Assert.True(Read(ColorFixtures.Jpeg(scene, new byte[300]), ImageFileFormat.Jpeg).IsUnknown);
// RAWs say nothing here: their decoders give Rec.709.
Assert.Same(SourceColor.Untagged, Read([1, 2, 3], ImageFileFormat.Cr2));
}
}
@@ -1,4 +1,5 @@
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
@@ -87,6 +88,67 @@ public sealed class LinearDngWriterTests
for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
}
/// <summary>
/// A conversion's archival DNG (owner review 2, R7): highlights above white and colours outside sRGB (negative in
/// Rec.709) read back through the in-house DNG reader and developer as they were written, to the 16-bit step.
/// </summary>
[Test]
public void ASceneReferredDngKeepsHighlightsAndColoursOutsideSrgb()
{
using var image = new ImageBuffer(64, 48);
for (var y = 0; y < 48; y++)
{
for (var x = 0; x < 64; x++)
{
image[0, x, y] = 0.02f + 0.9f * x / 63;
image[1, x, y] = 0.05f + 0.7f * y / 47;
image[2, x, y] = 0.1f + 0.3f * ((x + y) % 7) / 6;
}
}
(int X, int Y, float R, float G, float B)[] special =
[
(1, 1, 2.6f, 2.4f, 2.2f), // a highlight above white, as a RAW's reconstruction gives it
(2, 1, 3.5f, 1.0f, 0.5f), // a bright saturated sunset
(3, 1, -0.2246f, 1.0421f, -0.0786f), // Display P3 green, outside sRGB
(4, 1, -0.15f, 0.8f, 0.9f), // a cyan outside sRGB
(5, 1, 0.6f, -0.05f, 0.7f), // a magenta outside sRGB
];
foreach (var (x, y, r, g, b) in special) (image[0, x, y], image[1, x, y], image[2, x, y]) = (r, g, b);
var dng = LinearDngWriter.Write(image, new LinearDngOptions { SceneReferred = true, TileSize = 32 });
var reader = TiffReader.Open(new MemoryStream(dng))!;
var ifd = reader.ReadChain()[0];
// The peak, about 2.5 in ProPhoto, fits under white two stops down.
Assert.Equal(2.0, reader.GetDouble(ifd, TiffTags.BaselineExposure));
var fm = reader.GetDoubles(ifd, TiffTags.ForwardMatrix1)!;
double[] d50 = [0.3457 / 0.3585, 1.0, (1 - 0.3457 - 0.3585) / 0.3585];
for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
using var developed = RawDecoder.Decode(new MemoryStream(dng), "scene.dng", new RawDecodeOptions { ApplyOrientation = false });
var back = developed.Image;
Assert.Equal((64, 48, 3), (back.Width, back.Height, back.Channels));
var worst = 0.0;
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < image.PlaneLength; i++) worst = Math.Max(worst, Math.Abs(image.Plane(c)[i] - back.Plane(c)[i]));
}
Assert.Less(worst, 4e-4, "largest difference after the round trip");
foreach (var (x, y, r, g, b) in special)
{
Assert.Approximately(r, back[0, x, y], 4e-4);
Assert.Approximately(g, back[1, x, y], 4e-4);
Assert.Approximately(b, back[2, x, y], 4e-4);
}
// The export mode is unchanged: linear sRGB primaries, clipped to 0..1, no headroom.
var export = LinearDngWriter.Write(image, new LinearDngOptions { TileSize = 32 });
using var clipped = RawDecoder.Decode(new MemoryStream(export), "export.dng", new RawDecodeOptions { ApplyOrientation = false });
Assert.Less(clipped.Image[0, 2, 1], 1.01, "the export clips the highlight");
Assert.Greater(clipped.Image[0, 3, 1], -0.01, "the export clips the colour outside sRGB");
var exportReader = TiffReader.Open(new MemoryStream(export))!;
Assert.Equal(0.0, exportReader.GetDouble(exportReader.ReadChain()[0], TiffTags.BaselineExposure));
}
[Test]
public void GrayInputExifAndNonSeekableOutput()
{
@@ -0,0 +1,107 @@
using System.IO.Compression;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
namespace Chronos.Core.Tests.Conversion;
/// <summary>Photos that record their colour space: an embedded ICC profile in each container, or an Exif colour space.</summary>
internal static class ColorFixtures
{
/// <summary>Saturated colours (a P3 photo's greens and reds fall outside sRGB once converted), plus a gradient.</summary>
public static ImageBuffer Scene(int width = 48, int height = 32)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
image[0, x, y] = 0.05f + 0.6f * x / width;
image[1, x, y] = 0.1f + 0.5f * y / height;
image[2, x, y] = 0.15f + 0.2f * ((x / 4 + y / 4) % 2);
}
}
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
(image[0, x, y], image[1, x, y], image[2, x, y]) = (0.02f, 0.9f, 0.02f); // a saturated green
(image[0, x + 8, y], image[1, x + 8, y], image[2, x + 8, y]) = (0.9f, 0.02f, 0.02f); // a saturated red
}
}
return image;
}
/// <summary>A JPEG whose values are <paramref name="scene"/> in sRGB, with an Exif block and/or an ICC profile.</summary>
public static byte[] Jpeg(ImageBuffer scene, byte[]? icc = null, byte[]? exifTiff = null) => JpegEncoder.Encode(scene, new JpegEncodeOptions
{
Quality = 98,
Subsampling = JpegSubsampling.Yuv444,
App1Segments = exifTiff is null ? null : [[.. "Exif\0\0"u8, .. exifTiff]],
IccProfile = icc,
});
/// <summary>An Exif block recording <paramref name="colorSpace"/> (1 sRGB, 0xFFFF uncalibrated) and an Interop index.</summary>
public static byte[] Exif(ushort colorSpace, string? interop = null)
{
var exif = new IfdSpec().Short(TiffTags.ColorSpace, colorSpace);
if (interop is not null) exif.Child(TiffTags.InteropIfd, new IfdSpec().Ascii(TiffTags.InteropIndex, interop));
return TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, "Canon").Child(TiffTags.ExifIfd, exif));
}
/// <summary>A PNG of <paramref name="scene"/> with an iCCP chunk after its header.</summary>
public static byte[] Png(ImageBuffer scene, byte[] icc)
{
var png = PngEncoder.Encode(scene);
using var compressed = new MemoryStream();
using (var z = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true)) z.Write(icc);
var chunk = Box.Png("iCCP", [.. "Display P3\0"u8, 0, .. compressed.ToArray()]);
// Signature (8) and IHDR (25) come first.
return [.. png.AsSpan(0, 33), .. chunk, .. png.AsSpan(33)];
}
/// <summary>A HEIF whose primary item has the colr boxes given (no image data: only its colour is read).</summary>
public static byte[] Heif(params byte[][] colr) => Heif(1, colr);
/// <summary>A HEIF whose item <paramref name="item"/> has the colr boxes given; item 1 is the primary (a grid of tiles 2…).</summary>
public static byte[] Heif(ushort item, params byte[][] colr)
{
var associations = Enumerable.Range(1, colr.Length).Select(i => (byte)(0x80 | i)).ToArray();
return
[
.. Box.Make("ftyp", Box.Ascii("heic"), Box.U32(0), Box.Ascii("mif1"), Box.Ascii("heic")),
.. Box.Full("meta", 0, 0,
Box.Full("hdlr", 0, 0, Box.U32(0), Box.Ascii("pict"), Box.Zeros(12), [0]),
Box.Full("pitm", 0, 0, Box.U16(1)),
Box.Make("iprp",
Box.Make("ipco", [.. colr.SelectMany(c => c)]),
Box.Full("ipma", 0, 0, Box.U32(1), Box.U16(item), [(byte)associations.Length], associations))),
];
}
public static byte[] Prof(byte[] icc) => Box.Make("colr", Box.Ascii("prof"), icc);
public static byte[] Nclx(ushort primaries, ushort transfer) => Box.Make("colr", Box.Ascii("nclx"), Box.U16(primaries), Box.U16(transfer), Box.U16(1), [0x80]);
/// <summary>A profile that parses but describes CMYK, which no RGB file carries.</summary>
public static byte[] Cmyk()
{
var data = (byte[])IccProfile.AdobeRgb.Data.Clone();
"CMYK"u8.CopyTo(data.AsSpan(16));
return data;
}
/// <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()
{
var small = IccProfile.AdobeRgb.Data;
var data = new byte[small.Length + 150_000];
small.CopyTo(data, 0);
System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(data, (uint)data.Length);
for (var i = small.Length; i < data.Length; i++) data[i] = (byte)(i * 31);
return data;
}
}
@@ -1,8 +1,12 @@
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Conversion;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Tests.Raw;
using Chronos.Testing;
namespace Chronos.Core.Tests.Conversion;
@@ -43,9 +47,9 @@ public sealed class ConvertPlannerTests(TestContext context)
Frame(8, "IMG_0009.CR2", ImageFileFormat.Cr2, flags: FrameFlags.PreviewOnly | FrameFlags.Excluded, tier: DecodeTier.EmbeddedPreview),
];
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames, Versions = new ManifestVersions { Frames = 7 } };
// The third photo's file is gone; the preview-only one probes as preview here.
// The third photo's file is gone; the preview-only one probes as preview here, the first one native.
var present = frames.Where(f => f.I != 2).Select(f => f.File).ToList();
var decoder = new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview)]);
var decoder = new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview, path => path.EndsWith("IMG_0009.CR2", StringComparison.Ordinal))]);
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.LinearDng), decoder, "Roof");
Assert.Equal((manifest.Id, "Roof", "2026/roof", 7), (plan.SequenceId, plan.Title, plan.Folder, plan.FramesVersion));
@@ -71,6 +75,109 @@ public sealed class ConvertPlannerTests(TestContext context)
Assert.Empty(plan.Skipped);
}
/// <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.
/// </summary>
[Test]
public void AFrameIsAskedWhateverTierWasRecorded()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
SidecarFrame[] frames = [Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2), Frame(1, "IMG_0002.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native)];
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
var present = frames.Select(f => f.File).ToList();
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var preview = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview)]), "Roof");
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)));
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));
}
/// <summary>
/// The managed decoder develops every RAW it reads natively (at float precision) even where WIC could; a RAW only WIC's
/// Raw Image Extension develops, at 8 bits, converts to JPEG but not to TIFF-16 or linear DNG.
/// </summary>
[Test]
public void ARawDevelopedAtEightBitsOnlyConvertsToJpegOnly()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
using var scene = SyntheticRaw.Smooth(96, 64);
var active = new RawRect(24, 4, 24 + 96, 4 + 64);
var sensor = NativeRawWriters.Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383);
SidecarFrame[] frames =
[
Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native),
Frame(1, "IMG_0002.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native),
Frame(2, "IMG_0003.CR3", ImageFileFormat.Cr3, tier: DecodeTier.Native),
];
File.WriteAllBytes(folder.File(frames[0].File), NativeRawWriters.Cr2(sensor, active));
// A body the managed decoder has no matrix for: only the 8-bit development reads it.
File.WriteAllBytes(folder.File(frames[1].File), NativeRawWriters.Cr2(sensor, active, model: "Canon EOS R99"));
File.WriteAllBytes(folder.File(frames[2].File), [0]);
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
var present = frames.Select(f => f.File).ToList();
var desktop = new ImageDecoder([new EightBitRaw(), new ManagedDecoderProvider()]);
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
{
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(target), desktop, "Roof");
Assert.SequenceEqual([0], plan.Frames.Select(f => f.Index));
Assert.SequenceEqual([(ConvertSkip.EightBit, 2)], plan.Skipped.Select(s => (s.Reason, s.Frames)));
}
var jpeg = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Jpeg), desktop, "Roof");
Assert.SequenceEqual([0, 1, 2], jpeg.Frames.Select(f => f.Index));
// The server, without WIC: the unsupported body and the CR3 are to convert on a PC.
var server = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), "Roof");
Assert.SequenceEqual([0], server.Frames.Select(f => f.Index));
Assert.SequenceEqual([(ConvertSkip.NoNativeDecoder, 1), (ConvertSkip.PreviewOnly, 1)], server.Skipped.Select(s => (s.Reason, s.Frames)));
}
/// <summary>A photo whose colour space no target can keep, or which a target cannot hold, is planned out with why.</summary>
[Test]
public void ColourAndSizeTheTargetCannotHoldArePlannedOut()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
using var scene = ColorFixtures.Scene();
SidecarFrame[] frames =
[
Frame(0, "plain.jpg", ImageFileFormat.Jpeg),
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(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]);
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();
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 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)));
Assert.True(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Jpeg), 65_536, 10));
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Jpeg), 65_535, 10));
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Tiff16), 0, 0));
}
[Test]
public void SizesAreEstimatedFromThePixels()
{
@@ -112,14 +219,27 @@ public sealed class ConvertPlannerTests(TestContext context)
Plan(new ConvertOptions(ConvertTarget.Jpeg, 80), ConvertMode.Replace, Sequence(3, 2)).Fingerprint());
}
/// <summary>A provider that reads CR2 natively by format, and probes every file at a fixed tier.</summary>
private sealed class ProbeAs(DecodeTier tier) : IImageDecoderProvider
/// <summary>A provider that reads CR2 natively by format, and probes the files <paramref name="applies"/> picks (all
/// by default) at a fixed tier, the others native.</summary>
private sealed class ProbeAs(DecodeTier tier, Func<string, bool>? applies = null) : IImageDecoderProvider
{
public string Name => "probe";
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Cr2 ? DecodeTier.Native : null;
public FileTier Probe(string path, ImageFileFormat format) => new(format, tier, Name, null, 0, 0);
public FileTier Probe(string path, ImageFileFormat format) => new(format, applies?.Invoke(path) == false ? DecodeTier.Native : tier, Name, null, 0, 0);
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
{
public string Name => "wic";
public bool DevelopsRawAt8Bits => true;
public DecodeTier? TierFor(ImageFileFormat format) => ImageFormatInfo.Of(format).Family == ImageFamily.CameraRaw ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
}
@@ -1,10 +1,15 @@
using System.Globalization;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Mathematics;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Naming;
@@ -227,11 +232,13 @@ public sealed class FrameConverterTests(TestContext context)
var frame = Frame("frame.dng", ImageFileFormat.Dng, 32, 24);
var options = new ConvertOptions(ConvertTarget.Jpeg);
var target = Target(options);
Assert.Throws<ConversionException>(() =>
var preview = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([new PreviewOnlyProvider()]), target, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.PreviewOnly, preview.Reason);
Assert.FileMissing(target);
Assert.Throws<ConversionException>(() =>
var none = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([]), target, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.NoDecoder, none.Reason);
}
[Test]
@@ -247,7 +254,7 @@ public sealed class FrameConverterTests(TestContext context)
var bytes = File.ReadAllBytes(file.Path);
bytes[^10] ^= 0x40;
File.WriteAllBytes(file.Path, bytes);
Assert.Throws<ConversionException>(() => FrameConverter.Verify(file, written));
Assert.Equal(ConversionFailure.NotVerified, Assert.Throws<ConversionException>(() => FrameConverter.Verify(file, written)).Reason);
// A capture time that is not the one written.
File.WriteAllBytes(file.Path, File.ReadAllBytes(source));
Assert.Throws<ConversionException>(() => FrameConverter.Verify(file with { Sha256 = ContentHash.Sha256Async(file.Path).GetAwaiter().GetResult(), Size = new FileInfo(file.Path).Length }, written));
@@ -289,6 +296,224 @@ public sealed class FrameConverterTests(TestContext context)
Assert.Equal(new ConvertOptions(ConvertTarget.LinearDng, 10).Key, new ConvertOptions(ConvertTarget.LinearDng, 90).Key);
}
/// <summary>
/// The managed decoder develops a RAW wherever it reads it natively, ahead of WIC (owner review 2, R7): a 16-bit file is
/// never filled from WIC's 8-bit RAW development, which a JPEG may still use.
/// </summary>
[Test]
public void ASixteenBitFileNeverComesFromAnEightBitRawDevelopment()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "frame.dng");
using (var image = Scene(32, 24)) File.WriteAllBytes(path, LinearDngWriter.Write(image));
var frame = Frame("frame.dng", ImageFileFormat.Dng, 32, 24);
var wic = new EightBitRaw();
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng, ConvertTarget.Jpeg])
{
var options = new ConvertOptions(target);
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([wic, new ManagedDecoderProvider()]), Target(options),
cancellationToken: context.Cancellation);
}
Assert.Equal(0, wic.Calls);
// Where only the 8-bit development reads it: refused for 16 bits, converted to JPEG.
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
{
var options = new ConvertOptions(target);
var refused = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([wic]), Target(options), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.EightBit, refused.Reason);
}
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
FrameConverter.Convert(new ConvertSource(path, frame), jpeg, new ImageDecoder([wic]), Target(jpeg), cancellationToken: context.Cancellation);
Assert.Equal(1, wic.Calls);
}
/// <summary>A RAW developed above white and outside sRGB converts to a linear DNG that reads back the same.</summary>
[Test]
public void ALinearDngKeepsWhatTheRawHasAboveWhiteAndOutsideSrgb()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "IMG_0001.CR2");
using (var image = Scene(40, 30)) File.WriteAllBytes(path, JpegEncoder.Encode(image));
var developed = Scene(40, 30);
(developed[0, 1, 1], developed[1, 1, 1], developed[2, 1, 1]) = (2.4f, 1.9f, 1.2f);
(developed[0, 2, 1], developed[1, 2, 1], developed[2, 2, 1]) = (-0.2f, 1.0f, -0.07f);
var options = new ConvertOptions(ConvertTarget.LinearDng);
var file = FrameConverter.Convert(new ConvertSource(path, Frame("IMG_0001.CR2", ImageFileFormat.Cr2, 40, 30)), options,
new ImageDecoder([new Developed(developed)]), Target(options), cancellationToken: context.Cancellation);
using var back = Assert.NotNull(DecoderFactory.CreateServer().Decode(new DecodeRequest(file.Path, AllowPreview: false)));
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < developed.PlaneLength; i++) Assert.Approximately(developed.Plane(c)[i], back.Pixels.Plane(c)[i], 3e-4);
}
developed.Dispose();
}
/// <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.
/// </summary>
[Test]
public void TheOriginalsColourSpaceIsKept()
{
var folder = context.CreateTempDirectory("source");
var p3 = IccProfile.DisplayP3;
using var scene = ColorFixtures.Scene();
var jpegPath = Path.Combine(folder, "p3.jpg");
File.WriteAllBytes(jpegPath, ColorFixtures.Jpeg(scene, p3.Data, ExifWriter.BuildTiff(Camera)));
var source = new ConvertSource(jpegPath, Frame("p3.jpg", ImageFileFormat.Jpeg, 48, 32));
var server = DecoderFactory.CreateServer();
using var original = server.Decode(new DecodeRequest(jpegPath, AllowPreview: false))!;
foreach (var target in (ConvertTarget[])[ConvertTarget.Jpeg, ConvertTarget.Tiff16])
{
var options = new ConvertOptions(target);
var file = FrameConverter.Convert(source, options, server, Target(options), cancellationToken: context.Cancellation);
Assert.BytesEqual(p3.Data, SourceColor.Read(file.Path, file.Format).Profile!.Data);
using var converted = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
var error = 0.0;
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < scene.PlaneLength; i++) error += Math.Abs(original.Pixels.Plane(c)[i] - converted.Pixels.Plane(c)[i]);
}
Assert.Less(error / (3.0 * scene.PlaneLength), target == ConvertTarget.Jpeg ? 0.02 : 1e-3, $"the values of {target} pass unchanged");
}
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);
// 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");
File.WriteAllBytes(adobePath, ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF, "R03")));
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
var adobe = FrameConverter.Convert(new ConvertSource(adobePath, Frame("adobe.jpg", ImageFileFormat.Jpeg, 48, 32)), jpeg, server, Target(jpeg),
cancellationToken: context.Cancellation);
Assert.Equal("Compatible with Adobe RGB (1998)", SourceColor.Read(adobe.Path, adobe.Format).Profile!.Description);
var pngPath = Path.Combine(folder, "p3.png");
File.WriteAllBytes(pngPath, ColorFixtures.Png(scene, p3.Data));
var tiff = new ConvertOptions(ConvertTarget.Tiff16);
var fromPng = FrameConverter.Convert(new ConvertSource(pngPath, Frame("p3.png", ImageFileFormat.Png, 48, 32)), tiff, server, Target(tiff),
cancellationToken: context.Cancellation);
Assert.BytesEqual(p3.Data, SourceColor.Read(fromPng.Path, fromPng.Format).Profile!.Data);
}
/// <summary>A colour space nothing here can keep (uncalibrated without R03, a CMYK profile) refuses the photo, whatever the target.</summary>
[Test]
public void APhotoWhoseColourSpaceCannotBeKeptIsRefused()
{
var folder = context.CreateTempDirectory("source");
using var scene = ColorFixtures.Scene();
var unknown = Path.Combine(folder, "unknown.jpg");
File.WriteAllBytes(unknown, ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)));
var cmyk = Path.Combine(folder, "cmyk.jpg");
File.WriteAllBytes(cmyk, ColorFixtures.Jpeg(scene, ColorFixtures.Cmyk()));
foreach (var target in Enum.GetValues<ConvertTarget>())
{
var options = new ConvertOptions(target);
foreach (var path in (string[])[unknown, cmyk])
{
var output = Target(options);
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, Frame(Path.GetFileName(path), ImageFileFormat.Jpeg, 48, 32)),
options, DecoderFactory.CreateServer(), output, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.ColorProfile, refused.Reason);
Assert.FileMissing(output);
}
}
}
/// <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()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "panorama.png");
using (var image = Scene(8, 8)) File.WriteAllBytes(path, PngEncoder.Encode(image));
var frame = Frame("panorama.png", ImageFileFormat.Png, 70_000, 1);
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
using var wide = new ImageBuffer(65_536, 1);
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, frame), jpeg,
new ImageDecoder([new Developed(wide, ImageFileFormat.Png)]), Target(jpeg), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.TooLarge, refused.Reason);
var overflow = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, frame), new ConvertOptions(ConvertTarget.Tiff16),
new ImageDecoder([new Overflowing()]), Target(jpeg), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.TooLarge, overflow.Reason);
}
/// <summary>Why a photo failed reads as one sentence by cause in the job log, never the exception's English text.</summary>
[Test]
public void FailuresReadAsOneSentenceByCause()
{
foreach (var reason in Enum.GetValues<ConversionFailure>())
{
var text = FrameConverter.FailureText(new ConversionException(reason, "technical detail"));
Assert.Equal(Loc.L("Archive.Convert.Failed." + reason), text);
Assert.NotNull(Loc.Get("Archive.Convert.Failed." + reason, CultureInfo.GetCultureInfo("it")));
Assert.False(text.Contains("technical", StringComparison.Ordinal), text);
}
Assert.Equal(Loc.L("Archive.Convert.Failed.Full"), FrameConverter.FailureText(new IOException("full", unchecked((int)0x80070070))));
Assert.Equal(Loc.L("Archive.Failed.Access"), FrameConverter.FailureText(new UnauthorizedAccessException("denied")));
Assert.Equal(Loc.L("Archive.Convert.Failed.Unreadable"), FrameConverter.FailureText(new InvalidDataException("JPEG: bad Huffman")));
Assert.Equal(Loc.L("Archive.Failed.Files"), FrameConverter.FailureText(new IOException("network")));
Assert.Equal(Loc.L("Archive.Convert.Failed.Other"), FrameConverter.FailureText(new ArgumentOutOfRangeException("width")));
}
/// <summary>WIC with the Raw Image Extension, as a conversion sees it: every RAW native, developed at 8 bits (counted).</summary>
private sealed class EightBitRaw : IImageDecoderProvider
{
private readonly ManagedDecoderProvider _managed = new();
public int Calls { get; private set; }
public string Name => "wic";
public bool DevelopsRawAt8Bits => true;
public DecodeTier? TierFor(ImageFileFormat format) => ImageFormatInfo.Of(format).IsRaw ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
Calls++;
var decoded = _managed.Decode(request, cancellationToken)!;
foreach (ref var v in decoded.Pixels.Data) v = ColorSpace.Linear8(ColorSpace.Encode8(v));
return new DecodedImage(decoded.Pixels, DecodeTier.Native, Name, decoded.SourceWidth, decoded.SourceHeight);
}
}
/// <summary>A RAW decoder that develops every file of <paramref name="format"/> into a copy of <paramref name="image"/>.</summary>
private sealed class Developed(ImageBuffer image, ImageFileFormat format = ImageFileFormat.Cr2) : IImageDecoderProvider
{
public string Name => "developed";
public DecodeTier? TierFor(ImageFileFormat f) => f == format ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) =>
new(image.Clone(), DecodeTier.Native, Name, image.Width, image.Height);
}
/// <summary>A decoder whose image is too large for one buffer.</summary>
private sealed class Overflowing : IImageDecoderProvider
{
public string Name => "overflowing";
public DecodeTier? TierFor(ImageFileFormat format) => DecodeTier.Native;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => throw new OverflowException();
}
/// <summary>A provider that claims DNG natively but only ever gives the embedded-preview tier.</summary>
private sealed class PreviewOnlyProvider : IImageDecoderProvider
{