From 0e52929274a80f065e852a64b0eaadcbe696e5d5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 27 Oct 2026 15:44:33 +0100 Subject: [PATCH] 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-/ in parallel with each source re-hashed and each staged file appended to journal/convert-.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 (cherry picked from commit 809210d924cfc3f597ecdea26106fb3ff62d3762) (cherry picked from commit e13d4c0bb1bd9441933b6f3e5b6220e865a7228c) --- docs/ARCHITECTURE.md | 6 +- i18n/en/Admin.resx | 1 + i18n/en/Archive.resx | 23 + i18n/en/Jobs.resx | 1 + i18n/en/Server.resx | 3 + i18n/it/Admin.it.resx | 1 + i18n/it/Archive.it.resx | 23 + i18n/it/Jobs.it.resx | 1 + i18n/it/Server.it.resx | 3 + src/Chronos.Core/Archiving/ArchiveLayout.cs | 4 + src/Chronos.Core/Conversion/ConvertOptions.cs | 84 ++ src/Chronos.Core/Conversion/ConvertPlanner.cs | 224 ++++++ src/Chronos.Core/Conversion/FrameConverter.cs | 239 ++++++ src/Chronos.Core/Metadata/ExifWriter.cs | 17 +- src/Chronos.Core/Model/Enums.cs | 8 +- src/Chronos.Data/Archiving/ArchiveService.cs | 50 +- .../Archiving/FrameTrash.Replace.cs | 522 ++++++++++++ .../Archiving/FrameTrash.Restore.cs | 27 +- src/Chronos.Data/Archiving/FrameTrash.cs | 27 +- .../Archiving/Jobs/ArchiveJobParameters.cs | 16 + .../Archiving/Jobs/ConvertJobHandler.cs | 91 +++ src/Chronos.Data/Archiving/MassConverter.cs | 745 ++++++++++++++++++ src/Chronos.Data/Archiving/SequenceTrash.cs | 10 +- src/Chronos.Data/Archiving/SequenceWriter.cs | 14 +- src/Chronos.Protocol/Library.cs | 46 ++ src/Chronos.Protocol/ProtocolJson.cs | 2 + src/Chronos.Server/Api/ArchiveEndpoints.cs | 129 ++- .../Configuration/ServerSettingsStore.cs | 2 +- src/Chronos.Server/Storage/ArchiveModule.cs | 10 +- .../Conversion/ConvertPlannerTests.cs | 126 +++ .../Conversion/FrameConverterTests.cs | 286 +++++++ .../Archiving/ArchiveFixture.cs | 7 +- .../Archiving/ConvertTests.cs | 580 ++++++++++++++ .../Chronos.Server.Tests/Api/ConvertTests.cs | 223 ++++++ 34 files changed, 3519 insertions(+), 32 deletions(-) create mode 100644 src/Chronos.Core/Conversion/ConvertOptions.cs create mode 100644 src/Chronos.Core/Conversion/ConvertPlanner.cs create mode 100644 src/Chronos.Core/Conversion/FrameConverter.cs create mode 100644 src/Chronos.Data/Archiving/FrameTrash.Replace.cs create mode 100644 src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs create mode 100644 src/Chronos.Data/Archiving/MassConverter.cs create mode 100644 tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs create mode 100644 tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs create mode 100644 tests/Chronos.Data.Tests/Archiving/ConvertTests.cs create mode 100644 tests/Chronos.Server.Tests/Api/ConvertTests.cs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c8cf7d76..04fc6a2b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,6 +42,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | | `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint, which pins every file rename by its digest and not the frames version; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back together to their old names or a free `_2`, those that took their new names already with them; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) | | `Import` | Card scan, session detection, import plan (photos named through `FrameNaming` with the camera and lens of their session's first photo), hash-verified copy, card eraser (re-hash before delete) | +| `Conversion` | Mass conversion after import (owner review 2, R7): `ConvertOptions` (target JPEG 4:4:4 / TIFF-16 / linear DNG, JPEG quality, the converted name: same stem, the target's extension in the old one's case), `FrameConverter` (native-tier decode only, in-house encoders, Exif from the sidecar and the original via `ExifWriter`, hashed as made, written atomically, verified: read back, metadata again, decoded by the server's decoders), `ConvertPlanner` (per sequence the frames converted and skipped with `ConvertSkip`, size estimates per pixel, `ConvertPlan` with its space and fingerprint) | | `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles; `ExpandFile` shortens a long file name before its `.{ext}`); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses, the archive engine's new or changed templates included: a folder scans skip, a lost extension, names that repeat) | | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | @@ -58,7 +59,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Jobs` | `JobEngine` (one job at a time; reviews the priority queue and makes a lower running job yield, requeued with its checkpoint; no history purge, the housekeeping schedule's clean-up does it), `JobPriorityQueue` (a level per job kind, the claim order, settings round trip), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs that never interrupt their parent), `JobThroughput`/`JobEta` (rate and bounded time left) | | `Scheduling` | `Scheduler` (one per host: seeds the host's system schedules, claims due runs by compare-and-set, catch-up, clock changes, create/edit/reset/delete/run now as API v1 DTOs), `ScheduleRecurrence` (the in-house `every:`/`daily:`/`weekly:`/`monthly:` form, wall-clock times across DST), `ScheduleActions` (action names, parameters, availability, the archive jobs a run queues), `IScheduleHost` and `SystemSchedule` (what the server and the desktop supply), `ScheduleOutcome`, `ScheduleMapping` (model ↔ DTO) | | `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` | -| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index, `ArchiveSettings.CheckTemplates` and `TemplateRuleException` holding a template given anew to the template rules; `UnderLeaseAsync`: a write under a sequence's lease with its row read under it), `ArchiveIndexer` (scan, rebuild; a sequence found in another folder takes its exports' paths along), `ArchiveIngest` (uploads and imports, named through `FrameNaming`), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from when it changes it or names the folder or files after it), then the folder, with the sequences of the plan an earlier step left as they were inside it (taken along, their title and file names kept), every index row (the frame paths and render paths of the exports inside it, a file or an image-sequence folder, its own unless the export is still at the old place and another sequence's when it moved with it, follow it in one transaction; a sidecar that cannot be read or written then still has its row follow, and fails the step), then the files under the plan's journal in `journal/` (a sequence whose photos changed since, such as one still receiving them, or whose files are found changed or in use or have their new names taken keeps its file names, the renames being pinned by digest, and the step and the plan go on); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open, which completes any other plan an interruption left and tells each sequence changed; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceFolders` (`Holds`: the folder the index has for a sequence is there and its sidecar names no other sequence; every writer into a sequence's folder asks it), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed), job handlers | +| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index, `ArchiveSettings.CheckTemplates` and `TemplateRuleException` holding a template given anew to the template rules; `UnderLeaseAsync`: a write under a sequence's lease with its row read under it), `ArchiveIndexer` (scan, rebuild; a sequence found in another folder takes its exports' paths along), `ArchiveIngest` (uploads and imports, named through `FrameNaming`), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from when it changes it or names the folder or files after it), then the folder, with the sequences of the plan an earlier step left as they were inside it (taken along, their title and file names kept), every index row (the frame paths and render paths of the exports inside it, a file or an image-sequence folder, its own unless the export is still at the old place and another sequence's when it moved with it, follow it in one transaction; a sidecar that cannot be read or written then still has its row follow, and fails the step), then the files under the plan's journal in `journal/` (a sequence whose photos changed since, such as one still receiving them, or whose files are found changed or in use or have their new names taken keeps its file names, the renames being pinned by digest, and the step and the plan go on); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open, which completes any other plan an interruption left and tells each sequence changed; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceFolders` (`Holds`: the folder the index has for a sequence is there and its sidecar names no other sequence; every writer into a sequence's folder asks it), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed; a replaced entry swaps back while its converted frames are unchanged; `FrameTrash.Replace`: the files of frames swapped in place, same ids and indices, the old files into one `Replaced` entry with their replacements' hashes and a copy of `analysis.json`, tombstones aliasing old content to new, under `.chronos/replace.pending.json`, which the next writer undoes or completes), `MassConverter` (conversion's dry run with busy, offline and unreadable sequences and the space against `ArchiveServiceOptions.FreeSpace`; the job's stage A converts into `staging/convert-/` with `OrderedWork`, each staged file appended to `journal/convert-.staged`; stage B per sequence, all or nothing: replace through `FrameTrash.ReplaceAsync`, or a new sequence through the ingest with the source's tags, rating, notes and project), job handlers | | `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers | | `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncTombstones` (photos either side removed are not offered back, a replaced photo counts as its replacement), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) | @@ -85,7 +86,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost` (`Toast.Closed` once a toast leaves the screen), `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) | | `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) | | `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` | -| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, with `ReorganizePlanCache`: a dry run's plan, made apart from its request, kept a few minutes while what it reads from the index stays, for the same dry run and its confirmation), API errors, the WebSocket `EventHub` | +| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, with `ReorganizePlanCache`: a dry run's plan, made apart from its request, kept a few minutes while what it reads from the index stays, for the same dry run and its confirmation; Convert's dry run and `convert` job), API errors, the WebSocket `EventHub` | | `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log | | `Server/Storage`, `Server/Jobs` | Archive and processing modules (the archive module's `SequenceChanged` publishes `sequenceChanged` `reorganized`), uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step; `UploadService.ReceiveAgainAsync`: a verified upload whose filing was refused for now goes back to receiving, 503), render store (files a render under the sequence's lease, where the index has the folder then; `FolderMovedException`, 503 `folder_moved`, when the sequence is not in it); `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability | | `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back) | @@ -116,6 +117,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Cleanup` | `Housekeeping/CleanupJobHandler` (shared steps, plus the host's from `ArchiveServiceOptions.CleanupSteps`) | yes | yes | | `EmptyTrash` | `Archiving/Jobs/EmptyTrashJobHandler` (erases exactly a confirmed plan's trash entries; refuses a stale fingerprint) | yes | yes | | `Move` | `Archiving/Jobs/MoveJobHandler` (Reorganize, `MoveJobParameters`: the templates, the sequences and the confirmed fingerprint; plans again from the templates, applies the plan only while it is the one confirmed, holds it when paused, cancelled or failed, keeps it while the archive is offline, tells each sequence changed as its step completes) | yes | yes | +| `Convert` | `Archiving/Jobs/ConvertJobHandler` (mass conversion through `MassConverter`: targets are the sequences; plans again, refuses short space, converts each sequence all or nothing, resumes from its journal, queues the passes the frames need again) | yes | yes (formats the server cannot decode natively are skipped: convert on a PC) | | `Adopt` | none: done synchronously (`ArchiveService` actions) | — | — | A job engine claims only kinds it has handlers for. Light analysis is queued by the engine (`JobContext` follow-up) diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 49d1a133..ede437a0 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -133,6 +133,7 @@ Adopt Backup Clean-up + Convert Deep analysis Duplicates Empty trash diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 4eb785a4..2a693e3c 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -35,6 +35,19 @@ Remove row Remove {0} from the index?long Its sidecar is gone. Only the index row is removed; no file is deleted.long + A job is working on this sequence; convert it once the job is done.long: why a sequence is not converted in a conversion dry run + The sequence changed after the plan; review the plan again.long: why a sequence is not converted in a conversion dry run + The archive is offline or read-only.long: why a sequence is not converted in a conversion dry run + The sequence file cannot be read.long: why a sequence is not converted in a conversion dry run + Missing photos stay as they are.long: why photos are not converted in a conversion dry run + Photos of a format this computer cannot read at full resolution stay as they are.long: why photos are not converted in a conversion dry run + Photos read only from their embedded preview here stay as they are.long: why photos are not converted in a conversion dry run + Photos already in this format stay as they are.long: why photos are not converted in a conversion dry run + Unreadable photos stay as they are.long: why photos are not converted in a conversion dry run + Photos never verified stay as they are; verify the sequence first.long: why photos are not converted in a conversion dry run + Needs {0}, free {1}long: free space line of a conversion dry run; {0} and {1} sizes + Needs {0}, only {1} free: free some space first.long: free space line of a conversion dry run; {0} and {1} sizes + Needs {0}; the free space cannot be measured.long: free space line of a conversion dry run; {0} size Folder to copy into the archivelong Move to trash Not moved: {0} · {1}long @@ -80,6 +93,9 @@ Duplicates No archive yet Another Chronos ({0}) is writing here. Try again shortly.long: error sentence + {0:N0} sequence was not converted as planned; the job log says why.long: error sentence of a conversion job + {0:N0} sequences were not converted as planned; the job log says why.long: error sentence of a conversion job + The conversion needs {0} free on the archive's volume, and {1} are free.long: error sentence of a conversion job; {0} and {1} sizes The copy of {0} does not match the original.long: error sentence {0} could not be added to the sequence.long: error sentence {0} is already in the library.long: error sentence @@ -137,6 +153,13 @@ Audit log kept in fulllong: job log line; a clean-up step whose age limit is 0 Audit entries removed: {0}long: job log line Index copied to {0} ({1}); copies kept: {2}long: job log line; {0} file path; {1} size, e.g. "12.4 MB" + Left as it was, busy or unreadable: {0}long: job log line; {0} sequence title + Left as it was, changed after the plan: {0}long: job log line; {0} sequence title + Sequences converted: {0}, new sequences: {1}, photos: {2}long: job log line of a conversion + Left as it was, a photo could not be converted: {0}: {1}long: job log line; {0} sequence title, {1} the reason + Nothing to convert: {0}long: job log line; {0} sequence title + {0}: photos replaced by their conversion: {1}long: job log line; {0} sequence title, {1} photos + {0}: photos converted into a new sequence: {1}long: job log line; {0} sequence title, {1} photos Dry run: nothing was changed.long: job log line Extra copies of {0}: {1}long: job log line; {0} path of the first photo of a group sharing one hash Duplicate groups: {0}, extra copies: {1}long: job log line diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index d60462c4..9c2a5942 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -69,6 +69,7 @@ Adopt folder Index backup Clean-up + Convert Deep analysis Download Duplicates diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 5e7a8059..88aafc90 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -23,6 +23,7 @@ This PC's settings of {0} will be replaced by the server copy.long; {0} sequence title Take the server's settings? Connect + Convert these photos on a PC: the server cannot read them at full resolution.long: why photos are not converted in a conversion dry run on the server Disconnect Not connected to a server Too many failed sign-ins; the account is locked for a while.long @@ -72,8 +73,10 @@ The last administrator cannot be removed or disabled.long This method is not allowed here.long A new folder would lie inside the folder of another sequence.long + The archive's volume lacks the space the conversion needs.long Not found.long That address is not a Chronos Server.long + The plan converts nothing: every photo is skipped or every sequence is blocked.long Change your password first.long The photo was deleted from the sequence while it was being uploaded, so it was not added.long {0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.long diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index e7c21981..ff728d09 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -133,6 +133,7 @@ Adozione Copia dell'indice Pulizia + Conversione Analisi completa Duplicati Svuota cestino diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 53783f24..049a0213 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -32,6 +32,19 @@ Rimuovi riga Rimuovere {0} dall'indice? Il suo sidecar non c'è più. Viene rimossa solo la riga dell'indice; nessun file viene eliminato. + Un job sta lavorando su questa sequenza; convertila quando il job è finito. + La sequenza è cambiata dopo il piano; rivedi il piano. + L'archivio non è raggiungibile o è di sola lettura. + Il file della sequenza non si può leggere. + Le foto mancanti restano come sono. + Le foto di un formato che questo computer non legge a piena risoluzione restano come sono. + Le foto lette qui solo dalla loro anteprima incorporata restano come sono. + Le foto già in questo formato restano come sono. + Le foto illeggibili restano come sono. + Le foto mai verificate restano come sono; verifica prima la sequenza. + Servono {0}, liberi {1} + Servono {0}, liberi solo {1}: libera prima dello spazio. + Servono {0}; lo spazio libero non si può misurare. Cartella da copiare nell'archivio Sposta nel cestino Non spostata: {0} · {1} @@ -75,6 +88,9 @@ Doppioni Nessun archivio Un altro Chronos ({0}) sta scrivendo qui. Riprova tra poco. + {0:N0} sequenza non è stata convertita come previsto; il log del job dice perché. + {0:N0} sequenze non sono state convertite come previsto; il log del job dice perché. + La conversione richiede {0} liberi sul volume dell'archivio, e ne sono liberi {1}. La copia di {0} non corrisponde all'originale. Impossibile aggiungere {0} alla sequenza. {0} è già nella libreria. @@ -132,6 +148,13 @@ Registro di controllo conservato per intero Voci di controllo rimosse: {0} Indice copiato in {0} ({1}); copie conservate: {2} + Lasciata com'era, occupata o illeggibile: {0} + Lasciata com'era, cambiata dopo il piano: {0} + Sequenze convertite: {0}, nuove sequenze: {1}, foto: {2} + Lasciata com'era, una foto non si è potuta convertire: {0}: {1} + Niente da convertire: {0} + {0}: foto sostituite dalla loro conversione: {1} + {0}: foto convertite in una nuova sequenza: {1} Simulazione: nulla è stato modificato. Copie in più di {0}: {1} Gruppi di duplicati: {0}, copie in più: {1} diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 643ae63f..9bc5ce93 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -69,6 +69,7 @@ Adozione cartella Copia dell'indice Pulizia + Conversione Analisi approfondita Scaricamento Duplicati diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index e76fc6b9..8a3f0809 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -21,6 +21,7 @@ Le impostazioni di {0} su questo PC saranno sostituite dalla copia del server. Usare le impostazioni del server? Connetti + Converti queste foto su un PC: il server non le legge a piena risoluzione. Disconnetti Non connesso a un server Troppi accessi falliti; l'account è bloccato per un po'. @@ -70,8 +71,10 @@ L'ultimo amministratore non può essere rimosso o disattivato. Metodo non consentito qui. Una nuova cartella finirebbe dentro la cartella di un'altra sequenza. + Il volume dell'archivio non ha lo spazio che serve alla conversione. Non trovato. Questo indirizzo non è un Chronos Server. + Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata. Cambia prima la password. La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.long Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova. diff --git a/src/Chronos.Core/Archiving/ArchiveLayout.cs b/src/Chronos.Core/Archiving/ArchiveLayout.cs index 471b755a..5c1959a6 100644 --- a/src/Chronos.Core/Archiving/ArchiveLayout.cs +++ b/src/Chronos.Core/Archiving/ArchiveLayout.cs @@ -39,6 +39,9 @@ public static class ArchiveLayout /// File renames of a Reorganize that were started but not yet recorded in and the index. public const string FileRenameJournalFile = "rename-files.json"; + /// Moves of a frame replacement (a conversion, or its undo) that were started but not yet settled in and the trash. + public const string ReplaceJournalFile = "replace.pending.json"; + /// Folder names inside a sequence folder that never hold a sequence of their own. public static bool IsReservedFolder(string name) => name.Equals(MetaFolder, StringComparison.OrdinalIgnoreCase) @@ -108,6 +111,7 @@ public sealed class SequencePaths public string RemovalJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RemovalJournalFile); public string RestoreJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RestoreJournalFile); public string FileRenameJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.FileRenameJournalFile); + public string ReplaceJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.ReplaceJournalFile); public string Proxy(int index) => Path.Combine(Proxies, ArchiveLayout.ProxyFileName(index)); diff --git a/src/Chronos.Core/Conversion/ConvertOptions.cs b/src/Chronos.Core/Conversion/ConvertOptions.cs new file mode 100644 index 00000000..42ebaa55 --- /dev/null +++ b/src/Chronos.Core/Conversion/ConvertOptions.cs @@ -0,0 +1,84 @@ +using System.Globalization; +using Chronos.Core.Imaging; + +namespace Chronos.Core.Conversion; + +/// The format a mass conversion writes (owner review 2, R7; BRIEF §12.5). +public enum ConvertTarget +{ + /// Baseline JPEG, 8-bit sRGB, 4:4:4 chroma, quality 1–100 (). + Jpeg, + + /// TIFF, 16-bit sRGB RGB, Deflate with the horizontal predictor. + Tiff16, + + /// Linear DNG (LinearRaw, 16-bit, lossless JPEG tiles): the archival choice. + LinearDng, +} + +/// What a conversion does with the frames it converts; chosen at every run (owner review 2, R7). +public enum ConvertMode +{ + /// The converted files become the sequence's frames (same ids and indices); the old files go to the archive's trash. + Replace, + + /// The converted files go into a new sequence; the source is left as it is. + NewSequence, +} + +/// The target format of a conversion and its quality (JPEG only). +/// IJG quality 1–100 of a JPEG; ignored by the other targets. +public sealed record ConvertOptions(ConvertTarget Target, int Quality = ConvertOptions.DefaultQuality) +{ + /// JPEG quality when none is given. + public const int DefaultQuality = 95; + + /// The target suggested for archiving: lossless, 16-bit, and read by every raw editor. + public const ConvertTarget ArchivalTarget = ConvertTarget.LinearDng; + + /// The format the converted files have. + public ImageFileFormat Format => Target switch + { + ConvertTarget.Jpeg => ImageFileFormat.Jpeg, + ConvertTarget.Tiff16 => ImageFileFormat.Tiff, + _ => ImageFileFormat.Dng, + }; + + /// The extension of the converted files, lower case with its dot. + public string Extension => Target switch + { + ConvertTarget.Jpeg => ".jpg", + ConvertTarget.Tiff16 => ".tif", + _ => ".dng", + }; + + /// The format's short name, as a new sequence's title ends with it: "Harbour (DNG)". + public string Label => Target switch + { + ConvertTarget.Jpeg => "JPEG", + ConvertTarget.Tiff16 => "TIFF", + _ => "DNG", + }; + + /// The quality that counts: the JPEG's, 0 for the lossless targets. + public int EffectiveQuality => Target == ConvertTarget.Jpeg ? Quality : 0; + + /// Whether the target is known and the quality in 1–100. + public bool IsValid => Enum.IsDefined(Target) && Quality is >= 1 and <= 100; + + /// What identifies the options in a plan's fingerprint. + public string Key => string.Create(CultureInfo.InvariantCulture, $"{Target}|{EffectiveQuality}"); + + /// + /// The name a converted file of (a sequence-relative path) gets: the same folder and stem, this + /// target's extension, upper case when the old extension was (IMG_0001.CR2 → IMG_0001.DNG). + /// + public string NameFor(string file) + { + ArgumentNullException.ThrowIfNull(file); + var old = Path.GetExtension(file); + var stem = file[..^old.Length]; + var upper = old.Length > 1 && old.Skip(1).Where(char.IsLetter).All(char.IsUpper) && old.Skip(1).Any(char.IsLetter); + return stem + (upper ? Extension.ToUpperInvariant() : Extension); + } +} diff --git a/src/Chronos.Core/Conversion/ConvertPlanner.cs b/src/Chronos.Core/Conversion/ConvertPlanner.cs new file mode 100644 index 00000000..793f0b36 --- /dev/null +++ b/src/Chronos.Core/Conversion/ConvertPlanner.cs @@ -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; + +/// Why a frame of a sequence is not converted (owner review 2, R7); nothing of it is touched. +public enum ConvertSkip +{ + /// The photo is in the target's format already (a TIFF of 8 bits included). + SameFormat, + + /// This host has no full-resolution decoder for the photo's format (a server and a CR3 or HEIC): a PC may have one. + NoNativeDecoder, + + /// This host reads the photo only from its embedded preview (a camera body its RAW decoder does not support). + PreviewOnly, + + /// The photo is flagged unreadable: no decoder produced its pixels. + Undecodable, + + /// The photo's file is not there. + Missing, + + /// The photo was never hashed (adopted, not verified yet): its replacement could not name it. Verify it first. + Unhashed, +} + +/// Why a whole sequence is not converted now; nothing of it is touched. +public enum ConvertBlock +{ + /// A running or paused job works on the sequence or its whole archive. + Busy, + + /// The archive is offline or read-only. + Offline, + + /// The sequence's sidecar cannot be read, or belongs to another sequence. + Unreadable, + + /// The sequence's frames changed after the plan was made (found by the job, which then leaves it as it is). + FramesChanged, +} + +/// Frames of a sequence that are not converted, and why. +public sealed record ConvertSkipped(ConvertSkip Reason, int Frames); + +/// One frame a conversion converts: its id and index, its file and format, its size and the converted file's estimated size. +public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes); + +/// +/// 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 (). +/// +public sealed record ConvertSequencePlan(Guid SequenceId, string Title, string Folder, int FramesVersion, IReadOnlyList Frames, + IReadOnlyList Skipped, IReadOnlyList Blocked) +{ + /// Whether the sequence is converted: something to convert and nothing blocking it. + public bool Converts => Blocked.Count == 0 && Frames.Count > 0; + + /// Size of the originals converted. + public long BytesBefore => Frames.Sum(f => f.Size); + + /// Estimated size of the converted files. + public long BytesAfter => Frames.Sum(f => f.EstimatedBytes); + + public int SkippedFrames => Skipped.Sum(s => s.Frames); +} + +/// +/// The free space a conversion needs on the archive's volume (: the estimate with a margin and a +/// reserve, ) and what it has; null when it cannot be measured. +/// +public sealed record ConvertSpace(long Required, long? Free) +{ + public bool Enough => Free is not { } free || free >= Required; +} + +/// +/// 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 (). +/// +public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, ConvertMode Mode, IReadOnlyList Sequences, ConvertSpace Space) +{ + /// The sequences that are converted. + public IEnumerable 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); + + /// + /// 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. + /// + 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()))); + } +} + +/// +/// 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 (). +/// +public static class ConvertPlanner +{ + /// Margin over the estimate the free space must hold (estimates of compressed files vary with the content). + public const double SpaceMargin = 1.15; + + /// Space left free on the volume after the conversion, for the index, sidecars and everything else writing there. + public const long SpaceReserve = 512L << 20; + + /// Pixels assumed for a frame whose size is not known (a 24 MP sensor). + public const long UnknownPixels = 24_000_000; + + /// + /// 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. + /// + private const double FullChroma = 1.25; + + /// The plan of one sequence from its sidecar. + /// Every file in the folders of the sequence's frames, relative to the sequence folder + /// (): the frames whose file is not among them are missing. + /// This host's decoders. + public static ConvertSequencePlan Plan(SequenceManifest manifest, SequencePaths folder, IReadOnlyCollection 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 ?? new HashSet(present, StringComparer.OrdinalIgnoreCase); + var skipped = new Dictionary(); + var frames = new List(); + 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))], []); + } + + /// Why is not converted, or null when it is. + public static ConvertSkip? Skip(SidecarFrame frame, SequencePaths folder, IReadOnlySet 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; + } + + /// + /// Estimated size of a converted file of × pixels (unknown: + /// ), from the bits per pixel the Export tab estimates with (): + /// JPEG by quality (×1.25 for 4:4:4 chroma), TIFF-16 30, linear DNG 26. + /// + 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); + } + + /// The free space a conversion whose files are estimated at bytes needs. + 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; + } + } +} diff --git a/src/Chronos.Core/Conversion/FrameConverter.cs b/src/Chronos.Core/Conversion/FrameConverter.cs new file mode 100644 index 00000000..4162e30f --- /dev/null +++ b/src/Chronos.Core/Conversion/FrameConverter.cs @@ -0,0 +1,239 @@ +using System.Security.Cryptography; +using Chronos.Core.Archiving; +using Chronos.Core.Codecs.Dng; +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.Metadata; +using Chronos.Core.Model; + +namespace Chronos.Core.Conversion; + +/// The photo a conversion reads: its file, its sidecar record, and its sequence's camera and lens. +/// Absolute path of the original. +public sealed record ConvertSource(string Path, SidecarFrame Frame, SidecarCamera? Camera = null, string? Lens = null); + +/// A converted file as written and verified: where it is, its size and SHA-256, its format and its upright size. +public sealed record ConvertedFile(string Path, long Size, string Sha256, ImageFileFormat Format, int Width, int Height); + +/// A photo could not be converted, or its converted file did not verify; nothing of it is kept. +public sealed class ConversionException(string message, Exception? inner = null) : IOException(message, inner); + +/// +/// Converts one photo (owner review 2, R7; BRIEF §12.5): its original is decoded at full resolution only, never from an +/// embedded preview (, oriented upright), encoded by the in-house writers +/// ( 4:4:4, 16-bit sRGB with Deflate and the predictor, +/// ), with an Exif block () 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. +/// +public static class FrameConverter +{ + /// Long edge of the verification decode: enough to prove the full-resolution data decodes, cheap for JPEG and RAW. + private const int VerifyEdge = 256; + + private static readonly Lazy ServerDecoders = new(DecoderFactory.CreateServer); + + /// The decoders a converted file must decode with at full-resolution tier: the server's (managed only). + public static ImageDecoder Verifier => ServerDecoders.Value; + + /// Converts into (created or replaced atomically) and verifies it. + /// This host's decoders (WIC first on a desktop). + /// Worker limit of the encoder (-1: all cores); 1 when several photos convert at once. + /// The photo does not decode at full resolution here, or its converted file did not + /// verify (it is deleted). + /// The original cannot be read, or the target cannot be written. + 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); + ConvertedFile file; + FrameMetadata metadata; + using (var decoded = decoder.Decode(new DecodeRequest(source.Path, 0, DecodePurpose.Render, ApplyOrientation: true, AllowPreview: false), + cancellationToken)) + { + if (decoded is null) throw new ConversionException($"{name}: no decoder here reads it at full resolution"); + if (decoded.Tier != DecodeTier.Native || decoded.ByChoice) + throw new ConversionException($"{name}: decoded from its {decoded.Tier} only ({decoded.Decoder}), not at full resolution"); + 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); + 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); + } + try + { + Verify(file, metadata, cancellationToken); + } + catch + { + TryDelete(target); + throw; + } + return file; + } + + /// + /// 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. + /// + 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, + }; + } + + /// The file bytes of (linear light, RGB) in the target format with . + public static byte[] Encode(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, int encoderThreads = -1) + { + using var output = Encoded(image, metadata, options, encoderThreads); + return output.ToArray(); + } + + /// into a stream the caller disposes. + private static MemoryStream Encoded(ImageBuffer image, FrameMetadata metadata, ConvertOptions options, 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..]], + 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), + MaxDegreeOfParallelism = encoderThreads, + }); + break; + default: + LinearDngWriter.Write(output, image, new LinearDngOptions + { + Compression = DngCompression.LosslessJpeg, + Exif = ExifWriter.BuildTiff(metadata), + MaxDegreeOfParallelism = encoderThreads, + }); + break; + } + return output; + } + + /// + /// 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. + /// + /// The metadata the file was written with (). + /// The file does not verify. + 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 new ConversionException($"{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 (written.CapturedAt is { } captured && read.CapturedAt != captured) + throw new ConversionException($"{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}"); + 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"); + 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}"); + } + + /// Three channels from one (gray) or four (alpha dropped). + 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); + } + } +} diff --git a/src/Chronos.Core/Metadata/ExifWriter.cs b/src/Chronos.Core/Metadata/ExifWriter.cs index eae512b0..21d8fd7f 100644 --- a/src/Chronos.Core/Metadata/ExifWriter.cs +++ b/src/Chronos.Core/Metadata/ExifWriter.cs @@ -6,9 +6,10 @@ using Chronos.Core.Metadata.Tiff; namespace Chronos.Core.Metadata; /// -/// Writes a minimal, valid little-endian Exif block for proxies and exports (BRIEF §8.5, §9): IFD0 (camera, orientation, -/// software, date, authorship), the Exif IFD (capture time with sub-seconds and offset, exposure, lens and body) and, -/// when known, the GPS IFD. Strings longer than UTF-8 bytes are truncated. +/// Writes a minimal, valid little-endian Exif block for proxies, exports and converted frames (BRIEF §8.5, §9; owner +/// review 2, R7): IFD0 (camera, orientation, software, date, authorship), the Exif IFD (capture time with sub-seconds and +/// offset, exposure, exposure program, metering mode, flash, white balance, lens and body) and, when known, the GPS IFD. +/// Strings longer than UTF-8 bytes are truncated. /// public static class ExifWriter { @@ -60,6 +61,10 @@ public static class ExifWriter if (m.UtcOffsetMinutes is { } offset && Math.Abs(offset) < 24 * 60) exif.Ascii(TiffTags.OffsetTimeOriginal, $"{(offset < 0 ? '-' : '+')}{Math.Abs(offset) / 60:D2}:{Math.Abs(offset) % 60:D2}"); exif.SRational(TiffTags.ExposureBiasValue, m.ExposureBias); + exif.Mode(TiffTags.ExposureProgram, m.ExposureProgram); + exif.Mode(TiffTags.MeteringMode, m.MeteringMode); + exif.Mode(TiffTags.Flash, m.Flash); + exif.Mode(TiffTags.WhiteBalance, m.WhiteBalanceMode); exif.Rational(TiffTags.FocalLength, m.FocalLength); if (m.FocalLength35 is { } f35 and > 0 and < MaxShortIso) exif.Short(TiffTags.FocalLengthIn35mmFilm, (ushort)Math.Round(f35)); exif.Ascii(TiffTags.BodySerialNumber, m.BodySerial); @@ -190,6 +195,12 @@ public static class ExifWriter Bytes(tag, TiffType.Short, data); } + /// A SHORT mode or bit field (exposure program, metering, flash, white balance), when known and in range. + public void Mode(ushort tag, int? value) + { + if (value is { } v and >= 0 and <= ushort.MaxValue) Short(tag, (ushort)v); + } + public void Long(ushort tag, uint value) { var data = new byte[4]; diff --git a/src/Chronos.Core/Model/Enums.cs b/src/Chronos.Core/Model/Enums.cs index 29e3b8e9..15e6e0f8 100644 --- a/src/Chronos.Core/Model/Enums.cs +++ b/src/Chronos.Core/Model/Enums.cs @@ -93,6 +93,12 @@ public enum JobKind /// as 18. /// EmptyTrash = 18, + + /// + /// A mass conversion of sequences to JPEG, TIFF-16 or linear DNG, replacing their frames or into new sequences, as + /// confirmed (owner review 2, R7); stored as 19. + /// + Convert = 19, } /// Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number. @@ -101,7 +107,7 @@ public enum RemovalReason /// Deleted by a user into the archive's trash. Deleted = 0, - /// Replaced by a converted file (a later phase): the tombstone names the replacement's SHA-256. + /// Replaced by a converted file (owner review 2, R7): the tombstone names the replacement's SHA-256. Replaced = 1, } diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index 3b4a50d7..62b2a4cb 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -1,5 +1,6 @@ using System.Text.Json; using Chronos.Core.Archiving; +using Chronos.Core.Conversion; using Chronos.Core.Diagnostics; using Chronos.Core.Import; using Chronos.Core.Localization; @@ -14,8 +15,8 @@ namespace Chronos.Data.Archiving; /// /// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create -/// or adopt an archive, read and change its settings, plan and apply mass renames, plan imports and card erases, delete -/// sequences into the trash and restore them, query duplicates and orphans, and +/// or adopt an archive, read and change its settings, plan and apply mass renames, plan mass conversions, plan imports and +/// card erases, delete sequences into the trash and restore them, query duplicates and orphans, and /// the job handlers for the long operations (enqueue them with ). /// public sealed class ArchiveService : IJobHandlerProvider @@ -42,6 +43,7 @@ public sealed class ArchiveService : IJobHandlerProvider Imports = new ImportService(db, Ingest); Trash = new SequenceTrash(db, _writer, Indexer); FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash); + Converter = new MassConverter(db, _writer, Ingest, FrameTrash, Trash, this); var shared = Housekeeping.CleanupSteps.Shared(Trash); CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))]; } @@ -63,6 +65,9 @@ public sealed class ArchiveService : IJobHandlerProvider /// Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6). public FrameTrash FrameTrash { get; } + /// Converts sequences to JPEG, TIFF-16 or linear DNG, replacing their frames or into new sequences (owner review 2, R7). + public MassConverter Converter { get; } + /// /// The steps this host's jobs can run: the shared ones (), /// then the host's (). A schedule host lists their names. @@ -74,8 +79,9 @@ public sealed class ArchiveService : IJobHandlerProvider /// /// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans - /// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7, - /// ); register them on the . + /// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6), Reorganize (R7, + /// ) and mass conversion (R7, ); register them on the + /// . /// public IReadOnlyList CreateJobHandlers() => [ @@ -92,6 +98,7 @@ public sealed class ArchiveService : IJobHandlerProvider new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System), new EmptyTrashJobHandler(_db, Trash), new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged), + new ConvertJobHandler(_db, Converter, _writer.Options.SequenceChanged), ]; /// Makes a new, empty archive and indexes it. @@ -394,6 +401,21 @@ public sealed class ArchiveService : IJobHandlerProvider return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false); } + /// + /// The dry run of a mass conversion (owner review 2, R7): , or every sequence of the + /// archive (by folder) when null, converted with in . Apply it in a job + /// (). + /// + /// The archive is unknown, the options are invalid, or a sequence is not in the archive. + public async Task PlanConvertAsync(Guid archiveId, IReadOnlyList? sequenceIds, ConvertOptions options, ConvertMode mode, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(options); + var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false); + var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)]; + return await Converter.PlanAsync(archive, ids, options, mode, cancellationToken).ConfigureAwait(false); + } + public async Task ApplyRenameAsync(RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken) .ConfigureAwait(false); @@ -432,7 +454,7 @@ public sealed class ArchiveService : IJobHandlerProvider if (!Archiving.FrameTrash.IsPhotoEntry(entryName)) return new TrashRestoreResult(TrashKind.Sequence, await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false), 0, [], false); var photos = await FrameTrash.RestoreAsync(archive, entryName, followUps, cancellationToken).ConfigureAwait(false); - return new TrashRestoreResult(TrashKind.Photos, photos.Sequence, photos.Restored, photos.Kept, photos.NewSequence); + return new TrashRestoreResult(photos.Kind, photos.Sequence, photos.Restored, photos.Kept, photos.NewSequence); } /// The dry run of emptying an archive's trash: of the entries (null: all), measured, with the plan's fingerprint. @@ -673,6 +695,24 @@ public static class ArchiveJobs JobPriority.User); } + /// + /// : applies the conversion () + /// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions, are the job's + /// targets, so jobs that would touch them wait. A sequence that changed before it ran is left as it is and reported. + /// + /// The plan converts nothing. + public static ArchiveJobRequest Convert(Archive archive, ConvertPlan plan) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(plan); + var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion)).ToList(); + if (sequences.Count == 0) throw new ArgumentException("The plan converts nothing.", nameof(plan)); + var label = sequences.Count == 1 ? plan.Converted.First().Title : archive.Name; + return new(JobKind.Convert, [.. sequences.Select(s => s.Id)], label, + Json(new ConvertJobParameters(archive.Id, plan.Options.Target, plan.Options.Quality, plan.Mode, sequences, plan.Fingerprint()), + ArchiveJobJson.Default.ConvertJobParameters), JobPriority.User); + } + public static Task EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) => engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken); diff --git a/src/Chronos.Data/Archiving/FrameTrash.Replace.cs b/src/Chronos.Data/Archiving/FrameTrash.Replace.cs new file mode 100644 index 00000000..6f2a96c2 --- /dev/null +++ b/src/Chronos.Data/Archiving/FrameTrash.Replace.cs @@ -0,0 +1,522 @@ +using System.Text.Json; +using Chronos.Core.Archiving; +using Chronos.Core.Diagnostics; +using Chronos.Core.IO; +using Chronos.Core.Model; +using Chronos.Core.Naming; +using SequenceFrames = Chronos.Core.Archiving.SequenceFrames; + +namespace Chronos.Data.Archiving; + +/// +/// One frame a replacement swaps (owner review 2, R7): the file that comes in, its companions, the name it is filed under +/// and the record the frame gets. +/// +/// The file that comes in, relative to the archive root: a staged conversion, or an original in a +/// trash entry. +/// Files that come in with it (the XMP companions of an original back from the trash). +/// The name it is filed under, from the frame as the sidecar has it under the lease, relative to the +/// sequence folder; made unique with _2, _3… when it, or one of its companions' names, is taken. +/// The frame's record after the swap, from the frame as the sidecar has it under the lease (its +/// names the incoming file): the replacement keeps the frame's id and index, files it +/// under its name, and keeps the flags a user or the capture set ( come from the +/// record). +internal sealed record FrameSwap(Guid FrameId, string Incoming, IReadOnlyList Companions, Func Name, + Func Record); + +/// A companion that comes in with its photo: where it is (relative to the archive root), and what its name adds to the photo's stem. +internal sealed record IncomingCompanion(string From, string Tail); + +/// +/// The trash entry a replacement takes its incoming files from (the undo of a conversion): once the sidecar is written, +/// the photos of leave its record, and its copy of analysis.json () goes back +/// into the sequence. +/// +/// The entry's record, relative to the archive root. +/// The entry's folder, relative to the archive root. +/// The entry's lease, which the replacement's caller holds. +/// The entry's copy of analysis.json, relative to the archive root; null when it has none. +internal sealed record ConsumedEntry(string Record, string Folder, string Lease, IReadOnlyList Frames, string? Analysis); + +/// One file a replacement moves: its place in the sequence folder and the other end, relative to the archive root. +/// Relative to the sequence folder (forward slashes). +/// Relative to the archive root: the trash entry an outgoing file goes to, or where an incoming file comes from. +internal sealed record SwapMove(string Place, string Other); + +/// What a replacement did: the trash entry of the files that went, the sequence as it is now, and its statuses before. +internal sealed record ReplaceResult(TrashEntry Entry, Sequence Sequence, SequenceStatus Had); + +/// +/// Write-ahead record of a frame replacement (.chronos/replace.pending.json, owner review 2, R7): the sidecar's frames +/// version before it, the new trash entry (its record pending until the sidecar is written), every file that leaves the +/// sequence for the entry and every file that comes in, whether the entry holds a copy of analysis.json, and the +/// entry the incoming files come from (an undo). Written under the sequence's lease before the first move and removed once +/// the replacement is settled, so the next writer of the sequence () undoes one a +/// crash interrupted before its sidecar was written, and completes one interrupted after. +/// +/// The new entry's record, relative to the archive root (its name once the replacement is complete). +/// The new entry's folder, relative to the archive root. +/// Files that leave the sequence for the new entry. +/// Files that come into the sequence. +internal sealed record FrameReplaceJournal(int FramesVersion, string Record, string Folder, IReadOnlyList Out, IReadOnlyList In, + bool Analysis, ConsumedEntry? Consumed) +{ + public void Write(SequencePaths sequence) + { + System.IO.Directory.CreateDirectory(sequence.MetaDirectory); + AtomicFile.WriteAllBytes(sequence.ReplaceJournalPath, JsonSerializer.SerializeToUtf8Bytes(this, TrashJson.Default.FrameReplaceJournal)); + } + + /// The journal of a sequence; null when it is torn (written by a process that died while writing it: nothing moved yet). + public static FrameReplaceJournal? Read(SequencePaths sequence) + { + try + { + return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.ReplaceJournalPath), TrashJson.Default.FrameReplaceJournal); + } + catch (JsonException) + { + return null; + } + } + + public static void Delete(SequencePaths sequence) + { + if (File.Exists(sequence.ReplaceJournalPath)) File.Delete(sequence.ReplaceJournalPath); + } +} + +public sealed partial class FrameTrash +{ + /// + /// Flags that follow a frame's file, not the frame: a replacement takes them from the incoming record and keeps the + /// others (excluded, intervalometer, black, white) as the frame has them. + /// + internal const FrameFlags ContentFlags = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Duplicate | FrameFlags.PreviewOnly | FrameFlags.Undecodable; + + /// The name of the copy of a sequence's analysis.json a replaced entry keeps, inside its folder. + internal const string AnalysisCopy = "analysis.json"; + + /// + /// Replaces the files of frames of a sequence, keeping the frames (owner review 2, R7; BRIEF §7): under the sequence's + /// lease, with its frames version still (null: any) and + /// (when given) still true, every swapped frame's original and its XMP companions move into one trash entry of kind + /// (its record holds the old frame records and each one's replacement SHA-256, and a copy + /// of analysis.json), and the incoming files move in under their names (made unique). The sidecar takes the + /// records with the same ids and indices (frames version + 1, the statuses the frames uncovered cleared) and a tombstone + /// per old content naming its replacement, so sync counts the old photo as the new one; content that comes back loses + /// its tombstone. Then the index follows, the proxies of the swapped frames are deleted (the proxy pass makes them + /// again) and the project's positions stay on their frames. A journal () makes it all + /// or nothing: a failure before the sidecar is written puts every file back, and a crash is undone or completed by the + /// next writer of the sequence. Returns null, nothing touched, when the sequence is gone, its frames changed, a swapped + /// frame's original is not there whole or was never hashed, or said no. + /// + /// Who asked (user name or client), kept in the trash record. + /// The trash entry the incoming files come from (an undo), settled once the sidecar is written. + /// The archive is offline or read-only; nothing moved. + /// The sequence is busy, or holds a restore or a replacement not settled yet. + /// An incoming file is missing, or a file could not move; nothing changed. + internal async Task ReplaceAsync(Archive archive, Guid sequenceId, int? framesVersion, IReadOnlyList swaps, string? replacedBy, + ConsumedEntry? consumed, Func>? unchanged, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(swaps); + if (swaps.Count == 0) throw new ArgumentException("No frame is swapped.", nameof(swaps)); + var paths = new ArchivePaths(archive.RootPath); + ArchiveVolume.EnsureWritable(paths); + if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row || row.ArchiveId != archive.Id) return null; + var folder = paths.Sequence(row.Folder); + var had = row.Status; + TrashEntry entry; + SequenceManifest updated; + bool indexed; + await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false)) + { + var manifest = SequenceWriter.ReadLocked(folder, sequenceId, consumed?.Lease); + EnsureSettled(folder); + EnsureReplaced(folder); + if (framesVersion is { } expected && manifest.Versions.Frames != expected) return null; + var byId = manifest.Frames.ToDictionary(f => f.Id); + var swapped = new Dictionary(); + foreach (var swap in swaps) + { + if (!byId.TryGetValue(swap.FrameId, out var current) || current.Sha256 is null || swapped.ContainsKey(swap.FrameId)) return null; + var file = new FileInfo(folder.File(current.File)); + if (!file.Exists || file.Length != current.Size) return null; + var next = swap.Record(current); + if (next.Sha256 is null) throw new ArgumentException($"The record that replaces {current.File} names no content.", nameof(swaps)); + swapped[swap.FrameId] = next; + } + if (unchanged is not null && !await unchanged(manifest, folder, cancellationToken).ConfigureAwait(false)) return null; + foreach (var swap in swaps.Where(s => !File.Exists(paths.FromRelative(s.Incoming)))) + throw new FileNotFoundException($"The file that replaces {byId[swap.FrameId].File} is missing.", swap.Incoming); + var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false); + var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false); + + var leaving = manifest.Frames.Where(f => swapped.ContainsKey(f.Id)).ToList(); + var kept = manifest.Frames.Where(f => !swapped.ContainsKey(f.Id)).ToList(); + var photos = (await TrashedAsync(folder, leaving, kept, cancellationToken).ConfigureAwait(false)) + .Select(p => p with { Replacement = swapped[p.Frame.Id].Sha256!.ToLowerInvariant() }).ToList(); + var (incoming, names) = Incoming(folder, manifest, swaps, byId); + var now = DateTimeOffset.UtcNow; + updated = SequenceFrames.WithFrames(manifest, + [.. manifest.Frames.Select(f => swapped.TryGetValue(f.Id, out var record) ? Swapped(f, record, names[f.Id]) : f)]) with + { + Status = manifest.Status & ~Uncovered, + Removed = WithAliases(manifest.Removed, leaving, swapped, kept, now), + }; + + var trash = Directory(paths); + System.IO.Directory.CreateDirectory(trash); + var name = EntryName(trash, sequenceId); + var entryFolder = Path.Combine(trash, name); + var recordPath = entryFolder + RecordExtension; + var analysis = new FileInfo(folder.AnalysisPath); + List? leftovers = analysis.Exists + ? [new TrashedFile(ArchiveLayout.MetaFolder + "/" + ArchiveLayout.AnalysisFile, AnalysisCopy, analysis.Length, null)] + : null; + var record = new PhotoTrashRecord(TrashKind.Replaced, sequenceId, row.DisplayTitle, row.Folder, photos, + photos.Sum(p => p.Files.Sum(f => f.Size)) + (leftovers?.Sum(f => f.Size) ?? 0), now, replacedBy, leftovers); + var outgoing = photos.SelectMany(p => p.Files).Select(f => new SwapMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList(); + var journal = new FrameReplaceJournal(manifest.Versions.Frames, paths.ToRelative(recordPath), paths.ToRelative(entryFolder), outgoing, incoming, + analysis.Exists, consumed); + cancellationToken.ThrowIfCancellationRequested(); + // The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked). + journal.Write(folder); + // Under a name the trash does not list until the sidecar is written: half an entry is never restored or emptied. + AtomicFile.WriteAllText(FrameRemovalJournal.PendingRecord(recordPath), JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord)); + System.IO.Directory.CreateDirectory(entryFolder); + var movedOut = new List(); + var movedIn = new List(); + try + { + if (analysis.Exists) File.Copy(analysis.FullName, Path.Combine(entryFolder, AnalysisCopy), overwrite: false); + foreach (var move in outgoing) + { + MoveFile(folder.File(move.Place), paths.FromRelative(move.Other)); + movedOut.Add(move); + } + foreach (var move in incoming) + { + MoveFile(paths.FromRelative(move.Other), folder.File(move.Place)); + movedIn.Add(move); + } + ManifestStore.WriteSequence(folder.ManifestPath, updated); + } + catch (Exception ex) + { + // A file is open elsewhere, or the sidecar cannot be written: what moved goes back, and nothing changed. + Log.Warning("archive", $"{row.DisplayTitle}: the frames could not be replaced; the files that moved go back", ex); + UndoReplace(folder, movedOut, movedIn, journal); + throw; + } + CompleteReplace(folder, journal, consumed?.Lease); + Log.Info("archive", $"{row.DisplayTitle}: {photos.Count} frame(s) replaced; the files they had are in the trash ({name}, {record.Bytes} bytes)"); + // The files have moved: the index follows to the end, whatever the caller cancels meanwhile. + indexed = await IndexAsync(archive, folder, updated, photosChanged, row.DisplayTitle).ConfigureAwait(false); + DropProxies(folder, leaving); + entry = Entry(archive.Id, name, record); + } + var sequence = await RowAsync(row, updated, indexed).ConfigureAwait(false); + return new ReplaceResult(entry, sequence, had); + } + + /// + /// Settles the replacement a crash interrupted (), if any; the caller holds the + /// sequence's lease, and when it holds a trash entry's lease too. While + /// is at the journal's frames version the sidecar was not written: every file that moved + /// goes back (one whose place is taken again stays, logged, and keeps the journal) and the new entry goes. Otherwise the + /// replacement stands and is completed (). + /// + internal static void RecoverReplace(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null) + { + if (!File.Exists(sequence.ReplaceJournalPath)) return; + if (FrameReplaceJournal.Read(sequence) is not { } journal) + { + FrameReplaceJournal.Delete(sequence); + return; + } + if (manifest.Versions.Frames == journal.FramesVersion) + { + Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is undone"); + UndoReplace(sequence, journal.Out, journal.In, journal, onlyPresent: true); + } + else + { + Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is completed"); + CompleteReplace(sequence, journal, heldLease); + } + } + + /// + /// Refuses to go on while a replacement of is not settled after + /// (the entry its files came from was busy): its journal is not written over. + /// + /// The replacement is not settled; nothing was changed. + internal static void EnsureReplaced(SequencePaths sequence) + { + if (!File.Exists(sequence.ReplaceJournalPath)) return; + var lease = FrameReplaceJournal.Read(sequence)?.Consumed?.Lease ?? "replace"; + throw new LeaseUnavailableException(lease, LeaseFile.Holder(sequence.Archive.LocksDirectory, lease)); + } + + /// + /// The incoming moves, each file under its name made free: every name the sequence's folders hold stays taken, those of + /// the files that leave included, so no incoming file takes the place of one that leaves (a crash between the two is + /// then undone without doubt), and so do the files of every frame and the names already given. + /// + private static (List Moves, Dictionary Names) Incoming(SequencePaths folder, SequenceManifest manifest, IReadOnlyList swaps, + Dictionary frames) + { + var taken = new HashSet(FileRenames.ListPresent(folder, manifest), StringComparer.OrdinalIgnoreCase); + foreach (var frame in manifest.Frames) taken.Add(frame.File); + var unique = new UniqueNames(taken); + var moves = new List(); + var names = new Dictionary(); + foreach (var swap in swaps) + { + var file = unique.Claim(swap.Name(frames[swap.FrameId]), c => swap.Companions.All(t => !taken.Contains(StemOf(c) + t.Tail))); + names[swap.FrameId] = file; + moves.Add(new SwapMove(file, swap.Incoming)); + foreach (var companion in swap.Companions) + { + var to = StemOf(file) + companion.Tail; + taken.Add(to); + moves.Add(new SwapMove(to, companion.From)); + } + } + return (moves, names); + } + + /// A path without its extension (originals/IMG_0001): companions add their tail to it. + private static string StemOf(string file) => file[..^Path.GetExtension(file).Length]; + + /// The frame's record after a swap: at the frame's id and index, under its new name, with its own user flags. + private static SidecarFrame Swapped(SidecarFrame current, SidecarFrame record, string file) => record with + { + Id = current.Id, + I = current.I, + File = file, + Sha256 = record.Sha256!.ToLowerInvariant(), + Flags = (current.Flags & ~ContentFlags) | (record.Flags & ContentFlags), + }; + + /// + /// The tombstones after a replacement: those of before but the ones of content that comes back, and one per content + /// that leaves naming its replacement (), unless a frame that stays holds it too. + /// + private static List? WithAliases(IReadOnlyList? before, List leaving, Dictionary swapped, + List kept, DateTimeOffset at) + { + var incoming = swapped.Values.Select(s => s.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase); + var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase); + var tombstones = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var tombstone in before ?? []) + { + if (!incoming.Contains(tombstone.Sha256)) tombstones[tombstone.Sha256] = tombstone; + } + foreach (var frame in leaving) + { + var old = frame.Sha256!.ToLowerInvariant(); + var replacement = swapped[frame.Id].Sha256!.ToLowerInvariant(); + if (old == replacement || held.Contains(old)) continue; + tombstones[old] = new RemovedPhoto { Sha256 = old, Replacement = replacement, Reason = RemovalReason.Replaced, At = at }; + } + return tombstones.Count == 0 ? null : [.. tombstones.Values]; + } + + /// + /// Puts back what a replacement moved before its sidecar was written (incoming files back where they came from, the + /// files that left back into the sequence) and removes its entry and journal. With (a + /// recovery) a file not at its new place, or whose old place is taken, is left where it is (logged); the journal and the + /// entry then stay, and the entry is listed under its record's own name. A failure (logged) keeps the journal, and the + /// next writer of the sequence tries again. + /// + private static void UndoReplace(SequencePaths folder, IReadOnlyList movedOut, IReadOnlyList movedIn, FrameReplaceJournal journal, + bool onlyPresent = false) + { + var archive = folder.Archive; + var recordPath = archive.FromRelative(journal.Record); + var entryFolder = archive.FromRelative(journal.Folder); + var stuck = 0; + try + { + foreach (var move in movedIn.Reverse()) + { + if (!Back(folder.File(move.Place), archive.FromRelative(move.Other))) stuck++; + } + foreach (var move in movedOut.Reverse()) + { + if (!Back(archive.FromRelative(move.Other), folder.File(move.Place))) stuck++; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Error("archive", $"A frame replacement in {folder.RelativeFolder} could not be undone; the journal puts it back later", ex); + return; + } + if (stuck > 0) + { + // What could not go back is in the entry, listed, restorable and erasable like any entry. + FrameRemovalJournal.Publish(recordPath); + FrameReplaceJournal.Delete(folder); + return; + } + var copy = Path.Combine(entryFolder, AnalysisCopy); + if (journal.Analysis && File.Exists(copy)) File.Delete(copy); + if (File.Exists(FrameRemovalJournal.PendingRecord(recordPath))) File.Delete(FrameRemovalJournal.PendingRecord(recordPath)); + FrameRemovalJournal.RemoveEmpty(entryFolder); + FrameReplaceJournal.Delete(folder); + + bool Back(string from, string to) + { + if (!File.Exists(from)) return !onlyPresent || File.Exists(to) || Gone(from, to); + if (File.Exists(to)) + { + Log.Warning("archive", $"{to} is there again; {from} stays where it is"); + return false; + } + MoveFile(from, to); + return true; + } + + // Neither here nor there: nothing to put back for this file. + static bool Gone(string from, string to) + { + Log.Warning("archive", $"{from} is not there to go back to {to}"); + return true; + } + } + + /// + /// Completes a replacement whose sidecar is written: its entry is listed under its record's own name, the entry its + /// incoming files came from (if any) is settled under its lease (the photos swapped leave its record, its copy of + /// analysis.json goes back into the sequence, and an entry left without anything goes), and the journal goes. An + /// entry busy now (or a failure, logged) keeps the journal for the next writer of the sequence. + /// + private static void CompleteReplace(SequencePaths folder, FrameReplaceJournal journal, string? heldLease) + { + var archive = folder.Archive; + try + { + FrameRemovalJournal.Publish(archive.FromRelative(journal.Record)); + if (journal.Consumed is { } consumed && !Settle(folder, consumed, heldLease)) return; + FrameReplaceJournal.Delete(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("archive", $"A frame replacement in {folder.RelativeFolder} is not settled yet; the next writer of the sequence settles it", ex); + } + } + + /// Settles the entry a replacement took its files from (); false while it is busy. + private static bool Settle(SequencePaths folder, ConsumedEntry consumed, string? heldLease) + { + var archive = folder.Archive; + LeaseFile? taken = null; + if (consumed.Lease != heldLease) + { + taken = LeaseFile.TryAcquire(archive.LocksDirectory, consumed.Lease, SettleOwner); + if (taken is null) + { + Log.Info("archive", $"A frame replacement in {folder.RelativeFolder} waits: the trash entry its files came from is busy"); + return false; + } + } + using var held = taken; + var recordPath = archive.FromRelative(consumed.Record); + var entryFolder = archive.FromRelative(consumed.Folder); + // The copy of the analysis of the frames that came back takes the place of the analysis of the frames that went + // (the new entry keeps a copy of that one). + if (consumed.Analysis is { } copy && File.Exists(archive.FromRelative(copy))) + { + System.IO.Directory.CreateDirectory(folder.MetaDirectory); + File.Move(archive.FromRelative(copy), folder.AnalysisPath, overwrite: true); + } + if (ReadRecord(recordPath) is { } record) + { + var frames = consumed.Frames.ToHashSet(); + var leftovers = record.Leftovers?.Where(f => File.Exists(Path.Combine(entryFolder, f.Path))).ToList(); + Rewrite(recordPath, entryFolder, record with + { + Photos = [.. record.Photos.Where(p => !frames.Contains(p.Frame.Id))], + Leftovers = leftovers is { Count: > 0 } ? leftovers : null, + }); + } + return true; + } + + /// + /// Deletes the proxies of frames whose file was replaced: a proxy carries its frame's capture time, which a converted file + /// keeps, so the proxy pass would take the old one for current. A failure is logged; the pass then reuses what is left. + /// + private static void DropProxies(SequencePaths folder, IReadOnlyList frames) + { + if (!System.IO.Directory.Exists(folder.Proxies)) return; + try + { + foreach (var frame in frames) + { + var proxy = folder.Proxy(frame.I); + if (File.Exists(proxy)) File.Delete(proxy); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("archive", $"Proxies of the frames replaced in {folder.RelativeFolder} could not be deleted; the proxy pass may keep them", ex); + } + } + + /// + /// Whether every photo of a replaced entry may swap back into its sequence: each one's frame is there with the content + /// that replaced it (its file re-hashed now) and still names the photo as its source. + /// + private static async Task SwappableAsync(PhotoTrashRecord record, SequenceManifest manifest, SequencePaths folder, CancellationToken cancellationToken) + { + var frames = manifest.Frames.ToDictionary(f => f.Id); + foreach (var photo in record.Photos) + { + if (photo.Replacement is not { } replacement || photo.Frame.Sha256 is not { } original || !frames.TryGetValue(photo.Frame.Id, out var frame)) return false; + if (!string.Equals(frame.Sha256, replacement, StringComparison.OrdinalIgnoreCase) + || !string.Equals(frame.Source?.Sha256, original, StringComparison.OrdinalIgnoreCase)) return false; + var file = new FileInfo(folder.File(frame.File)); + if (!file.Exists || file.Length != frame.Size + || !string.Equals(await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase)) + return false; + } + return true; + } + + /// + /// The undo of a conversion: the originals of a replaced entry take their frames' place again + /// (), and the files that replaced them go to the trash as a replaced entry in turn. Null, + /// nothing touched, when a frame changed since () or the sequence did. + /// + /// The entry's lease, which the caller holds. + private async Task SwapBackAsync(Archive archive, ArchivePaths paths, Sequence sequence, PhotoTrashRecord record, string recordPath, + string entryFolder, string lease, CancellationToken cancellationToken) + { + if (record.Photos.Count == 0 || record.Photos.Any(p => p.Files.Count == 0 || p.Frame.Sha256 is null || p.Replacement is null)) return null; + var swaps = record.Photos.Select(p => new FrameSwap(p.Frame.Id, paths.ToRelative(Path.Combine(entryFolder, p.Files[0].Path)), + [.. p.Files.Skip(1).Select(c => new IncomingCompanion(paths.ToRelative(Path.Combine(entryFolder, c.Path)), FrameCompanions.Tail(c.From, p.Files[0].From)))], + _ => p.Files[0].From, _ => p.Frame)).ToList(); + var copy = Path.Combine(entryFolder, AnalysisCopy); + var analysis = record.Leftovers?.Any(f => f.Path == AnalysisCopy) == true && File.Exists(copy) ? paths.ToRelative(copy) : null; + var consumed = new ConsumedEntry(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), lease, [.. record.Photos.Select(p => p.Frame.Id)], analysis); + return await ReplaceAsync(archive, sequence.Id, null, swaps, null, consumed, (manifest, folder, ct) => SwappableAsync(record, manifest, folder, ct), + cancellationToken).ConfigureAwait(false); + } + + /// + /// A replaced entry's record without its copy of analysis.json once no photo is left in it (all of them filed into + /// a new sequence, which is analysed again): the copy, derived from those photos, goes with the entry. + /// + private static PhotoTrashRecord WithoutAnalysisCopy(string entryFolder, PhotoTrashRecord record) + { + if (record.Kind != TrashKind.Replaced || record.Photos.Count > 0 || record.Leftovers?.Any(f => f.Path == AnalysisCopy) != true) return record; + var copy = Path.Combine(entryFolder, AnalysisCopy); + if (File.Exists(copy)) File.Delete(copy); + var leftovers = record.Leftovers.Where(f => f.Path != AnalysisCopy).ToList(); + return record with { Leftovers = leftovers.Count > 0 ? leftovers : null }; + } +} diff --git a/src/Chronos.Data/Archiving/FrameTrash.Restore.cs b/src/Chronos.Data/Archiving/FrameTrash.Restore.cs index 19c077a5..538599b2 100644 --- a/src/Chronos.Data/Archiving/FrameTrash.Restore.cs +++ b/src/Chronos.Data/Archiving/FrameTrash.Restore.cs @@ -32,7 +32,10 @@ public sealed partial class FrameTrash /// () settles a restore a crash interrupted, and once the first file moves the restore /// runs to its end whatever the caller cancels. When the sequence is gone (deleted, or never indexed in this archive), /// they go into a new sequence through the archive ingest, titled and placed as theirs was, the record rewritten after - /// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it. + /// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it. An entry of + /// (originals a conversion replaced, owner review 2, R7) swaps back instead while every + /// converted frame is as the conversion left it (: the converted files go to the trash as a + /// replaced entry in turn); otherwise its originals come back as a new sequence. /// /// The entry's (photos-…). /// The entry is not in the trash. @@ -69,6 +72,19 @@ public sealed partial class FrameTrash var (intact, kept) = await CheckAsync(entryFolder, record, cancellationToken).ConfigureAwait(false); // Nothing that matches its record: the entry stays as it is. if (intact.Count == 0) throw new TrashMismatchException(); + if (record.Kind == TrashKind.Replaced) + { + // The undo of a conversion: while every converted frame is as the conversion left it, the originals take their + // place again; otherwise they come back as a new sequence, beside the converted one. + if (into is not null && kept.Count == 0 + && await SwapBackAsync(archive, paths, into, record, recordPath, entryFolder, lease, cancellationToken).ConfigureAwait(false) is { } swapped) + { + Log.Info("archive", $"{record.SequenceTitle}: {record.Photos.Count} converted frame(s) swapped back to their originals"); + await QueueAsync(followUps, archive, swapped.Sequence, swapped.Had, CancellationToken.None).ConfigureAwait(false); + return new PhotoRestoreResult(swapped.Sequence, record.Photos.Count, [], false) { Kind = TrashKind.Replaced }; + } + into = null; + } var had = into?.Status ?? SequenceStatus.None; PhotoRestoreResult result; List stays; @@ -83,7 +99,8 @@ public sealed partial class FrameTrash { var restore = await IntoNewSequenceAsync(archive, paths, record, recordPath, entryFolder, intact, cancellationToken).ConfigureAwait(false); stays = [.. kept, .. restore.Left]; - Rewrite(recordPath, entryFolder, record with { Photos = [.. stays.Select(s => s.Photo)], Leftovers = Merge(record.Leftovers, restore.Leftovers) }); + Rewrite(recordPath, entryFolder, WithoutAnalysisCopy(entryFolder, + record with { Photos = [.. stays.Select(s => s.Photo)], Leftovers = Merge(record.Leftovers, restore.Leftovers) })); restore.Failure?.Throw(); stopped = restore.Stopped; if (stopped && restore.Restored == 0) throw new OperationCanceledException(cancellationToken); @@ -94,7 +111,11 @@ public sealed partial class FrameTrash result = new PhotoRestoreResult(row, restore.Restored, [], true); } Log.Info("archive", $"{record.SequenceTitle}: {result.Restored} photo(s) restored from the trash, {stays.Count} kept there"); - var all = result with { Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))] }; + var all = result with + { + Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))], + Kind = record.Kind, + }; if (result.Restored > 0) await QueueAsync(followUps, archive, all.Sequence, had, CancellationToken.None).ConfigureAwait(false); // A cancel stopped a restore into a new sequence before its last photo: those not done stay in the trash, listed. if (stopped) throw new OperationCanceledException(cancellationToken); diff --git a/src/Chronos.Data/Archiving/FrameTrash.cs b/src/Chronos.Data/Archiving/FrameTrash.cs index 452d3d4f..6b3ef7dd 100644 --- a/src/Chronos.Data/Archiving/FrameTrash.cs +++ b/src/Chronos.Data/Archiving/FrameTrash.cs @@ -89,7 +89,11 @@ public sealed record KeptPhoto(string Name, KeptReason Reason) /// What a restore of photos did: the sequence they went back into (a new one when theirs is gone), how many came back, and /// the photos kept in the trash, each with why (). /// -public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList Kept, bool NewSequence); +public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList Kept, bool NewSequence) +{ + /// The kind of entry restored: deleted photos, or originals a conversion replaced (). + public TrashKind Kind { get; init; } = TrashKind.Photos; +} /// /// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): @@ -611,10 +615,13 @@ public sealed partial class FrameTrash } } - /// Queues what the frames need again (see ), as an orphans fix does; an index that cannot take them is logged. - private async Task QueueAsync(JobEngine? followUps, Archive archive, Sequence sequence, SequenceStatus had, CancellationToken cancellationToken) + /// + /// What the frames of need again after they changed, by the statuses it + /// : the light analysis, a background deep analysis when it had one, and the thumbnails and proxies + /// the host keeps (always on a server; on a desktop those it had). + /// + internal List FollowUps(Archive archive, Sequence sequence, SequenceStatus had) { - if (followUps is null) return; var label = sequence.DisplayTitle; List requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)]; if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background }); @@ -622,6 +629,15 @@ public sealed partial class FrameTrash if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label)); if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled) requests.Add(ArchiveJobs.Proxies([sequence.Id], label)); + return requests; + } + + /// Queues what the frames need again (), as an orphans fix does; an index that cannot take them is logged. + private async Task QueueAsync(JobEngine? followUps, Archive archive, Sequence sequence, SequenceStatus had, CancellationToken cancellationToken) + { + if (followUps is null) return; + var label = sequence.DisplayTitle; + var requests = FollowUps(archive, sequence, had); try { foreach (var request in requests) @@ -676,7 +692,8 @@ public sealed partial class FrameTrash /// /// What the trash keeps next to deleted photos (owner review 2, R6): the frame records, where each file was and is, the -/// sequence they came from. entries (a later conversion) name each photo's replacement. +/// sequence they came from. entries (a conversion, R7) name each photo's replacement and +/// keep a copy of the sequence's analysis.json as a leftover (). /// /// Files of the entry whose photo is back in a sequence without them (a companion whose name was /// taken there): counted and erased with the entry, never restored. diff --git a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs index 74aa2437..edc94cde 100644 --- a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs +++ b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs @@ -1,5 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; +using Chronos.Core.Conversion; using Chronos.Core.Import; using Chronos.Core.Model; @@ -51,6 +52,18 @@ public sealed record MoveJobParameters(string? FolderTemplate, string? FileTempl /// A sequence of a (a job queued by an earlier build also names a frames version, which is ignored). public sealed record MoveSequence(Guid Id); +/// +/// (owner review 2, R7): targets = the sequences converted, so the jobs that would touch them +/// wait; the archive, the target format and JPEG quality, the mode chosen for this run, the sequences of the confirmed plan +/// in its order with the frames version each was planned at, and the plan's fingerprint +/// (). A sequence whose frames changed since is left as it is and reported. +/// +public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target, int Quality, ConvertMode Mode, IReadOnlyList Sequences, + string Fingerprint); + +/// A sequence of a and the frames version it was planned at. +public sealed record ConvertSequence(Guid Id, int FramesVersion); + /// A job ready to enqueue. public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets, string? Label, string? ParametersJson, JobPriority Priority); @@ -64,6 +77,9 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets [JsonSerializable(typeof(CleanupParameters))] [JsonSerializable(typeof(EmptyTrashParameters))] [JsonSerializable(typeof(MoveJobParameters))] +[JsonSerializable(typeof(ConvertJobParameters))] +[JsonSerializable(typeof(ConvertJournal))] +[JsonSerializable(typeof(StagedLine))] [JsonSerializable(typeof(CardProfile))] internal sealed partial class ArchiveJobJson : JsonSerializerContext { diff --git a/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs new file mode 100644 index 00000000..14112130 --- /dev/null +++ b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs @@ -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; + +/// +/// : a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan +/// () through , 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 converted, each new sequence as created (), +/// 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. +/// +internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func? sequenceChanged) : IJobHandler +{ + /// The change told about a sequence whose frames a conversion replaced. + public const string Converted = "converted"; + + /// The change told about a sequence a conversion made. + 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)); + } + + /// Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on. + 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); + } + } + } + + /// Tells each sequence changed or made; a failure is logged, never passed on to the job. + 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); + } + } + } +} diff --git a/src/Chronos.Data/Archiving/MassConverter.cs b/src/Chronos.Data/Archiving/MassConverter.cs new file mode 100644 index 00000000..ffaa8810 --- /dev/null +++ b/src/Chronos.Data/Archiving/MassConverter.cs @@ -0,0 +1,745 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using Chronos.Core.Archiving; +using Chronos.Core.Conversion; +using Chronos.Core.Diagnostics; +using Chronos.Core.Imaging; +using Chronos.Core.IO; +using Chronos.Core.Localization; +using Chronos.Core.Metadata; +using Chronos.Core.Model; +using Chronos.Core.Project; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Processing; + +namespace Chronos.Data.Archiving; + +/// What a conversion did with one sequence (owner review 2, R7). +public enum ConvertOutcome +{ + /// Its frames were replaced by the converted files (). + Converted, + + /// The converted files went into a new sequence (). + Created, + + /// It had nothing to convert. + Nothing, + + /// Left as it was: its frames changed after the plan, or it is no longer in the archive. + Changed, + + /// Left as it was: it is busy, or its sidecar cannot be read. + Blocked, + + /// Left as it was: a photo could not be converted (all or nothing), or the files could not move. + Failed, +} + +/// One sequence of a conversion: what happened, how many photos, the new sequence when one was made, and the failure. +public sealed record ConvertSequenceResult(Guid SequenceId, string Title, ConvertOutcome Outcome, int Frames, Guid? NewSequenceId = null, string? Error = null) +{ + /// Whether the sequence is done with: converted, made, or with nothing to convert. + public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing; +} + +/// What a conversion did, and the passes the sequences it changed or made need (to queue as follow-ups). +public sealed record ConvertResult(IReadOnlyList Sequences, IReadOnlyList FollowUps) +{ + /// Photos converted, into their sequence or a new one. + public int Frames => Sequences.Where(s => s.Outcome is ConvertOutcome.Converted or ConvertOutcome.Created).Sum(s => s.Frames); + + /// The sequences left as they were (changed, blocked, failed). + public IEnumerable Kept => Sequences.Where(s => !s.Final); +} + +/// How a running conversion reports: progress in photos, a checkpoint after each sequence, and job log lines. +internal sealed record ConvertCallbacks(Func Progress, Func Checkpoint, Action Log); + +/// +/// Mass conversion of existing sequences (owner review 2, R7; BRIEF §12.5): +/// is the dry run ( per sequence, what blocks it, the space needed against the free space of +/// the archive's volume, ), and a job applies the +/// confirmed plan one sequence at a time. Stage A, without a lease: each photo is hashed against its record and converted +/// (, several at once as the host's parallelism and memory allow) into +/// .chronos/staging/convert-<job>/<sequence>/, each staged file appended to the job's journal +/// (), so a resumed job keeps the staged files whose hash still verifies. Stage B, all or nothing, +/// under the sequence's lease and while its frames are still at the version planned: +/// swaps the frames' files (: the originals into one trash entry of kind +/// , same ids and indices, tombstones naming the replacements); +/// files the converted copies into a new sequence through the archive ingest (session key convert:<job>:<source>, +/// so a resume finds it again), titled "title (FORMAT)", with the source's tags, rating, notes and project, the source left +/// as it is. A sequence that changed after the plan, is busy, or has a photo that fails is left as it was and reported. +/// +public sealed class MassConverter +{ + private readonly ChronosDatabase _db; + private readonly SequenceWriter _writer; + private readonly ArchiveIngest _ingest; + private readonly FrameTrash _frames; + private readonly SequenceTrash _trash; + private readonly ArchiveService _service; + + internal MassConverter(ChronosDatabase db, SequenceWriter writer, ArchiveIngest ingest, FrameTrash frames, SequenceTrash trash, ArchiveService service) + { + _db = db; + _writer = writer; + _ingest = ingest; + _frames = frames; + _trash = trash; + _service = service; + } + + /// + /// The dry run of converting of : per sequence the frames + /// converted and those skipped with why, the bytes before and after, what blocks it (busy, offline, unreadable); the + /// space needed and free; the fingerprint a confirmation sends back. Reads only. + /// + /// The options are invalid, or a sequence is not in the archive. + public Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, ConvertOptions options, ConvertMode mode, + CancellationToken cancellationToken = default) => PlanAsync(archive, sequenceIds, options, mode, null, cancellationToken); + + /// The job asking (a conversion planning again): what it holds does not make its sequences busy. + internal async Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, ConvertOptions options, ConvertMode mode, Guid? job, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(sequenceIds); + ArgumentNullException.ThrowIfNull(options); + if (!options.IsValid) throw new ArgumentException("Unknown target or a quality outside 1–100.", nameof(options)); + if (!Enum.IsDefined(mode)) throw new ArgumentException($"Unknown mode {mode}.", nameof(mode)); + var paths = new ArchivePaths(archive.RootPath); + var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online; + var busy = await _trash.BusyAsync(job, cancellationToken).ConfigureAwait(false); + var plans = new List(); + foreach (var id in sequenceIds.Distinct()) + { + cancellationToken.ThrowIfCancellationRequested(); + var row = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false); + if (row is null || row.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Name}.", nameof(sequenceIds)); + plans.Add(await PlanOneAsync(paths, row, online, busy.Contains(id) || busy.Contains(archive.Id), options, cancellationToken).ConfigureAwait(false)); + } + var estimated = plans.Where(p => p.Converts).Sum(p => p.BytesAfter); + return new ConvertPlan(archive.Id, options, mode, plans, new ConvertSpace(ConvertPlanner.Required(estimated), FreeSpace(paths))); + } + + private async Task PlanOneAsync(ArchivePaths paths, Sequence row, bool online, bool busy, ConvertOptions options, + CancellationToken cancellationToken) + { + List blocked = []; + if (!online) blocked.Add(ConvertBlock.Offline); + if (busy) blocked.Add(ConvertBlock.Busy); + var empty = new ConvertSequencePlan(row.Id, row.DisplayTitle, row.Folder, row.FramesVersion, [], [], blocked); + // Created without photos (no folder yet), or nothing to read while offline. + if (!online || row.FrameCount == 0 && ArchiveIngest.AwaitsFolder(row, paths)) return empty; + var folder = paths.Sequence(row.Folder); + if (Read(folder, row.Id) is not { } manifest) return empty with { Blocked = [.. blocked, ConvertBlock.Unreadable] }; + var decoder = _writer.Options.Decoder; + var plan = await Task.Run(() => ConvertPlanner.Plan(manifest, folder, FileRenames.ListPresent(folder, manifest), options, decoder, row.DisplayTitle), + cancellationToken).ConfigureAwait(false); + return plan with { Blocked = blocked }; + } + + /// + /// Applies a confirmed conversion () as the job : plans again, + /// refuses when the archive's volume lacks the space the photos still to convert need, then converts each sequence that + /// still fits the plan (stage A, then stage B), resuming from the job's journal. Sequences left as they were are in the + /// result; the journal stays while there are any, so a retry tries them again and knows what was done. + /// + /// The archive is offline or read-only; the job resumes where it stopped. + /// The volume lacks the space (Archive.Error.ConvertSpace); nothing was converted since. + internal async Task RunAsync(Archive archive, ConvertJobParameters parameters, Guid jobId, string? createdBy, ConvertCallbacks callbacks, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(parameters); + ArgumentNullException.ThrowIfNull(callbacks); + var options = new ConvertOptions(parameters.Target, parameters.Quality); + if (!options.IsValid || !Enum.IsDefined(parameters.Mode)) throw new InvalidOperationException($"Convert job {jobId} has invalid options."); + var paths = new ArchivePaths(archive.RootPath); + ArchiveVolume.EnsureWritable(paths); + var journal = ConvertJournal.Read(paths, jobId) ?? new ConvertJournal { JobId = jobId }; + var steps = parameters.Sequences.DistinctBy(s => s.Id).ToList(); + // What is still to do: every sequence not final in an earlier attempt that is still in the archive. + var rows = new Dictionary(); + foreach (var step in steps.Where(s => journal.Of(s.Id)?.Final != true)) + { + if (await _db.Sequences.GetAsync(step.Id, cancellationToken).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id) rows[step.Id] = row; + } + var plan = await PlanAsync(archive, [.. rows.Keys], options, parameters.Mode, jobId, cancellationToken).ConfigureAwait(false); + var plans = plan.Sequences.ToDictionary(p => p.SequenceId); + var versions = steps.ToDictionary(s => s.Id, s => s.FramesVersion); + var runnable = plan.Sequences.Where(p => p.Converts && p.FramesVersion == versions[p.SequenceId]).ToList(); + var staged = journal.Staged(paths); + var stagedBytes = runnable.Sum(p => staged.Of(p.SequenceId, p.FramesVersion).Sum(s => s.Size)); + var space = new ConvertSpace(ConvertPlanner.Required(Math.Max(0, runnable.Sum(p => p.BytesAfter) - stagedBytes)), FreeSpace(paths)); + if (runnable.Count > 0 && !space.Enough) + throw new IOException(Loc.L("Archive.Error.ConvertSpace", Gigabytes(space.Required), Gigabytes(space.Free ?? 0))); + var progress = new Progress(runnable.Sum(p => p.Frames.Count), runnable.Sum(p => staged.Of(p.SequenceId, p.FramesVersion).Count)); + await callbacks.Progress(progress.Done, progress.Total).ConfigureAwait(false); + + var results = new List(); + var followUps = new List(); + foreach (var step in steps) + { + cancellationToken.ThrowIfCancellationRequested(); + var noted = journal.Of(step.Id); + ConvertSequenceResult result; + if (noted?.Final == true) + { + result = new ConvertSequenceResult(step.Id, noted.Title ?? step.Id.ToString(), noted.Outcome!.Value, noted.Frames, noted.NewSequenceId); + } + else if (!rows.TryGetValue(step.Id, out var row) || !plans.TryGetValue(step.Id, out var planned)) + { + result = new ConvertSequenceResult(step.Id, step.Id.ToString(), ConvertOutcome.Changed, 0); + } + else if (planned.Blocked.Contains(ConvertBlock.Offline)) + { + throw new ArchiveOfflineException(paths.Root, ArchiveVolume.Probe(paths)); + } + else if (planned.FramesVersion != step.FramesVersion) + { + // Replaced already, by this job before a crash, or changed by someone else since the plan. + if (parameters.Mode == ConvertMode.Replace && ReplacedEarlier(paths, row, staged.Of(step.Id, step.FramesVersion)) is { } frames) + { + result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Converted, frames); + followUps.AddRange(_frames.FollowUps(archive, row, row.Status)); + } + else + { + result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Changed, 0); + } + } + else if (planned.Blocked.Count > 0) + { + result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0); + } + else if (planned.Frames.Count == 0) + { + result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Nothing, 0); + } + else + { + (result, var queued) = await ConvertOneAsync(archive, paths, row, planned, options, parameters.Mode, jobId, createdBy, journal, staged, progress, + callbacks, cancellationToken).ConfigureAwait(false); + followUps.AddRange(queued); + } + results.Add(result); + journal.Note(result); + journal.Write(paths); + if (!result.Final) DeleteStaging(StagingOf(paths, jobId, step.Id)); + Log(callbacks, result); + await callbacks.Checkpoint(progress.Done, progress.Total).ConfigureAwait(false); + } + DeleteStaging(Path.Combine(paths.StagingDirectory, StagingFolder(jobId))); + // Kept while a sequence is left as it was: a retry knows what was done and tries the others again. + if (results.All(r => r.Final)) ConvertJournal.Delete(paths, jobId); + return new ConvertResult(results, followUps); + } + + /// Stage A and stage B of one sequence. + private async Task<(ConvertSequenceResult, IReadOnlyList)> ConvertOneAsync(Archive archive, ArchivePaths paths, Sequence row, + ConvertSequencePlan planned, ConvertOptions options, ConvertMode mode, Guid jobId, string? createdBy, ConvertJournal journal, StagedLog staged, + Progress progress, ConvertCallbacks callbacks, CancellationToken cancellationToken) + { + var folder = paths.Sequence(row.Folder); + if (Read(folder, row.Id) is not { } manifest) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0), []); + if (manifest.Versions.Frames != planned.FramesVersion) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Changed, 0), []); + var staging = StagingOf(paths, jobId, row.Id); + var key = SessionKey(jobId, row.Id); + // A new sequence a resumed job finds again holds the photos it filed before it stopped. + var filed = mode == ConvertMode.NewSequence + ? await FiledAsync(archive, key, cancellationToken).ConfigureAwait(false) + : new HashSet(StringComparer.OrdinalIgnoreCase); + var ready = await Task.Run(() => Ready(manifest, planned, staged.Of(row.Id, planned.FramesVersion), staging, filed), cancellationToken).ConfigureAwait(false); + progress.Done -= staged.Of(row.Id, planned.FramesVersion).Count - ready.Count; + + var failure = await StageAsync(row, manifest, folder, planned, ready, staging, options, staged, progress, callbacks, cancellationToken).ConfigureAwait(false); + if (failure is not null) + return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: failure), []); + try + { + return mode == ConvertMode.Replace + ? await ReplaceAsync(archive, paths, row, planned, manifest, ready, staging, options, createdBy, cancellationToken).ConfigureAwait(false) + : await CreateAsync(archive, paths, row, manifest, ready, staging, options, key, createdBy, cancellationToken).ConfigureAwait(false); + } + catch (LeaseUnavailableException ex) + { + return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0, Error: ex.Message), []); + } + catch (ArchiveOfflineException) + { + throw; + } + 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), []); + } + } + + /// + /// The staged conversions of a sequence that still hold: of a frame the plan converts, at the content it had then, + /// whose staged file is there with its size and SHA-256 (re-hashed now: a pause, a crash or a clean-up may have taken it + /// since), or which a new sequence holds already (). + /// + private static Dictionary Ready(SequenceManifest manifest, ConvertSequencePlan planned, IReadOnlyList noted, + string staging, IReadOnlySet filed) + { + var frames = manifest.Frames.ToDictionary(f => f.Id); + var converted = planned.Frames.Select(f => f.FrameId).ToHashSet(); + var ready = new Dictionary(); + foreach (var conversion in noted) + { + if (!converted.Contains(conversion.FrameId) || !frames.TryGetValue(conversion.FrameId, out var frame) + || !string.Equals(frame.Sha256, conversion.Source, StringComparison.OrdinalIgnoreCase)) + continue; + if (filed.Contains(conversion.Sha256) || Intact(Path.Combine(staging, conversion.File), conversion)) ready[conversion.FrameId] = conversion; + } + return ready; + } + + private static bool Intact(string path, StagedConversion conversion) + { + var file = new FileInfo(path); + if (!file.Exists || file.Length != conversion.Size) return false; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan); + return string.Equals(Convert.ToHexStringLower(SHA256.HashData(stream)), conversion.Sha256, StringComparison.OrdinalIgnoreCase); + } + + /// + /// 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. + /// + private async Task StageAsync(Sequence row, SequenceManifest manifest, SequencePaths folder, ConvertSequencePlan planned, + Dictionary ready, string staging, ConvertOptions options, StagedLog staged, Progress progress, ConvertCallbacks callbacks, + CancellationToken cancellationToken) + { + var frames = manifest.Frames.ToDictionary(f => f.Id); + var todo = planned.Frames.Where(f => !ready.ContainsKey(f.FrameId)).Select(f => frames[f.FrameId]).ToList(); + if (todo.Count == 0) return null; + System.IO.Directory.CreateDirectory(staging); + var decoder = _writer.Options.Decoder; + var largest = todo.Max(f => (long)Math.Max(f.W, 0) * Math.Max(f.H, 0)); + // Photos at once as the host's parallelism and memory allow; each encoder then works alone. + var atOnce = DecodeBudget.PhotosAtOnce(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), largest); + var threads = atOnce > 1 ? 1 : -1; + string? failure = null; + await using var work = new OrderedWork(atOnce, async result => + { + if (result.Conversion is not { } conversion) + { + failure ??= $"{result.File}: {result.Error?.Message}"; + return; + } + staged.Append(row.Id, planned.FramesVersion, conversion); + ready[conversion.FrameId] = conversion; + await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false); + }, cancellationToken); + foreach (var frame in todo) + { + if (failure is not null) break; + 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}"); + return failure; + } + + /// One photo of stage A: hashed against its record, converted into the staging folder and verified. + private static Staged Stage(SidecarFrame frame, SequenceManifest manifest, SequencePaths folder, string staging, ConvertOptions options, ImageDecoder decoder, + int threads, CancellationToken cancellationToken) + { + var source = folder.File(frame.File); + try + { + // Converted only as archived: a photo whose bytes no longer match its hash waits for a verify. + string sha; + 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"); + 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); + return new Staged(frame.File, new StagedConversion(frame.Id, sha, Path.GetFileName(target), file.Size, file.Sha256, file.Width, file.Height), null); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NotSupportedException or FormatException + or InvalidOperationException or ArgumentException) + { + return new Staged(frame.File, null, ex); + } + } + + /// Stage B of : the staged files take their frames' place (). + private async Task<(ConvertSequenceResult, IReadOnlyList)> ReplaceAsync(Archive archive, ArchivePaths paths, Sequence row, + ConvertSequencePlan planned, SequenceManifest manifest, Dictionary ready, string staging, ConvertOptions options, + string? createdBy, CancellationToken cancellationToken) + { + var swaps = manifest.Frames.Where(f => ready.ContainsKey(f.Id)).Select(f => + { + var conversion = ready[f.Id]; + return new FrameSwap(f.Id, paths.ToRelative(Path.Combine(staging, conversion.File)), [], current => options.NameFor(current.File), + current => Converted(current, conversion, options)); + }).ToList(); + // The frames hold the content that was converted: a frames version that did not move says so, and each hash agrees. + var replaced = await _frames.ReplaceAsync(archive, row.Id, planned.FramesVersion, swaps, createdBy, null, + (now, _, _) => Task.FromResult(now.Frames.Where(f => ready.ContainsKey(f.Id)) + .All(f => string.Equals(f.Sha256, ready[f.Id].Source, StringComparison.OrdinalIgnoreCase))), cancellationToken).ConfigureAwait(false); + if (replaced is null) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Changed, 0), []); + return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Converted, swaps.Count), + _frames.FollowUps(archive, replaced.Sequence, replaced.Had)); + } + + /// + /// A converted frame's record: the frame as it is with the converted file's size, hash, format and upright size, read at + /// full-resolution tier, without the embedded preview it no longer has, without the flags of its old file, and with the + /// old file as its ; capture time, exposure and the other facts stay. + /// + internal static SidecarFrame Converted(SidecarFrame current, StagedConversion conversion, ConvertOptions options) => current with + { + Size = conversion.Size, + Sha256 = conversion.Sha256.ToLowerInvariant(), + Format = options.Format, + W = conversion.Width, + H = conversion.Height, + Orientation = 1, + Tier = DecodeTier.Native, + PreviewOffset = null, + PreviewLength = null, + PreviewW = null, + PreviewH = null, + Flags = current.Flags & ~FrameTrash.ContentFlags, + Source = new FrameSource { Sha256 = current.Sha256, Format = current.Format, File = current.File, Size = current.Size }, + }; + + /// + /// Stage B of : the staged files filed into the sequence of + /// (made on first use, titled "title (FORMAT)"), named as their originals with the target's extension, with the source's + /// capture facts; then the source's tags, rating, notes and project (its positions translated to the new frames). + /// + private async Task<(ConvertSequenceResult, IReadOnlyList)> CreateAsync(Archive archive, ArchivePaths paths, Sequence row, + SequenceManifest manifest, Dictionary ready, string staging, ConvertOptions options, string key, string? createdBy, + CancellationToken cancellationToken) + { + var frames = manifest.Frames.ToDictionary(f => f.Id); + var pending = manifest.Frames.Where(f => ready.ContainsKey(f.Id) && File.Exists(Path.Combine(staging, ready[f.Id].File))).Select(f => + { + var conversion = ready[f.Id]; + var path = Path.Combine(staging, conversion.File); + return new StagedFrame(path, f.Original ?? Path.GetFileName(f.File), conversion.Size, conversion.Sha256, Metadata(path, f), null, + Path.GetFileName(options.NameFor(f.File))); + }).ToList(); + var title = $"{manifest.Title ?? row.DisplayTitle} ({options.Label})"; + // Once the first file moves, the commit runs to its end whatever the caller cancels meanwhile. + if (pending.Count > 0) + await _ingest.CommitSessionAsync(archive, new SequenceTarget(key, title, null, createdBy), pending, CancellationToken.None).ConfigureAwait(false); + var id = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false) + ?? throw new IOException($"No converted photo of {row.DisplayTitle} could be filed into a new sequence."); + await CopyAsync(paths, row, manifest, ready, id, cancellationToken).ConfigureAwait(false); + var made = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false) + ?? throw new InvalidOperationException($"The new sequence {id} is not indexed."); + Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: {ready.Count} photo(s) converted into the new sequence {made.DisplayTitle}"); + return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Created, ready.Count, id), + _frames.FollowUps(archive, made, row.Status & (SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt))); + } + + /// + /// The metadata a converted copy is filed with: what its file says, with the source frame's capture time, offset and + /// time source (the sidecar wins, to the tick) and its intervalometer flag, which the MakerNote left behind carried. + /// + private static FrameMetadata Metadata(string path, SidecarFrame source) + { + var read = MetadataReader.Read(path, CancellationToken.None); + var interval = (source.Flags & FrameFlags.Intervalometer) != 0 ? true : read.IntervalShooting; + return source.CapturedAt is { } captured + ? read with { CapturedAt = captured, UtcOffsetMinutes = source.UtcOffset, TimestampSource = source.TimeSource, IntervalShooting = interval } + : read with { IntervalShooting = interval }; + } + + /// + /// Gives the new sequence the source's tags, rating and notes, and its project with the frame positions (exclusions, + /// hero, keyframes) moved from the source's frames to the copies of them; a project that cannot be read is left out + /// (logged). + /// + private async Task CopyAsync(ArchivePaths paths, Sequence source, SequenceManifest manifest, Dictionary ready, Guid id, + CancellationToken cancellationToken) + { + await _service.EditSequenceInfoAsync(id, info => info with { Tags = source.Tags, Rating = source.Rating, Notes = source.Notes }, cancellationToken) + .ConfigureAwait(false); + var folder = paths.Sequence(source.Folder); + var json = source.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null); + if (string.IsNullOrWhiteSpace(json)) return; + var made = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"The new sequence {id} is not indexed."); + var copy = Read(paths.Sequence(made.Folder), id) ?? throw new InvalidDataException($"The sidecar of the new sequence {made.DisplayTitle} cannot be read."); + // The source's frames as the copies the conversion made of them; a frame not converted keeps its own photo, which the + // new sequence lacks (its positions wait as pending frames). + var from = new FramePhotos(manifest.Frames.Select(f => (f.I, ready.TryGetValue(f.Id, out var c) + ? new FramePhoto(c.Sha256.ToLowerInvariant(), c.Size, f.CapturedAt) + : new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))); + var to = new FramePhotos(copy.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))); + try + { + var translated = ProjectSettings.TranslateFramePositions(json, from, to) ?? json; + var project = ProjectStore.Parse(translated); + await new ProjectStore(_db, _writer).UpdateAsync(paths, made, _ => project, cancellationToken).ConfigureAwait(false); + } + catch (InvalidDataException ex) + { + Core.Diagnostics.Log.Warning("archive", $"{source.DisplayTitle}: its project cannot be read; the new sequence {made.DisplayTitle} starts without it", ex); + } + } + + /// The SHA-256 of the frames the sequence of holds; empty when there is none yet. + private async Task> FiledAsync(Archive archive, string key, CancellationToken cancellationToken) + { + var shas = new HashSet(StringComparer.OrdinalIgnoreCase); + if (await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, cancellationToken).ConfigureAwait(false) is not { } id) return shas; + for (var after = -1; ;) + { + var page = await _db.Frames.ListBySequenceAsync(id, after, 1000, cancellationToken).ConfigureAwait(false); + foreach (var frame in page.Where(f => f.Sha256 is not null)) shas.Add(frame.Sha256!); + if (page.Count < 1000) return shas; + after = page[^1].Index; + } + } + + /// + /// The photos converted, when this job replaced the sequence's frames already (a crash after its stage B, before the + /// journal said so): every staged conversion is a frame of the sidecar now, holding the converted content and naming the + /// converted content as its source. Null otherwise. + /// + private static int? ReplacedEarlier(ArchivePaths paths, Sequence row, IReadOnlyList noted) + { + if (noted.Count == 0 || Read(paths.Sequence(row.Folder), row.Id) is not { } manifest) return null; + var frames = manifest.Frames.ToDictionary(f => f.Id); + return noted.All(c => frames.TryGetValue(c.FrameId, out var f) && string.Equals(f.Sha256, c.Sha256, StringComparison.OrdinalIgnoreCase) + && string.Equals(f.Source?.Sha256, c.Source, StringComparison.OrdinalIgnoreCase)) + ? noted.Select(c => c.FrameId).Distinct().Count() + : null; + } + + /// The sidecar of a sequence, read without its lease; null when it cannot be read or names another sequence. + private static SequenceManifest? Read(SequencePaths folder, Guid id) + { + try + { + var manifest = ManifestStore.ReadSequence(folder.ManifestPath); + return manifest.Id == id ? manifest : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) + { + Core.Diagnostics.Log.Warning("archive", $"The sidecar of {folder.RelativeFolder} cannot be read", ex); + return null; + } + } + + /// Free bytes of the archive's volume as the host counts them (); null when unknown. + private long? FreeSpace(ArchivePaths paths) + { + if (_writer.Options.FreeSpace is { } measure) return measure(paths.Root); + try + { + // Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on. + return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(paths.Root)! : paths.Root).AvailableFreeSpace; + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) + { + return null; + } + } + + private static void Log(ConvertCallbacks callbacks, ConvertSequenceResult result) + { + var line = result.Outcome switch + { + ConvertOutcome.Converted => Loc.L("Archive.Log.Converted", result.Title, result.Frames), + ConvertOutcome.Created => Loc.L("Archive.Log.ConvertedNew", result.Title, result.Frames), + ConvertOutcome.Nothing => Loc.L("Archive.Log.ConvertNothing", result.Title), + ConvertOutcome.Changed => Loc.L("Archive.Log.ConvertChanged", result.Title), + ConvertOutcome.Blocked => Loc.L("Archive.Log.ConvertBlocked", result.Title), + _ => Loc.L("Archive.Log.ConvertFailed", result.Title, result.Error), + }; + callbacks.Log(line); + } + + private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / 1e9).ToString("0.#", Loc.Culture)); + + /// The session key of the new sequence a conversion makes from . + internal static string SessionKey(Guid job, Guid source) => $"convert:{job:N}:{source:N}"; + + private static string StagingFolder(Guid job) => $"convert-{job:N}"; + + private static string StagingOf(ArchivePaths paths, Guid job, Guid sequence) => + Path.Combine(paths.StagingDirectory, StagingFolder(job), sequence.ToString("N")); + + /// Deletes what a conversion staged that no step needs any more (converted copies, never originals); a failure is logged. + private static void DeleteStaging(string folder) + { + try + { + if (System.IO.Directory.Exists(folder)) System.IO.Directory.Delete(folder, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Core.Diagnostics.Log.Warning("archive", $"{folder} could not be deleted; maintenance removes it later", ex); + } + } + + /// Photos converted so far and in all. + private sealed class Progress(long total, long done) + { + public long Total { get; } = total; + public long Done { get; set; } = done; + } + + /// A photo of stage A: its file and its staged conversion, or why it failed. + private sealed record Staged(string File, StagedConversion? Conversion, Exception? Error); +} + +/// One photo converted and staged: its frame, the content it was converted from, the staged file's name, size and SHA-256, and its size in pixels. +/// SHA-256 of the original it was converted from. +/// The staged file's name inside the sequence's staging folder. +internal sealed record StagedConversion(Guid FrameId, string Source, string File, long Size, string Sha256, int Width, int Height); + +/// A line of the staged log: a staged conversion of a sequence at a frames version. +internal sealed record StagedLine(Guid Sequence, int FramesVersion, StagedConversion Conversion); + +/// +/// The journal of a conversion job (.chronos/journal/convert-<job>.json, owner review 2, R7): what each sequence +/// came to, written after each one; with it, the staged log (convert-<job>.staged), one line per photo staged, +/// appended and flushed as it is staged, so a job of thousands of photos journals each once. A resumed or retried job keeps +/// the sequences that are final and the staged files whose hash still verifies. +/// +internal sealed class ConvertJournal +{ + public Guid JobId { get; set; } + + public List Sequences { get; set; } = []; + + public ConvertJournalSequence? Of(Guid id) => Sequences.FirstOrDefault(s => s.Id == id); + + public void Note(ConvertSequenceResult result) + { + var noted = Of(result.SequenceId); + if (noted is null) Sequences.Add(noted = new ConvertJournalSequence { Id = result.SequenceId }); + noted.Title = result.Title; + noted.Outcome = result.Outcome; + noted.Frames = result.Frames; + noted.NewSequenceId = result.NewSequenceId; + } + + public static string PathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.json"); + + public static string StagedPathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.staged"); + + /// The journal of ; null when there is none, or it is torn. + public static ConvertJournal? Read(ArchivePaths paths, Guid job) + { + var path = PathFor(paths, job); + if (!File.Exists(path)) return null; + try + { + return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(path), ArchiveJobJson.Default.ConvertJournal); + } + catch (JsonException ex) + { + Core.Diagnostics.Log.Warning("archive", $"The conversion journal {path} is torn; the job starts over", ex); + return null; + } + } + + public void Write(ArchivePaths paths) + { + System.IO.Directory.CreateDirectory(paths.JournalDirectory); + AtomicFile.WriteAllBytes(PathFor(paths, JobId), JsonSerializer.SerializeToUtf8Bytes(this, ArchiveJobJson.Default.ConvertJournal)); + } + + /// The staged log of this job, read now. + public StagedLog Staged(ArchivePaths paths) => StagedLog.Open(StagedPathFor(paths, JobId)); + + public static void Delete(ArchivePaths paths, Guid job) + { + foreach (var path in new[] { StagedPathFor(paths, job), PathFor(paths, job) }) + { + if (File.Exists(path)) File.Delete(path); + } + } +} + +/// What the journal knows of one sequence of a conversion. +internal sealed class ConvertJournalSequence +{ + public Guid Id { get; set; } + + public string? Title { get; set; } + + public ConvertOutcome? Outcome { get; set; } + + public int Frames { get; set; } + + public Guid? NewSequenceId { get; set; } + + [JsonIgnore] + public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing; +} + +/// The staged log of a conversion job (): read once, appended to line by line. +internal sealed class StagedLog +{ + private readonly string _path; + private readonly Dictionary<(Guid, int), Dictionary> _lines = []; + + private StagedLog(string path) => _path = path; + + /// The log at ; a line torn by a crash, or unreadable, is skipped. + public static StagedLog Open(string path) + { + var log = new StagedLog(path); + if (!File.Exists(path)) return log; + foreach (var line in File.ReadLines(path, Encoding.UTF8)) + { + if (string.IsNullOrWhiteSpace(line)) continue; + try + { + if (JsonSerializer.Deserialize(line, ArchiveJobJson.Default.StagedLine) is { } staged) log.Add(staged); + } + catch (JsonException) + { + // Torn while appended: that photo is converted again. + } + } + return log; + } + + /// The staged conversions of a sequence at a frames version, latest per frame. + public IReadOnlyList Of(Guid sequence, int framesVersion) => + _lines.TryGetValue((sequence, framesVersion), out var frames) ? [.. frames.Values] : []; + + /// Appends a staged conversion and flushes it to disk. + public void Append(Guid sequence, int framesVersion, StagedConversion conversion) + { + var line = new StagedLine(sequence, framesVersion, conversion); + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_path)!); + using (var stream = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Read)) + { + stream.Write(JsonSerializer.SerializeToUtf8Bytes(line, ArchiveJobJson.Default.StagedLine)); + stream.WriteByte((byte)'\n'); + stream.Flush(flushToDisk: true); + } + Add(line); + } + + private void Add(StagedLine line) + { + if (!_lines.TryGetValue((line.Sequence, line.FramesVersion), out var frames)) _lines[(line.Sequence, line.FramesVersion)] = frames = []; + frames[line.Conversion.FrameId] = line.Conversion; + } +} diff --git a/src/Chronos.Data/Archiving/SequenceTrash.cs b/src/Chronos.Data/Archiving/SequenceTrash.cs index 9e8acacd..8873fa61 100644 --- a/src/Chronos.Data/Archiving/SequenceTrash.cs +++ b/src/Chronos.Data/Archiving/SequenceTrash.cs @@ -57,7 +57,7 @@ public enum TrashKind /// Photos deleted from a sequence (). Photos, - /// Originals a conversion replaced (a later phase): erased only while their replacements still match. + /// Originals a conversion replaced (owner review 2, R7): erased only while their replacements still match. Replaced, } @@ -477,7 +477,10 @@ public sealed partial class SequenceTrash /// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders /// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those. /// - internal async Task> BusyAsync(CancellationToken cancellationToken) + internal Task> BusyAsync(CancellationToken cancellationToken) => BusyAsync(null, cancellationToken); + + /// What running and paused jobs hold, but the job (the one asking). + internal async Task> BusyAsync(Guid? except, CancellationToken cancellationToken) { var busy = new HashSet(); foreach (var state in new[] { JobState.Running, JobState.Paused }) @@ -486,7 +489,7 @@ public sealed partial class SequenceTrash do { var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false); - foreach (var job in page.Items) busy.UnionWith(Holds(job)); + foreach (var job in page.Items.Where(j => j.Id != except)) busy.UnionWith(Holds(job)); cursor = page.NextCursor; } while (cursor is not null); @@ -608,4 +611,5 @@ internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList Rend [JsonSerializable(typeof(TrashRecord))] [JsonSerializable(typeof(PhotoTrashRecord))] [JsonSerializable(typeof(FrameRestoreJournal))] +[JsonSerializable(typeof(FrameReplaceJournal))] internal sealed partial class TrashJson : JsonSerializerContext; diff --git a/src/Chronos.Data/Archiving/SequenceWriter.cs b/src/Chronos.Data/Archiving/SequenceWriter.cs index 4c6726f0..32a94a44 100644 --- a/src/Chronos.Data/Archiving/SequenceWriter.cs +++ b/src/Chronos.Data/Archiving/SequenceWriter.cs @@ -55,12 +55,20 @@ public sealed record ArchiveServiceOptions /// /// Told after a Reorganize changed a sequence's folder, title or file names (change reorganized), once its step is /// journaled, or once its folder moved and its index row followed when the step then failed: by its job, or by an archive - /// open that completed a plan an interruption left (). + /// open that completed a plan an interruption left (). Told too after a conversion + /// replaced a sequence's frames (converted) or made a new sequence of them (created). /// A server tells its connected clients (BRIEF §14.3); the service it opens its archive with at start sets none, as no /// client is connected yet. The desktop reloads an editor open on the sequence. A failure is logged and never fails the job. /// public Func? SequenceChanged { get; init; } + /// + /// The free bytes of the volume an archive root lies on, as the host counts them (a server measures its space volume, + /// owner review 2, R2); null: the volume of the root itself. A conversion checks its estimate against it (R7). The + /// function returns null when the space cannot be measured. + /// + public Func? FreeSpace { get; init; } + /// Half the logical cores, at least one: the parallelism when the host sets none. public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2); @@ -99,7 +107,8 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options) /// /// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (), - /// undoing an interrupted photo deletion (), settling an interrupted restore from the + /// undoing an interrupted photo deletion (), undoing or completing an interrupted frame + /// replacement (, a conversion or its undo), settling an interrupted restore from the /// trash (; left for later while its trash entry is busy) and completing an interrupted /// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the /// next scan reads it. @@ -121,6 +130,7 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options) FileRenameJournal.Delete(sequence); } FrameRemovalJournal.Recover(sequence, manifest); + FrameTrash.RecoverReplace(sequence, manifest, heldEntryLease); FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease); if (IngestJournal.Recover(sequence, manifest) is { } recovered) { diff --git a/src/Chronos.Protocol/Library.cs b/src/Chronos.Protocol/Library.cs index 8b3f863e..77eaf242 100644 --- a/src/Chronos.Protocol/Library.cs +++ b/src/Chronos.Protocol/Library.cs @@ -123,3 +123,49 @@ public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, strin /// whole, unreadable, counts none), and the fingerprint the change sends back. /// public sealed record ReorganizePlanDto(IReadOnlyList Steps, int Sequences, int Files, int Kept, string Fingerprint); + +/// +/// POST /api/v1/archive/convert (owner review 2, R7; administrators of the archive): the photos of +/// , or of every sequence with (exactly one of the two), converted to +/// (jpeg, tiff16 or linear-dng, the archival choice) with 1–100 +/// for a JPEG (default 95, ignored otherwise). , chosen at every run: replace (the converted files +/// become the frames, the originals go to the archive's trash) or new-sequence (copies in a new sequence, the source +/// untouched). answers the plan () and changes nothing; the change itself +/// sends that plan's back (409 plan_changed when the archive changed since) and runs as a +/// convert job (202). +/// +public sealed record ConvertRequest(IReadOnlyList? SequenceIds, bool All, string? Target, int? Quality, string? Mode, bool DryRun, + string? Fingerprint = null); + +/// +/// Photos of a sequence a conversion leaves as they are: same_format, convert_on_pc (the +/// server cannot read them at full resolution: a CR3, a HEIC, a body its RAW decoder does not support), undecodable, +/// missing or unhashed (never verified), how many, and the reason as one localised sentence. +/// +public sealed record ConvertSkippedDto(string Reason, int Photos, string Message); + +/// Why a whole sequence is not converted now: busy, offline, unreadable or frames_changed, as one localised sentence too. +public sealed record ConvertBlockedDto(string Reason, string Message); + +/// +/// One sequence of a conversion plan: its title, folder and the frames version it was planned at, the photos converted +/// with their size now and the estimated size after, the photos left as they are and why, and what blocks the sequence +/// (it is then not converted). +/// +public sealed record ConvertSequenceDto(Guid SequenceId, string Title, string Folder, int FramesVersion, int Photos, long BytesBefore, long BytesAfter, + IReadOnlyList Skipped, IReadOnlyList Blocked); + +/// +/// The space a conversion needs on the archive's volume (the estimate × 1.15 plus a 512 MiB reserve; with replace the +/// originals stay in the trash, so it adds up), what is free there (null when it cannot be measured), whether it is +/// enough, and the line the dialog shows. +/// +public sealed record ConvertSpaceDto(long Required, long? Free, bool Enough, string Message); + +/// +/// The dry run of a conversion: the target, quality and mode, each sequence asked for in order (), the +/// sequences and photos converted, the photos skipped, the bytes before and the estimate after, the space, and the +/// fingerprint the change sends back. +/// +public sealed record ConvertPlanDto(string Target, int Quality, string Mode, IReadOnlyList Steps, int Sequences, int Photos, int Skipped, + long BytesBefore, long BytesAfter, ConvertSpaceDto Space, string Fingerprint); diff --git a/src/Chronos.Protocol/ProtocolJson.cs b/src/Chronos.Protocol/ProtocolJson.cs index 0bdf7cf1..712f48e1 100644 --- a/src/Chronos.Protocol/ProtocolJson.cs +++ b/src/Chronos.Protocol/ProtocolJson.cs @@ -89,4 +89,6 @@ namespace Chronos.Protocol; [JsonSerializable(typeof(LibraryFacetsDto))] [JsonSerializable(typeof(ReorganizeRequest))] [JsonSerializable(typeof(ReorganizePlanDto))] +[JsonSerializable(typeof(ConvertRequest))] +[JsonSerializable(typeof(ConvertPlanDto))] public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs index 900f7c11..443fe6af 100644 --- a/src/Chronos.Server/Api/ArchiveEndpoints.cs +++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs @@ -1,5 +1,7 @@ +using System.Globalization; using Microsoft.AspNetCore.Mvc; using Chronos.Core.Archiving; +using Chronos.Core.Conversion; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Naming; @@ -15,8 +17,9 @@ using Chronos.Server.Storage; namespace Chronos.Server.Api; /// -/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and -/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive. +/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, +/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive, and Convert (R7): their +/// photos converted to JPEG, TIFF-16 or linear DNG, replacing them or into new sequences. /// public static class ArchiveEndpoints { @@ -24,6 +27,7 @@ public static class ArchiveEndpoints { var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive); archive.MapPost("/reorganize", ReorganizeAsync); + archive.MapPost("/convert", ConvertAsync); // The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll. archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) => Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto)); @@ -250,6 +254,127 @@ public static class ArchiveEndpoints _ => "unreadable", }; + /// + /// Convert: the photos of sequenceIds or, with all, of every sequence of the archive, converted to + /// target (jpeg, tiff16, linear-dng) at quality (JPEG, 1–100, default 95) in mode + /// (replace or new-sequence; BRIEF §12.5). With dryRun the plan, nothing touched: per sequence the + /// photos converted, their size and the estimate after, the photos left as they are with why (convert_on_pc for a + /// format the server cannot read at full resolution), what blocks it; the totals; the space needed and free; the + /// fingerprint. Otherwise the request carries that fingerprint and the server queues a convert job (202) that + /// applies exactly that plan, leaving as it is (and reporting) a sequence that changed before it ran. 400 + /// bad_request (details sequenceIds: neither or both of them, none, or more than + /// ; target, quality, mode, fingerprint); 404 + /// not_found (sequence: not in the archive); 409 plan_changed (details: the fingerprint now), + /// nothing_to_convert, not_enough_space (details: the bytes needed), job_unavailable; 503 + /// archive_offline. Audited (archive_converted: sequences · photos · target · mode); the job tells each sequence + /// it replaces the frames of as sequenceChanged converted, each new one as created. + /// + private static async Task ConvertAsync(HttpContext context, Caller caller, ConvertRequest request, ChronosDatabase db, ServerArchive archive, + [FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit) + { + var ct = context.RequestAborted; + if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds }) + return ApiErrors.BadRequest(context, "bad_request", "sequenceIds"); + if (TargetOf(request.Target) is not { } target) return ApiErrors.BadRequest(context, "bad_request", "target"); + var quality = request.Quality ?? ConvertOptions.DefaultQuality; + if (quality is < 1 or > 100) return ApiErrors.BadRequest(context, "bad_request", "quality"); + if (ModeOf(request.Mode) is not { } mode) return ApiErrors.BadRequest(context, "bad_request", "mode"); + if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint"); + if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online) + return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"); + ConvertPlan plan; + try + { + plan = await LibraryEndpoints.Engine(archives, db).PlanConvertAsync(archive.Id, request.All ? null : request.SequenceIds, + new ConvertOptions(target, quality), mode, ct); + } + catch (ArgumentException) + { + return ApiErrors.NotFound(context, "sequence"); + } + var fingerprint = plan.Fingerprint(); + if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ConvertPlanDto); + if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint); + if (plan.Frames == 0) return ApiErrors.Conflict(context, "nothing_to_convert"); + if (!plan.Space.Enough) return ApiErrors.Conflict(context, "not_enough_space", plan.Space.Required.ToString(CultureInfo.InvariantCulture)); + if (!host.CanRun(JobKind.Convert)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Convert)); + var job = await host.Engine.EnqueueAsync(ArchiveJobs.Convert(archive.Current, plan), caller.Id, ct); + await audit.WriteAsync(caller, context, "archive_converted", "job", job.Id.ToString(), + $"{plan.Converted.Count()} · {plan.Frames} · {Wire(target)} · {Wire(mode)}"); + return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted); + } + + /// The conversion dry run as the API answers it, each reason in the request's language. + private static ConvertPlanDto Plan(HttpContext context, ConvertPlan plan, string fingerprint) + { + var culture = RequestCulture.Of(context); + var space = plan.Space; + var spaceLine = space.Free is not { } free + ? Loc.Text("Archive.Convert.SpaceUnknown", [Size(space.Required, culture)], culture) + : Loc.Text(space.Enough ? "Archive.Convert.Space" : "Archive.Convert.SpaceShort", [Size(space.Required, culture), Size(free, culture)], culture); + return new ConvertPlanDto(Wire(plan.Options.Target), plan.Options.Quality, Wire(plan.Mode), + [.. plan.Sequences.Select(s => new ConvertSequenceDto(s.SequenceId, s.Title, s.Folder, s.FramesVersion, s.Frames.Count, s.BytesBefore, s.BytesAfter, + [.. s.Skipped.GroupBy(k => Wire(k.Reason)).Select(g => new ConvertSkippedDto(g.Key, g.Sum(k => k.Frames), SkipMessage(g.First().Reason, culture)))], + [.. s.Blocked.Select(b => new ConvertBlockedDto(Wire(b), Loc.Get("Archive.Convert.Blocked." + b, culture) ?? Wire(b)))]))], + plan.Converted.Count(), + plan.Frames, + plan.Skipped, + plan.BytesBefore, + plan.BytesAfter, + new ConvertSpaceDto(space.Required, space.Free, space.Enough, spaceLine), + fingerprint); + } + + /// + /// Wire name of why photos are not converted: same_format, convert_on_pc (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), undecodable, missing, unhashed. + /// + public static string Wire(ConvertSkip reason) => reason switch + { + ConvertSkip.SameFormat => "same_format", + ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly => "convert_on_pc", + ConvertSkip.Undecodable => "undecodable", + ConvertSkip.Missing => "missing", + _ => "unhashed", + }; + + /// Wire name of why a sequence is not converted: busy, offline, unreadable, frames_changed. + public static string Wire(ConvertBlock reason) => reason switch + { + ConvertBlock.Busy => "busy", + ConvertBlock.Offline => "offline", + ConvertBlock.Unreadable => "unreadable", + _ => "frames_changed", + }; + + /// Wire name of a conversion target: jpeg, tiff16, linear-dng. + public static string Wire(ConvertTarget target) => target switch + { + ConvertTarget.Jpeg => "jpeg", + ConvertTarget.Tiff16 => "tiff16", + _ => "linear-dng", + }; + + /// Wire name of a conversion mode: replace, new-sequence. + public static string Wire(ConvertMode mode) => mode == ConvertMode.Replace ? "replace" : "new-sequence"; + + private static ConvertTarget? TargetOf(string? text) => + Enum.GetValues().Select(t => (ConvertTarget?)t).FirstOrDefault(t => string.Equals(Wire(t!.Value), text?.Trim(), StringComparison.OrdinalIgnoreCase)); + + private static ConvertMode? ModeOf(string? text) => + Enum.GetValues().Select(m => (ConvertMode?)m).FirstOrDefault(m => string.Equals(Wire(m!.Value), text?.Trim(), StringComparison.OrdinalIgnoreCase)); + + /// Why photos are not converted, in : on the server, a format it cannot read says to convert on a PC. + private static string SkipMessage(ConvertSkip reason, CultureInfo culture) => reason is ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly + ? Loc.Get("Server.Convert.OnPc", culture) ?? Wire(reason) + : Loc.Get("Archive.Convert.Skipped." + reason, culture) ?? Wire(reason); + + /// A size as the dry run's space line shows it: GB from one gigabyte, MB below. + private static string Size(long bytes, CultureInfo culture) => bytes >= 1_000_000_000 + ? Loc.Text("Common.Size.GB", [(bytes / 1e9).ToString("0.#", culture)], culture) + : Loc.Text("Common.Size.MB", [(bytes / 1e6).ToString("0.#", culture)], culture); + private static async Task EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind) { if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind)); diff --git a/src/Chronos.Server/Configuration/ServerSettingsStore.cs b/src/Chronos.Server/Configuration/ServerSettingsStore.cs index d57eb19f..af8161b4 100644 --- a/src/Chronos.Server/Configuration/ServerSettingsStore.cs +++ b/src/Chronos.Server/Configuration/ServerSettingsStore.cs @@ -26,7 +26,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log [ JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup, - JobKind.EmptyTrash, + JobKind.EmptyTrash, JobKind.Convert, ]; private readonly Lock _gate = new(); diff --git a/src/Chronos.Server/Storage/ArchiveModule.cs b/src/Chronos.Server/Storage/ArchiveModule.cs index 6e00c265..768bece1 100644 --- a/src/Chronos.Server/Storage/ArchiveModule.cs +++ b/src/Chronos.Server/Storage/ArchiveModule.cs @@ -12,8 +12,9 @@ namespace Chronos.Server.Storage; /// /// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and /// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and -/// orphans reports, index backups and clean-ups with the server's own steps, the s in DI, and Reorganize's -/// move jobs, which tell connected clients of the sequences they change); a scan +/// orphans reports, index backups and clean-ups with the server's own steps, the s in DI, Reorganize's +/// move jobs and the convert jobs, which tell connected clients of the sequences they change or make, and check +/// their space against the space volume's free bytes, ); a scan /// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring /// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules /// (, owner review 2, R10). @@ -30,16 +31,19 @@ public static class ArchiveModule var options = sp.GetRequiredService(); var db = sp.GetRequiredService(); var events = sp.GetRequiredService(); + var volumes = sp.GetService(); // Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1). return new ArchiveService(db, new ArchiveServiceOptions { - // A Reorganize tells connected clients of every sequence it changed (BRIEF §14.3). + // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3). SequenceChanged = async (id, change, ct) => { if (await db.Sequences.GetAsync(id, ct) is { } sequence) events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); }, Decoder = DecoderFactory.CreateServer(), + // What the panel shows as the archive's free space (owner review 2, R2): a conversion's estimate is checked against it. + FreeSpace = volumes is null ? null : root => volumes.Report(root).Space?.FreeBytes, Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism, diff --git a/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs new file mode 100644 index 00000000..0a8b9162 --- /dev/null +++ b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs @@ -0,0 +1,126 @@ +using Chronos.Core.Archiving; +using Chronos.Core.Conversion; +using Chronos.Core.Export; +using Chronos.Core.Imaging; +using Chronos.Core.Model; +using Chronos.Testing; + +namespace Chronos.Core.Tests.Conversion; + +/// The dry run of a conversion (owner review 2, R7): which frames convert, which stay and why, the sizes, the space and the fingerprint. +[Category("conversion")] +public sealed class ConvertPlannerTests(TestContext context) +{ + private static SidecarFrame Frame(int i, string file, ImageFileFormat format, string? sha = "s", FrameFlags flags = FrameFlags.None, + DecodeTier tier = default) => new() + { + Id = Guid.NewGuid(), + I = i, + File = "originals/" + file, + Size = 1000 + i, + Sha256 = sha is null ? null : sha + i, + Format = format, + W = 6000, + H = 4000, + Flags = flags, + Tier = tier, + }; + + [Test] + public void EachFrameThatCannotConvertSaysWhy() + { + var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("2026/roof"); + SidecarFrame[] frames = + [ + Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2), + Frame(1, "IMG_0002.DNG", ImageFileFormat.Dng), + Frame(2, "IMG_0003.CR2", ImageFileFormat.Cr2), + Frame(3, "IMG_0004.CR2", ImageFileFormat.Cr2, sha: null), + Frame(4, "IMG_0005.CR2", ImageFileFormat.Cr2, flags: FrameFlags.Undecodable), + Frame(5, "IMG_0006.CR3", ImageFileFormat.Cr3), + Frame(6, "IMG_0007.HEIC", ImageFileFormat.Heif), + Frame(7, "IMG_0008.JPG", ImageFileFormat.Jpeg, flags: FrameFlags.Missing), + 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. + var present = frames.Where(f => f.I != 2).Select(f => f.File).ToList(); + var decoder = new ImageDecoder([new ProbeAs(DecodeTier.EmbeddedPreview)]); + 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)); + Assert.SequenceEqual([0], plan.Frames.Select(f => f.Index)); + Assert.SequenceEqual( + [(ConvertSkip.SameFormat, 1), (ConvertSkip.NoNativeDecoder, 2), (ConvertSkip.PreviewOnly, 1), (ConvertSkip.Undecodable, 1), (ConvertSkip.Missing, 2), + (ConvertSkip.Unhashed, 1)], + plan.Skipped.Select(s => (s.Reason, s.Frames))); + Assert.True(plan.Converts); + Assert.Equal(1000, plan.BytesBefore); + Assert.Equal(ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.LinearDng), 6000, 4000), plan.BytesAfter); + Assert.Equal(8, plan.SkippedFrames); + } + + [Test] + public void APhotoRecordedAsPreviewOnlyElsewhereConvertsWhereItDecodes() + { + var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof"); + var frame = Frame(0, "IMG_0001.CR2", ImageFileFormat.Cr2, flags: FrameFlags.PreviewOnly, tier: DecodeTier.EmbeddedPreview); + var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = [frame] }; + var plan = ConvertPlanner.Plan(manifest, folder, [frame.File], new ConvertOptions(ConvertTarget.Tiff16), new ImageDecoder([new ProbeAs(DecodeTier.Native)]), "Roof"); + Assert.Count(1, plan.Frames); + Assert.Empty(plan.Skipped); + } + + [Test] + public void SizesAreEstimatedFromThePixels() + { + const long pixels = 6000L * 4000; + Assert.Equal((long)Math.Ceiling(pixels * 30 / 8.0), ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Tiff16), 6000, 4000)); + Assert.Equal((long)Math.Ceiling(pixels * 26 / 8.0), ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.LinearDng), 6000, 4000)); + Assert.Equal((long)Math.Ceiling(pixels * ExportEstimator.JpegBitsPerPixel(95) * 1.25 / 8), + ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Jpeg), 6000, 4000)); + Assert.Less(ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Jpeg, 50), 6000, 4000), + ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Jpeg, 95), 6000, 4000)); + // Unknown size: a 24 MP frame. + Assert.Equal(ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Tiff16), 6000, 4000), ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Tiff16), 0, 0)); + Assert.Equal((long)Math.Ceiling(1_000_000_000 * 1.15) + (512L << 20), ConvertPlanner.Required(1_000_000_000)); + Assert.True(new ConvertSpace(100, null).Enough); + Assert.True(new ConvertSpace(100, 100).Enough); + Assert.False(new ConvertSpace(100, 99).Enough); + } + + [Test] + public void TheFingerprintFollowsWhatThePlanConverts() + { + var id = Guid.NewGuid(); + ConvertSequencePlan Sequence(int version, int frames, params ConvertBlock[] blocked) => + new(id, "Roof", "roof", version, [.. Enumerable.Range(0, frames).Select(i => new ConvertFramePlan(Guid.Empty, i, $"f{i}", ImageFileFormat.Cr2, 10, 20))], + [], blocked); + ConvertPlan Plan(ConvertOptions options, ConvertMode mode, ConvertSequencePlan sequence) => new(Guid.Empty, options, mode, [sequence], new ConvertSpace(0, null)); + var dng = new ConvertOptions(ConvertTarget.LinearDng); + var reference = Plan(dng, ConvertMode.Replace, Sequence(3, 2)).Fingerprint(); + Assert.Equal(64, reference.Length); + Assert.Equal(reference, Plan(dng with { Quality = 40 }, ConvertMode.Replace, Sequence(3, 2)).Fingerprint()); + Assert.NotEqual(reference, Plan(dng, ConvertMode.NewSequence, Sequence(3, 2)).Fingerprint()); + Assert.NotEqual(reference, Plan(new ConvertOptions(ConvertTarget.Jpeg), ConvertMode.Replace, Sequence(3, 2)).Fingerprint()); + Assert.NotEqual(reference, Plan(dng, ConvertMode.Replace, Sequence(4, 2)).Fingerprint()); + Assert.NotEqual(reference, Plan(dng, ConvertMode.Replace, Sequence(3, 1)).Fingerprint()); + var busy = Plan(dng, ConvertMode.Replace, Sequence(3, 2, ConvertBlock.Busy)); + Assert.NotEqual(reference, busy.Fingerprint()); + Assert.Equal((0, 0L), (busy.Frames, busy.BytesAfter)); + Assert.NotEqual(Plan(new ConvertOptions(ConvertTarget.Jpeg, 90), ConvertMode.Replace, Sequence(3, 2)).Fingerprint(), + Plan(new ConvertOptions(ConvertTarget.Jpeg, 80), ConvertMode.Replace, Sequence(3, 2)).Fingerprint()); + } + + /// A provider that reads CR2 natively by format, and probes every file at a fixed tier. + private sealed class ProbeAs(DecodeTier tier) : 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 DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null; + } +} diff --git a/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs b/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs new file mode 100644 index 00000000..91234d8d --- /dev/null +++ b/tests/Chronos.Core.Tests/Conversion/FrameConverterTests.cs @@ -0,0 +1,286 @@ +using Chronos.Core.Archiving; +using Chronos.Core.Codecs.Dng; +using Chronos.Core.Codecs.Jpeg; +using Chronos.Core.Codecs.Tiff; +using Chronos.Core.Conversion; +using Chronos.Core.Imaging; +using Chronos.Core.Imaging.Decoders; +using Chronos.Core.Metadata; +using Chronos.Core.Model; +using Chronos.Testing; + +namespace Chronos.Core.Tests.Conversion; + +/// +/// One photo converted (owner review 2, R7): to JPEG, TIFF-16 and linear DNG, decoded at full resolution only, with the +/// sidecar's capture facts to the tick and the original's camera, lens, modes and GPS, verified (read back, metadata, the +/// server's decoders) before it counts. +/// +[Category("conversion")] +public sealed class FrameConverterTests(TestContext context) +{ + private static readonly DateTime Captured = new DateTime(2026, 9, 28, 18, 0, 5).AddTicks(1_234_567); + + /// The camera's file says one second earlier, without sub-seconds: the sidecar wins. + private static readonly FrameMetadata Camera = new() + { + Make = "Canon", + Model = "Canon EOS R5", + BodySerial = "032021001234", + LensModel = "RF15-35mm F2.8 L IS USM", + CapturedAt = new DateTime(2026, 9, 28, 18, 0, 4), + UtcOffsetMinutes = 60, + ExposureTime = 1 / 250.0, + FNumber = 8, + Iso = 100, + FocalLength = 15, + FocalLength35 = 15, + ExposureBias = -2 / 3.0, + ExposureProgram = 3, + MeteringMode = 5, + Flash = 16, + WhiteBalanceMode = 1, + Artist = "Alberto", + Gps = new GpsPosition(45.4642035, 9.1899817, 122.5, null), + }; + + private static SidecarFrame Frame(string file, ImageFileFormat format, int width, int height) => new() + { + Id = Guid.NewGuid(), + File = "originals/" + file, + Original = file, + Sha256 = new string('a', 64), + CapturedAt = Captured, + UtcOffset = 120, + TimeSource = TimestampSource.ExifOriginal, + Exposure = 1 / 125.0, + FNumber = 5.6, + Iso = 200, + Focal = 24, + Bias = -1, + W = width, + H = height, + Format = format, + Flags = FrameFlags.Intervalometer, + }; + + /// A gradient with some texture, so every encoder has real work and errors show. + private static ImageBuffer Scene(int width, int height) + { + 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.2f + 0.2f * ((x / 8 + y / 8) % 2); + } + } + return image; + } + + private string Source(int width = 96, int height = 64, int orientation = 1) + { + var path = Path.Combine(context.CreateTempDirectory("source"), "IMG_0001.JPG"); + using var image = Scene(width, height); + var exif = ExifWriter.BuildJpegApp1(Camera with { Orientation = orientation }); + File.WriteAllBytes(path, JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 97, Subsampling = JpegSubsampling.Yuv444, App1Segments = [exif[4..]] })); + return path; + } + + private string Target(ConvertOptions options) => Path.Combine(context.CreateTempDirectory("staged"), "converted" + options.Extension); + + [Theory] + [Case(ConvertTarget.Jpeg)] + [Case(ConvertTarget.Tiff16)] + [Case(ConvertTarget.LinearDng)] + public void TheSidecarsCaptureFactsAndTheCamerasMetadataRoundTrip(ConvertTarget target) + { + var options = new ConvertOptions(target); + var source = Source(); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 96, 64); + var file = FrameConverter.Convert(new ConvertSource(source, frame), options, DecoderFactory.CreateServer(), Target(options), cancellationToken: context.Cancellation); + + Assert.Equal((options.Format, 96, 64), (file.Format, file.Width, file.Height)); + Assert.Equal(new FileInfo(file.Path).Length, file.Size); + Assert.Equal(file.Sha256, ContentHash.Sha256Async(file.Path).GetAwaiter().GetResult()); + var read = MetadataReader.Read(file.Path); + Assert.Equal(options.Format, read.Format); + // The sidecar wins: the capture time to the tick, its offset, exposure, aperture, ISO, focal length and bias. + Assert.Equal(Captured, read.CapturedAt); + Assert.Equal(120, read.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, read.TimestampSource); + Assert.Approximately(1 / 125.0, read.ExposureTime!.Value, 1e-12); + Assert.Approximately(5.6, read.FNumber!.Value, 1e-9); + Assert.Equal(200, read.Iso); + Assert.Approximately(24, read.FocalLength!.Value, 1e-9); + Assert.Approximately(-1, read.ExposureBias!.Value, 1e-4); + // The original's own: camera, serial, lens, 35 mm focal length, modes, GPS, artist. + Assert.Equal(("Canon", "Canon EOS R5", "032021001234", "RF15-35mm F2.8 L IS USM"), (read.Make, read.Model, read.BodySerial, read.LensModel)); + Assert.Approximately(15, read.FocalLength35!.Value, 1e-9); + Assert.Equal((3, 5, 16, 1), (read.ExposureProgram, read.MeteringMode, read.Flash, read.WhiteBalanceMode)); + var gps = Assert.NotNull(read.Gps); + Assert.Approximately(45.4642035, gps.Latitude, 1e-6); + Assert.Approximately(9.1899817, gps.Longitude, 1e-6); + Assert.Equal(1, read.Orientation); + Assert.Equal((96, 64), read.OrientedSize); + } + + [Theory] + [Case(ConvertTarget.Jpeg)] + [Case(ConvertTarget.Tiff16)] + [Case(ConvertTarget.LinearDng)] + public void TheConvertedFileDecodesAtFullResolutionWithTheServersDecoders(ConvertTarget target) + { + var options = new ConvertOptions(target); + var source = Source(); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 96, 64); + var file = FrameConverter.Convert(new ConvertSource(source, frame), options, DecoderFactory.CreateServer(), Target(options), cancellationToken: context.Cancellation); + + var server = DecoderFactory.CreateServer(); + Assert.Equal(DecodeTier.Native, server.Probe(file.Path, file.Format).Tier); + using var original = server.Decode(new DecodeRequest(source, AllowPreview: false))!; + using var converted = Assert.NotNull(server.Decode(new DecodeRequest(file.Path, AllowPreview: false))); + Assert.Equal(DecodeTier.Native, converted.Tier); + Assert.Equal((96, 64), (converted.Pixels.Width, converted.Pixels.Height)); + // The same picture: TIFF-16 and DNG keep it to 16 bits, the JPEG within its quantisation. + var tolerance = target == ConvertTarget.Jpeg ? 0.03 : 0.01; + var error = 0.0; + for (var c = 0; c < 3; c++) + { + var a = original.Pixels.Plane(c); + var b = converted.Pixels.Plane(c); + for (var i = 0; i < a.Length; i++) error += Math.Abs(a[i] - b[i]); + } + Assert.Less(error / (3.0 * 96 * 64), tolerance, $"mean error of {target}"); + } + + [Test] + public void TheJpegQualityAndFullChromaAreTheOnesAsked() + { + var source = Source(160, 120); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 160, 120); + var decoder = DecoderFactory.CreateServer(); + var high = FrameConverter.Convert(new ConvertSource(source, frame), new ConvertOptions(ConvertTarget.Jpeg, 95), decoder, + Target(new ConvertOptions(ConvertTarget.Jpeg)), cancellationToken: context.Cancellation); + var low = FrameConverter.Convert(new ConvertSource(source, frame), new ConvertOptions(ConvertTarget.Jpeg, 20), decoder, + Target(new ConvertOptions(ConvertTarget.Jpeg)), cancellationToken: context.Cancellation); + Assert.Less(low.Size, high.Size); + var info = JpegDecoder.ReadInfo(File.ReadAllBytes(high.Path)); + Assert.Equal("4:4:4", info.SamplingNotation); + Assert.Equal(ConvertOptions.DefaultQuality, new ConvertOptions(ConvertTarget.Jpeg).Quality); + } + + [Test] + public void TiffAndLinearDngAreSixteenBitsAndReadByTheInHouseReaders() + { + var source = Source(); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 96, 64); + var decoder = DecoderFactory.CreateServer(); + var tiff = FrameConverter.Convert(new ConvertSource(source, frame), new ConvertOptions(ConvertTarget.Tiff16), decoder, + Target(new ConvertOptions(ConvertTarget.Tiff16)), cancellationToken: context.Cancellation); + var dng = FrameConverter.Convert(new ConvertSource(source, frame), new ConvertOptions(ConvertTarget.LinearDng), decoder, + Target(new ConvertOptions(ConvertTarget.LinearDng)), cancellationToken: context.Cancellation); + + Assert.Equal(16, MetadataReader.Read(tiff.Path).BitsPerSample); + using (var back = TiffImageReader.Decode(File.ReadAllBytes(tiff.Path))) + Assert.Equal((96, 64, 3), (back.Width, back.Height, back.Channels)); + Assert.Equal(ImageFileFormat.Dng, MetadataReader.Read(dng.Path).Format); + using (var back = TiffImageReader.Decode(File.ReadAllBytes(dng.Path))) + Assert.Equal((96, 64, 3), (back.Width, back.Height, back.Channels)); + } + + [Test] + public void APortraitOriginalIsConvertedUpright() + { + var source = Source(96, 64, orientation: 6); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 96, 64) with { Orientation = 6 }; + var options = new ConvertOptions(ConvertTarget.Jpeg); + var file = FrameConverter.Convert(new ConvertSource(source, frame), options, DecoderFactory.CreateServer(), Target(options), cancellationToken: context.Cancellation); + Assert.Equal((64, 96), (file.Width, file.Height)); + var read = MetadataReader.Read(file.Path); + Assert.Equal((1, 64, 96), (read.Orientation, read.Width, read.Height)); + } + + [Test] + public void ACameraAndLensTheFileLacksComeFromTheSequence() + { + var path = Path.Combine(context.CreateTempDirectory("source"), "frame.png"); + using (var image = Scene(32, 24)) File.WriteAllBytes(path, Chronos.Core.Codecs.Png.PngEncoder.Encode(image)); + var frame = Frame("frame.png", ImageFileFormat.Png, 32, 24); + var options = new ConvertOptions(ConvertTarget.Tiff16); + var file = FrameConverter.Convert(new ConvertSource(path, frame, new SidecarCamera { Make = "Sony", Model = "ILCE-7RM5", Serial = "77" }, "FE 24mm F1.4 GM"), + options, DecoderFactory.CreateServer(), Target(options), cancellationToken: context.Cancellation); + var read = MetadataReader.Read(file.Path); + Assert.Equal(("Sony", "ILCE-7RM5", "77", "FE 24mm F1.4 GM"), (read.Make, read.Model, read.BodySerial, read.LensModel)); + Assert.Equal(Captured, read.CapturedAt); + } + + [Test] + public void APhotoReadOnlyFromItsPreviewIsNotConverted() + { + // A DNG the managed decoder reads natively, behind a chain that offers only a preview. + 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 options = new ConvertOptions(ConvertTarget.Jpeg); + var target = Target(options); + Assert.Throws(() => + FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([new PreviewOnlyProvider()]), target, cancellationToken: context.Cancellation)); + Assert.FileMissing(target); + Assert.Throws(() => + FrameConverter.Convert(new ConvertSource(path, frame), options, new ImageDecoder([]), target, cancellationToken: context.Cancellation)); + } + + [Test] + public void AFileThatDoesNotReadBackIsRefused() + { + var source = Source(); + var frame = Frame("IMG_0001.JPG", ImageFileFormat.Jpeg, 96, 64); + var options = new ConvertOptions(ConvertTarget.Jpeg); + var file = FrameConverter.Convert(new ConvertSource(source, frame), options, DecoderFactory.CreateServer(), Target(options), cancellationToken: context.Cancellation); + var written = FrameConverter.Metadata(MetadataReader.Read(source), new ConvertSource(source, frame)); + Assert.DoesNotThrow(() => FrameConverter.Verify(file, written)); + // A bit flipped on the way to the disk. + var bytes = File.ReadAllBytes(file.Path); + bytes[^10] ^= 0x40; + File.WriteAllBytes(file.Path, bytes); + Assert.Throws(() => FrameConverter.Verify(file, written)); + // A capture time that is not the one written. + File.WriteAllBytes(file.Path, File.ReadAllBytes(source)); + Assert.Throws(() => FrameConverter.Verify(file with { Sha256 = ContentHash.Sha256Async(file.Path).GetAwaiter().GetResult(), Size = new FileInfo(file.Path).Length }, written)); + } + + [Test] + public void ConvertedNamesKeepTheStemAndTheCaseOfTheExtension() + { + Assert.Equal("originals/IMG_0001.DNG", new ConvertOptions(ConvertTarget.LinearDng).NameFor("originals/IMG_0001.CR2")); + Assert.Equal("originals/img_0001.tif", new ConvertOptions(ConvertTarget.Tiff16).NameFor("originals/img_0001.cr3")); + Assert.Equal("originals/2026-09-28_0001.jpg", new ConvertOptions(ConvertTarget.Jpeg).NameFor("originals/2026-09-28_0001.Nef")); + Assert.Equal("frame.jpg", new ConvertOptions(ConvertTarget.Jpeg).NameFor("frame")); + Assert.Equal(ConvertTarget.LinearDng, ConvertOptions.ArchivalTarget); + Assert.False(new ConvertOptions(ConvertTarget.Jpeg, 0).IsValid); + Assert.False(new ConvertOptions(ConvertTarget.Jpeg, 101).IsValid); + Assert.Equal(new ConvertOptions(ConvertTarget.LinearDng, 10).Key, new ConvertOptions(ConvertTarget.LinearDng, 90).Key); + } + + /// A provider that claims DNG natively but only ever gives the embedded-preview tier. + private sealed class PreviewOnlyProvider : IImageDecoderProvider + { + private readonly ManagedDecoderProvider _managed = new(); + + public string Name => "preview-only"; + + public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Dng ? DecodeTier.Native : null; + + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + var decoded = _managed.Decode(request with { AllowPreview = true }, cancellationToken); + if (decoded is null) return null; + var copy = decoded.Pixels.Clone(); + decoded.Dispose(); + return new DecodedImage(copy, DecodeTier.EmbeddedPreview, Name, copy.Width, copy.Height); + } + } +} diff --git a/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs b/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs index a75fb906..199688fb 100644 --- a/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs +++ b/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs @@ -34,10 +34,13 @@ internal sealed class ArchiveFixture : IAsyncDisposable public CancellationToken Ct => _context.Cancellation; /// The index to use (a PostgreSQL schema); a temporary SQLite file when null. - public static async Task CreateAsync(TestContext context, string? root = null, DatabaseOptions? database = null) + /// Changes to the archive service's options (decoders, free space). + public static async Task CreateAsync(TestContext context, string? root = null, DatabaseOptions? database = null, + Func? configure = null) { var db = await ChronosDatabase.OpenAsync(database ?? DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation); - var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); + var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }; + var service = new ArchiveService(db, configure?.Invoke(options) ?? options); var archive = await service.AdoptAsync(root ?? context.CreateTempDirectory("archive"), "Main", context.Cancellation); return new ArchiveFixture(context, db, service, archive); } diff --git a/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs new file mode 100644 index 00000000..59cfe849 --- /dev/null +++ b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs @@ -0,0 +1,580 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Chronos.Core.Archiving; +using Chronos.Core.Conversion; +using Chronos.Core.Import; +using Chronos.Core.Imaging; +using Chronos.Core.Imaging.Decoders; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Core.Project; +using Chronos.Data.Archiving; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Jobs; +using Chronos.Data.Repositories; +using Chronos.Testing; +using static Chronos.Data.Tests.Archiving.ArchiveFixture; + +namespace Chronos.Data.Tests.Archiving; + +/// +/// Mass conversion after import (owner review 2, R7): the dry run, the convert job in both modes, its undo through the +/// trash, all or nothing per sequence, resumes in stage A and B, plans gone stale, the space check, and the gates that must +/// keep holding (the card erase, the emptying of a replaced entry). +/// +[Category("archive")] +public sealed class ConvertTests(TestContext context) +{ + private Task FixtureAsync(Func? more = null) => + CreateAsync(context, configure: o => + { + var options = o with { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 }; + return more is null ? options : more(options); + }); + + /// A sequence of uploaded photos (hashed, under originals/), ten seconds apart. + private static async Task UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100) + { + Guid? id = null; + for (var i = 0; i < count; i++) + { + var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i).AddTicks(1_234_567), seed + i); + var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG", + size, sha, null, null), fx.Ct); + id = result.SequenceId; + } + return id!.Value; + } + + private static Task PlanAsync(ArchiveFixture fx, ConvertTarget target, ConvertMode mode, params Guid[] ids) => + fx.Service.PlanConvertAsync(fx.Archive.Id, ids, new ConvertOptions(target), mode, fx.Ct); + + private static async Task RunAsync(ArchiveFixture fx, JobEngine engine, ConvertPlan plan, JobState state = JobState.Done) + { + var job = await engine.EnqueueAsync(ArchiveJobs.Convert(fx.Archive, plan), cancellationToken: fx.Ct); + return await fx.WaitForAsync(job.Id, state, (int)TestTiming.Budget(60)); + } + + private static SequenceManifest Sidecar(ArchiveFixture fx, Sequence sequence) => ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath); + + private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path))); + + /// The index rows of a sequence, after checking that each file holds its row's content and that the sidecar agrees. + private static async Task> FramesAsync(ArchiveFixture fx, Guid id) + { + var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id)); + var rows = (await fx.Db.Frames.ListBySequenceAsync(id)).ToList(); + var sidecar = Sidecar(fx, sequence); + Assert.Equal(sidecar.Versions.Frames, sequence.FramesVersion); + Assert.SequenceEqual(sidecar.Frames.Select(f => (f.Id, f.I, f.Sha256)), rows.Select(r => (r.Id, r.Index, r.Sha256))); + foreach (var row in rows) Assert.Equal(row.Sha256, Sha(fx.Paths.FromRelative(row.RelativePath))); + Assert.FileMissing(fx.Paths.Sequence(sequence.Folder).ReplaceJournalPath); + return rows; + } + + private static string Staging(ArchiveFixture fx) => fx.Paths.StagingDirectory; + + private static bool StagedAnything(ArchiveFixture fx) => + Directory.Exists(Staging(fx)) && Directory.EnumerateDirectories(Staging(fx), "convert-*").Any(); + + [Test] + public async Task TheDryRunCountsWhatConvertsAndChangesNothing() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + + var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id); + var step = plan.Sequences.Single(); + Assert.Equal((3, 0, true), (step.Frames.Count, step.SkippedFrames, step.Converts)); + Assert.Equal((await fx.Db.Sequences.GetAsync(id))!.FramesVersion, step.FramesVersion); + Assert.Equal(step.Frames.Sum(f => f.Size), plan.BytesBefore); + Assert.Equal(3 * ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.LinearDng), 48, 32), plan.BytesAfter); + Assert.Equal(ConvertPlanner.Required(plan.BytesAfter), plan.Space.Required); + Assert.True(plan.Space.Enough); + Assert.Equal(plan.Fingerprint(), (await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id)).Fingerprint()); + Assert.NotEqual(plan.Fingerprint(), (await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.NewSequence, id)).Fingerprint()); + + // JPEG to JPEG converts nothing. + var same = (await PlanAsync(fx, ConvertTarget.Jpeg, ConvertMode.Replace, id)).Sequences.Single(); + Assert.Equal((0, ConvertSkip.SameFormat, 3), (same.Frames.Count, same.Skipped.Single().Reason, same.Skipped.Single().Frames)); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.False(StagedAnything(fx)); + await Assert.ThrowsAsync(() => PlanAsync(fx, ConvertTarget.Jpeg, ConvertMode.Replace, Guid.NewGuid())); + } + + [Test] + public async Task ASequenceBusyOrUnreadableIsBlocked() + { + await using var fx = await FixtureAsync(); + var busy = await UploadedAsync(fx, 2); + var unreadable = await UploadedAsync(fx, 2, "upload-2", seed: 200); + await fx.Db.Jobs.EnqueueAsync(new Job + { + Id = Guid.CreateVersion7(), + Kind = JobKind.Render, + TargetIds = [busy], + State = JobState.Running, + NodeId = "test#0", + Created = DateTimeOffset.UtcNow, + Started = DateTimeOffset.UtcNow, + }); + File.WriteAllText(fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(unreadable))!.Folder).ManifestPath, "{ not json"); + + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, busy, unreadable); + Assert.SequenceEqual([ConvertBlock.Busy], plan.Sequences.Single(s => s.SequenceId == busy).Blocked); + Assert.SequenceEqual([ConvertBlock.Unreadable], plan.Sequences.Single(s => s.SequenceId == unreadable).Blocked); + Assert.Equal(0, plan.Frames); + Assert.Throws(() => ArchiveJobs.Convert(fx.Archive, plan)); + } + + [Test] + public async Task AReplaceKeepsTheFramesAndTrashesTheOriginalsWithTheirReplacements() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var originals = await FramesAsync(fx, id); + var project = new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }.ToJson(); + await fx.Db.Sequences.EditAsync(id, new SequenceEdit { SettingsJson = project, HeroFrameId = originals[2].Id }, null, fx.Ct); + var folder = fx.Paths.Sequence(sequence.Folder); + Directory.CreateDirectory(folder.MetaDirectory); + File.WriteAllText(folder.AnalysisPath, "{\"frames\":3}"); + var before = Sidecar(fx, sequence); + + var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id); + var job = await RunAsync(fx, engine, plan); + Assert.Contains(Loc.L("Archive.Log.Converted", sequence.DisplayTitle, 3), job.LogTail); + + var row = (await fx.Db.Sequences.GetAsync(id))!; + var frames = await FramesAsync(fx, id); + Assert.Equal(before.Versions.Frames + 1, row.FramesVersion); + Assert.SequenceEqual(originals.Select(f => (f.Id, f.Index)), frames.Select(f => (f.Id, f.Index))); + var after = Sidecar(fx, row); + var options = new ConvertOptions(ConvertTarget.LinearDng); + foreach (var (was, now) in before.Frames.Zip(after.Frames)) + { + Assert.Equal((options.NameFor(was.File), ImageFileFormat.Dng, DecodeTier.Native, 1), (now.File, now.Format, now.Tier, now.Orientation)); + Assert.Equal((was.CapturedAt, was.Original, was.Flags), (now.CapturedAt, now.Original, now.Flags)); + var source = Assert.NotNull(now.Source); + Assert.Equal((was.Sha256, was.Format, was.File, was.Size), (source.Sha256, source.Format, source.File, source.Size)); + Assert.FileMissing(folder.File(was.File)); + } + // The project's positions stay on their frames. + var settings = ProjectSettings.FromJson(row.SettingsJson!); + Assert.SequenceEqual([1], settings.ExcludedFrames); + Assert.Equal((2, originals[2].Id), (settings.HeroFrame, row.HeroFrameId)); + + // One replaced entry with the originals, each naming its replacement, and the analysis as it was. + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + Assert.Equal((TrashKind.Replaced, id, 3), (entry.Kind, entry.SequenceId, entry.Frames)); + var record = Assert.NotNull(FrameTrash.ReadEntry(fx.Paths, entry.Name)); + var entryFolder = FrameTrash.Location(fx.Paths, entry.Name).Folder; + foreach (var photo in record.Photos) + { + var now = after.Frames.Single(f => f.Id == photo.Frame.Id); + Assert.Equal(now.Sha256, photo.Replacement); + Assert.Equal(photo.Frame.Sha256, Sha(Path.Combine(entryFolder, photo.Files[0].Path))); + } + Assert.Equal("{\"frames\":3}", File.ReadAllText(Path.Combine(entryFolder, FrameTrash.AnalysisCopy))); + // Tombstones alias the old content to the new, in the sidecar and the index. + var tombstones = Assert.NotNull(after.Removed); + Assert.SequenceEqual(before.Frames.Select(f => (f.Sha256, after.Frames.Single(n => n.Id == f.Id).Sha256, RemovalReason.Replaced)).Order(), + tombstones.Select(t => ((string?)t.Sha256, t.Replacement, t.Reason)).Order()); + Assert.SequenceEqual(tombstones.Select(t => (t.Sha256, t.Replacement)).Order(), + (await fx.Db.FrameRemovals.ListBySequenceAsync(id)).Select(r => (r.Sha256, r.ReplacementSha256)).Order()); + Assert.Equal((SequenceStatus)0, row.Status & (SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt)); + Assert.False(StagedAnything(fx)); + Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, job.Id)); + Assert.FileMissing(ConvertJournal.StagedPathFor(fx.Paths, job.Id)); + // Converted again, nothing is left to convert. + Assert.Equal(0, (await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id)).Frames); + } + + [Test] + public async Task RestoringTheReplacedEntrySwapsTheOriginalsBack() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + var originals = await FramesAsync(fx, id); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var before = Sidecar(fx, sequence); + var analysis = fx.Paths.Sequence(sequence.Folder).AnalysisPath; + Directory.CreateDirectory(Path.GetDirectoryName(analysis)!); + File.WriteAllText(analysis, "of the originals"); + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id)); + var converted = Sidecar(fx, (await fx.Db.Sequences.GetAsync(id))!); + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + // The light analysis of the converted frames, as it would be written again. + File.WriteAllText(analysis, "of the conversions"); + + var result = await fx.Service.RestoreEntryAsync(fx.Archive.Id, entry.Name, null, fx.Ct); + Assert.Equal((TrashKind.Replaced, 3, false, id), (result.Kind, result.Photos, result.NewSequence, result.Sequence.Id)); + var frames = await FramesAsync(fx, id); + Assert.SequenceEqual(originals.Select(f => (f.Id, f.Index, f.Sha256, f.RelativePath, f.Format)), frames.Select(f => (f.Id, f.Index, f.Sha256, f.RelativePath, f.Format))); + var back = Sidecar(fx, (await fx.Db.Sequences.GetAsync(id))!); + Assert.True(back.Frames.All(f => f.Source is null)); + // The converted files are in the trash in turn, naming the originals as their replacements; the old entry is gone. + var turned = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + Assert.NotEqual(entry.Name, turned.Name); + Assert.Equal(TrashKind.Replaced, turned.Kind); + var record = FrameTrash.ReadEntry(fx.Paths, turned.Name)!; + Assert.SequenceEqual(converted.Frames.Select(f => (f.Sha256, before.Frames.Single(o => o.Id == f.Id).Sha256)).Order(), + record.Photos.Select(p => (p.Frame.Sha256, p.Replacement)).Order()); + // Each analysis goes with its frames: the originals' back in the sequence, the conversions' into the new entry. + Assert.Equal("of the originals", File.ReadAllText(analysis)); + Assert.Equal("of the conversions", File.ReadAllText(Path.Combine(FrameTrash.Location(fx.Paths, turned.Name).Folder, FrameTrash.AnalysisCopy))); + Assert.False(Directory.Exists(FrameTrash.Location(fx.Paths, entry.Name).Folder)); + Assert.SequenceEqual(converted.Frames.Select(f => (f.Sha256, before.Frames.Single(o => o.Id == f.Id).Sha256)).Order(), + back.Removed!.Select(t => ((string?)t.Sha256, t.Replacement)).Order()); + + // That entry erases: its replacements (the originals) are where it says, re-hashed now. + var empty = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct); + var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, empty), cancellationToken: fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Done); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + await FramesAsync(fx, id); + } + + [Test] + public async Task AnUndoAfterTheFramesChangedBringsTheOriginalsBackAsANewSequence() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + var originals = await FramesAsync(fx, id); + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id)); + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + var converted = await FramesAsync(fx, id); + // A converted frame deleted since: the frames are no longer the ones the conversion left. + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var delete = await fx.Service.FrameTrash.PlanDeleteAsync(id, [converted[1].Id], sequence.FramesVersion, fx.Ct); + await fx.Service.FrameTrash.DeleteAsync(delete, "alberto", null, fx.Ct); + + var result = await fx.Service.RestoreEntryAsync(fx.Archive.Id, entry.Name, null, fx.Ct); + Assert.Equal((TrashKind.Replaced, 3, true), (result.Kind, result.Photos, result.NewSequence)); + Assert.NotEqual(id, result.Sequence.Id); + Assert.SequenceEqual(originals.Select(f => f.Sha256), (await FramesAsync(fx, result.Sequence.Id)).Select(f => f.Sha256)); + Assert.Count(2, await FramesAsync(fx, id)); + // The replaced entry is gone with its last photo (and its copy of the analysis); the deleted frame's entry stays. + Assert.DoesNotContain(entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name)); + } + + [Test] + public async Task ANewSequenceTakesTheCopiesAndLeavesTheSourceAsItIs() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + await fx.Service.SetSequenceInfoAsync(id, "Roof", ["sunset", "milan"], 4, "From the roof", fx.Ct); + var originals = await FramesAsync(fx, id); + await fx.Db.Sequences.EditAsync(id, new SequenceEdit { SettingsJson = new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }.ToJson() }, null, fx.Ct); + var source = (await fx.Db.Sequences.GetAsync(id))!; + var sidecar = File.ReadAllText(fx.Paths.Sequence(source.Folder).ManifestPath); + + var job = await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id)); + var made = Assert.NotNull(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(job.Id, id))); + var copy = (await fx.Db.Sequences.GetAsync(made))!; + Assert.Equal(("Roof (TIFF)", 4, "From the roof"), (copy.Title, copy.Rating, copy.Notes)); + Assert.SequenceEqual(["milan", "sunset"], copy.Tags.Order()); + var frames = await FramesAsync(fx, made); + Assert.SequenceEqual(originals.Select(f => f.CapturedAt), frames.Select(f => f.CapturedAt)); + Assert.True(frames.All(f => f.Format == ImageFileFormat.Tiff)); + Assert.SequenceEqual(originals.Select(f => Path.ChangeExtension(f.FileName, ".tif")), frames.Select(f => Path.ChangeExtension(f.FileName, ".tif"))); + var settings = ProjectSettings.FromJson(copy.SettingsJson!); + Assert.SequenceEqual([1], settings.ExcludedFrames); + Assert.Equal((2, frames[2].Id), (settings.HeroFrame, copy.HeroFrameId)); + // The source: not a byte of its sidecar, nor a row, changed; nothing went to the trash. + Assert.Equal(sidecar, File.ReadAllText(fx.Paths.Sequence(source.Folder).ManifestPath)); + var now = (await fx.Db.Sequences.GetAsync(id))!; + Assert.Equal((source.FramesVersion, source.SettingsVersion, source.Title, source.Folder), (now.FramesVersion, now.SettingsVersion, now.Title, now.Folder)); + Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256)), (await FramesAsync(fx, id)).Select(f => (f.Id, f.Sha256))); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + Assert.False(StagedAnything(fx)); + } + + [Test] + public async Task APhotoThatFailsLeavesItsWholeSequenceAsItWasAndTheOthersConvert() + { + await using var fx = await FixtureAsync(); + var bad = await UploadedAsync(fx, 3); + var good = await UploadedAsync(fx, 2, "upload-2", seed: 300); + var engine = await fx.StartEngineAsync(); + var damaged = (await FramesAsync(fx, bad))[1]; + var originals = await FramesAsync(fx, bad); + // Rot after the plan: the photo no longer matches the hash it was archived with. + var path = fx.Paths.FromRelative(damaged.RelativePath); + var bytes = File.ReadAllBytes(path); + bytes[^20] ^= 0x10; + File.WriteAllBytes(path, bytes); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, bad, good); + Assert.Equal(5, plan.Frames); + + 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); + // 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))); + Assert.True((await FramesAsync(fx, good)).All(f => f.Format == ImageFileFormat.Tiff)); + Assert.SequenceEqual([good], (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.SequenceId)); + Assert.False(StagedAnything(fx)); + // The journal stays for a retry, which tries the failed sequence again and leaves the converted one. + var journal = Assert.NotNull(ConvertJournal.Read(fx.Paths, job.Id)); + Assert.Equal(ConvertOutcome.Converted, journal.Of(good)!.Outcome); + Assert.Equal(ConvertOutcome.Failed, journal.Of(bad)!.Outcome); + } + + [Test] + public async Task AResumedJobKeepsTheStagedFilesThatStillVerify() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + // To JPEG needs other originals than the JPEGs uploaded: they become TIFF first. + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id)); + var plan = await PlanAsync(fx, ConvertTarget.Jpeg, ConvertMode.Replace, id); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var folder = fx.Paths.Sequence(sequence.Folder); + var manifest = Sidecar(fx, sequence); + var jobId = Guid.CreateVersion7(); + var staging = Path.Combine(Staging(fx), $"convert-{jobId:N}", $"{id:N}"); + var log = StagedLog.Open(ConvertJournal.StagedPathFor(fx.Paths, jobId)); + // An earlier attempt staged the first photo (at another quality, so its use shows) and the second, damaged since. + StagedConversion Stage(SidecarFrame frame, int quality) + { + var target = Path.Combine(staging, frame.Id.ToString("N") + ".jpg"); + var file = FrameConverter.Convert(new ConvertSource(folder.File(frame.File), frame, manifest.Camera, manifest.Lens), new ConvertOptions(ConvertTarget.Jpeg, quality), + DecoderFactory.CreateServer(), target, cancellationToken: fx.Ct); + var conversion = new StagedConversion(frame.Id, frame.Sha256!, Path.GetFileName(target), file.Size, file.Sha256, file.Width, file.Height); + log.Append(id, manifest.Versions.Frames, conversion); + return conversion; + } + var kept = Stage(manifest.Frames[0], 40); + var torn = Stage(manifest.Frames[1], 95); + File.WriteAllBytes(Path.Combine(staging, torn.File), [1, 2, 3]); + + var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Convert(fx.Archive, plan), "convert", jobId); + await fx.WaitForAsync(job.Id, JobState.Done); + var frames = await FramesAsync(fx, id); + Assert.Equal(kept.Sha256, frames[0].Sha256); + Assert.Equal(torn.Sha256, frames[1].Sha256); + Assert.True(frames.All(f => f.Format == ImageFileFormat.Jpeg)); + } + + [Test] + public async Task AJobThatStoppedAfterItsReplacementReportsTheSequenceConverted() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id); + var request = ArchiveJobs.Convert(fx.Archive, plan); + await RunAsync(fx, engine, plan); + // As a crash between the replacement and the journal's note leaves it: the staged log names the conversions done. + var sidecar = Sidecar(fx, (await fx.Db.Sequences.GetAsync(id))!); + var jobId = Guid.CreateVersion7(); + var log = StagedLog.Open(ConvertJournal.StagedPathFor(fx.Paths, jobId)); + foreach (var frame in sidecar.Frames) + log.Append(id, plan.Sequences.Single().FramesVersion, new StagedConversion(frame.Id, frame.Source!.Sha256!, "gone.dng", frame.Size, frame.Sha256!, frame.W, frame.H)); + + var job = await fx.EnqueueWithCheckpointAsync(engine, request, "convert", jobId); + var done = await fx.WaitForAsync(job.Id, JobState.Done); + Assert.Contains(Loc.L("Archive.Log.Converted", (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle, 2), done.LogTail); + Assert.Count(1, await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + } + + [Test] + public async Task ASequenceThatChangedAfterThePlanIsLeftAsItWas() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id); + // Another photo arrives before the job runs. + var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999); + await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + + var job = await RunAsync(fx, engine, plan, JobState.Failed); + Assert.Equal(Loc.Plural("Archive.Error.ConvertKept", 1), job.Error); + Assert.Contains(Loc.L("Archive.Log.ConvertChanged", (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle), job.LogTail); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + } + + [Test] + public async Task AVolumeWithoutTheSpaceConvertsNothing() + { + await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => 1_000 }); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id); + Assert.False(plan.Space.Enough); + Assert.Equal(1_000, plan.Space.Free); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + + var job = await RunAsync(fx, engine, plan, JobState.Failed); + Assert.True(job.Error!.StartsWith("The conversion needs", StringComparison.Ordinal), job.Error); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.False(StagedAnything(fx)); + } + + [Test] + public async Task ACardKeepsTheCopyOfAPhotoThatWasConverted() + { + await using var fx = await FixtureAsync(); + var card = context.CreateTempDirectory("card"); + Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 3); + var media = await fx.Service.Imports.RegisterCardAsync(new CardVolume("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592), fx.Ct); + var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct); + await fx.Service.Imports.ExecuteAsync(new ImportJobParameters(fx.Archive.Id, import, media.Id, true, null), Guid.NewGuid(), 0, + _ => ValueTask.CompletedTask, null, fx.Ct); + var id = (await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, import.Sessions.Single().SessionKey))!.Value; + Assert.Equal(3, (await fx.Service.PlanCardEraseAsync(fx.Archive.Id, media.Id, card, null, fx.Ct)).ToDelete.Count()); + var engine = await fx.StartEngineAsync(); + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id)); + + // The frames now hold converted files: nothing in the archive matches the card's photos byte for byte, so they stay. + var erase = await fx.Service.PlanCardEraseAsync(fx.Archive.Id, media.Id, card, null, fx.Ct); + Assert.Empty(erase.ToDelete); + Assert.True(erase.Items.All(i => i.Verdict == EraseVerdict.CopyMismatch)); + Assert.Equal(0, CardEraser.Execute(erase).Deleted); + Assert.Count(3, Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories)); + } + + [Test] + public async Task AReplacedEntryIsErasedOnlyWhileTheConvertedFilesStillHashToTheirRecord() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id)); + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + var converted = (await FramesAsync(fx, id))[0]; + var file = fx.Paths.FromRelative(converted.RelativePath); + var bytes = File.ReadAllBytes(file); + var damaged = (byte[])bytes.Clone(); + damaged[^10] ^= 0x01; + File.WriteAllBytes(file, damaged); + + var plan = await PlanEmptyAsync(fx); + var kept = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct); + await fx.WaitForAsync(kept.Id, JobState.Failed); + Assert.Contains(entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name)); + + File.WriteAllBytes(file, bytes); + var erased = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, await PlanEmptyAsync(fx)), cancellationToken: fx.Ct); + await fx.WaitForAsync(erased.Id, JobState.Done); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + + static Task PlanEmptyAsync(ArchiveFixture fx) => fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct); + } + + [Test] + public async Task AReplacementACrashInterruptedBeforeItsSidecarIsUndoneByTheNextWriter() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var folder = fx.Paths.Sequence(sequence.Folder); + var manifest = Sidecar(fx, sequence); + var frame = manifest.Frames[0]; + // Half a replacement: the original in its entry, the converted file in its place, the record pending, the sidecar as it was. + var staged = Path.Combine(Staging(fx), "convert-test", frame.Id.ToString("N") + ".tif"); + FrameConverter.Convert(new ConvertSource(folder.File(frame.File), frame), new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), staged, + cancellationToken: fx.Ct); + var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), $"{id:N}-20261027120000"); + var record = entryFolder + ".json"; + var trashed = Path.Combine(entryFolder, "originals", Path.GetFileName(frame.File)); + var placed = Path.ChangeExtension(frame.File, ".tif"); + var journal = new FrameReplaceJournal(manifest.Versions.Frames, fx.Paths.ToRelative(record), fx.Paths.ToRelative(entryFolder), + [new SwapMove(frame.File, fx.Paths.ToRelative(trashed))], [new SwapMove(placed, fx.Paths.ToRelative(staged))], false, null); + journal.Write(folder); + Directory.CreateDirectory(FrameTrash.Directory(fx.Paths)); + File.WriteAllText(FrameRemovalJournal.PendingRecord(record), "{}"); + Directory.CreateDirectory(Path.GetDirectoryName(trashed)!); + File.Move(folder.File(frame.File), trashed); + File.Move(staged, folder.File(placed)); + + await fx.Service.EditSequenceInfoAsync(id, info => info with { Rating = 2 }, fx.Ct); + Assert.FileExists(folder.File(frame.File)); + Assert.FileMissing(folder.File(placed)); + Assert.FileExists(staged); + Assert.False(Directory.Exists(entryFolder)); + Assert.FileMissing(FrameRemovalJournal.PendingRecord(record)); + Assert.FileMissing(folder.ReplaceJournalPath); + Assert.Equal(frame.Sha256, Sha(folder.File(frame.File))); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + } + + [Test] + public async Task AReplacementACrashInterruptedAfterItsSidecarIsCompletedByTheNextWriter() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var version = (await fx.Db.Sequences.GetAsync(id))!.FramesVersion; + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id)); + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + var (entryFolder, record) = FrameTrash.Location(fx.Paths, entry.Name); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var folder = fx.Paths.Sequence(sequence.Folder); + // As a crash right after the sidecar was written leaves it: the record still pending, the journal there. + File.Move(record, FrameRemovalJournal.PendingRecord(record)); + new FrameReplaceJournal(version, fx.Paths.ToRelative(record), fx.Paths.ToRelative(entryFolder), [], [], true, null).Write(folder); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + + await fx.Service.EditSequenceInfoAsync(id, info => info with { Rating = 2 }, fx.Ct); + Assert.FileMissing(folder.ReplaceJournalPath); + Assert.Equal(entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name); + Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff)); + } + + [Test] + public async Task APhotoTheServerCannotReadAtFullResolutionIsSkipped() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + // The sidecar says the second photo is a HEIC (a desktop with WIC filed it): the managed decoders have only its preview. + var manifest = Sidecar(fx, sequence); + ManifestStore.WriteSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath, + manifest with { Frames = [manifest.Frames[0], manifest.Frames[1] with { Format = ImageFileFormat.Heif }] }); + var step = (await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.NewSequence, id)).Sequences.Single(); + Assert.Equal(1, step.Frames.Count); + Assert.Equal((ConvertSkip.NoNativeDecoder, 1), (step.Skipped.Single().Reason, step.Skipped.Single().Frames)); + } + + [Test] + public async Task TheJournalsSurviveARoundTrip() + { + await using var fx = await FixtureAsync(); + var journal = new ConvertJournal { JobId = Guid.NewGuid() }; + var first = Guid.NewGuid(); + journal.Note(new ConvertSequenceResult(first, "Roof", ConvertOutcome.Created, 3, Guid.NewGuid())); + journal.Note(new ConvertSequenceResult(Guid.NewGuid(), "Harbour", ConvertOutcome.Failed, 0, Error: "no")); + journal.Write(fx.Paths); + var read = Assert.NotNull(ConvertJournal.Read(fx.Paths, journal.JobId)); + Assert.SequenceEqual(journal.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final)), + read.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final))); + Assert.True(read.Of(first)!.Final); + // A line torn by a crash is skipped; a later line for a frame replaces an earlier one. + var path = ConvertJournal.StagedPathFor(fx.Paths, journal.JobId); + var log = StagedLog.Open(path); + var frame = Guid.NewGuid(); + log.Append(first, 4, new StagedConversion(frame, "a", "x.dng", 1, "b", 2, 3)); + log.Append(first, 4, new StagedConversion(frame, "a", "x.dng", 1, "c", 2, 3)); + File.AppendAllText(path, "{\"sequence\":"); + var reread = StagedLog.Open(path); + Assert.Equal("c", reread.Of(first, 4).Single().Sha256); + Assert.Empty(reread.Of(first, 5)); + ConvertJournal.Delete(fx.Paths, journal.JobId); + Assert.FileMissing(path); + Assert.Null(ConvertJournal.Read(fx.Paths, journal.JobId)); + _ = JsonSerializer.Serialize(new ConvertJobParameters(fx.Archive.Id, ConvertTarget.Jpeg, 80, ConvertMode.NewSequence, [new ConvertSequence(first, 2)], "f"), + ArchiveJobJson.Default.ConvertJobParameters); + } +} diff --git a/tests/Chronos.Server.Tests/Api/ConvertTests.cs b/tests/Chronos.Server.Tests/Api/ConvertTests.cs new file mode 100644 index 00000000..7ec53692 --- /dev/null +++ b/tests/Chronos.Server.Tests/Api/ConvertTests.cs @@ -0,0 +1,223 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Chronos.Core.Codecs.Jpeg; +using Chronos.Core.Imaging; +using Chronos.Core.Model; +using Chronos.Protocol; +using Chronos.Server.Events; +using Chronos.Server.Storage; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Api; + +/// +/// Mass conversion on the server (owner review 2, R7): POST /api/v1/archive/convert, its dry run, the convert job +/// that applies the confirmed plan, what the request may not do, and the formats the server leaves to a PC. +/// +[Category("server")] +public sealed class ConvertTests(TestContext context) +{ + private const string Url = "/api/v1/archive/convert"; + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(60)); + + [Test] + public async Task AConversionIsDryRunThenAppliedByAJob() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + Guid id = default; + for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId; + await UntilIdleAsync(server); + var before = await server.Database.Frames.ListBySequenceAsync(id); + + var request = new ConvertRequest([id], false, "linear-dng", null, "replace", DryRun: true); + ConvertPlanDto plan; + using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ConvertRequest)) + plan = await dry.ReadAsync(ProtocolJson.Default.ConvertPlanDto); + Assert.Equal(("linear-dng", 95, "replace", 1, 3, 0), (plan.Target, plan.Quality, plan.Mode, plan.Sequences, plan.Photos, plan.Skipped)); + var step = plan.Steps.Single(); + Assert.Equal((id, 3, before.Sum(f => f.Size)), (step.SequenceId, step.Photos, step.BytesBefore)); + Assert.True(step.BytesAfter > 0 && plan.BytesAfter == step.BytesAfter); + Assert.Empty(step.Blocked); + Assert.True(plan.Space.Enough); + Assert.True(plan.Space.Required > plan.BytesAfter); + Assert.False(string.IsNullOrWhiteSpace(plan.Space.Message)); + Assert.Equal(64, plan.Fingerprint.Length); + Assert.SequenceEqual(before.Select(f => f.Sha256), (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.Sha256)); + + using (var missing = await admin.PostAsJsonAsync(Url, request with { DryRun = false }, ProtocolJson.Default.ConvertRequest)) + Assert.Equal("fingerprint", (await missing.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details); + using (var wrong = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = "0123" }, ProtocolJson.Default.ConvertRequest)) + Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details); + + using var events = server.Services.GetRequiredService().Subscribe(); + JobDto job; + using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ConvertRequest)) + { + await applied.ExpectAsync(HttpStatusCode.Accepted); + job = await applied.ReadAsync(ProtocolJson.Default.JobDto); + } + Assert.Equal("convert", job.Kind); + Assert.SequenceEqual([id], job.TargetIds); + await UntilJobAsync(admin, job.Id, "done"); + + var after = await server.Database.Frames.ListBySequenceAsync(id); + Assert.SequenceEqual(before.Select(f => (f.Id, f.Index)), after.Select(f => (f.Id, f.Index))); + Assert.True(after.All(f => f.Format == ImageFileFormat.Dng)); + foreach (var frame in after) Assert.Equal(frame.Sha256, Uploads.Sha(File.ReadAllBytes(Path.Combine(server.Options.ArchivePath, frame.RelativePath)))); + Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "archive_converted", 10, null)).Items); + var sequence = (await server.Database.Sequences.GetAsync(id))!; + var until = DateTime.UtcNow + Wait; + while (true) + { + using var timeout = new CancellationTokenSource(until - DateTime.UtcNow); + var e = await events.Reader.ReadAsync(timeout.Token); + if (e is SequenceChangedEvent { Change: "converted" } changed && changed.SequenceId == id) + { + Assert.Equal(sequence.FramesVersion, changed.FramesVersion); + break; + } + } + // The originals are in the trash as a replaced entry. + using (var trash = await admin.GetAsync("/api/v1/archive/trash")) + Assert.Contains("replaced", await trash.Content.ReadAsStringAsync()); + } + + [Test] + public async Task ANewSequenceIsMadeBesideTheSource() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + Guid id = default; + for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId; + await UntilIdleAsync(server); + var archive = (await server.Database.Archives.ListAsync()).Single().Id; + var before = (await server.Database.Sequences.ListLocationsAsync(archive)).Count; + + var request = new ConvertRequest([id], false, "tiff16", null, "new-sequence", DryRun: true); + ConvertPlanDto plan; + using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ConvertRequest)) + plan = await dry.ReadAsync(ProtocolJson.Default.ConvertPlanDto); + using var events = server.Services.GetRequiredService().Subscribe(); + JobDto job; + using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ConvertRequest)) + job = await applied.ReadAsync(ProtocolJson.Default.JobDto); + await UntilJobAsync(admin, job.Id, "done"); + + var locations = await server.Database.Sequences.ListLocationsAsync(archive); + Assert.Equal(before + 1, locations.Count); + var made = locations.Single(l => l.Id != id).Id; + Assert.True((await server.Database.Frames.ListBySequenceAsync(made)).All(f => f.Format == ImageFileFormat.Tiff)); + Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Jpeg)); + var until = DateTime.UtcNow + Wait; + while (true) + { + using var timeout = new CancellationTokenSource(until - DateTime.UtcNow); + if (await events.Reader.ReadAsync(timeout.Token) is SequenceChangedEvent { Change: "created" } created && created.SequenceId == made) break; + } + } + + [Test] + public async Task AConversionAsksForTheArchiveAndAValidRequest() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + var a = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId; + await UntilIdleAsync(server); + var valid = new ConvertRequest([a], false, "jpeg", 80, "replace", DryRun: true); + + using (var forbidden = await editor.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ConvertRequest)) + await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden"); + foreach (var (bad, details) in new[] + { + (valid with { All = true }, "sequenceIds"), + (valid with { SequenceIds = null }, "sequenceIds"), + (valid with { SequenceIds = [] }, "sequenceIds"), + (valid with { Target = "webp" }, "target"), + (valid with { Target = null }, "target"), + (valid with { Quality = 0 }, "quality"), + (valid with { Quality = 101 }, "quality"), + (valid with { Mode = "overwrite" }, "mode"), + }) + { + using var response = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ConvertRequest); + Assert.Equal(details, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details); + } + using (var unknown = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = [Guid.NewGuid()] }, ProtocolJson.Default.ConvertRequest)) + await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found"); + + // JPEG to JPEG: the dry run says why, and the change is refused. + ConvertPlanDto plan; + using (var dry = await admin.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ConvertRequest)) + plan = await dry.ReadAsync(ProtocolJson.Default.ConvertPlanDto); + Assert.Equal((0, 1), (plan.Photos, plan.Skipped)); + Assert.Equal(("same_format", 1), (plan.Steps.Single().Skipped.Single().Reason, plan.Steps.Single().Skipped.Single().Photos)); + using (var nothing = await admin.PostAsJsonAsync(Url, valid with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ConvertRequest)) + await nothing.ExpectErrorAsync(HttpStatusCode.Conflict, "nothing_to_convert"); + using (var all = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = null, All = true, Target = "LINEAR-DNG" }, ProtocolJson.Default.ConvertRequest)) + Assert.Equal(1, (await all.ReadAsync(ProtocolJson.Default.ConvertPlanDto)).Photos); + Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Convert)).Items); + } + + [Test] + public async Task PhotosTheServerCannotReadAtFullResolutionAreLeftToAPc() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId; + for (var i = 2; i <= 3; i++) await Uploads.UploadAsync(editor, Heif(i), $"IMG_{i:0000}.HEIC", sessionKey: "roof"); + await UntilIdleAsync(server); + + admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it"); + using var dry = await admin.PostAsJsonAsync(Url, new ConvertRequest([id], false, "linear-dng", null, "new-sequence", DryRun: true), ProtocolJson.Default.ConvertRequest); + var plan = await dry.ReadAsync(ProtocolJson.Default.ConvertPlanDto); + Assert.Equal((1, 2), (plan.Photos, plan.Skipped)); + var skipped = plan.Steps.Single().Skipped.Single(); + Assert.Equal(("convert_on_pc", 2), (skipped.Reason, skipped.Photos)); + Assert.Equal(Chronos.Core.Localization.Loc.Get("Server.Convert.OnPc", System.Globalization.CultureInfo.GetCultureInfo("it")), skipped.Message); + } + + private static async Task UntilJobAsync(HttpClient client, Guid id, string state) + { + var until = DateTime.UtcNow + Wait; + while (true) + { + using var response = await client.GetAsync($"/api/v1/jobs/{id}"); + var job = await response.ReadAsync(ProtocolJson.Default.JobDto); + if (job.State == state) return; + if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}"); + Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}"); + await Task.Delay(50); + } + } + + /// Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue). + private static async Task UntilIdleAsync(TestServer server) + { + var until = DateTime.UtcNow + Wait; + foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running }) + { + while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0) + { + Assert.True(DateTime.UtcNow < until, $"jobs still {state}"); + await Task.Delay(50); + } + } + } + + private static byte[] Photo(int seed) + { + const int width = 96, height = 64; + var pixels = new byte[width * height * 3]; + for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251); + return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 }); + } + + /// A HEIF file as far as signature sniffing goes (an ftyp box naming heic), with no pixels the server can read. + private static byte[] Heif(int seed) => [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, seed)]; +}