diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index a2399630..0fa0ac79 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -43,22 +43,37 @@ The sequence file cannot be read.long: why a sequence is not converted in a conversion dry run {0:N0} sequence converted {0:N0} sequences converted + The photo no longer matches the copy that was archived; verify the sequence.long: why a photo was not converted, in the job log + Its colour profile can be neither kept nor converted in this format.long: why a photo was not converted, in the job log + This computer develops this RAW at 8 bits only, too few for a 16-bit file; JPEG converts it.long: why a photo was not converted, in the job log + The archive's disk is full.long: why a photo was not converted, in the job log + No decoder on this computer reads it at full resolution.long: why a photo was not converted, in the job log + The converted file did not read back as it was written.long: why a photo was not converted, in the job log + The converted file could not be made.long: why a photo was not converted, in the job log + This computer reads it only from its embedded preview: convert it on a PC that reads it at full resolution.long: why a photo was not converted, in the job log + It is larger than this format or the memory for one photo can hold.long: why a photo was not converted, in the job log + The photo could not be decoded.long: why a photo was not converted, in the job log Format Convert {0:N0} sequence Convert {0:N0} sequences Convert {0}long: dialog heading; {0} archive name Mode New sequence + The converted photos could not take their place. {0}long: job log; {0} why (one sentence) + {0} could not be converted. {1}long: job log; {0} the photo's file, {1} why (one sentence) Quality Replace Replace the photos of {0:N0} sequence?long Replace the photos of {0:N0} sequences?long {0} ({1}) are replaced by their conversion to {2}; the originals move to the archive's trash and can be restored until it is emptied.long: {0} photos, e.g. "120 photos"; {1} their size; {2} the format, e.g. "Linear DNG" {0} → {1}sizes before and after a conversion + Photos whose colour profile this format can neither keep nor convert stay as they are.long: why photos are not converted in a conversion dry run + RAW photos this computer develops at 8 bits only stay as they are; JPEG converts them.long: why photos are not converted in a conversion dry run Missing photos stay as they are.long: why photos are not converted in a conversion dry run Photos of a format this computer cannot read at full resolution stay as they are.long: why photos are not converted in a conversion dry run Photos read only from their embedded preview here stay as they are.long: why photos are not converted in a conversion dry run Photos already in this format stay as they are.long: why photos are not converted in a conversion dry run + Photos larger than this format can hold stay as they are.long: why photos are not converted in a conversion dry run Unreadable photos stay as they are.long: why photos are not converted in a conversion dry run Photos never verified stay as they are; verify the sequence first.long: why photos are not converted in a conversion dry run {0:N0} skippedphotos a conversion leaves as they are @@ -183,7 +198,7 @@ Left as it was, busy or unreadable: {0}long: job log line; {0} sequence title Left as it was, changed after the plan: {0}long: job log line; {0} sequence title Sequences converted: {0}, new sequences: {1}, photos: {2}long: job log line of a conversion - Left as it was, a photo could not be converted: {0}: {1}long: job log line; {0} sequence title, {1} the reason + Left as it was: {0}. {1}long: job log line; {0} sequence title, {1} what failed and why (sentences) Nothing to convert: {0}long: job log line; {0} sequence title {0}: photos replaced by their conversion: {1}long: job log line; {0} sequence title, {1} photos {0}: photos converted into a new sequence: {1}long: job log line; {0} sequence title, {1} photos diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 9038136a..44c29bf2 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -40,22 +40,37 @@ Il file della sequenza non si può leggere. {0:N0} sequenza convertita {0:N0} sequenze convertite + La foto non corrisponde più alla copia archiviata; verifica la sequenza. + Il suo profilo colore non si può né conservare né convertire in questo formato. + Questo computer sviluppa questo RAW solo a 8 bit, troppo pochi per un file a 16 bit; JPEG lo converte. + Il disco dell'archivio è pieno. + Nessun decodificatore di questo computer la legge a piena risoluzione. + Il file convertito non si è riletto come era stato scritto. + Non è stato possibile creare il file convertito. + Questo computer la legge solo dalla sua anteprima incorporata: convertila su un PC che la legga a piena risoluzione. + È più grande di quanto questo formato o la memoria per una foto possano contenere. + Non è stato possibile decodificare la foto. Formato Converti {0:N0} sequenza Converti {0:N0} sequenze Converti {0} Modalità Nuova sequenza + Le foto convertite non hanno potuto prendere il loro posto. {0} + Impossibile convertire {0}. {1} Qualità Sostituisci Sostituire le foto di {0:N0} sequenza? Sostituire le foto di {0:N0} sequenze? {0} ({1}) vengono sostituite dalla loro conversione in {2}; gli originali vanno nel cestino dell'archivio e si possono ripristinare finché non viene svuotato. {0} → {1} + Le foto il cui profilo colore questo formato non può né conservare né convertire restano come sono. + Le foto RAW che questo computer sviluppa solo a 8 bit restano come sono; JPEG le converte. Le foto mancanti restano come sono. Le foto di un formato che questo computer non legge a piena risoluzione restano come sono. Le foto lette qui solo dalla loro anteprima incorporata restano come sono. Le foto già in questo formato restano come sono. + Le foto più grandi di quanto questo formato possa contenere restano come sono. Le foto illeggibili restano come sono. Le foto mai verificate restano come sono; verifica prima la sequenza. {0:N0} esclusa @@ -177,7 +192,7 @@ Lasciata com'era, occupata o illeggibile: {0} Lasciata com'era, cambiata dopo il piano: {0} Sequenze convertite: {0}, nuove sequenze: {1}, foto: {2} - Lasciata com'era, una foto non si è potuta convertire: {0}: {1} + Lasciata com'era: {0}. {1} Niente da convertire: {0} {0}: foto sostituite dalla loro conversione: {1} {0}: foto convertite in una nuova sequenza: {1} diff --git a/src/Chronos.Core.Windows/Wic/WicDecoderProvider.cs b/src/Chronos.Core.Windows/Wic/WicDecoderProvider.cs index b9945e32..8a343b3e 100644 --- a/src/Chronos.Core.Windows/Wic/WicDecoderProvider.cs +++ b/src/Chronos.Core.Windows/Wic/WicDecoderProvider.cs @@ -53,6 +53,9 @@ public sealed class WicDecoderProvider : IImageDecoderProvider public DecodeTier? TierFor(ImageFileFormat format) => format != ImageFileFormat.Dng && Inventory.IsNative(format) ? DecodeTier.Native : null; + /// The Raw Image Extension, the only decoder this provider develops RAWs with, gives 24bppRGB (8 bits per channel). + public bool DevelopsRawAt8Bits => true; + /// /// Decodes the first frame. Returns null when WIC cannot natively decode this format here, when the request /// forces the embedded preview, or when no installed decoder recognises the content. Corrupt files raise the diff --git a/src/Chronos.Core/Codecs/Dng/LinearDngWriter.cs b/src/Chronos.Core/Codecs/Dng/LinearDngWriter.cs index a33bef4c..19bb5ec4 100644 --- a/src/Chronos.Core/Codecs/Dng/LinearDngWriter.cs +++ b/src/Chronos.Core/Codecs/Dng/LinearDngWriter.cs @@ -2,6 +2,7 @@ using System.Buffers.Binary; using Chronos.Core.Codecs.Jpeg; using Chronos.Core.Codecs.Tiff; using Chronos.Core.Imaging; +using Chronos.Core.Mathematics; using Chronos.Core.Metadata.Tiff; namespace Chronos.Core.Codecs.Dng; @@ -33,15 +34,29 @@ public sealed record LinearDngOptions /// Worker limit for tile encoding (-1 = all cores). public int MaxDegreeOfParallelism { get; init; } = -1; + + /// + /// Keeps scene-referred data whole, as a conversion's archival copy needs (owner review 2, R7): the pixels are stored in + /// linear ProPhoto (ROMM) primaries, where colours outside sRGB stay positive, divided by the power of two (at most + /// 2^) that brings their peak below the white level, which BaselineExposure + /// gives back; ColorMatrix1 and ForwardMatrix1 describe that space. Off (exports): linear sRGB primaries, values + /// outside 0..1 clipped. + /// + public bool SceneReferred { get; init; } } /// /// Writes linear Rec.709/sRGB-primaries RGB as a 16-bit LinearRaw DNG 1.4 that raw editors render with correct /// colours: ColorMatrix1 = XYZ(D65) → linear sRGB, ForwardMatrix1 = linear sRGB → XYZ(D50), illuminant D65, -/// AsShotNeutral 1/1/1, WhiteLevel 65535, BaselineExposure 0. Values above 1.0 are clipped. +/// AsShotNeutral 1/1/1, WhiteLevel 65535, BaselineExposure 0. Values above 1.0 are clipped. With +/// the data are stored in linear ProPhoto primaries with headroom instead, +/// so highlights above 1 and colours outside sRGB survive. /// public static class LinearDngWriter { + /// Most stops of headroom a scene-referred DNG keeps above diffuse white (its data then use 12 of their 16 bits below it). + public const int MaxHeadroomStops = 4; + /// XYZ (D65) → linear sRGB, i.e. the inverse of the sRGB → XYZ matrix (IEC 61966-2-1). internal static readonly double[] XyzToLinearSrgb = [ @@ -85,13 +100,18 @@ public static class LinearDngWriter var start = output.Position; output.Write("II*\0\0\0\0\0"u8); var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }; + var scene = o.SceneReferred ? SceneEncoding.For(image, parallel) : null; var band = new ushort[w * t * 3]; var tiles = new byte[across][]; for (var ty = 0; ty < down; ty++) { var y0 = ty * t; var rows = Math.Min(t, h - y0); - Parallel.For(0, rows, parallel, r => PixelConvert.EncodeRow16(image, y0 + r, band.AsSpan(r * w * 3, w * 3), 3, TransferFunction.Linear)); + Parallel.For(0, rows, parallel, r => + { + if (scene is null) PixelConvert.EncodeRow16(image, y0 + r, band.AsSpan(r * w * 3, w * 3), 3, TransferFunction.Linear); + else scene.EncodeRow(image, y0 + r, band.AsSpan(r * w * 3, w * 3)); + }); Parallel.For(0, across, parallel, tx => tiles[tx] = EncodeTile(band, w, rows, tx * t, t, o.Compression)); for (var tx = 0; tx < across; tx++) { @@ -124,11 +144,11 @@ public static class LinearDngWriter ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0); ifd.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0); ifd.Ascii(TiffTags.UniqueCameraModel, o.UniqueCameraModel); - ifd.SRational(TiffTags.ColorMatrix1, Rationals(XyzToLinearSrgb)); - ifd.SRational(TiffTags.ForwardMatrix1, Rationals(LinearSrgbToXyzD50)); + ifd.SRational(TiffTags.ColorMatrix1, Rationals(scene is null ? XyzToLinearSrgb : SceneEncoding.ColorMatrix)); + ifd.SRational(TiffTags.ForwardMatrix1, Rationals(scene is null ? LinearSrgbToXyzD50 : SceneEncoding.ForwardMatrix)); ifd.Short(TiffTags.CalibrationIlluminant1, 21); // D65 ifd.Rational(TiffTags.AsShotNeutral, (1u, 1u), (1u, 1u), (1u, 1u)); - ifd.SRational(TiffTags.BaselineExposure, (0, 1)); + ifd.SRational(TiffTags.BaselineExposure, (scene?.Stops ?? 0, 1)); ifd.Long(TiffTags.WhiteLevel, 65535, 65535, 65535); TiffWriter.WriteDirectory(output, start, ifd); } @@ -152,4 +172,103 @@ public static class LinearDngWriter } private static (int, int)[] Rationals(double[] matrix) => matrix.Select(v => ((int)Math.Round(v * 10000), 10000)).ToArray(); + + /// The values a matrix tag holds once written (): what a reader computes with. + private static double[] Written(double[] matrix) => [.. matrix.Select(v => Math.Round(v * 10000) / 10000)]; + + private static double[] Elements(Matrix3 m) => [m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33]; + + private static Matrix3 Matrix(double[] m) => new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]); + + /// + /// The scene-referred encoding of one image (): linear Rec.709 to linear + /// ProPhoto, white-balanced so (1, 1, 1) stays the scene white, divided by 2^. + /// + private sealed class SceneEncoding + { + /// Stored values stay below this fraction of the white level, under the 0.999 a reader takes for clipped. + private const double Ceiling = 0.998; + + /// Linear ProPhoto (ROMM RGB, D50) to XYZ (D50), as written. + public static readonly double[] ForwardMatrix = Written(Elements( + Matrix3.RgbToXyz(new Chromaticity(0.7347, 0.2653), new Chromaticity(0.1596, 0.8404), new Chromaticity(0.0366, 0.0001), Chromaticity.D50))); + + /// XYZ (D65) to linear ProPhoto with the D65 white on (1, 1, 1), as written. + public static readonly double[] ColorMatrix = Written(Elements( + Matrix(ForwardMatrix).Inverse() * Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), Chromaticity.D50.ToXyz()))); + + /// + /// Linear Rec.709 to the stored space: the inverse of the matrix a DNG reader develops these tags with (the in-house + /// reader's own solve), so the image reads back as it was written, to the 16-bit step. + /// + private static readonly Matrix3 FromRec709 = new DngColorProfile + { + ColorMatrix1 = Matrix(ColorMatrix), + ForwardMatrix1 = Matrix(ForwardMatrix), + CalibrationIlluminant1 = 21, + AsShotNeutral = new Vector3D(1, 1, 1), + }.Solve([]).BalancedToRec709.Inverse(); + + private readonly float[] _matrix; + + private SceneEncoding(int stops) + { + Stops = stops; + var scale = 1 / double.Exp2(stops); + _matrix = [.. Elements(FromRec709).Select(v => (float)(v * scale))]; + } + + /// The stops of headroom: BaselineExposure. + public int Stops { get; } + + /// The encoding of : the fewest stops that bring its peak in the stored space below the ceiling. + public static SceneEncoding For(ImageBuffer image, ParallelOptions parallel) + { + var m = FromRec709; + var peak = 0.0; + var gate = new object(); + Parallel.For(0, image.Height, parallel, () => 0.0, (y, _, local) => + { + Rows(image, y, out var r, out var g, out var b); + for (var x = 0; x < r.Length; x++) + { + double vr = r[x], vg = g[x], vb = b[x]; + local = Math.Max(local, m.M11 * vr + m.M12 * vg + m.M13 * vb); + local = Math.Max(local, m.M21 * vr + m.M22 * vg + m.M23 * vb); + local = Math.Max(local, m.M31 * vr + m.M32 * vg + m.M33 * vb); + } + return local; + }, local => + { + lock (gate) peak = Math.Max(peak, local); + }); + var stops = 0; + while (stops < MaxHeadroomStops && !(peak / double.Exp2(stops) < Ceiling)) stops++; + return new SceneEncoding(stops); + } + + /// Row as interleaved 16-bit stored values. + public void EncodeRow(ImageBuffer image, int y, Span row) + { + var m = _matrix; + Rows(image, y, out var r, out var g, out var b); + for (var x = 0; x < r.Length; x++) + { + float vr = r[x], vg = g[x], vb = b[x]; + row[3 * x] = Sample(m[0] * vr + m[1] * vg + m[2] * vb); + row[3 * x + 1] = Sample(m[3] * vr + m[4] * vg + m[5] * vb); + row[3 * x + 2] = Sample(m[6] * vr + m[7] * vg + m[8] * vb); + } + } + + private static ushort Sample(float v) => (ushort)(Math.Clamp(float.IsNaN(v) ? 0f : v, 0f, 1f) * 65535f + 0.5f); + + /// The red, green and blue rows of (gray: its one plane three times). + private static void Rows(ImageBuffer image, int y, out Span r, out Span g, out Span b) + { + r = image.Row(0, y); + g = image.Channels >= 3 ? image.Row(1, y) : r; + b = image.Channels >= 3 ? image.Row(2, y) : r; + } + } } diff --git a/src/Chronos.Core/Codecs/Icc/IccProfile.cs b/src/Chronos.Core/Codecs/Icc/IccProfile.cs new file mode 100644 index 00000000..fba7027d --- /dev/null +++ b/src/Chronos.Core/Codecs/Icc/IccProfile.cs @@ -0,0 +1,336 @@ +using System.Buffers.Binary; +using System.Text; +using Chronos.Core.Imaging; +using Chronos.Core.Mathematics; + +namespace Chronos.Core.Codecs.Icc; + +/// +/// A tone curve of an ICC profile (ICC.1:2010 §10.6 curveType, §10.18 parametricCurveType): device code value 0..1 → +/// linear 0..1. A curveType with no entry is the identity, with one a gamma (u8Fixed8), with more a table interpolated +/// linearly; a parametricCurveType is one of the functions 0–4. +/// +public sealed class IccCurve +{ + private readonly double[]? _table; + private readonly double[] _parameters; + private readonly int _function; + + private IccCurve(int function, double[] parameters, double[]? table) + { + _function = function; + _parameters = parameters; + _table = table; + } + + /// A pure power law. + public static IccCurve Gamma(double gamma) => new(0, [gamma], null); + + /// The sRGB (IEC 61966-2-1) electro-optical transfer function. + public static IccCurve Srgb { get; } = new(3, [2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045], null); + + /// The linear value of code value (clamped to 0..1). + public double Evaluate(double code) + { + var x = double.IsNaN(code) ? 0 : Math.Clamp(code, 0, 1); + if (_table is { } table) + { + var t = x * (table.Length - 1); + var i = Math.Min((int)t, table.Length - 2); + return table[i] + (table[i + 1] - table[i]) * (t - i); + } + double P(int i) => i < _parameters.Length ? _parameters[i] : 0; + double g = P(0), a = P(1), b = P(2), c = P(3), d = P(4), e = P(5), f = P(6); + var y = _function switch + { + 0 => Math.Pow(x, g), + 1 => a != 0 && x >= -b / a ? Math.Pow(Math.Max(0, a * x + b), g) : 0, + 2 => a != 0 && x >= -b / a ? Math.Pow(Math.Max(0, a * x + b), g) + c : c, + 3 => x >= d ? Math.Pow(Math.Max(0, a * x + b), g) : c * x, + _ => x >= d ? Math.Pow(Math.Max(0, a * x + b), g) + e : c * x + f, + }; + return double.IsFinite(y) ? Math.Clamp(y, 0, 1) : 0; + } + + /// The curve of a curveType or parametricCurveType tag, or null when the tag is neither or is malformed. + internal static IccCurve? Parse(ReadOnlySpan tag) + { + if (tag.Length < 12) return null; + var type = tag[..4]; + if (type.SequenceEqual("curv"u8)) + { + var count = BinaryPrimitives.ReadUInt32BigEndian(tag[8..]); + if (count == 0) return Gamma(1); + if (count > (uint)(tag.Length - 12) / 2) return null; + if (count == 1) return BinaryPrimitives.ReadUInt16BigEndian(tag[12..]) is var gamma and > 0 ? Gamma(gamma / 256.0) : null; + var table = new double[count]; + for (var i = 0; i < table.Length; i++) table[i] = BinaryPrimitives.ReadUInt16BigEndian(tag[(12 + 2 * i)..]) / 65535.0; + return new IccCurve(-1, [], table); + } + if (!type.SequenceEqual("para"u8)) return null; + var function = BinaryPrimitives.ReadUInt16BigEndian(tag[8..]); + int[] counts = [1, 3, 4, 5, 7]; + if (function >= counts.Length || tag.Length < 12 + 4 * counts[function]) return null; + var parameters = new double[counts[function]]; + for (var i = 0; i < parameters.Length; i++) parameters[i] = IccProfile.S15Fixed16(tag[(12 + 4 * i)..]); + return new IccCurve(function, parameters, null); + } + + /// This curve as a version 2 curveType tag: a gamma when it is one that u8Fixed8 holds, else a 1024-entry table. + internal byte[] Encode() + { + if (_table is null && _function == 0 && Math.Abs(_parameters[0] * 256 - Math.Round(_parameters[0] * 256)) < 1e-9) + { + var tag = new byte[14]; + "curv"u8.CopyTo(tag); + BinaryPrimitives.WriteUInt32BigEndian(tag.AsSpan(8), 1); + BinaryPrimitives.WriteUInt16BigEndian(tag.AsSpan(12), (ushort)Math.Round(_parameters[0] * 256)); + return tag; + } + const int entries = 1024; + var table = new byte[12 + 2 * entries]; + "curv"u8.CopyTo(table); + BinaryPrimitives.WriteUInt32BigEndian(table.AsSpan(8), entries); + for (var i = 0; i < entries; i++) + BinaryPrimitives.WriteUInt16BigEndian(table.AsSpan(12 + 2 * i), (ushort)Math.Round(Evaluate(i / (double)(entries - 1)) * 65535)); + return table; + } +} + +/// +/// An ICC colour profile (ICC.1:2010) as a photo embeds it, kept byte for byte so a converted file can carry it, with what a +/// conversion needs to read from it: its colour space, its description, and for a matrix/TRC profile its colorants (RGB → +/// PCS XYZ, D50) and tone curves. Profiles Chronos writes itself (, ) are +/// version 2.1 display profiles with a matrix and curveType TRCs, read by every colour-managed program. +/// +public sealed class IccProfile +{ + /// Largest profile read: big camera and printer profiles stay well below. + public const int MaxBytes = 4 << 20; + + private const uint Rgb = 0x52474220, Gray = 0x47524159, Xyz = 0x58595A20; + private static readonly uint[] RgbColorants = [Tag("rXYZ"), Tag("gXYZ"), Tag("bXYZ")]; + private static readonly uint[] RgbCurves = [Tag("rTRC"), Tag("gTRC"), Tag("bTRC")]; + + /// The ICC D50 profile connection white (PCS illuminant). + private static readonly Vector3D PcsWhite = new(0.9642, 1.0, 0.8249); + + private IccProfile(byte[] data, uint colorSpace, string? description, Matrix3? colorants, IReadOnlyList? curves) + { + Data = data; + ColorSpace = colorSpace; + Description = description; + Colorants = colorants; + Curves = curves; + } + + /// The profile's bytes, as embedded. + public byte[] Data { get; } + + /// The data colour space signature ("RGB ", "GRAY", "CMYK"…) as a big-endian four-character code. + public uint ColorSpace { get; } + + public bool IsRgb => ColorSpace == Rgb; + + public bool IsGray => ColorSpace == Gray; + + /// The profile's description (its 'desc' tag), when it has one. + public string? Description { get; } + + /// Whether the profile describes sRGB (its description names it: "sRGB IEC61966-2.1", "sRGB built-in"…). + public bool IsSrgb => IsRgb && Description?.Contains("sRGB", StringComparison.Ordinal) == true; + + /// RGB → PCS XYZ (D50) of a matrix/TRC profile: rXYZ, gXYZ and bXYZ as columns; null otherwise. + public Matrix3? Colorants { get; } + + /// The tone curves: red, green and blue of a matrix/TRC profile, or the gray one; null when absent. + public IReadOnlyList? Curves { get; } + + /// Whether pixels in this profile's space convert to another through its matrix and curves alone. + public bool IsMatrixShaper => IsRgb && Colorants is not null && Curves is { Count: 3 }; + + /// Whether this is a gray profile with its tone curve. + public bool IsGrayCurve => IsGray && Curves is { Count: 1 }; + + /// Adobe RGB (1998) as a camera marks it in its Exif (ColorSpace uncalibrated, Interop index "R03"). + public static IccProfile AdobeRgb { get; } = Synthesize("Compatible with Adobe RGB (1998)", new(0.64, 0.33), new(0.21, 0.71), new(0.15, 0.06), IccCurve.Gamma(563 / 256.0)); + + /// Display P3 (P3 primaries, D65, the sRGB curve) as a HEIF nclx box names it (colour primaries 12). + public static IccProfile DisplayP3 { get; } = Synthesize("Display P3", new(0.680, 0.320), new(0.265, 0.690), new(0.150, 0.060), IccCurve.Srgb); + + /// + /// Linear RGB of a matrix/TRC profile → linear Rec.709 (D65): its colorants, adapted from the white they add up to + /// (the profile's white in the PCS) to D65, so neutrals stay neutral. + /// + /// The profile is not a matrix/TRC one. + public Matrix3 ToLinearRec709() + { + if (Colorants is not { } colorants) throw new InvalidOperationException("Only a matrix/TRC profile has a matrix."); + var white = colorants * new Vector3D(1, 1, 1); + return Matrix3.XyzToRec709 * Matrix3.BradfordAdaptation(white, Chromaticity.D65.ToXyz()) * colorants; + } + + /// The profile in , or null when it is not an ICC profile (no 'acsp' signature, a size + /// that does not fit, or a broken tag table). Tags it does not use are not checked. + public static IccProfile? Parse(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + if (data.Length < 132 || data.Length > MaxBytes) return null; + var span = data.AsSpan(); + var size = BinaryPrimitives.ReadUInt32BigEndian(span); + if (size < 132 || size > data.Length || !span.Slice(36, 4).SequenceEqual("acsp"u8)) return null; + span = span[..(int)size]; + var count = BinaryPrimitives.ReadUInt32BigEndian(span[128..]); + if (count > (span.Length - 132) / 12) return null; + var tags = new Dictionary(); + for (var i = 0; i < count; i++) + { + var entry = span.Slice(132 + 12 * i, 12); + var signature = BinaryPrimitives.ReadUInt32BigEndian(entry); + var offset = BinaryPrimitives.ReadUInt32BigEndian(entry[4..]); + var length = BinaryPrimitives.ReadUInt32BigEndian(entry[8..]); + if (offset < 128 || length > span.Length || offset > span.Length - length) continue; + tags.TryAdd(signature, ((int)offset, (int)length)); + } + ReadOnlySpan TagData(uint signature, ReadOnlySpan all) => + tags.TryGetValue(signature, out var t) ? all.Slice(t.Offset, t.Length) : default; + + var colorSpace = BinaryPrimitives.ReadUInt32BigEndian(span[16..]); + var pcs = BinaryPrimitives.ReadUInt32BigEndian(span[20..]); + var description = Text(TagData(Tag("desc"), span)); + Matrix3? colorants = null; + IccCurve[]? curves = null; + if (pcs == Xyz && colorSpace == Rgb) + { + var columns = new Vector3D[3]; + var matrix = true; + for (var c = 0; c < 3 && matrix; c++) + { + if (XyzValue(TagData(RgbColorants[c], span)) is { } column) columns[c] = column; + else matrix = false; + } + if (matrix) colorants = Matrix3.FromColumns(columns[0], columns[1], columns[2]); + curves = new IccCurve[3]; + for (var c = 0; c < 3 && curves is not null; c++) + { + if (IccCurve.Parse(TagData(RgbCurves[c], span)) is { } curve) curves[c] = curve; + else curves = null; + } + if (colorants is { } m && !(double.IsFinite(m.Determinant) && m.TryInvert(out _))) colorants = null; + } + else if (pcs == Xyz && colorSpace == Gray && IccCurve.Parse(TagData(Tag("kTRC"), span)) is { } gray) + { + curves = [gray]; + } + return new IccProfile(data, colorSpace, description, colorants, curves); + } + + /// + /// A version 2.1 RGB display profile (ICC.1:2001-04): its colorants from the primaries and white, adapted to the D50 PCS + /// with Bradford; its media white; the same tone curve for the three channels. + /// + internal static IccProfile Synthesize(string description, Chromaticity red, Chromaticity green, Chromaticity blue, IccCurve curve) + { + var white = Chromaticity.D65; + var colorants = Matrix3.BradfordAdaptation(white.ToXyz(), PcsWhite) * Matrix3.RgbToXyz(red, green, blue, white); + var text = Encoding.ASCII.GetBytes(description + "\0"); + var desc = new byte[12 + text.Length + 4 + 4 + 2 + 1 + 67]; + "desc"u8.CopyTo(desc); + BinaryPrimitives.WriteUInt32BigEndian(desc.AsSpan(8), (uint)text.Length); + text.CopyTo(desc.AsSpan(12)); + var cprt = Encoding.ASCII.GetBytes("text\0\0\0\0No copyright, use freely\0"); + var trc = curve.Encode(); + (uint Signature, byte[] Data)[] tags = + [ + (Tag("desc"), desc), + (Tag("cprt"), cprt), + (Tag("wtpt"), XyzTag(white.ToXyz())), + (Tag("rXYZ"), XyzTag(new Vector3D(colorants.M11, colorants.M21, colorants.M31))), + (Tag("gXYZ"), XyzTag(new Vector3D(colorants.M12, colorants.M22, colorants.M32))), + (Tag("bXYZ"), XyzTag(new Vector3D(colorants.M13, colorants.M23, colorants.M33))), + (Tag("rTRC"), trc), + (Tag("gTRC"), trc), + (Tag("bTRC"), trc), + ]; + using var body = new MemoryStream(); + var offsets = new Dictionary(ReferenceEqualityComparer.Instance); + var start = 128 + 4 + 12 * tags.Length; + var table = new byte[4 + 12 * tags.Length]; + BinaryPrimitives.WriteUInt32BigEndian(table, (uint)tags.Length); + for (var i = 0; i < tags.Length; i++) + { + var (signature, data) = tags[i]; + if (!offsets.TryGetValue(data, out var offset)) + { + offset = start + (int)body.Length; + offsets[data] = offset; + body.Write(data); + while (body.Length % 4 != 0) body.WriteByte(0); + } + BinaryPrimitives.WriteUInt32BigEndian(table.AsSpan(4 + 12 * i), signature); + BinaryPrimitives.WriteUInt32BigEndian(table.AsSpan(8 + 12 * i), (uint)offset); + BinaryPrimitives.WriteUInt32BigEndian(table.AsSpan(12 + 12 * i), (uint)data.Length); + } + var profile = new byte[start + body.Length]; + var header = profile.AsSpan(0, 128); + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)profile.Length); + BinaryPrimitives.WriteUInt32BigEndian(header[8..], 0x02100000); + "mntrRGB XYZ "u8.CopyTo(header[12..]); + ushort[] date = [2026, 10, 27, 0, 0, 0]; + for (var i = 0; i < date.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(header[(24 + 2 * i)..], date[i]); + "acsp"u8.CopyTo(header[36..]); + S15Fixed16(PcsWhite, header[68..]); + table.CopyTo(profile.AsSpan(128)); + body.ToArray().CopyTo(profile.AsSpan(start)); + return Parse(profile) ?? throw new InvalidOperationException("A synthesized ICC profile did not parse."); + } + + internal static double S15Fixed16(ReadOnlySpan value) => BinaryPrimitives.ReadInt32BigEndian(value) / 65536.0; + + private static void S15Fixed16(Vector3D value, Span destination) + { + BinaryPrimitives.WriteInt32BigEndian(destination, (int)Math.Round(value.X * 65536)); + BinaryPrimitives.WriteInt32BigEndian(destination[4..], (int)Math.Round(value.Y * 65536)); + BinaryPrimitives.WriteInt32BigEndian(destination[8..], (int)Math.Round(value.Z * 65536)); + } + + private static byte[] XyzTag(Vector3D value) + { + var tag = new byte[20]; + "XYZ "u8.CopyTo(tag); + S15Fixed16(value, tag.AsSpan(8)); + return tag; + } + + private static Vector3D? XyzValue(ReadOnlySpan tag) + { + if (tag.Length < 20 || !tag[..4].SequenceEqual("XYZ "u8)) return null; + return new Vector3D(S15Fixed16(tag[8..]), S15Fixed16(tag[12..]), S15Fixed16(tag[16..])); + } + + /// The text of a textDescriptionType (v2 'desc'), multiLocalizedUnicodeType (v4 'mluc', its first record) or + /// textType tag; null for anything else. + private static string? Text(ReadOnlySpan tag) + { + if (tag.Length < 12) return null; + var type = tag[..4]; + if (type.SequenceEqual("desc"u8)) + { + var count = BinaryPrimitives.ReadUInt32BigEndian(tag[8..]); + if (count == 0 || count > (uint)(tag.Length - 12)) return null; + return Encoding.ASCII.GetString(tag.Slice(12, (int)count)).TrimEnd('\0'); + } + if (type.SequenceEqual("mluc"u8) && tag.Length >= 28) + { + var records = BinaryPrimitives.ReadUInt32BigEndian(tag[8..]); + var length = BinaryPrimitives.ReadUInt32BigEndian(tag[20..]); + var offset = BinaryPrimitives.ReadUInt32BigEndian(tag[24..]); + if (records == 0 || length > (uint)tag.Length || offset > (uint)tag.Length - length) return null; + return Encoding.BigEndianUnicode.GetString(tag.Slice((int)offset, (int)length & ~1)).TrimEnd('\0'); + } + if (type.SequenceEqual("text"u8)) return Encoding.ASCII.GetString(tag[8..]).TrimEnd('\0'); + return null; + } + + private static uint Tag(string signature) => BinaryPrimitives.ReadUInt32BigEndian(Encoding.ASCII.GetBytes(signature)); +} diff --git a/src/Chronos.Core/Codecs/Icc/SourceColor.cs b/src/Chronos.Core/Codecs/Icc/SourceColor.cs new file mode 100644 index 00000000..19afd573 --- /dev/null +++ b/src/Chronos.Core/Codecs/Icc/SourceColor.cs @@ -0,0 +1,261 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Chronos.Core.Imaging; +using Chronos.Core.Metadata; +using Chronos.Core.Metadata.Bmff; +using Chronos.Core.Metadata.Jpeg; +using Chronos.Core.Metadata.Tiff; + +namespace Chronos.Core.Codecs.Icc; + +/// +/// What a photo's file says of the colour space its pixel values are in (owner review 2, R7), read from its headers only: +/// nothing (: sRGB, as every decoder reads it), an ICC profile (embedded: JPEG APP2 ICC_PROFILE, PNG +/// iCCP, TIFF InterColorProfile, HEIF/AVIF colr 'prof', WebP ICCP; or the one a marker names: Exif ColorSpace uncalibrated +/// with Interop index "R03" is Adobe RGB, a HEIF nclx box with P3 primaries is Display P3), or something no profile here +/// describes (: a profile that does not parse, Exif uncalibrated without R03, an nclx box with other +/// primaries or an HDR transfer). Camera RAWs and other formats say nothing here: their decoders give Rec.709 pixels. +/// +public sealed class SourceColor +{ + private const int MaxChunks = 4096; + private const ushort Uncalibrated = 0xFFFF, AdobeRgbColorSpace = 2; + private static ReadOnlySpan IccSignature => "ICC_PROFILE\0"u8; + + private SourceColor(IccProfile? profile, bool unknown) + { + Profile = profile; + IsUnknown = unknown; + } + + /// No colour space recorded: the pixel values are sRGB. + public static SourceColor Untagged { get; } = new(null, false); + + /// A colour space recorded that no profile here describes. + public static SourceColor Unknown { get; } = new(null, true); + + /// The profile the pixel values are in; null when untagged or unknown. + public IccProfile? Profile { get; } + + public bool IsUnknown { get; } + + /// The colour space of the photo at , whose signature says . + /// The file cannot be read. + public static SourceColor Read(string path, ImageFileFormat format) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + if (!Reads(format)) return Untagged; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16, FileOptions.RandomAccess); + return Read(stream, format); + } + + /// + /// Headers this reader cannot make sense of record a space it does not know (). + public static SourceColor Read(Stream stream, ImageFileFormat format) + { + ArgumentNullException.ThrowIfNull(stream); + try + { + return ImageFormatInfo.Of(format).Family switch + { + ImageFamily.Jpeg => Jpeg(stream), + ImageFamily.Png => Png(stream), + ImageFamily.Tiff => Tiff(stream), + ImageFamily.Heif => Heif(stream), + ImageFamily.WebP => WebP(stream), + _ => Untagged, + }; + } + catch (Exception ex) when (ex is InvalidDataException or ArgumentException or OverflowException or FormatException) + { + return Unknown; + } + } + + /// Whether files of are looked into (the formats whose pixel values a profile may describe). + public static bool Reads(ImageFileFormat format) => + ImageFormatInfo.Of(format).Family is ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff or ImageFamily.Heif or ImageFamily.WebP; + + private static SourceColor Of(byte[]? icc) => icc is null ? Unknown : IccProfile.Parse(icc) is { } profile ? new SourceColor(profile, false) : Unknown; + + /// APP2 ICC_PROFILE chunks in sequence order (ICC.1 Annex B.4), else the Exif colour space of the first APP1 Exif. + private static SourceColor Jpeg(Stream stream) + { + var scanner = new JpegParser.SegmentScanner(stream, 0, stream.Length, long.MaxValue); + if (!scanner.StartsWithSoi()) return Untagged; + SortedDictionary? chunks = null; + var declared = 0; + long total = 0; + SourceColor? exif = null; + Span head = stackalloc byte[14]; + while (scanner.Next(out var segment)) + { + if (segment.Marker is 0xDA or 0xD9) break; + if (segment.Marker == 0xE2 && segment.Length > head.Length && stream.TryReadAt(segment.Payload, head) && head[..12].SequenceEqual(IccSignature)) + { + chunks ??= []; + declared = head[13]; + total += segment.Length - head.Length; + if (total > IccProfile.MaxBytes) return Unknown; + chunks[head[12]] = stream.ReadAt(segment.Payload + head.Length, segment.Length - head.Length, IccProfile.MaxBytes) ?? []; + } + else if (segment.Marker == 0xE1 && exif is null && segment.Length > 14 && stream.TryReadAt(segment.Payload, head[..6]) && head[..6].SequenceEqual("Exif\0\0"u8)) + { + exif = Exif(TiffReader.Open(stream, segment.Payload + 6)); + } + } + if (chunks is null) return exif ?? Untagged; + // Every chunk from 1 to the count the chunks declare, once each. + if (declared == 0 || chunks.Count != declared || chunks.Keys.First() != 1 || chunks.Keys.Last() != declared) return Unknown; + return Of([.. chunks.Values.SelectMany(c => c)]); + } + + /// iCCP (zlib-compressed after its name and method byte) or sRGB before the image data. + private static SourceColor Png(Stream stream) + { + Span head = stackalloc byte[8]; + long position = 8; + for (var i = 0; i < MaxChunks && stream.TryReadAt(position, head); i++) + { + var length = BinaryPrimitives.ReadUInt32BigEndian(head); + var type = head[4..]; + var data = position + 8; + if (type.SequenceEqual("IDAT"u8) || type.SequenceEqual("IEND"u8) || length > int.MaxValue) break; + if (type.SequenceEqual("sRGB"u8)) return Untagged; + if (type.SequenceEqual("iCCP"u8)) + { + if (stream.ReadAt(data, length, IccProfile.MaxBytes) is not { } chunk) return Unknown; + var name = Array.IndexOf(chunk, (byte)0); + if (name < 1 || name + 2 > chunk.Length || chunk[name + 1] != 0) return Unknown; + return Of(Inflate(chunk.AsMemory(name + 2))); + } + position = data + length + 4; + } + return Untagged; + } + + /// IFD0's InterColorProfile, else the colour space its Exif IFD records. + private static SourceColor Tiff(Stream stream) + { + if (TiffReader.Open(stream) is not { } reader || reader.ReadIfd(reader.FirstIfdOffset) is not { } ifd0) return Untagged; + if (ifd0.Entries.TryGetValue(TiffTags.InterColorProfile, out var entry)) return Of(reader.ReadBytes(entry, IccProfile.MaxBytes)); + return Exif(reader, ifd0) ?? Untagged; + } + + /// The colr properties of the primary item: an ICC profile ('prof', 'rICC') first, else its nclx box. + private static SourceColor Heif(Stream stream) + { + if (BmffReader.Find(BmffReader.ReadChildren(stream, 0, stream.Length), "meta") is not { } meta) return Untagged; + var children = BmffReader.ReadChildren(stream, meta.PayloadStart + 4, meta.End); + if (BmffReader.Find(children, "pitm") is not { } pitm || BmffReader.Find(children, "iprp") is not { } iprp) return Untagged; + Span item = stackalloc byte[8]; + var read = stream.ReadUpTo(pitm.PayloadStart, item[..(int)Math.Min(item.Length, pitm.PayloadLength)]); + if (read < 6) return Untagged; + uint primary = item[0] == 0 ? BinaryPrimitives.ReadUInt16BigEndian(item[4..]) : read >= 8 ? BinaryPrimitives.ReadUInt32BigEndian(item[4..]) : 0; + var properties = BmffReader.ReadChildren(stream, iprp.PayloadStart, iprp.End); + if (BmffReader.Find(properties, "ipco") is not { } ipco || BmffReader.Find(properties, "ipma") is not { } ipma) return Untagged; + var boxes = BmffReader.ReadChildren(stream, ipco.PayloadStart, ipco.End); + var colours = Associations(stream, ipma, primary).Where(i => i >= 1 && i <= boxes.Count && boxes[i - 1].Is("colr")).ToList(); + // A grid whose colour only its tiles carry (as libheif reads it): the colour of the items it is made of. + if (colours.Count == 0) colours = [.. Enumerable.Range(1, boxes.Count).Where(i => boxes[i - 1].Is("colr"))]; + SourceColor? nclx = null; + foreach (var index in colours) + { + var colr = boxes[index - 1]; + if (stream.ReadAt(colr.PayloadStart, colr.PayloadLength, IccProfile.MaxBytes + 4) is not { Length: >= 4 } data) return Unknown; + var type = data.AsSpan(0, 4); + if (type.SequenceEqual("prof"u8) || type.SequenceEqual("rICC"u8)) return Of(data[4..]); + if (type.SequenceEqual("nclx"u8) && data.Length >= 10) nclx ??= Nclx(BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(4)), BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(6))); + } + return nclx ?? Untagged; + } + + /// + /// An nclx box (ISO/IEC 23091-2 code points): BT.709 primaries (or unspecified) with an SDR transfer are sRGB, P3 D65 + /// primaries (12) with one are Display P3; other primaries (BT.2020…) or an HDR transfer (PQ, HLG) are unknown here. + /// + private static SourceColor Nclx(int primaries, int transfer) + { + var sdr = transfer is 1 or 2 or 6 or 13 or 14 or 15; + if (!sdr) return Unknown; + return primaries switch + { + 1 or 2 => Untagged, + 12 => new SourceColor(IccProfile.DisplayP3, false), + _ => Unknown, + }; + } + + /// The ipco indices (1-based) associated with in an ipma box. + private static List Associations(Stream stream, BmffBox ipma, uint primary) + { + var result = new List(); + if (stream.ReadAt(ipma.PayloadStart, ipma.PayloadLength, 1 << 20) is not { } data) return result; + var r = new SpanReader(data); + var version = r.U8(); + r.Skip(2); + var wide = (r.U8() & 1) != 0; + var count = r.U32(); + for (uint i = 0; i < count && r.Ok; i++) + { + var id = version < 1 ? r.U16() : r.U32(); + var associations = r.U8(); + for (var a = 0; a < associations && r.Ok; a++) + { + var index = wide ? r.U16() & 0x7FFF : r.U8() & 0x7F; + if (id == primary && r.Ok) result.Add(index); + } + } + return result; + } + + /// The ICCP chunk of an extended WebP (RIFF), which comes before the image data. + private static SourceColor WebP(Stream stream) + { + Span head = stackalloc byte[12]; + if (!stream.TryReadAt(0, head) || !head[..4].SequenceEqual("RIFF"u8) || !head[8..].SequenceEqual("WEBP"u8)) return Untagged; + long position = 12; + for (var i = 0; i < MaxChunks && stream.TryReadAt(position, head[..8]); i++) + { + var size = BinaryPrimitives.ReadUInt32LittleEndian(head[4..]); + if (head[..4].SequenceEqual("ICCP"u8)) return Of(stream.ReadAt(position + 8, size, IccProfile.MaxBytes)); + if (head[..4].SequenceEqual("VP8 "u8) || head[..4].SequenceEqual("VP8L"u8) || head[..4].SequenceEqual("ANIM"u8)) break; + position += 8 + size + (size & 1); + } + return Untagged; + } + + /// The colour space an Exif block records: uncalibrated with Interop index "R03" (or the non-standard 2) is Adobe RGB, uncalibrated otherwise unknown; null when it records sRGB or nothing. + private static SourceColor? Exif(TiffReader? reader) => reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd0 ? Exif(reader, ifd0) : null; + + private static SourceColor? Exif(TiffReader reader, Ifd ifd0) + { + if (reader.GetUInt(ifd0, TiffTags.ExifIfd) is not { } offset || reader.ReadIfd(offset) is not { } exif) return null; + var space = reader.GetUInt(exif, TiffTags.ColorSpace); + if (space == AdobeRgbColorSpace) return new SourceColor(IccProfile.AdobeRgb, false); + if (space != Uncalibrated) return null; + var interop = reader.GetUInt(exif, TiffTags.InteropIfd) is { } at && reader.ReadIfd(at) is { } ifd ? reader.GetString(ifd, TiffTags.InteropIndex) : null; + return interop == "R03" ? new SourceColor(IccProfile.AdobeRgb, false) : Unknown; + } + + private static byte[]? Inflate(ReadOnlyMemory compressed) + { + try + { + using var z = new ZLibStream(new MemoryStream(compressed.ToArray(), writable: false), CompressionMode.Decompress); + using var profile = new MemoryStream(); + var buffer = new byte[16 * 1024]; + int read; + while ((read = z.Read(buffer)) > 0) + { + if (profile.Length + read > IccProfile.MaxBytes) return null; + profile.Write(buffer, 0, read); + } + return profile.ToArray(); + } + catch (InvalidDataException) + { + return null; + } + } +} diff --git a/src/Chronos.Core/Codecs/Jpeg/JpegEncoder.cs b/src/Chronos.Core/Codecs/Jpeg/JpegEncoder.cs index b270995c..32b3b0a0 100644 --- a/src/Chronos.Core/Codecs/Jpeg/JpegEncoder.cs +++ b/src/Chronos.Core/Codecs/Jpeg/JpegEncoder.cs @@ -34,6 +34,12 @@ public sealed record JpegEncodeOptions /// namespace + packet); at most 65533 bytes each. When present the JFIF APP0 segment is omitted (Exif layout). public IReadOnlyList? App1Segments { get; init; } + /// + /// ICC profile of the colour space the encoded values are in, written after the APP1 segments as APP2 "ICC_PROFILE" + /// chunks (ICC.1 Annex B.4: at most 65519 bytes each, numbered from 1); null writes none (sRGB). + /// + public byte[]? IccProfile { get; init; } + /// Ordered dither when quantising linear float input to 8-bit sRGB. public bool Dither { get; init; } @@ -407,6 +413,7 @@ public static class JpegEncoder { Segment(h, JpegTables.App0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]); } + if (o.IccProfile is { Length: > 0 } icc) IccSegments(h, icc); var tables = p.Components == 1 ? 1 : 2; var dqt = new byte[65 * tables]; for (var t = 0; t < tables; t++) @@ -464,6 +471,24 @@ public static class JpegEncoder s.Write(code.Values); } + /// The profile split into APP2 chunks: "ICC_PROFILE\0", the chunk's number from 1, the count, its bytes. + private static void IccSegments(Stream s, byte[] profile) + { + const int chunk = 65533 - 14; + var count = (profile.Length + chunk - 1) / chunk; + if (count > 255) throw new ArgumentException("ICC profile exceeds 255 APP2 chunks", nameof(profile)); + for (var i = 0; i < count; i++) + { + var part = profile.AsSpan(i * chunk, Math.Min(chunk, profile.Length - i * chunk)); + var payload = new byte[14 + part.Length]; + "ICC_PROFILE\0"u8.CopyTo(payload); + payload[12] = (byte)(i + 1); + payload[13] = (byte)count; + part.CopyTo(payload.AsSpan(14)); + Segment(s, JpegTables.App2, payload); + } + } + internal static void Segment(Stream s, byte marker, ReadOnlySpan payload) { var length = payload.Length + 2; diff --git a/src/Chronos.Core/Codecs/Jpeg/JpegTables.cs b/src/Chronos.Core/Codecs/Jpeg/JpegTables.cs index 3a985df4..d6b175ed 100644 --- a/src/Chronos.Core/Codecs/Jpeg/JpegTables.cs +++ b/src/Chronos.Core/Codecs/Jpeg/JpegTables.cs @@ -4,7 +4,7 @@ namespace Chronos.Core.Codecs.Jpeg; internal static class JpegTables { public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC; - public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE; + public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App2 = 0xE2, App14 = 0xEE; /// Natural (row-major) index of the coefficient at each zig-zag position. public static ReadOnlySpan NaturalOrder => diff --git a/src/Chronos.Core/Codecs/Tiff/TiffWriter.cs b/src/Chronos.Core/Codecs/Tiff/TiffWriter.cs index 1a0bfcd0..966b64d8 100644 --- a/src/Chronos.Core/Codecs/Tiff/TiffWriter.cs +++ b/src/Chronos.Core/Codecs/Tiff/TiffWriter.cs @@ -34,6 +34,9 @@ public sealed record TiffWriteOptions /// TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded. public byte[]? Exif { get; init; } + /// ICC profile of the colour space the samples are in (InterColorProfile, tag 34675); null writes none (sRGB). + public byte[]? IccProfile { get; init; } + /// Worker limit for strip encoding (-1 = all cores). public int MaxDegreeOfParallelism { get; init; } = -1; } @@ -171,6 +174,7 @@ public static class TiffWriter ifd.Ascii(TiffTags.Software, "Chronos"); if (predictor) ifd.Short(TiffTags.Predictor, 2); if (channels == 4) ifd.Short(TiffTags.ExtraSamples, 2); + if (o.IccProfile is { Length: > 0 } icc) ifd.Add(TiffTags.InterColorProfile, TiffType.Undefined, icc.Length, icc); if (o.Exif is { } exif) ifd.AttachExif(exif); WriteDirectory(output, start, ifd); } diff --git a/src/Chronos.Core/Conversion/ConvertOptions.cs b/src/Chronos.Core/Conversion/ConvertOptions.cs index 25e0c063..58975887 100644 --- a/src/Chronos.Core/Conversion/ConvertOptions.cs +++ b/src/Chronos.Core/Conversion/ConvertOptions.cs @@ -62,6 +62,9 @@ public sealed record ConvertOptions(ConvertTarget Target, int Quality = ConvertO _ => "DNG", }; + /// Whether the target keeps 16 bits per channel (TIFF-16, linear DNG), which an 8-bit development of a RAW does not fill. + public bool IsSixteenBit => Target != ConvertTarget.Jpeg; + /// The quality that counts: the JPEG's, 0 for the lossless targets. public int EffectiveQuality => Target == ConvertTarget.Jpeg ? Quality : 0; diff --git a/src/Chronos.Core/Conversion/ConvertPlanner.cs b/src/Chronos.Core/Conversion/ConvertPlanner.cs index 793f0b36..a9dccc50 100644 --- a/src/Chronos.Core/Conversion/ConvertPlanner.cs +++ b/src/Chronos.Core/Conversion/ConvertPlanner.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Security.Cryptography; using System.Text; using Chronos.Core.Archiving; +using Chronos.Core.Codecs.Icc; using Chronos.Core.Export; using Chronos.Core.Imaging; using Chronos.Core.Model; @@ -28,6 +29,15 @@ public enum ConvertSkip /// The photo was never hashed (adopted, not verified yet): its replacement could not name it. Verify it first. Unhashed, + + /// A 16-bit target, and this host develops the RAW at 8 bits only (WIC's Raw Image Extension): JPEG converts it. + EightBit, + + /// The photo's colour profile can be neither carried into the target nor converted to it (CMYK, an unknown space…). + ColorProfile, + + /// The photo is larger than the target holds (a JPEG side above 65535) or one image in memory can. + TooLarge, } /// Why a whole sequence is not converted now; nothing of it is touched. @@ -117,12 +127,18 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert /// /// Plans the conversion of a sequence's frames (owner review 2, R7): a frame is converted when it is not in the target's -/// format already, its file is there, it was hashed, it is not flagged unreadable, and this host decodes it at full -/// resolution (its format has a native decoder here, and the tier the last host to decode it recorded is native, or the -/// file probes native now). Sizes after are estimated from the pixels (). +/// format already, its file is there, it was hashed, it is not flagged unreadable, the target holds its size, this host +/// decodes it at full resolution with the decoders the conversion uses (: its format +/// has a native decoder here and the file itself probes native now, whatever tier another host or an earlier pass +/// recorded; for a 16-bit target, not through a RAW development at 8 bits), and its colour profile can be kept +/// (). The plan asks the files what the conversion will ask them, reading headers +/// only, several at once. Sizes after are estimated from the pixels (). /// public static class ConvertPlanner { + /// Files asked at once while a sequence is planned: header reads, bound by the disk more than the cores. + private const int ProbesAtOnce = 8; + /// Margin over the estimate the free space must hold (estimates of compressed files vary with the content). public const double SpaceMargin = 1.15; @@ -151,11 +167,15 @@ public static class ConvertPlanner ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(decoder); var onDisk = present as IReadOnlySet ?? new HashSet(present, StringComparer.OrdinalIgnoreCase); + var reasons = new ConvertSkip?[manifest.Frames.Count]; + Parallel.For(0, reasons.Length, new ParallelOptions { MaxDegreeOfParallelism = ProbesAtOnce }, + i => reasons[i] = Skip(manifest.Frames[i], folder, onDisk, options, decoder)); var skipped = new Dictionary(); var frames = new List(); - foreach (var frame in manifest.Frames) + for (var i = 0; i < reasons.Length; i++) { - if (Skip(frame, folder, onDisk, options, decoder) is { } reason) + var frame = manifest.Frames[i]; + if (reasons[i] is { } reason) { skipped[reason] = skipped.GetValueOrDefault(reason) + 1; continue; @@ -167,21 +187,51 @@ public static class ConvertPlanner } /// Why is not converted, or null when it is. + /// This host's decoders; the conversion's are made from them (). public static ConvertSkip? Skip(SidecarFrame frame, SequencePaths folder, IReadOnlySet present, ConvertOptions options, ImageDecoder decoder) { ArgumentNullException.ThrowIfNull(frame); + ArgumentNullException.ThrowIfNull(folder); + ArgumentNullException.ThrowIfNull(present); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(decoder); if (frame.Format == options.Format) return ConvertSkip.SameFormat; if ((frame.Flags & FrameFlags.Missing) != 0 || !present.Contains(frame.File)) return ConvertSkip.Missing; if (frame.Sha256 is null) return ConvertSkip.Unhashed; if ((frame.Flags & (FrameFlags.Undecodable | FrameFlags.Corrupt)) != 0) return ConvertSkip.Undecodable; - if (decoder.TierFor(frame.Format) != DecodeTier.Native) return ConvertSkip.NoNativeDecoder; - // Recorded below the native tier by the last host to decode it (one without this host's decoders, or a body its RAW - // decoder does not support): this host asks the file itself. - if (frame.Tier is DecodeTier.EmbeddedPreview or DecodeTier.Unavailable || (frame.Flags & FrameFlags.PreviewOnly) != 0) - return Probe(frame, folder, decoder); - return null; + if (TooLarge(options, frame.W, frame.H)) return ConvertSkip.TooLarge; + var decoders = FrameConverter.Decoders(decoder, options, frame.Format); + var eightBit = FrameConverter.OnlyAt8Bits(decoder, options, frame.Format); + if (decoders.TierFor(frame.Format) != DecodeTier.Native) return eightBit ? ConvertSkip.EightBit : ConvertSkip.NoNativeDecoder; + // Whatever tier was recorded (unknown before the light analysis, or by another host with other decoders, or for a + // body this host's RAW decoder does not support), the file itself is asked: headers only, and nothing at all for the + // formats every file of which decodes alike. + var path = folder.File(frame.File); + try + { + var probe = decoders.Probe(path, frame.Format); + if (probe.Tier != DecodeTier.Native) + return probe.Tier == DecodeTier.EmbeddedPreview ? eightBit ? ConvertSkip.EightBit : ConvertSkip.PreviewOnly : ConvertSkip.Undecodable; + if (TooLarge(options, probe.Width, probe.Height)) return ConvertSkip.TooLarge; + return FrameConverter.Treatment(SourceColor.Read(path, frame.Format), options.Target) == ColorTreatment.Refuse ? ConvertSkip.ColorProfile : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return ConvertSkip.Missing; + } + } + + /// + /// Whether a frame of × (unknown: 0) cannot be converted to + /// : a JPEG side above , more samples than one image + /// buffer indexes, or an estimated file larger than the array it is made in. + /// + public static bool TooLarge(ConvertOptions options, int width, int height) + { + ArgumentNullException.ThrowIfNull(options); + if (width <= 0 || height <= 0) return false; + if (options.Target == ConvertTarget.Jpeg && Math.Max(width, height) > FrameConverter.MaxJpegSide) return true; + return (long)width * height * 3 > Array.MaxLength || EstimateBytes(options, width, height) > Array.MaxLength; } /// @@ -204,21 +254,4 @@ public static class ConvertPlanner /// The free space a conversion whose files are estimated at bytes needs. public static long Required(long estimated) => (long)Math.Ceiling(Math.Max(0, estimated) * SpaceMargin) + SpaceReserve; - - private static ConvertSkip? Probe(SidecarFrame frame, SequencePaths folder, ImageDecoder decoder) - { - try - { - return decoder.Probe(folder.File(frame.File), frame.Format).Tier switch - { - DecodeTier.Native => null, - DecodeTier.EmbeddedPreview => ConvertSkip.PreviewOnly, - _ => ConvertSkip.Undecodable, - }; - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - return ConvertSkip.Missing; - } - } } diff --git a/src/Chronos.Core/Conversion/FrameConverter.cs b/src/Chronos.Core/Conversion/FrameConverter.cs index 4162e30f..3ddc7a50 100644 --- a/src/Chronos.Core/Conversion/FrameConverter.cs +++ b/src/Chronos.Core/Conversion/FrameConverter.cs @@ -1,11 +1,14 @@ using System.Security.Cryptography; using Chronos.Core.Archiving; using Chronos.Core.Codecs.Dng; +using Chronos.Core.Codecs.Icc; using Chronos.Core.Codecs.Jpeg; using Chronos.Core.Codecs.Tiff; using Chronos.Core.Imaging; using Chronos.Core.Imaging.Decoders; using Chronos.Core.IO; +using Chronos.Core.Localization; +using Chronos.Core.Mathematics; using Chronos.Core.Metadata; using Chronos.Core.Model; @@ -18,35 +21,118 @@ public sealed record ConvertSource(string Path, SidecarFrame Frame, SidecarCamer /// A converted file as written and verified: where it is, its size and SHA-256, its format and its upright size. public sealed record ConvertedFile(string Path, long Size, string Sha256, ImageFileFormat Format, int Width, int Height); -/// A photo could not be converted, or its converted file did not verify; nothing of it is kept. -public sealed class ConversionException(string message, Exception? inner = null) : IOException(message, inner); +/// Why a photo was not converted; each has its sentence, Archive.Convert.Failed.<reason>. +public enum ConversionFailure +{ + /// No decoder of this host reads the photo at full resolution. + NoDecoder, + + /// This host reads the photo only from its embedded preview. + PreviewOnly, + + /// A 16-bit target, and this host develops the RAW at 8 bits only (WIC's Raw Image Extension). + EightBit, + + /// The photo's colour profile cannot be carried into the target or converted to it. + ColorProfile, + + /// The photo is larger than the target or the memory of one image holds. + TooLarge, + + /// The converted file did not verify: read back, metadata, or a decode by the server's decoders. + NotVerified, + + /// The original no longer matches the SHA-256 it was archived with. + Changed, +} + +/// A photo could not be converted, or its converted file did not verify; nothing of it is kept. The message is the +/// diagnostics log's (English, technical); chooses what the user reads (). +public sealed class ConversionException(ConversionFailure reason, string message, Exception? inner = null) : IOException(message, inner) +{ + public ConversionFailure Reason { get; } = reason; +} /// /// Converts one photo (owner review 2, R7; BRIEF §12.5): its original is decoded at full resolution only, never from an -/// embedded preview (, oriented upright), encoded by the in-house writers -/// ( 4:4:4, 16-bit sRGB with Deflate and the predictor, -/// ), with an Exif block () whose capture time, offset and exposure -/// come from the sidecar (to the tick) and whose camera, lens, modes and GPS come from the original's metadata, the -/// sequence's camera and lens filling what it lacks. The bytes are hashed as they are made and written atomically; then the -/// file is read back (its SHA-256 must match), its metadata read again (the same capture time and offset) and it is decoded -/// at full-resolution tier by the server's decoders, so every host can read it. MakerNote, XMP and ICC profiles are not -/// carried (the pixels are sRGB, or linear sRGB primaries in a DNG); the orientation is 1, the pixels being upright. +/// embedded preview (, oriented upright), by the managed decoders wherever they read it +/// natively (RAWs developed at float precision, the same on every host) and by the host's others (WIC) only for what they +/// do not (); a 16-bit target never takes a RAW developed at 8 bits. It is encoded by the in-house +/// writers ( 4:4:4, 16-bit with Deflate and the predictor, +/// scene-referred: highlights above white and colours outside sRGB kept), with an Exif block +/// () whose capture time, offset and exposure come from the sidecar (to the tick) and whose camera, +/// lens, modes and GPS come from the original's metadata, the sequence's camera and lens filling what it lacks. The colour +/// space the original's values are in () is kept: a JPEG or TIFF carries the original's ICC profile +/// (its values pass through unchanged), a DNG gets them converted through the profile's matrix and curves, a gray profile +/// is converted to sRGB; a profile none of that applies to refuses the photo (). The bytes are hashed +/// as they are made and written atomically; then the file is read back (its SHA-256 must match), its metadata read again +/// (the same capture time and offset) and it is decoded at full-resolution tier by the server's decoders, so every host can +/// read it. MakerNote and XMP are not carried; the orientation is 1, the pixels being upright. /// public static class FrameConverter { /// Long edge of the verification decode: enough to prove the full-resolution data decodes, cheap for JPEG and RAW. private const int VerifyEdge = 256; + /// Largest side of a JPEG (its frame header holds 16 bits). + public const int MaxJpegSide = 65535; + + private const int DiskFull = unchecked((int)0x80070070); + private const int HandleDiskFull = unchecked((int)0x80070027); + + /// ENOSPC, the HResult .NET gives a full disk on Linux. + private const int NoSpace = 28; + private static readonly Lazy ServerDecoders = new(DecoderFactory.CreateServer); /// The decoders a converted file must decode with at full-resolution tier: the server's (managed only). public static ImageDecoder Verifier => ServerDecoders.Value; + /// + /// The decoders a conversion to reads a photo with, from this host's + /// : the managed provider first, so every format it reads natively is decoded in-house (a RAW + /// developed at float precision, as the server does), the others (WIC) after it, for what it cannot read; for a 16-bit + /// target, a RAW never through a provider that develops RAWs at 8 bits (). + /// + public static ImageDecoder Decoders(ImageDecoder decoder, ConvertOptions options, ImageFileFormat format) + { + ArgumentNullException.ThrowIfNull(decoder); + ArgumentNullException.ThrowIfNull(options); + var eightBit = options.IsSixteenBit && ImageFormatInfo.Of(format).IsRaw; + var providers = decoder.Providers.Where(p => !(eightBit && p.DevelopsRawAt8Bits)).OrderBy(p => p is ManagedDecoderProvider ? 0 : 1).ToList(); + return providers.SequenceEqual(decoder.Providers) ? decoder : new ImageDecoder(providers); + } + + /// + /// Whether reads a photo natively only through a provider that + /// develops RAWs at 8 bits, which a conversion to does not use: the reason it is not converted. + /// + public static bool OnlyAt8Bits(ImageDecoder decoder, ConvertOptions options, ImageFileFormat format) + { + ArgumentNullException.ThrowIfNull(decoder); + ArgumentNullException.ThrowIfNull(options); + return options.IsSixteenBit && ImageFormatInfo.Of(format).IsRaw + && decoder.Providers.Any(p => p.DevelopsRawAt8Bits && p.TierFor(format) == DecodeTier.Native); + } + + /// What a conversion to does with a photo whose values are in . + public static ColorTreatment Treatment(SourceColor color, ConvertTarget target) + { + ArgumentNullException.ThrowIfNull(color); + if (color.IsUnknown) return ColorTreatment.Refuse; + if (color.Profile is not { } profile) return ColorTreatment.None; + if (profile.IsGray) return profile.IsGrayCurve ? ColorTreatment.Convert : ColorTreatment.Refuse; + if (!profile.IsRgb) return ColorTreatment.Refuse; + if (target != ConvertTarget.LinearDng) return ColorTreatment.Carry; + if (profile.IsSrgb) return ColorTreatment.None; + return profile.IsMatrixShaper ? ColorTreatment.Convert : ColorTreatment.Refuse; + } + /// Converts into (created or replaced atomically) and verifies it. - /// This host's decoders (WIC first on a desktop). + /// This host's decoders (WIC first on a desktop); the conversion orders them itself (). /// Worker limit of the encoder (-1: all cores); 1 when several photos convert at once. - /// The photo does not decode at full resolution here, or its converted file did not - /// verify (it is deleted). + /// The photo does not decode at full resolution here, at 16 bits for a 16-bit target, + /// its colour profile cannot be kept, it is too large, or its converted file did not verify (it is deleted). /// The original cannot be read, or the target cannot be written. public static ConvertedFile Convert(ConvertSource source, ConvertOptions options, ImageDecoder decoder, string target, int encoderThreads = -1, CancellationToken cancellationToken = default) @@ -57,20 +143,37 @@ public static class FrameConverter ArgumentException.ThrowIfNullOrWhiteSpace(target); if (!options.IsValid) throw new ArgumentException("Unknown target or a quality outside 1–100.", nameof(options)); var name = System.IO.Path.GetFileName(source.Path); + var format = source.Frame.Format; + var color = SourceColor.Read(source.Path, format); + var treatment = Treatment(color, options.Target); + if (treatment == ColorTreatment.Refuse) + throw new ConversionException(ConversionFailure.ColorProfile, $"{name}: its colour profile ({color.Profile?.Description ?? "unknown"}) cannot be kept in {options.Label}"); ConvertedFile file; FrameMetadata metadata; - using (var decoded = decoder.Decode(new DecodeRequest(source.Path, 0, DecodePurpose.Render, ApplyOrientation: true, AllowPreview: false), - cancellationToken)) + try { - if (decoded is null) throw new ConversionException($"{name}: no decoder here reads it at full resolution"); + using var decoded = Decoders(decoder, options, format) + .Decode(new DecodeRequest(source.Path, 0, DecodePurpose.Render, ApplyOrientation: true, AllowPreview: false), cancellationToken); + var eightBit = OnlyAt8Bits(decoder, options, format); + if (decoded is null) + { + throw new ConversionException(eightBit ? ConversionFailure.EightBit : ConversionFailure.NoDecoder, + $"{name}: no decoder here reads it at full resolution{(eightBit ? " at 16 bits" : "")}"); + } if (decoded.Tier != DecodeTier.Native || decoded.ByChoice) - throw new ConversionException($"{name}: decoded from its {decoded.Tier} only ({decoded.Decoder}), not at full resolution"); + { + throw new ConversionException(eightBit ? ConversionFailure.EightBit : ConversionFailure.PreviewOnly, + $"{name}: decoded from its {decoded.Tier} only ({decoded.Decoder}), not at full resolution"); + } + var pixels = decoded.Pixels; + if (options.Target == ConvertTarget.Jpeg && Math.Max(pixels.Width, pixels.Height) > MaxJpegSide) + throw new ConversionException(ConversionFailure.TooLarge, $"{name}: {pixels.Width}×{pixels.Height} exceeds a JPEG's {MaxJpegSide} pixels"); cancellationToken.ThrowIfCancellationRequested(); metadata = Metadata(MetadataReader.Read(source.Path, cancellationToken), source); - var pixels = decoded.Pixels; using var rgb = pixels.Channels == 3 ? null : Rgb(pixels); var image = rgb ?? pixels; - using var output = Encoded(image, metadata, options, encoderThreads); + if (treatment == ColorTreatment.Convert) ToLinearRec709(image, color.Profile!, encoderThreads, cancellationToken); + using var output = Encoded(image, metadata, options, treatment == ColorTreatment.Carry ? color.Profile!.Data : null, encoderThreads); cancellationToken.ThrowIfCancellationRequested(); // Hashed as made, and written from the same bytes (never copied again). var bytes = output.GetBuffer().AsSpan(0, (int)output.Length); @@ -78,6 +181,11 @@ public static class FrameConverter AtomicFile.WriteAllBytes(target, bytes); file = new ConvertedFile(target, bytes.Length, sha, options.Format, image.Width, image.Height); } + catch (OverflowException ex) + { + // An image whose samples exceed what one buffer indexes (a stitched panorama of hundreds of megapixels). + throw new ConversionException(ConversionFailure.TooLarge, $"{name}: too large to convert in memory", ex); + } try { Verify(file, metadata, cancellationToken); @@ -90,6 +198,27 @@ public static class FrameConverter return file; } + /// + /// Why a photo was not converted, as one localised sentence for the job log (BRIEF §0.2 rule 6): the conversion's own + /// checks by reason (), a full disk, a denied access, a file that does not + /// decode, else a file that could not be read or written. The exception's text, technical English, goes to the + /// diagnostics log only. + /// + public static string FailureText(Exception ex) + { + ArgumentNullException.ThrowIfNull(ex); + return ex switch + { + ConversionException conversion => Loc.L("Archive.Convert.Failed." + conversion.Reason), + IOException { HResult: DiskFull or HandleDiskFull } => Loc.L("Archive.Convert.Failed.Full"), + IOException { HResult: NoSpace } when !OperatingSystem.IsWindows() => Loc.L("Archive.Convert.Failed.Full"), + UnauthorizedAccessException => Loc.L("Archive.Failed.Access"), + InvalidDataException or NotSupportedException or FormatException => Loc.L("Archive.Convert.Failed.Unreadable"), + IOException => Loc.L("Archive.Failed.Files"), + _ => Loc.L("Archive.Convert.Failed.Other"), + }; + } + /// /// The Exif a converted file carries: the sidecar's capture time (to the tick), UTC offset, exposure, f-number, ISO, /// focal length, bias and white balance; the original's camera, serial, lens, 35 mm focal length, exposure program, @@ -130,14 +259,15 @@ public static class FrameConverter } /// The file bytes of (linear light, RGB) in the target format with . - public static byte[] Encode(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, int encoderThreads = -1) + /// The ICC profile the encoded values are in (a JPEG or TIFF carries it); null for sRGB. + public static byte[] Encode(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, int encoderThreads = -1, byte[]? iccProfile = null) { - using var output = Encoded(image, metadata, options, encoderThreads); + using var output = Encoded(image, metadata, options, iccProfile, encoderThreads); return output.ToArray(); } /// into a stream the caller disposes. - private static MemoryStream Encoded(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, int encoderThreads) + private static MemoryStream Encoded(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, byte[]? iccProfile, int encoderThreads) { ArgumentNullException.ThrowIfNull(image); ArgumentNullException.ThrowIfNull(metadata); @@ -154,6 +284,7 @@ public static class FrameConverter Subsampling = JpegSubsampling.Yuv444, OptimizeHuffman = true, App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]], + IccProfile = iccProfile, MaxDegreeOfParallelism = encoderThreads, }); break; @@ -165,14 +296,17 @@ public static class FrameConverter Predictor = true, Transfer = TransferFunction.Srgb, Exif = ExifWriter.BuildTiff(metadata), + IccProfile = iccProfile, MaxDegreeOfParallelism = encoderThreads, }); break; default: + // A DNG's colour is its matrices: values in another profile are converted before (Treatment), never tagged. LinearDngWriter.Write(output, image, new LinearDngOptions { Compression = DngCompression.LosslessJpeg, Exif = ExifWriter.BuildTiff(metadata), + SceneReferred = true, MaxDegreeOfParallelism = encoderThreads, }); break; @@ -180,6 +314,34 @@ public static class FrameConverter return output; } + /// + /// Values decoded as sRGB (the decoders linearise every code value with the sRGB curve) brought to linear Rec.709 + /// through the profile they really are in: each back to its code value, through the profile's curve, then its matrix + /// (a gray profile's curve gives a neutral). Values outside sRGB come out below 0 or above 1, which a scene-referred + /// DNG keeps. + /// + internal static void ToLinearRec709(ImageBuffer image, IccProfile profile, int threads, CancellationToken cancellationToken) + { + var curves = profile.Curves ?? throw new InvalidOperationException("The profile has no tone curve."); + var m = profile.IsMatrixShaper ? profile.ToLinearRec709() : Matrix3.Identity; + IccCurve red = curves[0], green = curves[Math.Min(1, curves.Count - 1)], blue = curves[Math.Min(2, curves.Count - 1)]; + Parallel.For(0, image.Height, new ParallelOptions { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken }, y => + { + var r = image.Row(0, y); + var g = image.Row(1, y); + var b = image.Row(2, y); + for (var x = 0; x < r.Length; x++) + { + var lr = red.Evaluate(ColorSpace.LinearToSrgb(r[x])); + var lg = green.Evaluate(ColorSpace.LinearToSrgb(g[x])); + var lb = blue.Evaluate(ColorSpace.LinearToSrgb(b[x])); + r[x] = (float)(m.M11 * lr + m.M12 * lg + m.M13 * lb); + g[x] = (float)(m.M21 * lr + m.M22 * lg + m.M23 * lb); + b[x] = (float)(m.M31 * lr + m.M32 * lg + m.M33 * lb); + } + }); + } + /// /// Checks a converted file: read back whole, its size and SHA-256 are those it was written with; its metadata names its /// format and the capture time and offset written into it; and the server's decoders read it at full-resolution tier, @@ -200,22 +362,24 @@ public static class FrameConverter sha = System.Convert.ToHexStringLower(SHA256.HashData(stream)); } if (length != file.Size || !string.Equals(sha, file.Sha256, StringComparison.OrdinalIgnoreCase)) - throw new ConversionException($"{name}: read back as {length} bytes with SHA-256 {sha}, written as {file.Size} bytes with {file.Sha256}"); + throw NotVerified($"{name}: read back as {length} bytes with SHA-256 {sha}, written as {file.Size} bytes with {file.Sha256}"); cancellationToken.ThrowIfCancellationRequested(); var read = MetadataReader.Read(file.Path, cancellationToken); - if (read.Format != file.Format) throw new ConversionException($"{name}: reads as {read.Format}, written as {file.Format}"); + if (read.Format != file.Format) throw NotVerified($"{name}: reads as {read.Format}, written as {file.Format}"); if (written.CapturedAt is { } captured && read.CapturedAt != captured) - throw new ConversionException($"{name}: its capture time reads {read.CapturedAt:O}, written {captured:O}"); + throw NotVerified($"{name}: its capture time reads {read.CapturedAt:O}, written {captured:O}"); if (written.CapturedAt is not null && written.UtcOffsetMinutes is { } offset && Math.Abs(offset) <= 14 * 60 && read.UtcOffsetMinutes != offset) - throw new ConversionException($"{name}: its UTC offset reads {read.UtcOffsetMinutes}, written {offset}"); + throw NotVerified($"{name}: its UTC offset reads {read.UtcOffsetMinutes}, written {offset}"); using var decoded = Verifier.Decode(new DecodeRequest(file.Path, VerifyEdge, DecodePurpose.Thumbnail, ApplyOrientation: true, AllowPreview: false), cancellationToken); if (decoded is not { Tier: DecodeTier.Native }) - throw new ConversionException($"{name}: the server's decoders do not read it at full resolution"); + throw NotVerified($"{name}: the server's decoders do not read it at full resolution"); if (decoded.SourceWidth != file.Width || decoded.SourceHeight != file.Height) - throw new ConversionException($"{name}: decodes as {decoded.SourceWidth}×{decoded.SourceHeight}, written as {file.Width}×{file.Height}"); + throw NotVerified($"{name}: decodes as {decoded.SourceWidth}×{decoded.SourceHeight}, written as {file.Width}×{file.Height}"); } + private static ConversionException NotVerified(string message) => new(ConversionFailure.NotVerified, message); + /// Three channels from one (gray) or four (alpha dropped). private static ImageBuffer Rgb(ImageBuffer image) { @@ -237,3 +401,19 @@ public static class FrameConverter } } } + +/// What a conversion does with the colour space a photo's values are in (). +public enum ColorTreatment +{ + /// sRGB (untagged, or an sRGB profile into a DNG): nothing to do. + None, + + /// A JPEG or TIFF carries the original's ICC profile; its values pass through unchanged. + Carry, + + /// The values are converted to linear Rec.709 through the profile (a DNG from a matrix/TRC profile, or a gray profile). + Convert, + + /// A profile none of that applies to (CMYK, Lab, a lookup-table RGB profile into a DNG, an unknown space): not converted. + Refuse, +} diff --git a/src/Chronos.Core/Imaging/Decoding.cs b/src/Chronos.Core/Imaging/Decoding.cs index e3cccf33..e49203b1 100644 --- a/src/Chronos.Core/Imaging/Decoding.cs +++ b/src/Chronos.Core/Imaging/Decoding.cs @@ -93,6 +93,12 @@ public interface IImageDecoderProvider bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null; + /// + /// Whether the camera RAWs this provider develops come out at 8 bits per channel (WIC's Raw Image Extension does), too + /// few to fill a 16-bit file: a conversion to TIFF-16 or linear DNG does not read RAWs through it. + /// + bool DevelopsRawAt8Bits => false; + /// /// The tier this provider would use for the file at , whose signature says /// , without decoding pixels. The default trusts ; a provider whose diff --git a/src/Chronos.Core/Metadata/Jpeg/JpegParser.cs b/src/Chronos.Core/Metadata/Jpeg/JpegParser.cs index 513bf70b..a41da14a 100644 --- a/src/Chronos.Core/Metadata/Jpeg/JpegParser.cs +++ b/src/Chronos.Core/Metadata/Jpeg/JpegParser.cs @@ -187,12 +187,13 @@ internal static class JpegParser m.AddXmp(buffer); } - private readonly record struct Segment(byte Marker, long Payload, int Length); + /// A marker segment: its marker, where its payload starts, and the payload bytes present (0 for markers without one). + internal readonly record struct Segment(byte Marker, long Payload, int Length); private readonly record struct ExtendedXmpChunk(string Guid, uint FullLength, uint Offset, long Position, int Length); /// Walks marker segments of one JPEG, reading only marker and length bytes within a read budget. - private sealed class SegmentScanner(Stream stream, long start, long end, long readBudget) + internal sealed class SegmentScanner(Stream stream, long start, long end, long readBudget) { private readonly byte[] _buffer = new byte[16]; private long _position = start + 2; diff --git a/src/Chronos.Core/Metadata/Tiff/TiffTags.cs b/src/Chronos.Core/Metadata/Tiff/TiffTags.cs index 8522bbe1..cd4da9f8 100644 --- a/src/Chronos.Core/Metadata/Tiff/TiffTags.cs +++ b/src/Chronos.Core/Metadata/Tiff/TiffTags.cs @@ -42,9 +42,16 @@ public static class TiffTags public const ushort Xmp = 0x02BC; public const ushort Copyright = 0x8298; public const ushort ExifIfd = 0x8769; + + /// InterColorProfile: the ICC profile of the image's colour space (UNDEFINED bytes). + public const ushort InterColorProfile = 0x8773; + public const ushort GpsIfd = 0x8825; public const ushort InteropIfd = 0xA005; + /// InteroperabilityIndex in the Interop IFD: "R98" (sRGB) or "R03" (Adobe RGB, DCF option file). + public const ushort InteropIndex = 0x0001; + // Exif public const ushort ExposureTime = 0x829A; public const ushort FNumber = 0x829D; diff --git a/src/Chronos.Data/Archiving/MassConverter.cs b/src/Chronos.Data/Archiving/MassConverter.cs index d8ac4acf..0d51f1de 100644 --- a/src/Chronos.Data/Archiving/MassConverter.cs +++ b/src/Chronos.Data/Archiving/MassConverter.cs @@ -302,7 +302,8 @@ public sealed class MassConverter catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) { Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the converted photos could not take their place", ex); - return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: ex.Message), []); + var cause = Loc.L(ex is UnauthorizedAccessException ? "Archive.Failed.Access" : "Archive.Failed.Files"); + return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: Loc.L("Archive.Convert.NotPlaced", cause)), []); } } @@ -337,8 +338,8 @@ public sealed class MassConverter /// /// Stage A: converts the planned frames not staged yet, several at once, each staged file appended to the journal as it - /// is consumed (in frame order). Returns the first failure (the file and why); the frames converted meanwhile stay - /// staged for a retry. + /// is consumed (in frame order). Returns the first failure (the file and why, localised; the exception goes to the + /// diagnostics log); the frames converted meanwhile stay staged for a retry. /// private async Task StageAsync(Sequence row, SequenceManifest manifest, SequencePaths folder, ConvertSequencePlan planned, Dictionary ready, string staging, ConvertOptions options, StagedLog staged, Progress progress, ConvertCallbacks callbacks, @@ -354,11 +355,16 @@ public sealed class MassConverter var atOnce = DecodeBudget.PhotosAtOnce(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), largest); var threads = atOnce > 1 ? 1 : -1; string? failure = null; + Exception? error = null; await using var work = new OrderedWork(atOnce, async result => { if (result.Conversion is not { } conversion) { - failure ??= $"{result.File}: {result.Error?.Message}"; + if (failure is null) + { + error = result.Error; + failure = Loc.L("Archive.Convert.PhotoFailed", result.File, FrameConverter.FailureText(result.Error!)); + } return; } staged.Append(row.Id, planned.FramesVersion, conversion); @@ -371,7 +377,7 @@ public sealed class MassConverter await work.AddAsync(token => Stage(frame, manifest, folder, staging, options, decoder, threads, token)).ConfigureAwait(false); } await work.CompleteAsync().ConfigureAwait(false); - if (failure is not null) Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: not converted, {failure}"); + if (failure is not null) Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: not converted", error); return failure; } @@ -387,7 +393,7 @@ public sealed class MassConverter using (var stream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1 << 20, FileOptions.SequentialScan)) sha = Convert.ToHexStringLower(SHA256.HashData(stream)); if (!string.Equals(sha, frame.Sha256, StringComparison.OrdinalIgnoreCase)) - throw new ConversionException($"{frame.File} no longer matches its SHA-256; verify the sequence"); + throw new ConversionException(ConversionFailure.Changed, $"{frame.File} no longer matches its SHA-256; verify the sequence"); cancellationToken.ThrowIfCancellationRequested(); var target = Path.Combine(staging, frame.Id.ToString("N") + options.Extension); var file = FrameConverter.Convert(new ConvertSource(source, frame, manifest.Camera, manifest.Lens), options, decoder, target, threads, cancellationToken); diff --git a/src/Chronos.Protocol/Library.cs b/src/Chronos.Protocol/Library.cs index 77eaf242..4f971201 100644 --- a/src/Chronos.Protocol/Library.cs +++ b/src/Chronos.Protocol/Library.cs @@ -140,7 +140,9 @@ public sealed record ConvertRequest(IReadOnlyList? SequenceIds, bool All, /// /// Photos of a sequence a conversion leaves as they are: same_format, convert_on_pc (the /// server cannot read them at full resolution: a CR3, a HEIC, a body its RAW decoder does not support), undecodable, -/// missing or unhashed (never verified), how many, and the reason as one localised sentence. +/// missing, unhashed (never verified), eight_bit (a RAW the host develops at 8 bits only, for a 16-bit +/// target), color_profile (a colour profile the target can neither keep nor convert to) or too_large, how +/// many, and the reason as one localised sentence. /// public sealed record ConvertSkippedDto(string Reason, int Photos, string Message); diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs index 443fe6af..471088c6 100644 --- a/src/Chronos.Server/Api/ArchiveEndpoints.cs +++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs @@ -328,7 +328,9 @@ public static class ArchiveEndpoints /// /// Wire name of why photos are not converted: same_format, convert_on_pc (a format the server has no /// full-resolution decoder for, or a file it reads only from its preview: a PC with the camera's codec may convert - /// them), undecodable, missing, unhashed. + /// them), undecodable, missing, unhashed, eight_bit (a RAW this host develops at 8 bits only, + /// for a 16-bit target), color_profile (a colour profile the target can neither keep nor convert to), + /// too_large. /// public static string Wire(ConvertSkip reason) => reason switch { @@ -336,6 +338,9 @@ public static class ArchiveEndpoints ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly => "convert_on_pc", ConvertSkip.Undecodable => "undecodable", ConvertSkip.Missing => "missing", + ConvertSkip.EightBit => "eight_bit", + ConvertSkip.ColorProfile => "color_profile", + ConvertSkip.TooLarge => "too_large", _ => "unhashed", }; diff --git a/tests/Chronos.Core.Tests/Codecs/IccProfileTests.cs b/tests/Chronos.Core.Tests/Codecs/IccProfileTests.cs new file mode 100644 index 00000000..b3810337 --- /dev/null +++ b/tests/Chronos.Core.Tests/Codecs/IccProfileTests.cs @@ -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; + +/// ICC profiles (owner review 2, R7): parsed, synthesized for the spaces a marker names, and read from each container. +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)); + } +} diff --git a/tests/Chronos.Core.Tests/Codecs/LinearDngWriterTests.cs b/tests/Chronos.Core.Tests/Codecs/LinearDngWriterTests.cs index 3d54cd63..0ab8195d 100644 --- a/tests/Chronos.Core.Tests/Codecs/LinearDngWriterTests.cs +++ b/tests/Chronos.Core.Tests/Codecs/LinearDngWriterTests.cs @@ -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); } + /// + /// 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. + /// + [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() { diff --git a/tests/Chronos.Core.Tests/Conversion/ColorFixtures.cs b/tests/Chronos.Core.Tests/Conversion/ColorFixtures.cs new file mode 100644 index 00000000..7cd51102 --- /dev/null +++ b/tests/Chronos.Core.Tests/Conversion/ColorFixtures.cs @@ -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; + +/// Photos that record their colour space: an embedded ICC profile in each container, or an Exif colour space. +internal static class ColorFixtures +{ + /// Saturated colours (a P3 photo's greens and reds fall outside sRGB once converted), plus a gradient. + 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; + } + + /// A JPEG whose values are in sRGB, with an Exif block and/or an ICC profile. + 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, + }); + + /// An Exif block recording (1 sRGB, 0xFFFF uncalibrated) and an Interop index. + 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)); + } + + /// A PNG of with an iCCP chunk after its header. + 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)]; + } + + /// A HEIF whose primary item has the colr boxes given (no image data: only its colour is read). + public static byte[] Heif(params byte[][] colr) => Heif(1, colr); + + /// A HEIF whose item has the colr boxes given; item 1 is the primary (a grid of tiles 2…). + 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]); + + /// A profile that parses but describes CMYK, which no RGB file carries. + public static byte[] Cmyk() + { + var data = (byte[])IccProfile.AdobeRgb.Data.Clone(); + "CMYK"u8.CopyTo(data.AsSpan(16)); + return data; + } + + /// A valid profile larger than one JPEG APP2 chunk holds (the Adobe RGB one padded with a private tag's room). + 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; + } +} diff --git a/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs index 0a8b9162..2dfa2d11 100644 --- a/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs +++ b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs @@ -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); } + /// + /// 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. + /// + [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)); + } + + /// + /// 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. + /// + [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))); + } + + /// A photo whose colour space no target can keep, or which a target cannot hold, is planned out with why. + [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()); } - /// A provider that reads CR2 natively by format, and probes every file at a fixed tier. - private sealed class ProbeAs(DecodeTier tier) : IImageDecoderProvider + /// A provider that reads CR2 natively by format, and probes the files picks (all + /// by default) at a fixed tier, the others native. + private sealed class ProbeAs(DecodeTier tier, Func? 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; + } + + /// WIC with the Raw Image Extension, as a conversion sees it: every camera RAW native, developed at 8 bits. + 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; } diff --git a/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs b/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs index ae4cb0fc..3451f5b9 100644 --- a/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs +++ b/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs @@ -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(() => + var preview = Assert.Throws(() => 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(() => + var none = Assert.Throws(() => 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(() => FrameConverter.Verify(file, written)); + Assert.Equal(ConversionFailure.NotVerified, Assert.Throws(() => FrameConverter.Verify(file, written)).Reason); // A capture time that is not the one written. File.WriteAllBytes(file.Path, File.ReadAllBytes(source)); Assert.Throws(() => 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); } + /// + /// 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. + /// + [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(() => + 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); + } + + /// A RAW developed above white and outside sRGB converts to a linear DNG that reads back the same. + [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(); + } + + /// + /// 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. + /// + [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); + } + + /// A colour space nothing here can keep (uncalibrated without R03, a CMYK profile) refuses the photo, whatever the target. + [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()) + { + var options = new ConvertOptions(target); + foreach (var path in (string[])[unknown, cmyk]) + { + var output = Target(options); + var refused = Assert.Throws(() => 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); + } + } + } + + /// A photo larger than the target or one buffer holds fails as too large, not with the encoder's own exception. + [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(() => 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(() => 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); + } + + /// Why a photo failed reads as one sentence by cause in the job log, never the exception's English text. + [Test] + public void FailuresReadAsOneSentenceByCause() + { + foreach (var reason in Enum.GetValues()) + { + 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"))); + } + + /// WIC with the Raw Image Extension, as a conversion sees it: every RAW native, developed at 8 bits (counted). + 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); + } + } + + /// A RAW decoder that develops every file of into a copy of . + 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); + } + + /// A decoder whose image is too large for one buffer. + 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(); + } + /// A provider that claims DNG natively but only ever gives the embedded-preview tier. private sealed class PreviewOnlyProvider : IImageDecoderProvider { diff --git a/tests/Chronos.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs b/tests/Chronos.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs index c1476b39..76789d58 100644 --- a/tests/Chronos.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs +++ b/tests/Chronos.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs @@ -21,6 +21,24 @@ public sealed class WicDecoderProviderTests(TestContext context) Assert.Null(Provider.TierFor(ImageFileFormat.Unknown)); } + /// + /// A conversion on the desktop (owner review 2, R7) reads every format the managed decoders read natively through them, + /// WIC after them, and a RAW for a 16-bit target never through WIC's Raw Image Extension (8 bits). + /// + [Test] + public void AConversionReadsWithTheManagedDecodersFirstAndRawsAtSixteenBitsWithoutWic() + { + Assert.True(((IImageDecoderProvider)Provider).DevelopsRawAt8Bits); + var desktop = Chronos.Core.Imaging.Decoders.DecoderFactory.CreateClient(Provider); + Assert.Equal("wic", desktop.Providers[0].Name); + var jpeg = Chronos.Core.Conversion.FrameConverter.Decoders(desktop, new Chronos.Core.Conversion.ConvertOptions(Chronos.Core.Conversion.ConvertTarget.Jpeg), ImageFileFormat.Cr2); + Assert.SequenceEqual(["managed", "wic"], jpeg.Providers.Select(p => p.Name)); + var tiff = Chronos.Core.Conversion.FrameConverter.Decoders(desktop, new Chronos.Core.Conversion.ConvertOptions(Chronos.Core.Conversion.ConvertTarget.Tiff16), ImageFileFormat.Cr2); + Assert.SequenceEqual(["managed"], tiff.Providers.Select(p => p.Name)); + var heif = Chronos.Core.Conversion.FrameConverter.Decoders(desktop, new Chronos.Core.Conversion.ConvertOptions(Chronos.Core.Conversion.ConvertTarget.Tiff16), ImageFileFormat.Heif); + Assert.SequenceEqual(["managed", "wic"], heif.Providers.Select(p => p.Name)); + } + [Test] public void PngMidGreyDecodesToLinearLight() { diff --git a/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs index e2a3c1b5..023b829d 100644 --- a/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs @@ -317,6 +317,9 @@ public sealed class ConvertTests(TestContext context) var job = await RunAsync(fx, engine, plan, JobState.Failed); Assert.Equal(Loc.Plural("Archive.Error.ConvertKept", 1), job.Error); Assert.Contains(damaged.FileName, job.LogTail); + // The log says why in one catalog sentence; the exception's English text stays in the diagnostics log. + Assert.Contains(Loc.L("Archive.Convert.Failed.Changed"), job.LogTail); + Assert.False(job.LogTail!.Contains("SHA-256", StringComparison.Ordinal), job.LogTail); // All or nothing: not one frame of that sequence changed, and nothing of it is in the trash. var rows = await fx.Db.Frames.ListBySequenceAsync(bad); Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256, f.RelativePath)), rows.Select(f => (f.Id, f.Sha256, f.RelativePath))); diff --git a/tests/Chronos.Server.Tests/Api/ConvertTests.cs b/tests/Chronos.Server.Tests/Api/ConvertTests.cs index 7ec53692..1324fd0b 100644 --- a/tests/Chronos.Server.Tests/Api/ConvertTests.cs +++ b/tests/Chronos.Server.Tests/Api/ConvertTests.cs @@ -182,6 +182,20 @@ public sealed class ConvertTests(TestContext context) Assert.Equal(Chronos.Core.Localization.Loc.Get("Server.Convert.OnPc", System.Globalization.CultureInfo.GetCultureInfo("it")), skipped.Message); } + /// Every reason a photo stays as it is has its wire name and its sentence in the catalog (en and it). + [Test] + public void EverySkipReasonHasItsWireNameAndSentence() + { + Assert.SequenceEqual( + ["same_format", "convert_on_pc", "convert_on_pc", "undecodable", "missing", "unhashed", "eight_bit", "color_profile", "too_large"], + Enum.GetValues().Select(Chronos.Server.Api.ArchiveEndpoints.Wire)); + foreach (var reason in Enum.GetValues()) + { + foreach (var culture in (string[])["en", "it"]) + Assert.NotNull(Chronos.Core.Localization.Loc.Get("Archive.Convert.Skipped." + reason, System.Globalization.CultureInfo.GetCultureInfo(culture))); + } + } + private static async Task UntilJobAsync(HttpClient client, Guid id, string state) { var until = DateTime.UtcNow + Wait;