fix(convert): keep what the original holds and plan only what converts
Phase 4b review, codec findings. A Replace makes the converted file the photo, so a conversion must not lose what the original held, and the dry run must promise only what the job will do. - Linear DNG from a conversion is scene-referred: the pixels are stored in linear ProPhoto primaries (colours outside sRGB stay positive) and divided by the power of two that brings their peak under the white level (at most 4 stops), with BaselineExposure giving it back and ColorMatrix1/ForwardMatrix1 describing that space. Highlights a RAW develops above 1 and its wide-gamut colours now read back as written. Exports keep the clipped linear-sRGB DNG. - A conversion reads with the managed decoders first for every format they read natively (RAWs developed at float precision, as on the server) and with WIC only for what they cannot. A RAW only WIC's Raw Image Extension develops (8 bits) is refused for TIFF-16 and linear DNG and planned out as "eight_bit"; JPEG still converts it. Providers say so through IImageDecoderProvider.DevelopsRawAt8Bits. - The original's colour space is kept: a JPEG (APP2) or TIFF (tag 34675) carries its ICC profile, with the values unchanged; a linear DNG gets the values converted through a matrix/TRC profile; a gray profile converts to sRGB. Exif Adobe RGB (uncalibrated + R03) and HEIF nclx P3 get an in-house profile. A space nothing here can keep (CMYK, a lookup-table profile into a DNG, uncalibrated without R03, HDR nclx) is planned out as "color_profile". New in-house ICC parser/writer and header reader for JPEG, PNG, TIFF, HEIF/AVIF and WebP. - The planner asks every file, whatever tier was recorded (unknown before the light analysis, or by another host), with the conversion's decoders, headers only and eight at a time; a RAW the server cannot develop is "convert_on_pc" in the plan instead of failing its sequence. Photos a target cannot hold (a JPEG side above 65535, more samples than one buffer) are planned out as "too_large", and an overflow fails its photo rather than the job. - A photo that fails reads in the job log as one catalog sentence by cause (Archive.Convert.Failed.*), the file named once; the exception's English text goes to the diagnostics log only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 0ca1e91ea09946d7a55f45695ee58e1a0ff5f779)
This commit is contained in:
1 parent
341fb77507
commit
f86a151a5d
26 files changed
+1755
-82
No files matched your search
@@ -53,6 +53,9 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format != ImageFileFormat.Dng && Inventory.IsNative(format) ? DecodeTier.Native : null;
|
||||
|
||||
/// <summary>The Raw Image Extension, the only decoder this provider develops RAWs with, gives 24bppRGB (8 bits per channel).</summary>
|
||||
public bool DevelopsRawAt8Bits => true;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>Worker limit for tile encoding (-1 = all cores).</summary>
|
||||
public int MaxDegreeOfParallelism { get; init; } = -1;
|
||||
|
||||
/// <summary>
|
||||
/// 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^<see cref="LinearDngWriter.MaxHeadroomStops"/>) 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.
|
||||
/// </summary>
|
||||
public bool SceneReferred { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="LinearDngOptions.SceneReferred"/> the data are stored in linear ProPhoto primaries with headroom instead,
|
||||
/// so highlights above 1 and colours outside sRGB survive.
|
||||
/// </summary>
|
||||
public static class LinearDngWriter
|
||||
{
|
||||
/// <summary>Most stops of headroom a scene-referred DNG keeps above diffuse white (its data then use 12 of their 16 bits below it).</summary>
|
||||
public const int MaxHeadroomStops = 4;
|
||||
|
||||
/// <summary>XYZ (D65) → linear sRGB, i.e. the inverse of the sRGB → XYZ matrix (IEC 61966-2-1).</summary>
|
||||
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();
|
||||
|
||||
/// <summary>The values a matrix tag holds once written (<see cref="Rationals"/>): what a reader computes with.</summary>
|
||||
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]);
|
||||
|
||||
/// <summary>
|
||||
/// The scene-referred encoding of one image (<see cref="LinearDngOptions.SceneReferred"/>): linear Rec.709 to linear
|
||||
/// ProPhoto, white-balanced so (1, 1, 1) stays the scene white, divided by 2^<see cref="Stops"/>.
|
||||
/// </summary>
|
||||
private sealed class SceneEncoding
|
||||
{
|
||||
/// <summary>Stored values stay below this fraction of the white level, under the 0.999 a reader takes for clipped.</summary>
|
||||
private const double Ceiling = 0.998;
|
||||
|
||||
/// <summary>Linear ProPhoto (ROMM RGB, D50) to XYZ (D50), as written.</summary>
|
||||
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)));
|
||||
|
||||
/// <summary>XYZ (D65) to linear ProPhoto with the D65 white on (1, 1, 1), as written.</summary>
|
||||
public static readonly double[] ColorMatrix = Written(Elements(
|
||||
Matrix(ForwardMatrix).Inverse() * Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), Chromaticity.D50.ToXyz())));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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))];
|
||||
}
|
||||
|
||||
/// <summary>The stops of headroom: BaselineExposure.</summary>
|
||||
public int Stops { get; }
|
||||
|
||||
/// <summary>The encoding of <paramref name="image"/>: the fewest stops that bring its peak in the stored space below the ceiling.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Row <paramref name="y"/> as interleaved 16-bit stored values.</summary>
|
||||
public void EncodeRow(ImageBuffer image, int y, Span<ushort> 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);
|
||||
|
||||
/// <summary>The red, green and blue rows of <paramref name="image"/> (gray: its one plane three times).</summary>
|
||||
private static void Rows(ImageBuffer image, int y, out Span<float> r, out Span<float> g, out Span<float> b)
|
||||
{
|
||||
r = image.Row(0, y);
|
||||
g = image.Channels >= 3 ? image.Row(1, y) : r;
|
||||
b = image.Channels >= 3 ? image.Row(2, y) : r;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Mathematics;
|
||||
|
||||
namespace Chronos.Core.Codecs.Icc;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A pure power law.</summary>
|
||||
public static IccCurve Gamma(double gamma) => new(0, [gamma], null);
|
||||
|
||||
/// <summary>The sRGB (IEC 61966-2-1) electro-optical transfer function.</summary>
|
||||
public static IccCurve Srgb { get; } = new(3, [2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045], null);
|
||||
|
||||
/// <summary>The linear value of code value <paramref name="code"/> (clamped to 0..1).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The curve of a curveType or parametricCurveType tag, or null when the tag is neither or is malformed.</summary>
|
||||
internal static IccCurve? Parse(ReadOnlySpan<byte> 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);
|
||||
}
|
||||
|
||||
/// <summary>This curve as a version 2 curveType tag: a gamma when it is one that u8Fixed8 holds, else a 1024-entry table.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="AdobeRgb"/>, <see cref="DisplayP3"/>) are
|
||||
/// version 2.1 display profiles with a matrix and curveType TRCs, read by every colour-managed program.
|
||||
/// </summary>
|
||||
public sealed class IccProfile
|
||||
{
|
||||
/// <summary>Largest profile read: big camera and printer profiles stay well below.</summary>
|
||||
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")];
|
||||
|
||||
/// <summary>The ICC D50 profile connection white (PCS illuminant).</summary>
|
||||
private static readonly Vector3D PcsWhite = new(0.9642, 1.0, 0.8249);
|
||||
|
||||
private IccProfile(byte[] data, uint colorSpace, string? description, Matrix3? colorants, IReadOnlyList<IccCurve>? curves)
|
||||
{
|
||||
Data = data;
|
||||
ColorSpace = colorSpace;
|
||||
Description = description;
|
||||
Colorants = colorants;
|
||||
Curves = curves;
|
||||
}
|
||||
|
||||
/// <summary>The profile's bytes, as embedded.</summary>
|
||||
public byte[] Data { get; }
|
||||
|
||||
/// <summary>The data colour space signature ("RGB ", "GRAY", "CMYK"…) as a big-endian four-character code.</summary>
|
||||
public uint ColorSpace { get; }
|
||||
|
||||
public bool IsRgb => ColorSpace == Rgb;
|
||||
|
||||
public bool IsGray => ColorSpace == Gray;
|
||||
|
||||
/// <summary>The profile's description (its 'desc' tag), when it has one.</summary>
|
||||
public string? Description { get; }
|
||||
|
||||
/// <summary>Whether the profile describes sRGB (its description names it: "sRGB IEC61966-2.1", "sRGB built-in"…).</summary>
|
||||
public bool IsSrgb => IsRgb && Description?.Contains("sRGB", StringComparison.Ordinal) == true;
|
||||
|
||||
/// <summary>RGB → PCS XYZ (D50) of a matrix/TRC profile: rXYZ, gXYZ and bXYZ as columns; null otherwise.</summary>
|
||||
public Matrix3? Colorants { get; }
|
||||
|
||||
/// <summary>The tone curves: red, green and blue of a matrix/TRC profile, or the gray one; null when absent.</summary>
|
||||
public IReadOnlyList<IccCurve>? Curves { get; }
|
||||
|
||||
/// <summary>Whether pixels in this profile's space convert to another through its matrix and curves alone.</summary>
|
||||
public bool IsMatrixShaper => IsRgb && Colorants is not null && Curves is { Count: 3 };
|
||||
|
||||
/// <summary>Whether this is a gray profile with its tone curve.</summary>
|
||||
public bool IsGrayCurve => IsGray && Curves is { Count: 1 };
|
||||
|
||||
/// <summary>Adobe RGB (1998) as a camera marks it in its Exif (ColorSpace uncalibrated, Interop index "R03").</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Display P3 (P3 primaries, D65, the sRGB curve) as a HEIF nclx box names it (colour primaries 12).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The profile is not a matrix/TRC one.</exception>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The profile in <paramref name="data"/>, 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.</summary>
|
||||
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<uint, (int Offset, int Length)>();
|
||||
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<byte> TagData(uint signature, ReadOnlySpan<byte> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<byte[], int>(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<byte> value) => BinaryPrimitives.ReadInt32BigEndian(value) / 65536.0;
|
||||
|
||||
private static void S15Fixed16(Vector3D value, Span<byte> 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<byte> tag)
|
||||
{
|
||||
if (tag.Length < 20 || !tag[..4].SequenceEqual("XYZ "u8)) return null;
|
||||
return new Vector3D(S15Fixed16(tag[8..]), S15Fixed16(tag[12..]), S15Fixed16(tag[16..]));
|
||||
}
|
||||
|
||||
/// <summary>The text of a textDescriptionType (v2 'desc'), multiLocalizedUnicodeType (v4 'mluc', its first record) or
|
||||
/// textType tag; null for anything else.</summary>
|
||||
private static string? Text(ReadOnlySpan<byte> 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));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="Untagged"/>: 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 (<see cref="Unknown"/>: 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.
|
||||
/// </summary>
|
||||
public sealed class SourceColor
|
||||
{
|
||||
private const int MaxChunks = 4096;
|
||||
private const ushort Uncalibrated = 0xFFFF, AdobeRgbColorSpace = 2;
|
||||
private static ReadOnlySpan<byte> IccSignature => "ICC_PROFILE\0"u8;
|
||||
|
||||
private SourceColor(IccProfile? profile, bool unknown)
|
||||
{
|
||||
Profile = profile;
|
||||
IsUnknown = unknown;
|
||||
}
|
||||
|
||||
/// <summary>No colour space recorded: the pixel values are sRGB.</summary>
|
||||
public static SourceColor Untagged { get; } = new(null, false);
|
||||
|
||||
/// <summary>A colour space recorded that no profile here describes.</summary>
|
||||
public static SourceColor Unknown { get; } = new(null, true);
|
||||
|
||||
/// <summary>The profile the pixel values are in; null when untagged or unknown.</summary>
|
||||
public IccProfile? Profile { get; }
|
||||
|
||||
public bool IsUnknown { get; }
|
||||
|
||||
/// <summary>The colour space of the photo at <paramref name="path"/>, whose signature says <paramref name="format"/>.</summary>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Read(string, ImageFileFormat)"/>
|
||||
/// <remarks>Headers this reader cannot make sense of record a space it does not know (<see cref="Unknown"/>).</remarks>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether files of <paramref name="format"/> are looked into (the formats whose pixel values a profile may describe).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>APP2 ICC_PROFILE chunks in sequence order (ICC.1 Annex B.4), else the Exif colour space of the first APP1 Exif.</summary>
|
||||
private static SourceColor Jpeg(Stream stream)
|
||||
{
|
||||
var scanner = new JpegParser.SegmentScanner(stream, 0, stream.Length, long.MaxValue);
|
||||
if (!scanner.StartsWithSoi()) return Untagged;
|
||||
SortedDictionary<int, byte[]>? chunks = null;
|
||||
var declared = 0;
|
||||
long total = 0;
|
||||
SourceColor? exif = null;
|
||||
Span<byte> 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)]);
|
||||
}
|
||||
|
||||
/// <summary>iCCP (zlib-compressed after its name and method byte) or sRGB before the image data.</summary>
|
||||
private static SourceColor Png(Stream stream)
|
||||
{
|
||||
Span<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>IFD0's InterColorProfile, else the colour space its Exif IFD records.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The colr properties of the primary item: an ICC profile ('prof', 'rICC') first, else its nclx box.</summary>
|
||||
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<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The ipco indices (1-based) associated with <paramref name="primary"/> in an ipma box.</summary>
|
||||
private static List<int> Associations(Stream stream, BmffBox ipma, uint primary)
|
||||
{
|
||||
var result = new List<int>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The ICCP chunk of an extended WebP (RIFF), which comes before the image data.</summary>
|
||||
private static SourceColor WebP(Stream stream)
|
||||
{
|
||||
Span<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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<byte> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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).</summary>
|
||||
public IReadOnlyList<byte[]>? App1Segments { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public byte[]? IccProfile { get; init; }
|
||||
|
||||
/// <summary>Ordered dither when quantising linear float input to 8-bit sRGB.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The profile split into APP2 chunks: "ICC_PROFILE\0", the chunk's number from 1, the count, its bytes.</summary>
|
||||
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<byte> payload)
|
||||
{
|
||||
var length = payload.Length + 2;
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Natural (row-major) index of the coefficient at each zig-zag position.</summary>
|
||||
public static ReadOnlySpan<byte> NaturalOrder =>
|
||||
|
||||
@@ -34,6 +34,9 @@ public sealed record TiffWriteOptions
|
||||
/// <summary>TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded.</summary>
|
||||
public byte[]? Exif { get; init; }
|
||||
|
||||
/// <summary>ICC profile of the colour space the samples are in (InterColorProfile, tag 34675); null writes none (sRGB).</summary>
|
||||
public byte[]? IccProfile { get; init; }
|
||||
|
||||
/// <summary>Worker limit for strip encoding (-1 = all cores).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,9 @@ public sealed record ConvertOptions(ConvertTarget Target, int Quality = ConvertO
|
||||
_ => "DNG",
|
||||
};
|
||||
|
||||
/// <summary>Whether the target keeps 16 bits per channel (TIFF-16, linear DNG), which an 8-bit development of a RAW does not fill.</summary>
|
||||
public bool IsSixteenBit => Target != ConvertTarget.Jpeg;
|
||||
|
||||
/// <summary>The quality that counts: the JPEG's, 0 for the lossless targets.</summary>
|
||||
public int EffectiveQuality => Target == ConvertTarget.Jpeg ? Quality : 0;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>The photo was never hashed (adopted, not verified yet): its replacement could not name it. Verify it first.</summary>
|
||||
Unhashed,
|
||||
|
||||
/// <summary>A 16-bit target, and this host develops the RAW at 8 bits only (WIC's Raw Image Extension): JPEG converts it.</summary>
|
||||
EightBit,
|
||||
|
||||
/// <summary>The photo's colour profile can be neither carried into the target nor converted to it (CMYK, an unknown space…).</summary>
|
||||
ColorProfile,
|
||||
|
||||
/// <summary>The photo is larger than the target holds (a JPEG side above 65535) or one image in memory can.</summary>
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// <summary>Why a whole sequence is not converted now; nothing of it is touched.</summary>
|
||||
@@ -117,12 +127,18 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="EstimateBytes"/>).
|
||||
/// 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 (<see cref="FrameConverter.Decoders"/>: 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
|
||||
/// (<see cref="FrameConverter.Treatment"/>). The plan asks the files what the conversion will ask them, reading headers
|
||||
/// only, several at once. Sizes after are estimated from the pixels (<see cref="EstimateBytes"/>).
|
||||
/// </summary>
|
||||
public static class ConvertPlanner
|
||||
{
|
||||
/// <summary>Files asked at once while a sequence is planned: header reads, bound by the disk more than the cores.</summary>
|
||||
private const int ProbesAtOnce = 8;
|
||||
|
||||
/// <summary>Margin over the estimate the free space must hold (estimates of compressed files vary with the content).</summary>
|
||||
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<string> ?? new HashSet<string>(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<ConvertSkip, int>();
|
||||
var frames = new List<ConvertFramePlan>();
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>Why <paramref name="frame"/> is not converted, or null when it is.</summary>
|
||||
/// <param name="decoder">This host's decoders; the conversion's are made from them (<see cref="FrameConverter.Decoders"/>).</param>
|
||||
public static ConvertSkip? Skip(SidecarFrame frame, SequencePaths folder, IReadOnlySet<string> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a frame of <paramref name="width"/> × <paramref name="height"/> (unknown: 0) cannot be converted to
|
||||
/// <paramref name="options"/>: a JPEG side above <see cref="FrameConverter.MaxJpegSide"/>, more samples than one image
|
||||
/// buffer indexes, or an estimated file larger than the array it is made in.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -204,21 +254,4 @@ public static class ConvertPlanner
|
||||
|
||||
/// <summary>The free space a conversion whose files are estimated at <paramref name="estimated"/> bytes needs.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
/// <summary>A converted file as written and verified: where it is, its size and SHA-256, its format and its upright size.</summary>
|
||||
public sealed record ConvertedFile(string Path, long Size, string Sha256, ImageFileFormat Format, int Width, int Height);
|
||||
|
||||
/// <summary>A photo could not be converted, or its converted file did not verify; nothing of it is kept.</summary>
|
||||
public sealed class ConversionException(string message, Exception? inner = null) : IOException(message, inner);
|
||||
/// <summary>Why a photo was not converted; each has its sentence, <c>Archive.Convert.Failed.<reason></c>.</summary>
|
||||
public enum ConversionFailure
|
||||
{
|
||||
/// <summary>No decoder of this host reads the photo at full resolution.</summary>
|
||||
NoDecoder,
|
||||
|
||||
/// <summary>This host reads the photo only from its embedded preview.</summary>
|
||||
PreviewOnly,
|
||||
|
||||
/// <summary>A 16-bit target, and this host develops the RAW at 8 bits only (WIC's Raw Image Extension).</summary>
|
||||
EightBit,
|
||||
|
||||
/// <summary>The photo's colour profile cannot be carried into the target or converted to it.</summary>
|
||||
ColorProfile,
|
||||
|
||||
/// <summary>The photo is larger than the target or the memory of one image holds.</summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>The converted file did not verify: read back, metadata, or a decode by the server's decoders.</summary>
|
||||
NotVerified,
|
||||
|
||||
/// <summary>The original no longer matches the SHA-256 it was archived with.</summary>
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// <summary>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); <see cref="Reason"/> chooses what the user reads (<see cref="FrameConverter.FailureText"/>).</summary>
|
||||
public sealed class ConversionException(ConversionFailure reason, string message, Exception? inner = null) : IOException(message, inner)
|
||||
{
|
||||
public ConversionFailure Reason { get; } = reason;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts one photo (owner review 2, R7; BRIEF §12.5): its original is decoded at full resolution only, never from an
|
||||
/// embedded preview (<see cref="DecodeTier.Native"/>, oriented upright), encoded by the in-house writers
|
||||
/// (<see cref="JpegEncoder"/> 4:4:4, <see cref="TiffWriter"/> 16-bit sRGB with Deflate and the predictor,
|
||||
/// <see cref="LinearDngWriter"/>), with an Exif block (<see cref="ExifWriter"/>) 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 (<see cref="DecodeTier.Native"/>, 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 (<see cref="Decoders"/>); a 16-bit target never takes a RAW developed at 8 bits. It is encoded by the in-house
|
||||
/// writers (<see cref="JpegEncoder"/> 4:4:4, <see cref="TiffWriter"/> 16-bit with Deflate and the predictor,
|
||||
/// <see cref="LinearDngWriter"/> scene-referred: highlights above white and colours outside sRGB kept), with an Exif block
|
||||
/// (<see cref="ExifWriter"/>) 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 (<see cref="SourceColor"/>) 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 (<see cref="Treatment"/>). 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.
|
||||
/// </summary>
|
||||
public static class FrameConverter
|
||||
{
|
||||
/// <summary>Long edge of the verification decode: enough to prove the full-resolution data decodes, cheap for JPEG and RAW.</summary>
|
||||
private const int VerifyEdge = 256;
|
||||
|
||||
/// <summary>Largest side of a JPEG (its frame header holds 16 bits).</summary>
|
||||
public const int MaxJpegSide = 65535;
|
||||
|
||||
private const int DiskFull = unchecked((int)0x80070070);
|
||||
private const int HandleDiskFull = unchecked((int)0x80070027);
|
||||
|
||||
/// <summary>ENOSPC, the HResult .NET gives a full disk on Linux.</summary>
|
||||
private const int NoSpace = 28;
|
||||
|
||||
private static readonly Lazy<ImageDecoder> ServerDecoders = new(DecoderFactory.CreateServer);
|
||||
|
||||
/// <summary>The decoders a converted file must decode with at full-resolution tier: the server's (managed only).</summary>
|
||||
public static ImageDecoder Verifier => ServerDecoders.Value;
|
||||
|
||||
/// <summary>
|
||||
/// The decoders a conversion to <paramref name="options"/> reads a <paramref name="format"/> photo with, from this host's
|
||||
/// <paramref name="decoder"/>: 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 (<see cref="IImageDecoderProvider.DevelopsRawAt8Bits"/>).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="decoder"/> reads a <paramref name="format"/> photo natively only through a provider that
|
||||
/// develops RAWs at 8 bits, which a conversion to <paramref name="options"/> does not use: the reason it is not converted.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>What a conversion to <paramref name="target"/> does with a photo whose values are in <paramref name="color"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Converts <paramref name="source"/> into <paramref name="target"/> (created or replaced atomically) and verifies it.</summary>
|
||||
/// <param name="decoder">This host's decoders (WIC first on a desktop).</param>
|
||||
/// <param name="decoder">This host's decoders (WIC first on a desktop); the conversion orders them itself (<see cref="Decoders"/>).</param>
|
||||
/// <param name="encoderThreads">Worker limit of the encoder (-1: all cores); 1 when several photos convert at once.</param>
|
||||
/// <exception cref="ConversionException">The photo does not decode at full resolution here, or its converted file did not
|
||||
/// verify (it is deleted).</exception>
|
||||
/// <exception cref="ConversionException">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).</exception>
|
||||
/// <exception cref="IOException">The original cannot be read, or the target cannot be written.</exception>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="ConversionException.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.
|
||||
/// </summary>
|
||||
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"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// <summary>The file bytes of <paramref name="image"/> (linear light, RGB) in the target format with <paramref name="metadata"/>.</summary>
|
||||
public static byte[] Encode(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, int encoderThreads = -1)
|
||||
/// <param name="iccProfile">The ICC profile the encoded values are in (a JPEG or TIFF carries it); null for sRGB.</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary><see cref="Encode"/> into a stream the caller disposes.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
|
||||
/// <summary>Three channels from one (gray) or four (alpha dropped).</summary>
|
||||
private static ImageBuffer Rgb(ImageBuffer image)
|
||||
{
|
||||
@@ -237,3 +401,19 @@ public static class FrameConverter
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a conversion does with the colour space a photo's values are in (<see cref="FrameConverter.Treatment"/>).</summary>
|
||||
public enum ColorTreatment
|
||||
{
|
||||
/// <summary>sRGB (untagged, or an sRGB profile into a DNG): nothing to do.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>A JPEG or TIFF carries the original's ICC profile; its values pass through unchanged.</summary>
|
||||
Carry,
|
||||
|
||||
/// <summary>The values are converted to linear Rec.709 through the profile (a DNG from a matrix/TRC profile, or a gray profile).</summary>
|
||||
Convert,
|
||||
|
||||
/// <summary>A profile none of that applies to (CMYK, Lab, a lookup-table RGB profile into a DNG, an unknown space): not converted.</summary>
|
||||
Refuse,
|
||||
}
|
||||
@@ -93,6 +93,12 @@ public interface IImageDecoderProvider
|
||||
|
||||
bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
bool DevelopsRawAt8Bits => false;
|
||||
|
||||
/// <summary>
|
||||
/// The tier this provider would use for the file at <paramref name="path"/>, whose signature says
|
||||
/// <paramref name="format"/>, without decoding pixels. The default trusts <see cref="TierFor"/>; a provider whose
|
||||
|
||||
@@ -187,12 +187,13 @@ internal static class JpegParser
|
||||
m.AddXmp(buffer);
|
||||
}
|
||||
|
||||
private readonly record struct Segment(byte Marker, long Payload, int Length);
|
||||
/// <summary>A marker segment: its marker, where its payload starts, and the payload bytes present (0 for markers without one).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Walks marker segments of one JPEG, reading only marker and length bytes within a read budget.</summary>
|
||||
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;
|
||||
|
||||
@@ -42,9 +42,16 @@ public static class TiffTags
|
||||
public const ushort Xmp = 0x02BC;
|
||||
public const ushort Copyright = 0x8298;
|
||||
public const ushort ExifIfd = 0x8769;
|
||||
|
||||
/// <summary>InterColorProfile: the ICC profile of the image's colour space (UNDEFINED bytes).</summary>
|
||||
public const ushort InterColorProfile = 0x8773;
|
||||
|
||||
public const ushort GpsIfd = 0x8825;
|
||||
public const ushort InteropIfd = 0xA005;
|
||||
|
||||
/// <summary>InteroperabilityIndex in the Interop IFD: "R98" (sRGB) or "R03" (Adobe RGB, DCF option file).</summary>
|
||||
public const ushort InteropIndex = 0x0001;
|
||||
|
||||
// Exif
|
||||
public const ushort ExposureTime = 0x829A;
|
||||
public const ushort FNumber = 0x829D;
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<string?> StageAsync(Sequence row, SequenceManifest manifest, SequencePaths folder, ConvertSequencePlan planned,
|
||||
Dictionary<Guid, StagedConversion> 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<Staged>(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);
|
||||
|
||||
@@ -140,7 +140,9 @@ public sealed record ConvertRequest(IReadOnlyList<Guid>? SequenceIds, bool All,
|
||||
/// <summary>
|
||||
/// Photos of a sequence a conversion leaves as they are: <see cref="Reason"/> <c>same_format</c>, <c>convert_on_pc</c> (the
|
||||
/// server cannot read them at full resolution: a CR3, a HEIC, a body its RAW decoder does not support), <c>undecodable</c>,
|
||||
/// <c>missing</c> or <c>unhashed</c> (never verified), how many, and the reason as one localised sentence.
|
||||
/// <c>missing</c>, <c>unhashed</c> (never verified), <c>eight_bit</c> (a RAW the host develops at 8 bits only, for a 16-bit
|
||||
/// target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to) or <c>too_large</c>, how
|
||||
/// many, and the reason as one localised sentence.
|
||||
/// </summary>
|
||||
public sealed record ConvertSkippedDto(string Reason, int Photos, string Message);
|
||||
|
||||
|
||||
@@ -328,7 +328,9 @@ public static class ArchiveEndpoints
|
||||
/// <summary>
|
||||
/// Wire name of why photos are not converted: <c>same_format</c>, <c>convert_on_pc</c> (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), <c>undecodable</c>, <c>missing</c>, <c>unhashed</c>.
|
||||
/// them), <c>undecodable</c>, <c>missing</c>, <c>unhashed</c>, <c>eight_bit</c> (a RAW this host develops at 8 bits only,
|
||||
/// for a 16-bit target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to),
|
||||
/// <c>too_large</c>.
|
||||
/// </summary>
|
||||
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",
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user