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,91 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Convert"/>: a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, which plans again, refuses when the archive's
/// volume lacks the space, and converts one sequence at a time, each all or nothing; its journal makes every stage
/// resumable. Progress counts photos; the checkpoint only marks a resume, the journal says where. Each sequence whose frames
/// were replaced is told as <c>converted</c>, each new sequence as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>),
/// and the passes they need (light analysis, a deep one when the source had it, thumbnails and proxies) are queued as
/// follow-ups. Sequences left as they were (changed after the plan, busy, a photo that failed) are logged and fail the job
/// at the end, after the others are converted; a retry tries them again.
/// </summary>
internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
{
/// <summary>The change told about a sequence whose frames a conversion replaced.</summary>
public const string Converted = "converted";
/// <summary>The change told about a sequence a conversion made.</summary>
public const string Created = "created";
private const string Checkpoint = "convert";
public JobKind Kind => JobKind.Convert;
public async Task RunAsync(JobContext context)
{
var parameters = (context.Job.ParametersJson is { Length: > 0 } json ? JsonSerializer.Deserialize(json, ArchiveJobJson.Default.ConvertJobParameters) : null)
?? throw new InvalidOperationException($"Convert job {context.Job.Id} has no plan.");
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Convert job {context.Job.Id} has no confirmed plan.");
var archive = await db.Archives.GetAsync(parameters.ArchiveId, context.Cancellation).ConfigureAwait(false)
?? throw new InvalidOperationException($"Convert job {context.Job.Id} does not name a known archive.");
var by = context.Job.CreatedBy is { } user ? (await db.Users.GetAsync(user, context.Cancellation).ConfigureAwait(false))?.Username : null;
var result = await converter.RunAsync(archive, parameters, context.Job.Id, by, new ConvertCallbacks(
(done, total) => context.ReportAsync(done, total),
(done, total) => context.CheckpointAsync(Checkpoint, done, total),
context.Log), context.Cancellation).ConfigureAwait(false);
await QueueAsync(context, result).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.ConvertDone", result.Sequences.Count(s => s.Outcome == ConvertOutcome.Converted),
result.Sequences.Count(s => s.Outcome == ConvertOutcome.Created), result.Frames));
await TellAsync(result).ConfigureAwait(false);
var kept = result.Kept.Count();
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ConvertKept", kept));
}
/// <summary>Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on.</summary>
private async Task QueueAsync(JobContext context, ConvertResult result)
{
foreach (var request in result.FollowUps)
{
try
{
if (request.Targets.Count > 0 && await db.Jobs.IsQueuedAsync(request.Kind, request.Targets[0], CancellationToken.None).ConfigureAwait(false)) continue;
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
catch (DatabaseException ex)
{
Log.Warning("archive", $"{request.Label}: the passes its converted frames need were not queued; the next scan queues them", ex);
}
}
}
/// <summary>Tells each sequence changed or made; a failure is logged, never passed on to the job.</summary>
private async Task TellAsync(ConvertResult result)
{
if (sequenceChanged is null) return;
foreach (var sequence in result.Sequences)
{
var (id, change) = sequence.Outcome switch
{
ConvertOutcome.Converted => (sequence.SequenceId, Converted),
ConvertOutcome.Created when sequence.NewSequenceId is { } made => (made, Created),
_ => (Guid.Empty, string.Empty),
};
if (id == Guid.Empty) continue;
try
{
await sequenceChanged(id, change, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("archive", $"The change of sequence {id} was not told", ex);
}
}
}
}