feat(archive): convert sequences to JPEG, TIFF-16 or linear DNG after import

Owner review 2, R7 asks for mass conversion after import on the web panel and the desktop,
with a choice at every run between Replace and New sequence. This is the engine and the
server API both UIs build on.

- Core/Conversion: ConvertOptions (JPEG 4:4:4 at quality 1-100, default 95; TIFF-16 sRGB
  Deflate with the predictor; linear DNG, the archival choice; converted names keep the
  stem and take the target's extension in the old one's case). FrameConverter decodes at
  the native tier only, encodes with the in-house writers, writes Exif from the sidecar
  (capture time to the tick, offset, exposure) and the original (camera, serial, lens,
  modes, GPS), hashes the bytes as made, writes atomically and verifies: read back, the
  metadata again, a decode by the server's decoders. ExifWriter now writes the exposure
  program, metering mode, flash and white balance. ConvertPlanner: convertible frames,
  skips with reasons, size estimates per pixel, the plan's space and fingerprint.
- FrameTrash.ReplaceAsync swaps the files of frames in place: same ids and indices, the old
  files and their XMP companions into one Replaced trash entry (records, replacement
  hashes, a copy of analysis.json), tombstones aliasing old content to new, proxies of the
  swapped frames dropped, under .chronos/replace.pending.json, which the next writer undoes
  or completes. Restoring a Replaced entry swaps back while every converted frame is
  unchanged (the converted files become a Replaced entry in turn), else the originals come
  back as a new sequence.
- MassConverter and JobKind.Convert (19): the dry run (busy, offline, unreadable, space
  against ArchiveServiceOptions.FreeSpace), stage A converting into
  staging/convert-<job>/ in parallel with each source re-hashed and each staged file
  appended to journal/convert-<job>.staged, stage B per sequence all or nothing under the
  lease at the planned frames version: Replace, or a new sequence through the ingest with
  the source's tags, rating, notes and project. Resumes keep verified staged files; a
  sequence changed, busy or with a failed photo is left as it was and fails the job at the
  end, the journal kept for a retry.
- POST /api/v1/archive/convert: dry run with the plan, its space line and fingerprint, or a
  202 convert job; formats the server cannot read at full resolution are skipped as
  convert_on_pc; validated, audited (archive_converted), sequenceChanged converted/created.
  The server measures the space volume for the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 809210d924cfc3f597ecdea26106fb3ff62d3762)
(cherry picked from commit e13d4c0bb1bd9441933b6f3e5b6220e865a7228c)
This commit is contained in:
Alby96 committed 2026-10-27 22:01:23 +01:00
1 parent d518e87733
commit 0e52929274
34 files changed
+3519 -32

No files matched your search

@@ -0,0 +1,224 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
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): 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: no decoder produced its pixels.</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>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.</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 sequence's frames changed after the plan was made (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 and the converted file's estimated size.</summary>
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes);
/// <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>
/// 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 frames
/// converted and 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}|");
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, 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"/>).
/// </summary>
public static class ConvertPlanner
{
/// <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>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 skipped = new Dictionary<ConvertSkip, int>();
var frames = new List<ConvertFramePlan>();
foreach (var frame in manifest.Frames)
{
if (Skip(frame, folder, onDisk, options, decoder) 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)));
}
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>
public static ConvertSkip? Skip(SidecarFrame frame, SequencePaths folder, IReadOnlySet<string> present, ConvertOptions options, ImageDecoder decoder)
{
ArgumentNullException.ThrowIfNull(frame);
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;
}
/// <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 (long)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;
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;
}
}
}