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

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

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

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

No files matched your search

+16 -1
View File
@@ -43,22 +43,37 @@
<data name="Archive.Convert.Blocked.Unreadable" xml:space="preserve"><value>The sequence file cannot be read.</value><comment>long: why a sequence is not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Done.one" xml:space="preserve"><value>{0:N0} sequence converted</value></data>
<data name="Archive.Convert.Done.other" xml:space="preserve"><value>{0:N0} sequences converted</value></data>
<data name="Archive.Convert.Failed.Changed" xml:space="preserve"><value>The photo no longer matches the copy that was archived; verify the sequence.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.ColorProfile" xml:space="preserve"><value>Its colour profile can be neither kept nor converted in this format.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.EightBit" xml:space="preserve"><value>This computer develops this RAW at 8 bits only, too few for a 16-bit file; JPEG converts it.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.Full" xml:space="preserve"><value>The archive's disk is full.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.NoDecoder" xml:space="preserve"><value>No decoder on this computer reads it at full resolution.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.NotVerified" xml:space="preserve"><value>The converted file did not read back as it was written.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.Other" xml:space="preserve"><value>The converted file could not be made.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.PreviewOnly" xml:space="preserve"><value>This computer reads it only from its embedded preview: convert it on a PC that reads it at full resolution.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.TooLarge" xml:space="preserve"><value>It is larger than this format or the memory for one photo can hold.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Failed.Unreadable" xml:space="preserve"><value>The photo could not be decoded.</value><comment>long: why a photo was not converted, in the job log</comment></data>
<data name="Archive.Convert.Format" xml:space="preserve"><value>Format</value></data>
<data name="Archive.Convert.Heading.one" xml:space="preserve"><value>Convert {0:N0} sequence</value></data>
<data name="Archive.Convert.Heading.other" xml:space="preserve"><value>Convert {0:N0} sequences</value></data>
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Convert {0}</value><comment>long: dialog heading; {0} archive name</comment></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Mode</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>New sequence</value></data>
<data name="Archive.Convert.NotPlaced" xml:space="preserve"><value>The converted photos could not take their place. {0}</value><comment>long: job log; {0} why (one sentence)</comment></data>
<data name="Archive.Convert.PhotoFailed" xml:space="preserve"><value>{0} could not be converted. {1}</value><comment>long: job log; {0} the photo's file, {1} why (one sentence)</comment></data>
<data name="Archive.Convert.Quality" xml:space="preserve"><value>Quality</value></data>
<data name="Archive.Convert.Replace" xml:space="preserve"><value>Replace</value></data>
<data name="Archive.Convert.ReplaceHeading.one" xml:space="preserve"><value>Replace the photos of {0:N0} sequence?</value><comment>long</comment></data>
<data name="Archive.Convert.ReplaceHeading.other" xml:space="preserve"><value>Replace the photos of {0:N0} sequences?</value><comment>long</comment></data>
<data name="Archive.Convert.ReplaceMessage" xml:space="preserve"><value>{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.</value><comment>long: {0} photos, e.g. "120 photos"; {1} their size; {2} the format, e.g. "Linear DNG"</comment></data>
<data name="Archive.Convert.Sizes" xml:space="preserve"><value>{0} → {1}</value><comment>sizes before and after a conversion</comment></data>
<data name="Archive.Convert.Skipped.ColorProfile" xml:space="preserve"><value>Photos whose colour profile this format can neither keep nor convert stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.EightBit" xml:space="preserve"><value>RAW photos this computer develops at 8 bits only stay as they are; JPEG converts them.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.Missing" xml:space="preserve"><value>Missing photos stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.NoNativeDecoder" xml:space="preserve"><value>Photos of a format this computer cannot read at full resolution stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.PreviewOnly" xml:space="preserve"><value>Photos read only from their embedded preview here stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.SameFormat" xml:space="preserve"><value>Photos already in this format stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.TooLarge" xml:space="preserve"><value>Photos larger than this format can hold stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.Undecodable" xml:space="preserve"><value>Unreadable photos stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.Unhashed" xml:space="preserve"><value>Photos never verified stay as they are; verify the sequence first.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.SkippedPhotos.one" xml:space="preserve"><value>{0:N0} skipped</value><comment>photos a conversion leaves as they are</comment></data>
@@ -183,7 +198,7 @@
<data name="Archive.Log.ConvertBlocked" xml:space="preserve"><value>Left as it was, busy or unreadable: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
<data name="Archive.Log.ConvertChanged" xml:space="preserve"><value>Left as it was, changed after the plan: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
<data name="Archive.Log.ConvertDone" xml:space="preserve"><value>Sequences converted: {0}, new sequences: {1}, photos: {2}</value><comment>long: job log line of a conversion</comment></data>
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Left as it was, a photo could not be converted: {0}: {1}</value><comment>long: job log line; {0} sequence title, {1} the reason</comment></data>
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Left as it was: {0}. {1}</value><comment>long: job log line; {0} sequence title, {1} what failed and why (sentences)</comment></data>
<data name="Archive.Log.ConvertNothing" xml:space="preserve"><value>Nothing to convert: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
<data name="Archive.Log.Converted" xml:space="preserve"><value>{0}: photos replaced by their conversion: {1}</value><comment>long: job log line; {0} sequence title, {1} photos</comment></data>
<data name="Archive.Log.ConvertedNew" xml:space="preserve"><value>{0}: photos converted into a new sequence: {1}</value><comment>long: job log line; {0} sequence title, {1} photos</comment></data>
+16 -1
View File
@@ -40,22 +40,37 @@
<data name="Archive.Convert.Blocked.Unreadable" xml:space="preserve"><value>Il file della sequenza non si può leggere.</value></data>
<data name="Archive.Convert.Done.one" xml:space="preserve"><value>{0:N0} sequenza convertita</value></data>
<data name="Archive.Convert.Done.other" xml:space="preserve"><value>{0:N0} sequenze convertite</value></data>
<data name="Archive.Convert.Failed.Changed" xml:space="preserve"><value>La foto non corrisponde più alla copia archiviata; verifica la sequenza.</value></data>
<data name="Archive.Convert.Failed.ColorProfile" xml:space="preserve"><value>Il suo profilo colore non si può né conservare né convertire in questo formato.</value></data>
<data name="Archive.Convert.Failed.EightBit" xml:space="preserve"><value>Questo computer sviluppa questo RAW solo a 8 bit, troppo pochi per un file a 16 bit; JPEG lo converte.</value></data>
<data name="Archive.Convert.Failed.Full" xml:space="preserve"><value>Il disco dell'archivio è pieno.</value></data>
<data name="Archive.Convert.Failed.NoDecoder" xml:space="preserve"><value>Nessun decodificatore di questo computer la legge a piena risoluzione.</value></data>
<data name="Archive.Convert.Failed.NotVerified" xml:space="preserve"><value>Il file convertito non si è riletto come era stato scritto.</value></data>
<data name="Archive.Convert.Failed.Other" xml:space="preserve"><value>Non è stato possibile creare il file convertito.</value></data>
<data name="Archive.Convert.Failed.PreviewOnly" xml:space="preserve"><value>Questo computer la legge solo dalla sua anteprima incorporata: convertila su un PC che la legga a piena risoluzione.</value></data>
<data name="Archive.Convert.Failed.TooLarge" xml:space="preserve"><value>È più grande di quanto questo formato o la memoria per una foto possano contenere.</value></data>
<data name="Archive.Convert.Failed.Unreadable" xml:space="preserve"><value>Non è stato possibile decodificare la foto.</value></data>
<data name="Archive.Convert.Format" xml:space="preserve"><value>Formato</value></data>
<data name="Archive.Convert.Heading.one" xml:space="preserve"><value>Converti {0:N0} sequenza</value></data>
<data name="Archive.Convert.Heading.other" xml:space="preserve"><value>Converti {0:N0} sequenze</value></data>
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Converti {0}</value></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Modalità</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>Nuova sequenza</value></data>
<data name="Archive.Convert.NotPlaced" xml:space="preserve"><value>Le foto convertite non hanno potuto prendere il loro posto. {0}</value></data>
<data name="Archive.Convert.PhotoFailed" xml:space="preserve"><value>Impossibile convertire {0}. {1}</value></data>
<data name="Archive.Convert.Quality" xml:space="preserve"><value>Qualità</value></data>
<data name="Archive.Convert.Replace" xml:space="preserve"><value>Sostituisci</value></data>
<data name="Archive.Convert.ReplaceHeading.one" xml:space="preserve"><value>Sostituire le foto di {0:N0} sequenza?</value></data>
<data name="Archive.Convert.ReplaceHeading.other" xml:space="preserve"><value>Sostituire le foto di {0:N0} sequenze?</value></data>
<data name="Archive.Convert.ReplaceMessage" xml:space="preserve"><value>{0} ({1}) vengono sostituite dalla loro conversione in {2}; gli originali vanno nel cestino dell'archivio e si possono ripristinare finché non viene svuotato.</value></data>
<data name="Archive.Convert.Sizes" xml:space="preserve"><value>{0} → {1}</value></data>
<data name="Archive.Convert.Skipped.ColorProfile" xml:space="preserve"><value>Le foto il cui profilo colore questo formato non può né conservare né convertire restano come sono.</value></data>
<data name="Archive.Convert.Skipped.EightBit" xml:space="preserve"><value>Le foto RAW che questo computer sviluppa solo a 8 bit restano come sono; JPEG le converte.</value></data>
<data name="Archive.Convert.Skipped.Missing" xml:space="preserve"><value>Le foto mancanti restano come sono.</value></data>
<data name="Archive.Convert.Skipped.NoNativeDecoder" xml:space="preserve"><value>Le foto di un formato che questo computer non legge a piena risoluzione restano come sono.</value></data>
<data name="Archive.Convert.Skipped.PreviewOnly" xml:space="preserve"><value>Le foto lette qui solo dalla loro anteprima incorporata restano come sono.</value></data>
<data name="Archive.Convert.Skipped.SameFormat" xml:space="preserve"><value>Le foto già in questo formato restano come sono.</value></data>
<data name="Archive.Convert.Skipped.TooLarge" xml:space="preserve"><value>Le foto più grandi di quanto questo formato possa contenere restano come sono.</value></data>
<data name="Archive.Convert.Skipped.Undecodable" xml:space="preserve"><value>Le foto illeggibili restano come sono.</value></data>
<data name="Archive.Convert.Skipped.Unhashed" xml:space="preserve"><value>Le foto mai verificate restano come sono; verifica prima la sequenza.</value></data>
<data name="Archive.Convert.SkippedPhotos.one" xml:space="preserve"><value>{0:N0} esclusa</value></data>
@@ -177,7 +192,7 @@
<data name="Archive.Log.ConvertBlocked" xml:space="preserve"><value>Lasciata com'era, occupata o illeggibile: {0}</value></data>
<data name="Archive.Log.ConvertChanged" xml:space="preserve"><value>Lasciata com'era, cambiata dopo il piano: {0}</value></data>
<data name="Archive.Log.ConvertDone" xml:space="preserve"><value>Sequenze convertite: {0}, nuove sequenze: {1}, foto: {2}</value></data>
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Lasciata com'era, una foto non si è potuta convertire: {0}: {1}</value></data>
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Lasciata com'era: {0}. {1}</value></data>
<data name="Archive.Log.ConvertNothing" xml:space="preserve"><value>Niente da convertire: {0}</value></data>
<data name="Archive.Log.Converted" xml:space="preserve"><value>{0}: foto sostituite dalla loro conversione: {1}</value></data>
<data name="Archive.Log.ConvertedNew" xml:space="preserve"><value>{0}: foto convertite in una nuova sequenza: {1}</value></data>
@@ -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
+124 -5
View File
@@ -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;
}
}
}
+336
View File
@@ -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));
}
+261
View File
@@ -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;
+1 -1
View File
@@ -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;
+61 -28
View File
@@ -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;
}
}
}
+208 -28
View File
@@ -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.&lt;reason&gt;</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,
}
+6
View File
@@ -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
+3 -2
View File
@@ -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;
+12 -6
View File
@@ -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);
+3 -1
View File
@@ -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);
+6 -1
View File
@@ -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",
};
@@ -0,0 +1,103 @@
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Mathematics;
using Chronos.Core.Tests.Conversion;
using Chronos.Testing;
namespace Chronos.Core.Tests.Codecs;
/// <summary>ICC profiles (owner review 2, R7): parsed, synthesized for the spaces a marker names, and read from each container.</summary>
public sealed class IccProfileTests
{
[Test]
public void TheSynthesizedProfilesAreMatrixShapersOfTheirSpace()
{
var adobe = IccProfile.AdobeRgb;
Assert.True(adobe.IsMatrixShaper && adobe.IsRgb && !adobe.IsSrgb);
Assert.Equal("Compatible with Adobe RGB (1998)", adobe.Description);
// Colorants add up to the D50 PCS white.
var white = adobe.Colorants!.Value * new Vector3D(1, 1, 1);
Assert.Approximately(0.9642, white.X, 2e-4);
Assert.Approximately(1.0, white.Y, 2e-4);
Assert.Approximately(0.8249, white.Z, 2e-4);
// Adobe RGB → linear sRGB: red reaches 1.398 with green −0.398, blue stays put but borrows from green.
var m = adobe.ToLinearRec709();
Assert.Approximately(1.3982, m.M11, 2e-3);
Assert.Approximately(-0.3982, m.M12, 2e-3);
Assert.Approximately(1.0, m.M22, 2e-3);
Assert.Approximately(-0.0429, m.M32, 2e-3);
Assert.Approximately(1.0429, m.M33, 2e-3);
var neutral = m * new Vector3D(1, 1, 1);
Assert.Approximately(1, neutral.X, 1e-9);
Assert.Approximately(1, neutral.Y, 1e-9);
Assert.Approximately(1, neutral.Z, 1e-9);
// Its gamma 563/256, written as a u8Fixed8 curve.
Assert.Approximately(Math.Pow(0.5, 563 / 256.0), adobe.Curves![0].Evaluate(0.5), 1e-12);
var p3 = IccProfile.DisplayP3;
Assert.True(p3.IsMatrixShaper);
// The sRGB curve, tabulated in 1024 entries.
for (var v = 0.0; v <= 1; v += 0.05) Assert.Approximately(ColorSpace.SrgbToLinear(v), p3.Curves![1].Evaluate(v), 2e-5);
// P3's own green is outside sRGB: negative red and blue in Rec.709.
var green = p3.ToLinearRec709() * new Vector3D(0, 1, 0);
Assert.Approximately(-0.2246, green.X, 3e-3);
Assert.Approximately(1.0421, green.Y, 3e-3);
Assert.Approximately(-0.0786, green.Z, 3e-3);
Assert.Null(IccProfile.Parse(new byte[200]));
Assert.Null(IccProfile.Parse(adobe.Data[..131]));
}
[Test]
public void ParametricCurvesFollowTheirFunctions()
{
// para function 3 with the sRGB parameters (as Apple's Display P3 profile writes it).
byte[] tag = [.. "para"u8, 0, 0, 0, 0, 0, 3, 0, 0, .. Fixed(2.4), .. Fixed(1 / 1.055), .. Fixed(0.055 / 1.055), .. Fixed(1 / 12.92), .. Fixed(0.04045)];
var curve = IccCurve.Parse(tag)!;
foreach (var v in new[] { 0.0, 0.02, 0.04045, 0.3, 0.75, 1.0 }) Assert.Approximately(ColorSpace.SrgbToLinear(v), curve.Evaluate(v), 2e-5);
Assert.Approximately(Math.Pow(0.5, 1.8), IccCurve.Parse([.. "para"u8, 0, 0, 0, 0, 0, 0, 0, 0, .. Fixed(1.8)])!.Evaluate(0.5), 1e-4);
Assert.Approximately(0.25, IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 0])!.Evaluate(0.25), 1e-12);
Assert.Approximately(0.5, IccCurve.Parse([.. "curv"u8, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0x80, 0, 0xFF, 0xFF])!.Evaluate(0.5), 1e-4);
Assert.Null(IccCurve.Parse([.. "para"u8, 0, 0, 0, 0, 0, 9, 0, 0]));
static byte[] Fixed(double v)
{
var b = new byte[4];
System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(b, (int)Math.Round(v * 65536));
return b;
}
}
[Test]
public void EachContainerSaysItsColourSpace()
{
using var scene = ColorFixtures.Scene();
var p3 = IccProfile.DisplayP3.Data;
SourceColor Read(byte[] file, ImageFileFormat format) => SourceColor.Read(new MemoryStream(file), format);
// Untagged and sRGB files are sRGB.
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Jpeg(scene), ImageFileFormat.Jpeg));
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(1, "R98")), ImageFileFormat.Jpeg));
// An embedded profile, byte for byte: JPEG APP2 (one chunk, or several), PNG iCCP, TIFF tag 34675, HEIF prof.
Assert.BytesEqual(p3, Read(ColorFixtures.Jpeg(scene, p3), ImageFileFormat.Jpeg).Profile!.Data);
var large = ColorFixtures.Large();
Assert.BytesEqual(large, Read(ColorFixtures.Jpeg(scene, large), ImageFileFormat.Jpeg).Profile!.Data);
Assert.BytesEqual(p3, Read(ColorFixtures.Png(scene, p3), ImageFileFormat.Png).Profile!.Data);
Assert.BytesEqual(p3, Read(TiffWriter.Write(scene, new TiffWriteOptions { IccProfile = p3 }), ImageFileFormat.Tiff).Profile!.Data);
Assert.BytesEqual(p3, Read(ColorFixtures.Heif(ColorFixtures.Nclx(1, 13), ColorFixtures.Prof(p3)), ImageFileFormat.Heif).Profile!.Data);
// A grid whose tiles carry the profile, not the grid item.
Assert.BytesEqual(p3, Read(ColorFixtures.Heif(2, ColorFixtures.Prof(p3)), ImageFileFormat.Heif).Profile!.Data);
// A camera's Adobe RGB marker (uncalibrated, Interop R03) names Adobe RGB, in a JPEG and in a TIFF.
Assert.Same(IccProfile.AdobeRgb, Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF, "R03")), ImageFileFormat.Jpeg).Profile);
// nclx: BT.709 is sRGB, P3 primaries Display P3, BT.2020 or PQ unknown.
Assert.Same(SourceColor.Untagged, Read(ColorFixtures.Heif(ColorFixtures.Nclx(1, 13)), ImageFileFormat.Heif));
Assert.Same(IccProfile.DisplayP3, Read(ColorFixtures.Heif(ColorFixtures.Nclx(12, 13)), ImageFileFormat.Heif).Profile);
Assert.True(Read(ColorFixtures.Heif(ColorFixtures.Nclx(9, 16)), ImageFileFormat.Heif).IsUnknown);
// Uncalibrated without R03, or a profile that does not parse: a space nothing here describes.
Assert.True(Read(ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)), ImageFileFormat.Jpeg).IsUnknown);
Assert.True(Read(ColorFixtures.Jpeg(scene, new byte[300]), ImageFileFormat.Jpeg).IsUnknown);
// RAWs say nothing here: their decoders give Rec.709.
Assert.Same(SourceColor.Untagged, Read([1, 2, 3], ImageFileFormat.Cr2));
}
}
@@ -1,4 +1,5 @@
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
@@ -87,6 +88,67 @@ public sealed class LinearDngWriterTests
for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
}
/// <summary>
/// A conversion's archival DNG (owner review 2, R7): highlights above white and colours outside sRGB (negative in
/// Rec.709) read back through the in-house DNG reader and developer as they were written, to the 16-bit step.
/// </summary>
[Test]
public void ASceneReferredDngKeepsHighlightsAndColoursOutsideSrgb()
{
using var image = new ImageBuffer(64, 48);
for (var y = 0; y < 48; y++)
{
for (var x = 0; x < 64; x++)
{
image[0, x, y] = 0.02f + 0.9f * x / 63;
image[1, x, y] = 0.05f + 0.7f * y / 47;
image[2, x, y] = 0.1f + 0.3f * ((x + y) % 7) / 6;
}
}
(int X, int Y, float R, float G, float B)[] special =
[
(1, 1, 2.6f, 2.4f, 2.2f), // a highlight above white, as a RAW's reconstruction gives it
(2, 1, 3.5f, 1.0f, 0.5f), // a bright saturated sunset
(3, 1, -0.2246f, 1.0421f, -0.0786f), // Display P3 green, outside sRGB
(4, 1, -0.15f, 0.8f, 0.9f), // a cyan outside sRGB
(5, 1, 0.6f, -0.05f, 0.7f), // a magenta outside sRGB
];
foreach (var (x, y, r, g, b) in special) (image[0, x, y], image[1, x, y], image[2, x, y]) = (r, g, b);
var dng = LinearDngWriter.Write(image, new LinearDngOptions { SceneReferred = true, TileSize = 32 });
var reader = TiffReader.Open(new MemoryStream(dng))!;
var ifd = reader.ReadChain()[0];
// The peak, about 2.5 in ProPhoto, fits under white two stops down.
Assert.Equal(2.0, reader.GetDouble(ifd, TiffTags.BaselineExposure));
var fm = reader.GetDoubles(ifd, TiffTags.ForwardMatrix1)!;
double[] d50 = [0.3457 / 0.3585, 1.0, (1 - 0.3457 - 0.3585) / 0.3585];
for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
using var developed = RawDecoder.Decode(new MemoryStream(dng), "scene.dng", new RawDecodeOptions { ApplyOrientation = false });
var back = developed.Image;
Assert.Equal((64, 48, 3), (back.Width, back.Height, back.Channels));
var worst = 0.0;
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < image.PlaneLength; i++) worst = Math.Max(worst, Math.Abs(image.Plane(c)[i] - back.Plane(c)[i]));
}
Assert.Less(worst, 4e-4, "largest difference after the round trip");
foreach (var (x, y, r, g, b) in special)
{
Assert.Approximately(r, back[0, x, y], 4e-4);
Assert.Approximately(g, back[1, x, y], 4e-4);
Assert.Approximately(b, back[2, x, y], 4e-4);
}
// The export mode is unchanged: linear sRGB primaries, clipped to 0..1, no headroom.
var export = LinearDngWriter.Write(image, new LinearDngOptions { TileSize = 32 });
using var clipped = RawDecoder.Decode(new MemoryStream(export), "export.dng", new RawDecodeOptions { ApplyOrientation = false });
Assert.Less(clipped.Image[0, 2, 1], 1.01, "the export clips the highlight");
Assert.Greater(clipped.Image[0, 3, 1], -0.01, "the export clips the colour outside sRGB");
var exportReader = TiffReader.Open(new MemoryStream(export))!;
Assert.Equal(0.0, exportReader.GetDouble(exportReader.ReadChain()[0], TiffTags.BaselineExposure));
}
[Test]
public void GrayInputExifAndNonSeekableOutput()
{
@@ -0,0 +1,107 @@
using System.IO.Compression;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
namespace Chronos.Core.Tests.Conversion;
/// <summary>Photos that record their colour space: an embedded ICC profile in each container, or an Exif colour space.</summary>
internal static class ColorFixtures
{
/// <summary>Saturated colours (a P3 photo's greens and reds fall outside sRGB once converted), plus a gradient.</summary>
public static ImageBuffer Scene(int width = 48, int height = 32)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
image[0, x, y] = 0.05f + 0.6f * x / width;
image[1, x, y] = 0.1f + 0.5f * y / height;
image[2, x, y] = 0.15f + 0.2f * ((x / 4 + y / 4) % 2);
}
}
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
(image[0, x, y], image[1, x, y], image[2, x, y]) = (0.02f, 0.9f, 0.02f); // a saturated green
(image[0, x + 8, y], image[1, x + 8, y], image[2, x + 8, y]) = (0.9f, 0.02f, 0.02f); // a saturated red
}
}
return image;
}
/// <summary>A JPEG whose values are <paramref name="scene"/> in sRGB, with an Exif block and/or an ICC profile.</summary>
public static byte[] Jpeg(ImageBuffer scene, byte[]? icc = null, byte[]? exifTiff = null) => JpegEncoder.Encode(scene, new JpegEncodeOptions
{
Quality = 98,
Subsampling = JpegSubsampling.Yuv444,
App1Segments = exifTiff is null ? null : [[.. "Exif\0\0"u8, .. exifTiff]],
IccProfile = icc,
});
/// <summary>An Exif block recording <paramref name="colorSpace"/> (1 sRGB, 0xFFFF uncalibrated) and an Interop index.</summary>
public static byte[] Exif(ushort colorSpace, string? interop = null)
{
var exif = new IfdSpec().Short(TiffTags.ColorSpace, colorSpace);
if (interop is not null) exif.Child(TiffTags.InteropIfd, new IfdSpec().Ascii(TiffTags.InteropIndex, interop));
return TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, "Canon").Child(TiffTags.ExifIfd, exif));
}
/// <summary>A PNG of <paramref name="scene"/> with an iCCP chunk after its header.</summary>
public static byte[] Png(ImageBuffer scene, byte[] icc)
{
var png = PngEncoder.Encode(scene);
using var compressed = new MemoryStream();
using (var z = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true)) z.Write(icc);
var chunk = Box.Png("iCCP", [.. "Display P3\0"u8, 0, .. compressed.ToArray()]);
// Signature (8) and IHDR (25) come first.
return [.. png.AsSpan(0, 33), .. chunk, .. png.AsSpan(33)];
}
/// <summary>A HEIF whose primary item has the colr boxes given (no image data: only its colour is read).</summary>
public static byte[] Heif(params byte[][] colr) => Heif(1, colr);
/// <summary>A HEIF whose item <paramref name="item"/> has the colr boxes given; item 1 is the primary (a grid of tiles 2…).</summary>
public static byte[] Heif(ushort item, params byte[][] colr)
{
var associations = Enumerable.Range(1, colr.Length).Select(i => (byte)(0x80 | i)).ToArray();
return
[
.. Box.Make("ftyp", Box.Ascii("heic"), Box.U32(0), Box.Ascii("mif1"), Box.Ascii("heic")),
.. Box.Full("meta", 0, 0,
Box.Full("hdlr", 0, 0, Box.U32(0), Box.Ascii("pict"), Box.Zeros(12), [0]),
Box.Full("pitm", 0, 0, Box.U16(1)),
Box.Make("iprp",
Box.Make("ipco", [.. colr.SelectMany(c => c)]),
Box.Full("ipma", 0, 0, Box.U32(1), Box.U16(item), [(byte)associations.Length], associations))),
];
}
public static byte[] Prof(byte[] icc) => Box.Make("colr", Box.Ascii("prof"), icc);
public static byte[] Nclx(ushort primaries, ushort transfer) => Box.Make("colr", Box.Ascii("nclx"), Box.U16(primaries), Box.U16(transfer), Box.U16(1), [0x80]);
/// <summary>A profile that parses but describes CMYK, which no RGB file carries.</summary>
public static byte[] Cmyk()
{
var data = (byte[])IccProfile.AdobeRgb.Data.Clone();
"CMYK"u8.CopyTo(data.AsSpan(16));
return data;
}
/// <summary>A valid profile larger than one JPEG APP2 chunk holds (the Adobe RGB one padded with a private tag's room).</summary>
public static byte[] Large()
{
var small = IccProfile.AdobeRgb.Data;
var data = new byte[small.Length + 150_000];
small.CopyTo(data, 0);
System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(data, (uint)data.Length);
for (var i = small.Length; i < data.Length; i++) data[i] = (byte)(i * 31);
return data;
}
}
@@ -1,8 +1,12 @@
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Conversion;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Tests.Raw;
using Chronos.Testing;
namespace Chronos.Core.Tests.Conversion;
@@ -43,9 +47,9 @@ public sealed class ConvertPlannerTests(TestContext context)
Frame(8, "IMG_0009.CR2", ImageFileFormat.Cr2, flags: FrameFlags.PreviewOnly | FrameFlags.Excluded, tier: DecodeTier.EmbeddedPreview),
];
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames, Versions = new ManifestVersions { Frames = 7 } };
// The third photo's file is gone; the preview-only one probes as preview here.
// The third photo's file is gone; the preview-only one probes as preview here, the first one native.
var present = frames.Where(f => f.I != 2).Select(f => f.File).ToList();
var decoder = new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview)]);
var decoder = new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview, path => path.EndsWith("IMG_0009.CR2", StringComparison.Ordinal))]);
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.LinearDng), decoder, "Roof");
Assert.Equal((manifest.Id, "Roof", "2026/roof", 7), (plan.SequenceId, plan.Title, plan.Folder, plan.FramesVersion));
@@ -71,6 +75,109 @@ public sealed class ConvertPlannerTests(TestContext context)
Assert.Empty(plan.Skipped);
}
/// <summary>
/// A frame whose tier is not known yet (imported, not analysed) or was recorded native by another host with other
/// decoders is asked again: the dry run promises only what the file says here now.
/// </summary>
[Test]
public void AFrameIsAskedWhateverTierWasRecorded()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
SidecarFrame[] frames = [Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2), Frame(1, "IMG_0002.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native)];
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
var present = frames.Select(f => f.File).ToList();
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var preview = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview)]), "Roof");
Assert.Empty(preview.Frames);
Assert.SequenceEqual([(ConvertSkip.PreviewOnly, 2)], preview.Skipped.Select(s => (s.Reason, s.Frames)));
var unreadable = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.Unavailable)]), "Roof");
Assert.SequenceEqual([(ConvertSkip.Undecodable, 2)], unreadable.Skipped.Select(s => (s.Reason, s.Frames)));
var native = ConvertPlanner.Plan(manifest, folder, present, dng, new ImageDecoder([new ProbeAs(DecodeTier.Native)]), "Roof");
Assert.SequenceEqual([0, 1], native.Frames.Select(f => f.Index));
}
/// <summary>
/// The managed decoder develops every RAW it reads natively (at float precision) even where WIC could; a RAW only WIC's
/// Raw Image Extension develops, at 8 bits, converts to JPEG but not to TIFF-16 or linear DNG.
/// </summary>
[Test]
public void ARawDevelopedAtEightBitsOnlyConvertsToJpegOnly()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
using var scene = SyntheticRaw.Smooth(96, 64);
var active = new RawRect(24, 4, 24 + 96, 4 + 64);
var sensor = NativeRawWriters.Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383);
SidecarFrame[] frames =
[
Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native),
Frame(1, "IMG_0002.CR2", ImageFileFormat.Cr2, tier: DecodeTier.Native),
Frame(2, "IMG_0003.CR3", ImageFileFormat.Cr3, tier: DecodeTier.Native),
];
File.WriteAllBytes(folder.File(frames[0].File), NativeRawWriters.Cr2(sensor, active));
// A body the managed decoder has no matrix for: only the 8-bit development reads it.
File.WriteAllBytes(folder.File(frames[1].File), NativeRawWriters.Cr2(sensor, active, model: "Canon EOS R99"));
File.WriteAllBytes(folder.File(frames[2].File), [0]);
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
var present = frames.Select(f => f.File).ToList();
var desktop = new ImageDecoder([new EightBitRaw(), new ManagedDecoderProvider()]);
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
{
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(target), desktop, "Roof");
Assert.SequenceEqual([0], plan.Frames.Select(f => f.Index));
Assert.SequenceEqual([(ConvertSkip.EightBit, 2)], plan.Skipped.Select(s => (s.Reason, s.Frames)));
}
var jpeg = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Jpeg), desktop, "Roof");
Assert.SequenceEqual([0, 1, 2], jpeg.Frames.Select(f => f.Index));
// The server, without WIC: the unsupported body and the CR3 are to convert on a PC.
var server = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), "Roof");
Assert.SequenceEqual([0], server.Frames.Select(f => f.Index));
Assert.SequenceEqual([(ConvertSkip.NoNativeDecoder, 1), (ConvertSkip.PreviewOnly, 1)], server.Skipped.Select(s => (s.Reason, s.Frames)));
}
/// <summary>A photo whose colour space no target can keep, or which a target cannot hold, is planned out with why.</summary>
[Test]
public void ColourAndSizeTheTargetCannotHoldArePlannedOut()
{
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder.File("originals/x"))!);
using var scene = ColorFixtures.Scene();
SidecarFrame[] frames =
[
Frame(0, "plain.jpg", ImageFileFormat.Jpeg),
Frame(1, "p3.jpg", ImageFileFormat.Jpeg),
Frame(2, "unknown.jpg", ImageFileFormat.Jpeg),
Frame(3, "cmyk.jpg", ImageFileFormat.Jpeg),
Frame(4, "panorama.png", ImageFileFormat.Png) with { W = 70_000, H = 3_800 },
Frame(5, "huge.png", ImageFileFormat.Png) with { W = 70_000, H = 12_000 },
];
File.WriteAllBytes(folder.File(frames[0].File), ColorFixtures.Jpeg(scene));
File.WriteAllBytes(folder.File(frames[1].File), ColorFixtures.Jpeg(scene, IccProfile.DisplayP3.Data));
File.WriteAllBytes(folder.File(frames[2].File), ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)));
File.WriteAllBytes(folder.File(frames[3].File), ColorFixtures.Jpeg(scene, ColorFixtures.Cmyk()));
File.WriteAllBytes(folder.File(frames[4].File), [0]);
File.WriteAllBytes(folder.File(frames[5].File), [0]);
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
var present = frames.Select(f => f.File).ToList();
var decoder = DecoderFactory.CreateServer();
// A TIFF and a DNG keep the P3 photo (carried, or converted), not the unknown and CMYK ones, nor 2.5 G samples.
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
{
var plan = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(target), decoder, "Roof");
Assert.SequenceEqual([0, 1, 4], plan.Frames.Select(f => f.Index));
Assert.SequenceEqual([(ConvertSkip.ColorProfile, 2), (ConvertSkip.TooLarge, 1)], plan.Skipped.Select(s => (s.Reason, s.Frames)));
}
// A JPEG side holds 65535 pixels.
var jpeg = ConvertPlanner.Plan(manifest, folder, present, new ConvertOptions(ConvertTarget.Jpeg), decoder, "Roof");
Assert.SequenceEqual([(ConvertSkip.SameFormat, 4), (ConvertSkip.TooLarge, 2)], jpeg.Skipped.Select(s => (s.Reason, s.Frames)));
Assert.True(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Jpeg), 65_536, 10));
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Jpeg), 65_535, 10));
Assert.False(ConvertPlanner.TooLarge(new ConvertOptions(ConvertTarget.Tiff16), 0, 0));
}
[Test]
public void SizesAreEstimatedFromThePixels()
{
@@ -112,14 +219,27 @@ public sealed class ConvertPlannerTests(TestContext context)
Plan(new ConvertOptions(ConvertTarget.Jpeg, 80), ConvertMode.Replace, Sequence(3, 2)).Fingerprint());
}
/// <summary>A provider that reads CR2 natively by format, and probes every file at a fixed tier.</summary>
private sealed class ProbeAs(DecodeTier tier) : IImageDecoderProvider
/// <summary>A provider that reads CR2 natively by format, and probes the files <paramref name="applies"/> picks (all
/// by default) at a fixed tier, the others native.</summary>
private sealed class ProbeAs(DecodeTier tier, Func<string, bool>? applies = null) : IImageDecoderProvider
{
public string Name => "probe";
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Cr2 ? DecodeTier.Native : null;
public FileTier Probe(string path, ImageFileFormat format) => new(format, tier, Name, null, 0, 0);
public FileTier Probe(string path, ImageFileFormat format) => new(format, applies?.Invoke(path) == false ? DecodeTier.Native : tier, Name, null, 0, 0);
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
}
/// <summary>WIC with the Raw Image Extension, as a conversion sees it: every camera RAW native, developed at 8 bits.</summary>
internal sealed class EightBitRaw : IImageDecoderProvider
{
public string Name => "wic";
public bool DevelopsRawAt8Bits => true;
public DecodeTier? TierFor(ImageFileFormat format) => ImageFormatInfo.Of(format).Family == ImageFamily.CameraRaw ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
}
@@ -1,10 +1,15 @@
using System.Globalization;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Icc;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Mathematics;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Naming;
@@ -227,11 +232,13 @@ public sealed class FrameConverterTests(TestContext context)
var frame = Frame("frame.dng", ImageFileFormat.Dng, 32, 24);
var options = new ConvertOptions(ConvertTarget.Jpeg);
var target = Target(options);
Assert.Throws<ConversionException>(() =>
var preview = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([new PreviewOnlyProvider()]), target, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.PreviewOnly, preview.Reason);
Assert.FileMissing(target);
Assert.Throws<ConversionException>(() =>
var none = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([]), target, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.NoDecoder, none.Reason);
}
[Test]
@@ -247,7 +254,7 @@ public sealed class FrameConverterTests(TestContext context)
var bytes = File.ReadAllBytes(file.Path);
bytes[^10] ^= 0x40;
File.WriteAllBytes(file.Path, bytes);
Assert.Throws<ConversionException>(() => FrameConverter.Verify(file, written));
Assert.Equal(ConversionFailure.NotVerified, Assert.Throws<ConversionException>(() => FrameConverter.Verify(file, written)).Reason);
// A capture time that is not the one written.
File.WriteAllBytes(file.Path, File.ReadAllBytes(source));
Assert.Throws<ConversionException>(() => FrameConverter.Verify(file with { Sha256 = ContentHash.Sha256Async(file.Path).GetAwaiter().GetResult(), Size = new FileInfo(file.Path).Length }, written));
@@ -289,6 +296,224 @@ public sealed class FrameConverterTests(TestContext context)
Assert.Equal(new ConvertOptions(ConvertTarget.LinearDng, 10).Key, new ConvertOptions(ConvertTarget.LinearDng, 90).Key);
}
/// <summary>
/// The managed decoder develops a RAW wherever it reads it natively, ahead of WIC (owner review 2, R7): a 16-bit file is
/// never filled from WIC's 8-bit RAW development, which a JPEG may still use.
/// </summary>
[Test]
public void ASixteenBitFileNeverComesFromAnEightBitRawDevelopment()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "frame.dng");
using (var image = Scene(32, 24)) File.WriteAllBytes(path, LinearDngWriter.Write(image));
var frame = Frame("frame.dng", ImageFileFormat.Dng, 32, 24);
var wic = new EightBitRaw();
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng, ConvertTarget.Jpeg])
{
var options = new ConvertOptions(target);
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([wic, new ManagedDecoderProvider()]), Target(options),
cancellationToken: context.Cancellation);
}
Assert.Equal(0, wic.Calls);
// Where only the 8-bit development reads it: refused for 16 bits, converted to JPEG.
foreach (var target in (ConvertTarget[])[ConvertTarget.Tiff16, ConvertTarget.LinearDng])
{
var options = new ConvertOptions(target);
var refused = Assert.Throws<ConversionException>(() =>
FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([wic]), Target(options), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.EightBit, refused.Reason);
}
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
FrameConverter.Convert(new ConvertSource(path, frame), jpeg, new ImageDecoder([wic]), Target(jpeg), cancellationToken: context.Cancellation);
Assert.Equal(1, wic.Calls);
}
/// <summary>A RAW developed above white and outside sRGB converts to a linear DNG that reads back the same.</summary>
[Test]
public void ALinearDngKeepsWhatTheRawHasAboveWhiteAndOutsideSrgb()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "IMG_0001.CR2");
using (var image = Scene(40, 30)) File.WriteAllBytes(path, JpegEncoder.Encode(image));
var developed = Scene(40, 30);
(developed[0, 1, 1], developed[1, 1, 1], developed[2, 1, 1]) = (2.4f, 1.9f, 1.2f);
(developed[0, 2, 1], developed[1, 2, 1], developed[2, 2, 1]) = (-0.2f, 1.0f, -0.07f);
var options = new ConvertOptions(ConvertTarget.LinearDng);
var file = FrameConverter.Convert(new ConvertSource(path, Frame("IMG_0001.CR2", ImageFileFormat.Cr2, 40, 30)), options,
new ImageDecoder([new Developed(developed)]), Target(options), cancellationToken: context.Cancellation);
using var back = Assert.NotNull(DecoderFactory.CreateServer().Decode(new DecodeRequest(file.Path, AllowPreview: false)));
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < developed.PlaneLength; i++) Assert.Approximately(developed.Plane(c)[i], back.Pixels.Plane(c)[i], 3e-4);
}
developed.Dispose();
}
/// <summary>
/// The colour space the original's values are in is kept: a JPEG or TIFF carries its ICC profile (or the Adobe RGB one
/// its Exif names) with the values unchanged; a linear DNG gets the values converted through the profile.
/// </summary>
[Test]
public void TheOriginalsColourSpaceIsKept()
{
var folder = context.CreateTempDirectory("source");
var p3 = IccProfile.DisplayP3;
using var scene = ColorFixtures.Scene();
var jpegPath = Path.Combine(folder, "p3.jpg");
File.WriteAllBytes(jpegPath, ColorFixtures.Jpeg(scene, p3.Data, ExifWriter.BuildTiff(Camera)));
var source = new ConvertSource(jpegPath, Frame("p3.jpg", ImageFileFormat.Jpeg, 48, 32));
var server = DecoderFactory.CreateServer();
using var original = server.Decode(new DecodeRequest(jpegPath, AllowPreview: false))!;
foreach (var target in (ConvertTarget[])[ConvertTarget.Jpeg, ConvertTarget.Tiff16])
{
var options = new ConvertOptions(target);
var file = FrameConverter.Convert(source, options, server, Target(options), cancellationToken: context.Cancellation);
Assert.BytesEqual(p3.Data, SourceColor.Read(file.Path, file.Format).Profile!.Data);
using var converted = server.Decode(new DecodeRequest(file.Path, AllowPreview: false))!;
var error = 0.0;
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < scene.PlaneLength; i++) error += Math.Abs(original.Pixels.Plane(c)[i] - converted.Pixels.Plane(c)[i]);
}
Assert.Less(error / (3.0 * scene.PlaneLength), target == ConvertTarget.Jpeg ? 0.02 : 1e-3, $"the values of {target} pass unchanged");
}
var dng = new ConvertOptions(ConvertTarget.LinearDng);
var linear = FrameConverter.Convert(source, dng, server, Target(dng), cancellationToken: context.Cancellation);
using var developed = server.Decode(new DecodeRequest(linear.Path, AllowPreview: false))!;
var matrix = p3.ToLinearRec709();
for (var i = 0; i < scene.PlaneLength; i += 7)
{
var code = new Vector3D(
p3.Curves![0].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(0)[i])),
p3.Curves[1].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(1)[i])),
p3.Curves[2].Evaluate(ColorSpace.LinearToSrgb(original.Pixels.Plane(2)[i])));
var expected = matrix * code;
Assert.Approximately(expected.X, developed.Pixels.Plane(0)[i], 5e-4);
Assert.Approximately(expected.Y, developed.Pixels.Plane(1)[i], 5e-4);
Assert.Approximately(expected.Z, developed.Pixels.Plane(2)[i], 5e-4);
}
// The P3 green patch is outside sRGB: its red is negative in the DNG, not clipped to 0.
Assert.Less(developed.Pixels[0, 2, 2], -0.05);
// A camera JPEG in Adobe RGB (Exif uncalibrated, Interop R03) carries the Adobe RGB profile; a PNG its iCCP.
var adobePath = Path.Combine(folder, "adobe.jpg");
File.WriteAllBytes(adobePath, ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF, "R03")));
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
var adobe = FrameConverter.Convert(new ConvertSource(adobePath, Frame("adobe.jpg", ImageFileFormat.Jpeg, 48, 32)), jpeg, server, Target(jpeg),
cancellationToken: context.Cancellation);
Assert.Equal("Compatible with Adobe RGB (1998)", SourceColor.Read(adobe.Path, adobe.Format).Profile!.Description);
var pngPath = Path.Combine(folder, "p3.png");
File.WriteAllBytes(pngPath, ColorFixtures.Png(scene, p3.Data));
var tiff = new ConvertOptions(ConvertTarget.Tiff16);
var fromPng = FrameConverter.Convert(new ConvertSource(pngPath, Frame("p3.png", ImageFileFormat.Png, 48, 32)), tiff, server, Target(tiff),
cancellationToken: context.Cancellation);
Assert.BytesEqual(p3.Data, SourceColor.Read(fromPng.Path, fromPng.Format).Profile!.Data);
}
/// <summary>A colour space nothing here can keep (uncalibrated without R03, a CMYK profile) refuses the photo, whatever the target.</summary>
[Test]
public void APhotoWhoseColourSpaceCannotBeKeptIsRefused()
{
var folder = context.CreateTempDirectory("source");
using var scene = ColorFixtures.Scene();
var unknown = Path.Combine(folder, "unknown.jpg");
File.WriteAllBytes(unknown, ColorFixtures.Jpeg(scene, exifTiff: ColorFixtures.Exif(0xFFFF)));
var cmyk = Path.Combine(folder, "cmyk.jpg");
File.WriteAllBytes(cmyk, ColorFixtures.Jpeg(scene, ColorFixtures.Cmyk()));
foreach (var target in Enum.GetValues<ConvertTarget>())
{
var options = new ConvertOptions(target);
foreach (var path in (string[])[unknown, cmyk])
{
var output = Target(options);
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, Frame(Path.GetFileName(path), ImageFileFormat.Jpeg, 48, 32)),
options, DecoderFactory.CreateServer(), output, cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.ColorProfile, refused.Reason);
Assert.FileMissing(output);
}
}
}
/// <summary>A photo larger than the target or one buffer holds fails as too large, not with the encoder's own exception.</summary>
[Test]
public void APhotoTooLargeForTheTargetFailsAsTooLarge()
{
var path = Path.Combine(context.CreateTempDirectory("source"), "panorama.png");
using (var image = Scene(8, 8)) File.WriteAllBytes(path, PngEncoder.Encode(image));
var frame = Frame("panorama.png", ImageFileFormat.Png, 70_000, 1);
var jpeg = new ConvertOptions(ConvertTarget.Jpeg);
using var wide = new ImageBuffer(65_536, 1);
var refused = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, frame), jpeg,
new ImageDecoder([new Developed(wide, ImageFileFormat.Png)]), Target(jpeg), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.TooLarge, refused.Reason);
var overflow = Assert.Throws<ConversionException>(() => FrameConverter.Convert(new ConvertSource(path, frame), new ConvertOptions(ConvertTarget.Tiff16),
new ImageDecoder([new Overflowing()]), Target(jpeg), cancellationToken: context.Cancellation));
Assert.Equal(ConversionFailure.TooLarge, overflow.Reason);
}
/// <summary>Why a photo failed reads as one sentence by cause in the job log, never the exception's English text.</summary>
[Test]
public void FailuresReadAsOneSentenceByCause()
{
foreach (var reason in Enum.GetValues<ConversionFailure>())
{
var text = FrameConverter.FailureText(new ConversionException(reason, "technical detail"));
Assert.Equal(Loc.L("Archive.Convert.Failed." + reason), text);
Assert.NotNull(Loc.Get("Archive.Convert.Failed." + reason, CultureInfo.GetCultureInfo("it")));
Assert.False(text.Contains("technical", StringComparison.Ordinal), text);
}
Assert.Equal(Loc.L("Archive.Convert.Failed.Full"), FrameConverter.FailureText(new IOException("full", unchecked((int)0x80070070))));
Assert.Equal(Loc.L("Archive.Failed.Access"), FrameConverter.FailureText(new UnauthorizedAccessException("denied")));
Assert.Equal(Loc.L("Archive.Convert.Failed.Unreadable"), FrameConverter.FailureText(new InvalidDataException("JPEG: bad Huffman")));
Assert.Equal(Loc.L("Archive.Failed.Files"), FrameConverter.FailureText(new IOException("network")));
Assert.Equal(Loc.L("Archive.Convert.Failed.Other"), FrameConverter.FailureText(new ArgumentOutOfRangeException("width")));
}
/// <summary>WIC with the Raw Image Extension, as a conversion sees it: every RAW native, developed at 8 bits (counted).</summary>
private sealed class EightBitRaw : IImageDecoderProvider
{
private readonly ManagedDecoderProvider _managed = new();
public int Calls { get; private set; }
public string Name => "wic";
public bool DevelopsRawAt8Bits => true;
public DecodeTier? TierFor(ImageFileFormat format) => ImageFormatInfo.Of(format).IsRaw ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
Calls++;
var decoded = _managed.Decode(request, cancellationToken)!;
foreach (ref var v in decoded.Pixels.Data) v = ColorSpace.Linear8(ColorSpace.Encode8(v));
return new DecodedImage(decoded.Pixels, DecodeTier.Native, Name, decoded.SourceWidth, decoded.SourceHeight);
}
}
/// <summary>A RAW decoder that develops every file of <paramref name="format"/> into a copy of <paramref name="image"/>.</summary>
private sealed class Developed(ImageBuffer image, ImageFileFormat format = ImageFileFormat.Cr2) : IImageDecoderProvider
{
public string Name => "developed";
public DecodeTier? TierFor(ImageFileFormat f) => f == format ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) =>
new(image.Clone(), DecodeTier.Native, Name, image.Width, image.Height);
}
/// <summary>A decoder whose image is too large for one buffer.</summary>
private sealed class Overflowing : IImageDecoderProvider
{
public string Name => "overflowing";
public DecodeTier? TierFor(ImageFileFormat format) => DecodeTier.Native;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => throw new OverflowException();
}
/// <summary>A provider that claims DNG natively but only ever gives the embedded-preview tier.</summary>
private sealed class PreviewOnlyProvider : IImageDecoderProvider
{
@@ -21,6 +21,24 @@ public sealed class WicDecoderProviderTests(TestContext context)
Assert.Null(Provider.TierFor(ImageFileFormat.Unknown));
}
/// <summary>
/// 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).
/// </summary>
[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()
{
@@ -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)));
@@ -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);
}
/// <summary>Every reason a photo stays as it is has its wire name and its sentence in the catalog (en and it).</summary>
[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<Chronos.Core.Conversion.ConvertSkip>().Select(Chronos.Server.Api.ArchiveEndpoints.Wire));
foreach (var reason in Enum.GetValues<Chronos.Core.Conversion.ConvertSkip>())
{
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;