feat: owner review 2 phase 4b: mass conversion after import (#13)
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
Convert photos already in the archive to JPEG, TIFF-16 or Linear DNG, from the panel's Library and the desktop's Archive and Library. Each run asks Replace (same frames, originals to the trash, recoverable) or New sequence. A dry run lists what converts, what is skipped and why, size before and after, and free space; the job converts exactly the confirmed photos, resumes, and commits all or nothing per sequence. A conversion never changes what Chronos reads from a photo. Replaced originals are erased only on the archive's own word that their conversion is gone. Desktop TIFFs that WIC showed black or as noise now go to the managed reader; the Edit picker no longer spins a core. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #13.
This commit is contained in:
1 parent
7e4a3b481d
commit
efa87f68ce
354 files changed
+24530
-843
No files matched your search
@@ -0,0 +1,104 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Core.Conversion;
|
||||
|
||||
/// <summary>The format a mass conversion writes (owner review 2, R7; BRIEF §12.5).</summary>
|
||||
public enum ConvertTarget
|
||||
{
|
||||
/// <summary>Baseline JPEG, 8-bit sRGB, 4:4:4 chroma, quality 1–100 (<see cref="ConvertOptions.Quality"/>).</summary>
|
||||
Jpeg,
|
||||
|
||||
/// <summary>TIFF, 16-bit sRGB RGB, Deflate with the horizontal predictor.</summary>
|
||||
Tiff16,
|
||||
|
||||
/// <summary>Linear DNG (LinearRaw, 16-bit, lossless JPEG tiles): the archival choice.</summary>
|
||||
LinearDng,
|
||||
}
|
||||
|
||||
/// <summary>What a conversion does with the frames it converts; chosen at every run (owner review 2, R7).</summary>
|
||||
public enum ConvertMode
|
||||
{
|
||||
/// <summary>The converted files become the sequence's frames (same ids and indices); the old files go to the archive's trash.</summary>
|
||||
Replace,
|
||||
|
||||
/// <summary>The converted files go into a new sequence; the source is left as it is.</summary>
|
||||
NewSequence,
|
||||
}
|
||||
|
||||
/// <summary>The target format of a conversion and its quality (JPEG only).</summary>
|
||||
/// <param name="Quality">IJG quality 1–100 of a JPEG; ignored by the other targets.</param>
|
||||
public sealed record ConvertOptions(ConvertTarget Target, int Quality = ConvertOptions.DefaultQuality)
|
||||
{
|
||||
/// <summary>JPEG quality when none is given.</summary>
|
||||
public const int DefaultQuality = 95;
|
||||
|
||||
/// <summary>The target suggested for archiving: lossless, 16-bit, and read by every raw editor.</summary>
|
||||
public const ConvertTarget ArchivalTarget = ConvertTarget.LinearDng;
|
||||
|
||||
/// <summary>The format the converted files have.</summary>
|
||||
public ImageFileFormat Format => Target switch
|
||||
{
|
||||
ConvertTarget.Jpeg => ImageFileFormat.Jpeg,
|
||||
ConvertTarget.Tiff16 => ImageFileFormat.Tiff,
|
||||
_ => ImageFileFormat.Dng,
|
||||
};
|
||||
|
||||
/// <summary>The extension of the converted files, lower case with its dot.</summary>
|
||||
public string Extension => Target switch
|
||||
{
|
||||
ConvertTarget.Jpeg => ".jpg",
|
||||
ConvertTarget.Tiff16 => ".tif",
|
||||
_ => ".dng",
|
||||
};
|
||||
|
||||
/// <summary>The format's short name, as a new sequence's title ends with it: "Harbour (DNG)".</summary>
|
||||
public string Label => Target switch
|
||||
{
|
||||
ConvertTarget.Jpeg => "JPEG",
|
||||
ConvertTarget.Tiff16 => "TIFF",
|
||||
_ => "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;
|
||||
|
||||
/// <summary>Whether the target is known and the quality in 1–100.</summary>
|
||||
public bool IsValid => Enum.IsDefined(Target) && Quality is >= 1 and <= 100;
|
||||
|
||||
/// <summary>What identifies the options in a plan's fingerprint.</summary>
|
||||
public string Key => string.Create(CultureInfo.InvariantCulture, $"{Target}|{EffectiveQuality}");
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/> with this target's extension in place of its own (<c>originals/IMG_0001.CR2</c> →
|
||||
/// <c>originals/IMG_0001.dng</c>): the file a converted copy takes its <c>{ext}</c> from when it is named
|
||||
/// (<see cref="FileName"/>, or the ingest filing it into a new sequence).
|
||||
/// </summary>
|
||||
public string WithExtension(string file)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
return file[..^Path.GetExtension(file).Length] + Extension;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name the converted copy of <paramref name="frame"/> is filed under in <paramref name="sequence"/> (relative to its
|
||||
/// folder), as filing names a photo there (<see cref="FrameNaming"/>: an import, an upload and Reorganize name it alike):
|
||||
/// the archive's file <paramref name="template"/> with the frame's context in the sequence (the sequence's camera and lens,
|
||||
/// <c>{n}</c> = its index + 1, the sequence's title), <c>{name}</c> the name the photo had on the card and <c>{ext}</c> this
|
||||
/// target's extension, a long name shortened before its extension; in the folder of the frame's file. Not made unique
|
||||
/// (<see cref="UniqueNames"/> does).
|
||||
/// </summary>
|
||||
public string FileName(PathTemplate template, SidecarFrame frame, SequenceManifest sequence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)];
|
||||
return directory + template.ExpandFile(FrameNaming.Context(frame with { File = WithExtension(frame.File) }, sequence, sequence.Title));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Icc;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Conversion;
|
||||
|
||||
/// <summary>Why a frame of a sequence is not converted (owner review 2, R7); nothing of it is touched.</summary>
|
||||
public enum ConvertSkip
|
||||
{
|
||||
/// <summary>The photo is in the target's format already (a TIFF of 8 bits included).</summary>
|
||||
SameFormat,
|
||||
|
||||
/// <summary>
|
||||
/// This host has no full-resolution decoder for the photo's format (a server and a CR3 or HEIC), or its decoders do not
|
||||
/// read this file at full resolution (a CMYK, CIELab or palette TIFF, a compression or size they do not take, a RAW body
|
||||
/// they do not develop and without a preview): a PC may have one.
|
||||
/// </summary>
|
||||
NoNativeDecoder,
|
||||
|
||||
/// <summary>This host reads the photo only from its embedded preview (a camera body its RAW decoder does not support).</summary>
|
||||
PreviewOnly,
|
||||
|
||||
/// <summary>
|
||||
/// The photo is flagged unreadable, damaged or corrupt: no decoder produced its pixels. A flag set where other decoders
|
||||
/// read the file (the server's, for a CMYK TIFF that WIC reads on a PC) holds only where a decode says so too.
|
||||
/// </summary>
|
||||
Undecodable,
|
||||
|
||||
/// <summary>The photo's file is not there.</summary>
|
||||
Missing,
|
||||
|
||||
/// <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 than Chronos reads back: the server's decoders,
|
||||
/// which every converted file must decode with (<see cref="ConvertPlanner.TooLarge"/>).
|
||||
/// </summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>
|
||||
/// The photo's file is there but could not be opened when the plan was made: another program holds it without sharing
|
||||
/// (a sync client, an editor), or access is denied. A plan made once it is free converts it.
|
||||
/// </summary>
|
||||
Inaccessible,
|
||||
}
|
||||
|
||||
/// <summary>Why a whole sequence is not converted now; nothing of it is touched.</summary>
|
||||
public enum ConvertBlock
|
||||
{
|
||||
/// <summary>A running or paused job works on the sequence or its whole archive, or a conversion of it waits in the queue.</summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>The archive is offline or read-only.</summary>
|
||||
Offline,
|
||||
|
||||
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
|
||||
Unreadable,
|
||||
|
||||
/// <summary>
|
||||
/// The photos the sequence converts are no longer those of the plan confirmed (found by the job, which then leaves it as
|
||||
/// it is).
|
||||
/// </summary>
|
||||
FramesChanged,
|
||||
}
|
||||
|
||||
/// <summary>Frames of a sequence that are not converted, and why.</summary>
|
||||
public sealed record ConvertSkipped(ConvertSkip Reason, int Frames);
|
||||
|
||||
/// <summary>
|
||||
/// One frame a conversion converts: its id and index, its file and format, its size, the converted file's estimated size,
|
||||
/// and the SHA-256 of the content converted.
|
||||
/// </summary>
|
||||
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes, string? Sha256 = null);
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of a conversion plan: the frames converted, those skipped with why, the frames version the plan was made at,
|
||||
/// and why the whole sequence cannot be converted now (<see cref="Blocked"/>).
|
||||
/// </summary>
|
||||
public sealed record ConvertSequencePlan(Guid SequenceId, string Title, string Folder, int FramesVersion, IReadOnlyList<ConvertFramePlan> Frames,
|
||||
IReadOnlyList<ConvertSkipped> Skipped, IReadOnlyList<ConvertBlock> Blocked)
|
||||
{
|
||||
/// <summary>Whether the sequence is converted: something to convert and nothing blocking it.</summary>
|
||||
public bool Converts => Blocked.Count == 0 && Frames.Count > 0;
|
||||
|
||||
/// <summary>Size of the originals converted.</summary>
|
||||
public long BytesBefore => Frames.Sum(f => f.Size);
|
||||
|
||||
/// <summary>Estimated size of the converted files.</summary>
|
||||
public long BytesAfter => Frames.Sum(f => f.EstimatedBytes);
|
||||
|
||||
public int SkippedFrames => Skipped.Sum(s => s.Frames);
|
||||
|
||||
/// <summary>
|
||||
/// A digest of the photos the sequence converts: each frame in order with the SHA-256 of the content converted. A
|
||||
/// conversion job converts the sequence only while its plan there still has the digest the user confirmed.
|
||||
/// </summary>
|
||||
public string Digest() => DigestOf(Frames.Select(f => (f.FrameId, f.Sha256)));
|
||||
|
||||
/// <summary>The digest of frames, each with the SHA-256 of its content, in order (<see cref="Digest"/>).</summary>
|
||||
public static string DigestOf(IEnumerable<(Guid FrameId, string? Sha256)> frames)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
var text = new StringBuilder();
|
||||
foreach (var (id, sha) in frames) text.Append(CultureInfo.InvariantCulture, $"{id:N}|{sha?.ToLowerInvariant()}\n");
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The free space a conversion needs on the archive's volume (<see cref="Required"/>: the estimate with a margin and a
|
||||
/// reserve, <see cref="ConvertPlanner.Required"/>) and what it has; <see cref="Free"/> null when it cannot be measured.
|
||||
/// </summary>
|
||||
public sealed record ConvertSpace(long Required, long? Free)
|
||||
{
|
||||
public bool Enough => Free is not { } free || free >= Required;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a mass conversion (owner review 2, R7): the options and mode, each sequence's plan, the space it needs,
|
||||
/// and the fingerprint the confirmation sends back (<see cref="Fingerprint"/>).
|
||||
/// </summary>
|
||||
public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, ConvertMode Mode, IReadOnlyList<ConvertSequencePlan> Sequences, ConvertSpace Space)
|
||||
{
|
||||
/// <summary>The sequences that are converted.</summary>
|
||||
public IEnumerable<ConvertSequencePlan> Converted => Sequences.Where(s => s.Converts);
|
||||
|
||||
public int Frames => Converted.Sum(s => s.Frames.Count);
|
||||
|
||||
public long BytesBefore => Converted.Sum(s => s.BytesBefore);
|
||||
|
||||
public long BytesAfter => Converted.Sum(s => s.BytesAfter);
|
||||
|
||||
public int Skipped => Sequences.Sum(s => s.SkippedFrames);
|
||||
|
||||
/// <summary>
|
||||
/// A digest of what the plan converts (options, mode, and each sequence in order with its frames version, the photos
|
||||
/// converted with their content (<see cref="ConvertSequencePlan.Digest"/>), those skipped, and what blocks it), the
|
||||
/// same for two plans of the same archive state.
|
||||
/// </summary>
|
||||
public string Fingerprint()
|
||||
{
|
||||
var text = new StringBuilder().Append(Options.Key).Append('|').Append(Mode).Append('\n');
|
||||
foreach (var s in Sequences)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FramesVersion}|{s.Frames.Count}|{s.BytesBefore}|{s.Digest()}|");
|
||||
foreach (var skipped in s.Skipped) text.Append(CultureInfo.InvariantCulture, $"{skipped.Reason}:{skipped.Frames};");
|
||||
foreach (var blocked in s.Blocked) text.Append(blocked).Append(';');
|
||||
text.Append('\n');
|
||||
}
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 (or another host's decoders flagged it and
|
||||
/// this host's decode it), its size is one the target holds and the server's decoders read back (<see cref="TooLarge"/>),
|
||||
/// 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, its headers saying what those decoders take; 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 (and decoding small the few frames flagged elsewhere), several at once; a file it
|
||||
/// cannot read now is inaccessible, never a verdict on its content. 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>Long edge of the decode that asks a frame flagged unreadable elsewhere whether this host's decoders read it.</summary>
|
||||
private const int ConfirmEdge = 64;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>Space left free on the volume after the conversion, for the index, sidecars and everything else writing there.</summary>
|
||||
public const long SpaceReserve = 512L << 20;
|
||||
|
||||
/// <summary>Pixels assumed for a frame whose size is not known (a 24 MP sensor).</summary>
|
||||
public const long UnknownPixels = 24_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// Bits per pixel of a 4:4:4 JPEG over a 4:2:0 one of the same quality: the chroma is coded at full resolution, about a
|
||||
/// quarter more bits on photographs.
|
||||
/// </summary>
|
||||
private const double FullChroma = 1.25;
|
||||
|
||||
/// <summary>
|
||||
/// Bits per pixel of pixels that do not compress at all (noise) in the costliest target: three 16-bit samples, 48 bits
|
||||
/// as Deflate stores them, and less than a bit more each as lossless JPEG codes them (an optimal Huffman code exceeds
|
||||
/// the entropy of what it codes by less than one bit); a 4:4:4 JPEG of noise at quality 100 takes about 22.
|
||||
/// </summary>
|
||||
public const int WorstBitsPerPixel = 51;
|
||||
|
||||
/// <summary>
|
||||
/// Margin on <see cref="WorstBitsPerPixel"/>: Deflate's stored blocks and zlib framing per strip, lossless JPEG's byte
|
||||
/// stuffing (a 0xFF byte in 256 of noise) and headers per tile stay below 1 %.
|
||||
/// </summary>
|
||||
private const double WorstMargin = 1.01;
|
||||
|
||||
/// <summary>What a converted file holds beyond its pixels at most: an ICC profile carried whole, the Exif block, the directory and its strip or tile tables.</summary>
|
||||
private const long WorstOverhead = IccProfile.MaxBytes + (4L << 20);
|
||||
|
||||
/// <summary>The plan of one sequence from its sidecar.</summary>
|
||||
/// <param name="present">Every file in the folders of the sequence's frames, relative to the sequence folder
|
||||
/// (<see cref="FileRenames.ListPresent"/>): the frames whose file is not among them are missing.</param>
|
||||
/// <param name="decoder">This host's decoders.</param>
|
||||
public static ConvertSequencePlan Plan(SequenceManifest manifest, SequencePaths folder, IReadOnlyCollection<string> present, ConvertOptions options,
|
||||
ImageDecoder decoder, string title)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
ArgumentNullException.ThrowIfNull(folder);
|
||||
ArgumentNullException.ThrowIfNull(present);
|
||||
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>();
|
||||
for (var i = 0; i < reasons.Length; i++)
|
||||
{
|
||||
var frame = manifest.Frames[i];
|
||||
if (reasons[i] is { } reason)
|
||||
{
|
||||
skipped[reason] = skipped.GetValueOrDefault(reason) + 1;
|
||||
continue;
|
||||
}
|
||||
frames.Add(new ConvertFramePlan(frame.Id, frame.I, frame.File, frame.Format, frame.Size, EstimateBytes(options, frame.W, frame.H), frame.Sha256));
|
||||
}
|
||||
return new ConvertSequencePlan(manifest.Id, title, folder.RelativeFolder, manifest.Versions.Frames, frames,
|
||||
[.. skipped.OrderBy(s => s.Key).Select(s => new ConvertSkipped(s.Key, s.Value))], []);
|
||||
}
|
||||
|
||||
/// <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.Corrupt) != 0) return ConvertSkip.Undecodable;
|
||||
var decoders = FrameConverter.Decoders(decoder, options, frame.Format);
|
||||
// Flagged unreadable by the host that analysed it last: on a server, whose managed decoders refuse what they do not
|
||||
// read (a CMYK or CIELab TIFF), that holds for a PC only where its own decoders (WIC) do not read it either.
|
||||
var flagged = (frame.Flags & FrameFlags.Undecodable) != 0;
|
||||
if (flagged && !OthersRead(decoders, frame.Format)) return ConvertSkip.Undecodable;
|
||||
if (TooLarge(options, frame.W, frame.H)) return ConvertSkip.TooLarge;
|
||||
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
|
||||
{
|
||||
// Not read at full resolution here, although the format is: what the file holds (its encoding, its size, a RAW
|
||||
// body) is beyond these decoders, and only a preview, or nothing, is left.
|
||||
var probe = decoders.Probe(path, frame.Format);
|
||||
if (probe.Tier != DecodeTier.Native)
|
||||
{
|
||||
return flagged ? ConvertSkip.Undecodable
|
||||
: eightBit ? ConvertSkip.EightBit
|
||||
: probe.Tier == DecodeTier.EmbeddedPreview ? ConvertSkip.PreviewOnly
|
||||
: ConvertSkip.NoNativeDecoder;
|
||||
}
|
||||
if (TooLarge(options, probe.Width, probe.Height)) return ConvertSkip.TooLarge;
|
||||
// The flag was another host's verdict, whose decoders failed where the headers say nothing: a decode here says
|
||||
// whether these read its pixels.
|
||||
if (flagged && !Decodes(decoders, path)) return ConvertSkip.Undecodable;
|
||||
return FrameConverter.Treatment(SourceColor.Read(path, frame.Format), options.Target) == ColorTreatment.Refuse ? ConvertSkip.ColorProfile : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
// Gone since the folder was listed.
|
||||
return ConvertSkip.Missing;
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
// Opened, and shorter than its own headers say: no decoder gets its pixels.
|
||||
return ConvertSkip.Undecodable;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// There, but held by another program or denied, or a read failed: not missing, and not planned (a conversion job
|
||||
// converts only the photos its plan listed), so the dry run says why. Nothing is concluded of its content.
|
||||
return ConvertSkip.Inaccessible;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="decoders"/> have, for <paramref name="format"/>, a native decoder besides the managed ones
|
||||
/// every host has (WIC on a PC): a frame those flagged unreadable may still decode here.
|
||||
/// </summary>
|
||||
private static bool OthersRead(ImageDecoder decoders, ImageFileFormat format) =>
|
||||
decoders.Providers.Any(p => p is not ManagedDecoderProvider && p.TierFor(format) == DecodeTier.Native);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="decoders"/> produce the pixels of the file at <paramref name="path"/> at full-resolution tier,
|
||||
/// asked with a small decode.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
private static bool Decodes(ImageDecoder decoders, string path)
|
||||
{
|
||||
using var decoded = decoders.Decode(new DecodeRequest(path, ConfirmEdge, DecodePurpose.Thumbnail, ApplyOrientation: false, AllowPreview: false));
|
||||
return decoded is { Tier: DecodeTier.Native, ByChoice: false };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a frame of <paramref name="width"/> × <paramref name="height"/> (unknown: 0) cannot be converted to
|
||||
/// <paramref name="options"/>, a bound and never an estimate: the target does not hold it (a JPEG side above
|
||||
/// <see cref="FrameConverter.MaxJpegSide"/>), Chronos does not read it back (the server's decoders, which every converted
|
||||
/// file must decode with, <see cref="FrameConverter.Verify"/>: a JPEG of more pixels than
|
||||
/// <see cref="JpegDecodeOptions.MaxPixels"/>, a TIFF-16 or DNG of more samples than <see cref="TiffDecodeOptions.MaxSamples"/>),
|
||||
/// or its file could outgrow the array it is made in (<see cref="WorstBytes"/>, which those sizes keep below it). What it
|
||||
/// lets through fits one image buffer, its file the array it is made in, and the server's decoders read it back. Any
|
||||
/// size is answered, a damaged header's included: nothing is multiplied beyond what a long holds.
|
||||
/// </summary>
|
||||
public static bool TooLarge(ConvertOptions options, int width, int height)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
// At most (2^31 - 1)^2, below 2^62.
|
||||
var pixels = (long)width * height;
|
||||
var readBack = options.Target == ConvertTarget.Jpeg
|
||||
? Math.Max(width, height) <= FrameConverter.MaxJpegSide && pixels <= JpegDecodeOptions.Default.MaxPixels
|
||||
: pixels <= TiffDecodeOptions.Default.MaxSamples / 3;
|
||||
return !readBack || WorstBytes(width, height) > Array.MaxLength;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The largest a converted file of <paramref name="width"/> × <paramref name="height"/> pixels can be when its pixels do
|
||||
/// not compress at all, in any target: <see cref="WorstBitsPerPixel"/> with its margin, and the most a file holds beyond
|
||||
/// its pixels; <see cref="long.MaxValue"/> for sizes beyond it.
|
||||
/// </summary>
|
||||
public static long WorstBytes(int width, int height) =>
|
||||
Saturated(Math.Ceiling((double)Math.Max(0, width) * Math.Max(0, height) * WorstBitsPerPixel / 8 * WorstMargin) + WorstOverhead);
|
||||
|
||||
/// <summary><paramref name="bytes"/> (whole, not negative) as a long, <see cref="long.MaxValue"/> when beyond it.</summary>
|
||||
private static long Saturated(double bytes) => bytes >= long.MaxValue ? long.MaxValue : (long)bytes;
|
||||
|
||||
/// <summary>
|
||||
/// Estimated size of a converted file of <paramref name="width"/> × <paramref name="height"/> pixels (unknown:
|
||||
/// <see cref="UnknownPixels"/>), from the bits per pixel the Export tab estimates with (<see cref="ExportEstimator"/>):
|
||||
/// JPEG by quality (×1.25 for 4:4:4 chroma), TIFF-16 30, linear DNG 26.
|
||||
/// </summary>
|
||||
public static long EstimateBytes(ConvertOptions options, int width, int height)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var pixels = width > 0 && height > 0 ? (double)width * height : UnknownPixels;
|
||||
var bits = options.Target switch
|
||||
{
|
||||
ConvertTarget.Jpeg => ExportEstimator.JpegBitsPerPixel(options.Quality) * FullChroma,
|
||||
ConvertTarget.Tiff16 => 30,
|
||||
_ => 26,
|
||||
};
|
||||
return Saturated(Math.Ceiling(pixels * bits / 8));
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
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.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Conversion;
|
||||
|
||||
/// <summary>The photo a conversion reads: its file, its sidecar record, and its sequence's camera and lens.</summary>
|
||||
/// <param name="Path">Absolute path of the original.</param>
|
||||
public sealed record ConvertSource(string Path, SidecarFrame Frame, SidecarCamera? Camera = null, string? Lens = null);
|
||||
|
||||
/// <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>Why a photo was not converted; each has its sentence, <c>Archive.Convert.Failed.<reason></c>.</summary>
|
||||
public enum ConversionFailure
|
||||
{
|
||||
/// <summary>No decoder of this host reads the photo at full resolution.</summary>
|
||||
NoDecoder,
|
||||
|
||||
/// <summary>This host reads the photo only from its embedded preview.</summary>
|
||||
PreviewOnly,
|
||||
|
||||
/// <summary>A 16-bit target, and this host develops the RAW at 8 bits only (WIC's Raw Image Extension).</summary>
|
||||
EightBit,
|
||||
|
||||
/// <summary>The photo's colour profile cannot be carried into the target or converted to it.</summary>
|
||||
ColorProfile,
|
||||
|
||||
/// <summary>
|
||||
/// The photo is larger than the target holds, than the server's decoders read back (<see cref="ConvertPlanner.TooLarge"/>)
|
||||
/// or than one image in memory can.
|
||||
/// </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>The photo's pixels hold values that are not numbers (NaN, or infinite): its data is damaged.</summary>
|
||||
Damaged,
|
||||
}
|
||||
|
||||
/// <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), 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. What
|
||||
/// Chronos reads from the photo never changes: the converted file decodes, with Chronos's own decoders, to the values the
|
||||
/// original decoded to, within what the target holds (a JPEG or TIFF-16 holds 0..1 at 8 or 16 bits, a DNG 16-bit linear
|
||||
/// values up to 4 stops above white), and says truthfully what they are (<see cref="Treatment"/>, from the colour space
|
||||
/// <see cref="SourceColor"/> reads): a JPEG or TIFF carries the original's ICC profile when it keeps the original's codes,
|
||||
/// or a profile made for the codes it holds; a DNG, whose matrices Chronos develops it with too, takes only values that are
|
||||
/// sRGB's as the decoders read them; any other photo is refused, as is one whose pixels are not numbers (damaged data). A
|
||||
/// photo larger than the plan allows is refused at the size decoded (<see cref="ConvertPlanner.TooLarge"/>). 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"/>).
|
||||
/// Every provider's probes read each file's headers (<see cref="IImageDecoderProvider.WithHeaderProbes"/>: the managed
|
||||
/// ones of JPEG, PNG and TIFF files, WIC's of any), so what a provider's decoder refuses (a CMYK or palette TIFF, a
|
||||
/// compression or size it does not take) is asked of the others, or is not planned where none takes it.
|
||||
/// </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))
|
||||
.Select(p => p.WithHeaderProbes())
|
||||
.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"/>, so that
|
||||
/// the converted file decodes, with Chronos's decoders, to the values the original decoded to, and says truthfully what
|
||||
/// they are. The decoders never read a profile: they take code values through the sRGB curve and linear values (a float
|
||||
/// TIFF's, <see cref="SourceColor.IsLinear"/>) as they are, and every converted file is written as they read it back. A
|
||||
/// JPEG or TIFF keeps the codes of code values in an RGB profile and carries that profile (<see cref="ColorTreatment.Carry"/>);
|
||||
/// it holds linear values as sRGB codes, with the profile's colorants and the sRGB curve (<see cref="ColorTreatment.Describe"/>),
|
||||
/// or the profile itself when it names sRGB without colorants; it keeps a gray profile's codes with its curve as an RGB
|
||||
/// profile (<see cref="ColorTreatment.Describe"/>), and takes its linear values as linear gray. A DNG says what its values
|
||||
/// are through its matrices, which Chronos develops it with too, so it takes only values that are sRGB's as the decoders
|
||||
/// read them (<see cref="IccProfile.IsSrgbFor"/>): what it would convert to another space would read back changed. A
|
||||
/// space nothing here describes, CMYK, Lab, or values a profile does not say enough of, is refused.
|
||||
/// </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 (target == ConvertTarget.LinearDng) return profile.IsSrgbFor(color.IsLinear) ? ColorTreatment.None : ColorTreatment.Refuse;
|
||||
if (profile.IsGray) return color.IsLinear ? ColorTreatment.None : profile.IsGrayCurve ? ColorTreatment.Describe : ColorTreatment.Refuse;
|
||||
if (!profile.IsRgb) return ColorTreatment.Refuse;
|
||||
if (!color.IsLinear) return ColorTreatment.Carry;
|
||||
return profile.IsMatrixShaper ? ColorTreatment.Describe : profile.IsSrgb ? ColorTreatment.Carry : ColorTreatment.Refuse;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile a JPEG or TIFF carries for <see cref="ColorTreatment.Describe"/>: a gray profile's curve as an RGB profile
|
||||
/// (<see cref="IccProfile.GrayAsRgb"/>), else a matrix/TRC profile's colorants with the sRGB curve the codes are in
|
||||
/// (<see cref="IccProfile.WithSrgbCurve"/>).
|
||||
/// </summary>
|
||||
internal static IccProfile Described(IccProfile profile) => profile.IsGray ? profile.GrayAsRgb() : profile.WithSrgbCurve();
|
||||
|
||||
/// <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); 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, at 16 bits for a 16-bit target,
|
||||
/// its colour profile cannot be kept, it is too large, its pixels are not numbers, 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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
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}");
|
||||
// The codes written are those the decoders read back as the original's values: the profile carried says what they are.
|
||||
var iccProfile = treatment switch
|
||||
{
|
||||
ColorTreatment.Carry => color.Profile!.Data,
|
||||
ColorTreatment.Describe => Described(color.Profile!).Data,
|
||||
_ => null,
|
||||
};
|
||||
ConvertedFile file;
|
||||
FrameMetadata metadata;
|
||||
try
|
||||
{
|
||||
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(eightBit ? ConversionFailure.EightBit : ConversionFailure.PreviewOnly,
|
||||
$"{name}: decoded from its {decoded.Tier} only ({decoded.Decoder}), not at full resolution");
|
||||
}
|
||||
var pixels = decoded.Pixels;
|
||||
// What the plan leaves out (ConvertPlanner.TooLarge) is refused here too, at the size decoded.
|
||||
if (ConvertPlanner.TooLarge(options, pixels.Width, pixels.Height))
|
||||
throw new ConversionException(ConversionFailure.TooLarge, $"{name}: {pixels.Width}×{pixels.Height} is too large for {options.Label}");
|
||||
// A float file's NaN or infinity is no value any file holds: written, it would be black (and a DNG's headroom all spent).
|
||||
if (!AllFinite(pixels.Data))
|
||||
throw new ConversionException(ConversionFailure.Damaged, $"{name}: its pixels hold values that are not numbers (NaN or infinite)");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
metadata = Metadata(MetadataReader.Read(source.Path, cancellationToken), source);
|
||||
using var rgb = pixels.Channels == 3 ? null : Rgb(pixels);
|
||||
var image = rgb ?? pixels;
|
||||
using var output = EncodedWithin(name, image, metadata, options, iccProfile, encoderThreads);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Hashed as made, and written from the same bytes (never copied again).
|
||||
var bytes = output.GetBuffer().AsSpan(0, (int)output.Length);
|
||||
var sha = System.Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
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);
|
||||
}
|
||||
catch
|
||||
{
|
||||
TryDelete(target);
|
||||
throw;
|
||||
}
|
||||
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,
|
||||
/// metering mode, flash, GPS, artist and copyright, the sequence's camera and lens where the original names none. A
|
||||
/// frame without a capture time keeps the original's own (Exif or XMP), never one taken from the file system.
|
||||
/// </summary>
|
||||
public static FrameMetadata Metadata(FrameMetadata original, ConvertSource source)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(original);
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
var f = source.Frame;
|
||||
var recorded = original.TimestampSource is TimestampSource.ExifOriginal or TimestampSource.ExifCreate or TimestampSource.Xmp;
|
||||
var captured = f.CapturedAt ?? (recorded ? original.CapturedAt : null);
|
||||
return new FrameMetadata
|
||||
{
|
||||
Make = original.Make ?? source.Camera?.Make,
|
||||
Model = original.Model ?? source.Camera?.Model,
|
||||
BodySerial = original.BodySerial ?? source.Camera?.Serial,
|
||||
LensModel = original.LensModel ?? source.Lens,
|
||||
Software = "Chronos",
|
||||
Artist = original.Artist,
|
||||
Copyright = original.Copyright,
|
||||
CapturedAt = captured is { } at ? DateTime.SpecifyKind(at, DateTimeKind.Unspecified) : null,
|
||||
UtcOffsetMinutes = f.CapturedAt is not null ? f.UtcOffset : recorded ? original.UtcOffsetMinutes : null,
|
||||
ExposureTime = f.Exposure ?? original.ExposureTime,
|
||||
FNumber = f.FNumber ?? original.FNumber,
|
||||
Iso = f.Iso ?? original.Iso,
|
||||
FocalLength = f.Focal ?? original.FocalLength,
|
||||
FocalLength35 = original.FocalLength35,
|
||||
ExposureBias = f.Bias ?? original.ExposureBias,
|
||||
ExposureProgram = original.ExposureProgram,
|
||||
MeteringMode = original.MeteringMode,
|
||||
WhiteBalanceMode = f.Wb ?? original.WhiteBalanceMode,
|
||||
Flash = original.Flash,
|
||||
Orientation = 1,
|
||||
Gps = original.Gps,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The file bytes of <paramref name="image"/> (linear light, RGB) in the target format with <paramref name="metadata"/>.</summary>
|
||||
/// <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, iccProfile, encoderThreads);
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Encoded"/>, where a file that outgrows the array it is made in (2 GB: the memory stream says its stream
|
||||
/// was too long) is too large, the photo's failure, never one of the archive's files. The plan leaves out what can
|
||||
/// (<see cref="ConvertPlanner.TooLarge"/>); this is what content beyond its worst case would do.
|
||||
/// </summary>
|
||||
private static MemoryStream EncodedWithin(string name, ImageBuffer image, FrameMetadata metadata, ConvertOptions options, byte[]? iccProfile, int encoderThreads)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Encoded(image, metadata, options, iccProfile, encoderThreads);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Encoding writes to memory only: an I/O error there is the stream's length limit.
|
||||
throw new ConversionException(ConversionFailure.TooLarge, $"{name}: its {options.Label} outgrew the memory one file is made in", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary><see cref="Encode"/> into a stream the caller disposes.</summary>
|
||||
private static MemoryStream Encoded(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, byte[]? iccProfile, int encoderThreads)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
ArgumentNullException.ThrowIfNull(metadata);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
// About the size the planner estimates, so the buffer seldom grows (and is copied) while the file is made.
|
||||
var capacity = (int)Math.Clamp(ConvertPlanner.EstimateBytes(options, image.Width, image.Height) * 5 / 4, 1 << 16, Array.MaxLength);
|
||||
var output = new MemoryStream(capacity);
|
||||
switch (options.Target)
|
||||
{
|
||||
case ConvertTarget.Jpeg:
|
||||
JpegEncoder.Encode(output, image, new JpegEncodeOptions
|
||||
{
|
||||
Quality = options.Quality,
|
||||
Subsampling = JpegSubsampling.Yuv444,
|
||||
OptimizeHuffman = true,
|
||||
App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]],
|
||||
IccProfile = iccProfile,
|
||||
MaxDegreeOfParallelism = encoderThreads,
|
||||
});
|
||||
break;
|
||||
case ConvertTarget.Tiff16:
|
||||
TiffWriter.Write(output, image, new TiffWriteOptions
|
||||
{
|
||||
BitsPerSample = 16,
|
||||
Compression = TiffCompression.Deflate,
|
||||
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;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether every value is a number: neither NaN nor infinite (a float TIFF or DNG whose data is damaged holds such
|
||||
/// values, which every decoder passes on as they are).
|
||||
/// </summary>
|
||||
internal static bool AllFinite(ReadOnlySpan<float> values)
|
||||
{
|
||||
var i = 0;
|
||||
if (Vector.IsHardwareAccelerated && values.Length >= Vector<float>.Count)
|
||||
{
|
||||
var infinity = new Vector<float>(float.PositiveInfinity);
|
||||
var vectors = MemoryMarshal.Cast<float, Vector<float>>(values);
|
||||
// |NaN| < ∞ and |±∞| < ∞ are both false.
|
||||
foreach (var v in vectors)
|
||||
{
|
||||
if (!Vector.LessThanAll(Vector.Abs(v), infinity)) return false;
|
||||
}
|
||||
i = vectors.Length * Vector<float>.Count;
|
||||
}
|
||||
for (; i < values.Length; i++)
|
||||
{
|
||||
if (!float.IsFinite(values[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <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,
|
||||
/// at the size it was written at.
|
||||
/// </summary>
|
||||
/// <param name="written">The metadata the file was written with (<see cref="Metadata"/>).</param>
|
||||
/// <exception cref="ConversionException">The file does not verify.</exception>
|
||||
public static void Verify(ConvertedFile file, FrameMetadata written, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
ArgumentNullException.ThrowIfNull(written);
|
||||
var name = System.IO.Path.GetFileName(file.Path);
|
||||
string sha;
|
||||
long length;
|
||||
using (var stream = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan))
|
||||
{
|
||||
length = stream.Length;
|
||||
sha = System.Convert.ToHexStringLower(SHA256.HashData(stream));
|
||||
}
|
||||
if (length != file.Size || !string.Equals(sha, file.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
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 NotVerified($"{name}: reads as {read.Format}, written as {file.Format}");
|
||||
if (written.CapturedAt is { } captured && read.CapturedAt != captured)
|
||||
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 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 NotVerified($"{name}: the server's decoders do not read it at full resolution");
|
||||
if (decoded.SourceWidth != file.Width || decoded.SourceHeight != 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)
|
||||
{
|
||||
if (image.Channels == 1) return PixelConvert.GrayToRgb(image);
|
||||
var rgb = new ImageBuffer(image.Width, image.Height, 3, clear: false);
|
||||
for (var c = 0; c < 3; c++) image.Plane(c).CopyTo(rgb.Plane(c));
|
||||
return rgb;
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Diagnostics.Log.Warning("archive", $"{path} did not verify and could not be deleted", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a conversion does with the colour space a photo's values are in (<see cref="FrameConverter.Treatment"/>). Whatever it
|
||||
/// does, the converted file holds the values Chronos's decoders read from the original, as they read them back.
|
||||
/// </summary>
|
||||
public enum ColorTreatment
|
||||
{
|
||||
/// <summary>The values are sRGB's as the decoders read them (untagged; an sRGB photo or linear gray into a DNG): no profile.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>A JPEG or TIFF keeps the original's codes and carries its ICC profile, which says what they are.</summary>
|
||||
Carry,
|
||||
|
||||
/// <summary>
|
||||
/// A JPEG or TIFF holds the codes the decoders read back as the original's values, and carries a profile made for them
|
||||
/// (<see cref="FrameConverter.Described"/>): the original's colorants with the sRGB curve (linear values, a float
|
||||
/// TIFF's), or a gray profile's curve as an RGB profile.
|
||||
/// </summary>
|
||||
Describe,
|
||||
|
||||
/// <summary>
|
||||
/// A space nothing here can keep: CMYK, Lab, an unknown space; linear values in a profile without colorants that is not
|
||||
/// sRGB; into a DNG, values that are not sRGB's as the decoders read them (another profile's primaries or curve).
|
||||
/// </summary>
|
||||
Refuse,
|
||||
}
|
||||
Reference in new issue
Block a user