From 83a54fb57b701af0abdfe3884d14037723a88af8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 08:59:40 +0000 Subject: [PATCH 001/188] chore: bootstrap repository foundation Solution layout, build rules with zero-package guard, in-house test framework, localization runtime, brand mark rasteriser with ICO/PNG generation, Core contracts (imaging, video, domain model, TIFF reader), Titano.Tools (make-icon, i18n, xaml-lint, package-guard) and docs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .editorconfig | 39 + .gitignore | 8 + CLAUDE.md | 19 + Directory.Build.props | 40 + Directory.Build.targets | 42 + Titano.slnx | 22 + branding/titano-mono.svg | 15 + branding/titano-server.svg | 17 + branding/titano-uploader.svg | 17 + branding/titano.svg | 16 + docs/ARCHITECTURE.md | 88 ++ docs/BRIEF.md | 1346 +++++++++++++++++ docs/CHANGELOG.md | 12 + docs/DECISIONS.md | 16 + docs/STATUS.md | 5 + docs/ui/DESIGN.md | 119 ++ docs/ui/mockups/Admin.html | 118 ++ docs/ui/mockups/AdminUsers.html | 76 + docs/ui/mockups/Archive.html | 142 ++ docs/ui/mockups/Components.html | 193 +++ docs/ui/mockups/Editor.html | 114 ++ docs/ui/mockups/Export.html | 102 ++ docs/ui/mockups/Icon.html | 80 + docs/ui/mockups/Import.html | 154 ++ docs/ui/mockups/Jobs.html | 80 + docs/ui/mockups/Main.html | 101 ++ docs/ui/mockups/Server.html | 112 ++ docs/ui/mockups/Settings.html | 83 + docs/ui/mockups/Uploader.html | 70 + docs/ui/mockups/Welcome.html | 81 + global.json | 7 + i18n/en/Shell.resx | 10 + i18n/it/Shell.it.resx | 9 + src/Titano.App/App.xaml | 4 + src/Titano.App/App.xaml.cs | 7 + src/Titano.App/Titano.App.csproj | 21 + src/Titano.App/app.manifest | 29 + .../Titano.Core.Windows.csproj | 13 + src/Titano.Core.Windows/WindowsPlatform.cs | 7 + src/Titano.Core/Branding/BrandMark.cs | 204 +++ src/Titano.Core/Codecs/Ico/IcoWriter.cs | 78 + src/Titano.Core/Codecs/Png/PngEncoder.cs | 133 ++ src/Titano.Core/Diagnostics/Log.cs | 116 ++ src/Titano.Core/Hashing/Crc32.cs | 47 + src/Titano.Core/IO/AtomicFile.cs | 81 + src/Titano.Core/IO/LongPath.cs | 23 + src/Titano.Core/Imaging/Decoding.cs | 112 ++ src/Titano.Core/Imaging/ImageBuffer.cs | 74 + src/Titano.Core/Imaging/ImageFileFormat.cs | 109 ++ src/Titano.Core/Localization/Languages.cs | 39 + src/Titano.Core/Localization/Loc.cs | 114 ++ src/Titano.Core/Localization/PluralRules.cs | 103 ++ src/Titano.Core/Metadata/FrameMetadata.cs | 71 + src/Titano.Core/Metadata/Tiff/TiffReader.cs | 251 +++ src/Titano.Core/Metadata/Tiff/TiffTags.cs | 126 ++ src/Titano.Core/Metadata/Tiff/TiffType.cs | 32 + src/Titano.Core/Model/Entities.cs | 238 +++ src/Titano.Core/Model/Enums.cs | 126 ++ src/Titano.Core/Naming/TemplateDefaults.cs | 8 + src/Titano.Core/Titano.Core.csproj | 11 + src/Titano.Core/Video/Encoding.cs | 134 ++ src/Titano.Core/Video/Rational.cs | 29 + src/Titano.Data/Dialect.cs | 8 + src/Titano.Data/Titano.Data.csproj | 13 + src/Titano.Protocol/ApiVersion.cs | 8 + src/Titano.Protocol/Titano.Protocol.csproj | 6 + src/Titano.Server/Admin/web/index.html | 1 + src/Titano.Server/Program.cs | 4 + src/Titano.Server/Titano.Server.csproj | 23 + src/Titano.Setup/App.xaml | 4 + src/Titano.Setup/App.xaml.cs | 7 + src/Titano.Setup/Titano.Setup.csproj | 15 + src/Titano.Setup/app.manifest | 29 + src/Titano.Tools/Commands/I18nCommand.cs | 203 +++ src/Titano.Tools/Commands/MakeIconCommand.cs | 51 + .../Commands/PackageGuardCommand.cs | 45 + src/Titano.Tools/Commands/XamlLintCommand.cs | 74 + src/Titano.Tools/ICommand.cs | 61 + src/Titano.Tools/Program.cs | 34 + src/Titano.Tools/Titano.Tools.csproj | 13 + src/Titano.Ui/Titano.Ui.csproj | 10 + src/Titano.Ui/UiAssembly.cs | 6 + src/Titano.Uploader/App.xaml | 4 + src/Titano.Uploader/App.xaml.cs | 7 + src/Titano.Uploader/Titano.Uploader.csproj | 16 + src/Titano.Uploader/app.manifest | 29 + tests/Titano.App.Tests/Program.cs | 8 + .../Titano.App.Tests/Titano.App.Tests.csproj | 13 + .../Branding/BrandMarkTests.cs | 62 + .../Foundation/AtomicFileTests.cs | 33 + .../Foundation/Crc32Tests.cs | 25 + .../Foundation/ImageBufferTests.cs | 44 + .../Localization/PluralRulesTests.cs | 38 + tests/Titano.Core.Tests/Program.cs | 8 + .../Titano.Core.Tests.csproj | 12 + tests/Titano.Core.Windows.Tests/Program.cs | 8 + .../Titano.Core.Windows.Tests.csproj | 11 + tests/Titano.Data.Tests/Program.cs | 8 + .../Titano.Data.Tests.csproj | 12 + tests/Titano.Server.Tests/Program.cs | 8 + .../Titano.Server.Tests.csproj | 12 + tests/Titano.Testing/Assert.cs | 251 +++ tests/Titano.Testing/AssertionException.cs | 7 + tests/Titano.Testing/Attributes.cs | 55 + tests/Titano.Testing/ConsoleReporter.cs | 64 + tests/Titano.Testing/TestCase.cs | 59 + tests/Titano.Testing/TestContext.cs | 96 ++ tests/Titano.Testing/TestRunner.cs | 319 ++++ tests/Titano.Testing/Titano.Testing.csproj | 6 + 109 files changed, 7523 insertions(+) create mode 100644 .editorconfig create mode 100644 CLAUDE.md create mode 100644 Directory.Build.props create mode 100644 Directory.Build.targets create mode 100644 Titano.slnx create mode 100644 branding/titano-mono.svg create mode 100644 branding/titano-server.svg create mode 100644 branding/titano-uploader.svg create mode 100644 branding/titano.svg create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/BRIEF.md create mode 100644 docs/CHANGELOG.md create mode 100644 docs/DECISIONS.md create mode 100644 docs/STATUS.md create mode 100644 docs/ui/DESIGN.md create mode 100644 docs/ui/mockups/Admin.html create mode 100644 docs/ui/mockups/AdminUsers.html create mode 100644 docs/ui/mockups/Archive.html create mode 100644 docs/ui/mockups/Components.html create mode 100644 docs/ui/mockups/Editor.html create mode 100644 docs/ui/mockups/Export.html create mode 100644 docs/ui/mockups/Icon.html create mode 100644 docs/ui/mockups/Import.html create mode 100644 docs/ui/mockups/Jobs.html create mode 100644 docs/ui/mockups/Main.html create mode 100644 docs/ui/mockups/Server.html create mode 100644 docs/ui/mockups/Settings.html create mode 100644 docs/ui/mockups/Uploader.html create mode 100644 docs/ui/mockups/Welcome.html create mode 100644 global.json create mode 100644 i18n/en/Shell.resx create mode 100644 i18n/it/Shell.it.resx create mode 100644 src/Titano.App/App.xaml create mode 100644 src/Titano.App/App.xaml.cs create mode 100644 src/Titano.App/Titano.App.csproj create mode 100644 src/Titano.App/app.manifest create mode 100644 src/Titano.Core.Windows/Titano.Core.Windows.csproj create mode 100644 src/Titano.Core.Windows/WindowsPlatform.cs create mode 100644 src/Titano.Core/Branding/BrandMark.cs create mode 100644 src/Titano.Core/Codecs/Ico/IcoWriter.cs create mode 100644 src/Titano.Core/Codecs/Png/PngEncoder.cs create mode 100644 src/Titano.Core/Diagnostics/Log.cs create mode 100644 src/Titano.Core/Hashing/Crc32.cs create mode 100644 src/Titano.Core/IO/AtomicFile.cs create mode 100644 src/Titano.Core/IO/LongPath.cs create mode 100644 src/Titano.Core/Imaging/Decoding.cs create mode 100644 src/Titano.Core/Imaging/ImageBuffer.cs create mode 100644 src/Titano.Core/Imaging/ImageFileFormat.cs create mode 100644 src/Titano.Core/Localization/Languages.cs create mode 100644 src/Titano.Core/Localization/Loc.cs create mode 100644 src/Titano.Core/Localization/PluralRules.cs create mode 100644 src/Titano.Core/Metadata/FrameMetadata.cs create mode 100644 src/Titano.Core/Metadata/Tiff/TiffReader.cs create mode 100644 src/Titano.Core/Metadata/Tiff/TiffTags.cs create mode 100644 src/Titano.Core/Metadata/Tiff/TiffType.cs create mode 100644 src/Titano.Core/Model/Entities.cs create mode 100644 src/Titano.Core/Model/Enums.cs create mode 100644 src/Titano.Core/Naming/TemplateDefaults.cs create mode 100644 src/Titano.Core/Titano.Core.csproj create mode 100644 src/Titano.Core/Video/Encoding.cs create mode 100644 src/Titano.Core/Video/Rational.cs create mode 100644 src/Titano.Data/Dialect.cs create mode 100644 src/Titano.Data/Titano.Data.csproj create mode 100644 src/Titano.Protocol/ApiVersion.cs create mode 100644 src/Titano.Protocol/Titano.Protocol.csproj create mode 100644 src/Titano.Server/Admin/web/index.html create mode 100644 src/Titano.Server/Program.cs create mode 100644 src/Titano.Server/Titano.Server.csproj create mode 100644 src/Titano.Setup/App.xaml create mode 100644 src/Titano.Setup/App.xaml.cs create mode 100644 src/Titano.Setup/Titano.Setup.csproj create mode 100644 src/Titano.Setup/app.manifest create mode 100644 src/Titano.Tools/Commands/I18nCommand.cs create mode 100644 src/Titano.Tools/Commands/MakeIconCommand.cs create mode 100644 src/Titano.Tools/Commands/PackageGuardCommand.cs create mode 100644 src/Titano.Tools/Commands/XamlLintCommand.cs create mode 100644 src/Titano.Tools/ICommand.cs create mode 100644 src/Titano.Tools/Program.cs create mode 100644 src/Titano.Tools/Titano.Tools.csproj create mode 100644 src/Titano.Ui/Titano.Ui.csproj create mode 100644 src/Titano.Ui/UiAssembly.cs create mode 100644 src/Titano.Uploader/App.xaml create mode 100644 src/Titano.Uploader/App.xaml.cs create mode 100644 src/Titano.Uploader/Titano.Uploader.csproj create mode 100644 src/Titano.Uploader/app.manifest create mode 100644 tests/Titano.App.Tests/Program.cs create mode 100644 tests/Titano.App.Tests/Titano.App.Tests.csproj create mode 100644 tests/Titano.Core.Tests/Branding/BrandMarkTests.cs create mode 100644 tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs create mode 100644 tests/Titano.Core.Tests/Foundation/Crc32Tests.cs create mode 100644 tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs create mode 100644 tests/Titano.Core.Tests/Localization/PluralRulesTests.cs create mode 100644 tests/Titano.Core.Tests/Program.cs create mode 100644 tests/Titano.Core.Tests/Titano.Core.Tests.csproj create mode 100644 tests/Titano.Core.Windows.Tests/Program.cs create mode 100644 tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj create mode 100644 tests/Titano.Data.Tests/Program.cs create mode 100644 tests/Titano.Data.Tests/Titano.Data.Tests.csproj create mode 100644 tests/Titano.Server.Tests/Program.cs create mode 100644 tests/Titano.Server.Tests/Titano.Server.Tests.csproj create mode 100644 tests/Titano.Testing/Assert.cs create mode 100644 tests/Titano.Testing/AssertionException.cs create mode 100644 tests/Titano.Testing/Attributes.cs create mode 100644 tests/Titano.Testing/ConsoleReporter.cs create mode 100644 tests/Titano.Testing/TestCase.cs create mode 100644 tests/Titano.Testing/TestContext.cs create mode 100644 tests/Titano.Testing/TestRunner.cs create mode 100644 tests/Titano.Testing/Titano.Testing.csproj diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..065e082f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{csproj,props,targets,slnx,xml,resx,xaml,json,yml,yaml,svg}] +indent_size = 2 + +[*.{js,css,html}] +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning +csharp_using_directive_placement = outside_namespace +dotnet_sort_system_directives_first = true +csharp_prefer_braces = when_multiline:suggestion +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_expression_bodied_methods = when_on_single_line:silent +csharp_new_line_before_open_brace = all +dotnet_style_qualification_for_field = false:suggestion +dotnet_naming_rule.private_fields_underscore.symbols = private_fields +dotnet_naming_rule.private_fields_underscore.style = underscore_camel +dotnet_naming_rule.private_fields_underscore.severity = suggestion +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private +dotnet_naming_style.underscore_camel.required_prefix = _ +dotnet_naming_style.underscore_camel.capitalization = camel_case + +# Interop and codec code legitimately uses these patterns. +dotnet_diagnostic.CA1416.severity = warning +dotnet_diagnostic.CA2101.severity = none +dotnet_diagnostic.SYSLIB1054.severity = none +dotnet_diagnostic.CA1401.severity = none diff --git a/.gitignore b/.gitignore index d5a18dee..1732a815 100644 --- a/.gitignore +++ b/.gitignore @@ -427,3 +427,11 @@ FodyWeavers.xsd *.msix *.msm *.msp + +# Titano +tests/fixtures/external/ +/out/ +/publish/ +/artifacts/ +*.junit.xml +TestResults/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..908e146a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,19 @@ +# Titano — working rules +Read docs/BRIEF.md when in doubt; it wins over these notes. +- Zero . Anything not in the .NET BCL / Microsoft shared frameworks / OS APIs is written here. +- No external processes at runtime (no ffmpeg, exiftool, powershell). Only OS dialogs listed in BRIEF §8.6. +- Titano.Core / Data / Protocol / Server target net10.0 and build on Linux; Windows-only code lives in *.Windows or the desktop apps. +- English identifiers, comments, commits (Conventional Commits). Prototype in docs/reference is Italian: port algorithms, not language. +- Every UI string is a resource (en source, it translation). Labels ≤ 3 words; explanations only in tooltips; every actionable control has a tooltip; no helper paragraphs. +- Destructive operations: dry-run plan first, hash verification, explicit user action. +- When the brief is silent: choose the simplest safe option, log it in docs/DECISIONS.md, continue. Ask only at phase gates or before irreversible choices. +- Definition of Done per phase: green on windows-latest + ubuntu-latest, tests green, no new warnings, DECISIONS + CHANGELOG updated, i18n check green, phase report with "how to try it". +- Build: dotnet build -c Release; tests: dotnet run --project tests/ -- --junit out.xml; tools: dotnet run --project src/Titano.Tools -- . +- Current phase and next steps: see docs/STATUS.md (update at every gate). + +## Repository specifics +- Visual target: docs/ui/DESIGN.md (tokens, controls) and docs/ui/mockups/*.html. Looks: mockup wins; behaviour: brief wins. +- Code conventions and module ownership: docs/ARCHITECTURE.md. +- Localization: keys `Area.Group.Name` in i18n/en/.resx, Italian in i18n/it/.it.resx. C# `Loc.L("Key")`, XAML `{l:Loc Key}`. +- Checks run in CI: `Titano.Tools package-guard`, `i18n check`, `xaml-lint`. +- Linux builds the Windows projects for compile checking (EnableWindowsTargeting); Windows-only tests carry [WindowsOnly]. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..5b59ad91 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,40 @@ + + + $(MSBuildThisFileDirectory) + 0.1.0 + $(TitanoVersion) + $([System.Text.RegularExpressions.Regex]::Match($(TitanoVersion), '^\d+\.\d+\.\d+').Value).0 + $(AssemblyVersion) + $(TitanoVersion) + Titano + Titano + © Titano + en + + latest + enable + enable + true + true + latest + false + false + true + true + false + en;it;de;fr;es;pt-BR;pt-PT;nl;pl;cs;sk;hu;ro;sv;da;nb;fi;ru;uk;tr;el;bg;hr;sl;lt;lv;et;ja;zh-Hans;zh-Hant;ko;ar;he;hi;id;ms;vi;th + + + true + + false + true + true + false + embedded + + + + true + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..60f0cca3 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,42 @@ + + + + + + + + + + i18n\%(Filename)%(Extension) + + + + + + $(RepoRoot)artifacts/icons/ + + + $(TitanoIconDir)$(TitanoIconVariant).ico + + + + + + + + + + + diff --git a/Titano.slnx b/Titano.slnx new file mode 100644 index 00000000..4ba03d78 --- /dev/null +++ b/Titano.slnx @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/branding/titano-mono.svg b/branding/titano-mono.svg new file mode 100644 index 00000000..58642c70 --- /dev/null +++ b/branding/titano-mono.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano-server.svg b/branding/titano-server.svg new file mode 100644 index 00000000..7cd565b2 --- /dev/null +++ b/branding/titano-server.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano-uploader.svg b/branding/titano-uploader.svg new file mode 100644 index 00000000..31fd2675 --- /dev/null +++ b/branding/titano-uploader.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/branding/titano.svg b/branding/titano.svg new file mode 100644 index 00000000..fb2f35ed --- /dev/null +++ b/branding/titano.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 00000000..351f5587 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,88 @@ +# Titano — Architecture and code conventions + +Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). This file says +*where code goes* and *how it is written*. + +## 1. Projects + +| Project | TFM | Purpose | +|---|---|---| +| `src/Titano.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, motion, render, video containers, archive model, naming, import planning, localization runtime, brand mark | +| `src/Titano.Core.Windows` | net10.0-windows | WIC decoder, Media Foundation encoder, DXGI, device APIs, shell helpers (P/Invoke/COM only) | +| `src/Titano.Data` | net10.0 | `IDatabase`, SQLite binding (winsqlite3 on Windows, system libsqlite3 elsewhere for tests/dev), PostgreSQL wire client, migrations, repositories | +| `src/Titano.Protocol` | net10.0 | API DTOs, source-generated JSON contexts, upload/sync/event schemas | +| `src/Titano.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, jobs, storage, admin web panel (embedded) | +| `src/Titano.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, custom controls, `Loc` markup extension, MVVM helpers | +| `src/Titano.App` | WPF exe `Titano.exe` | Desktop client | +| `src/Titano.Uploader` | WPF exe | Uploader | +| `src/Titano.Setup` | WPF exe | Installer/uninstaller | +| `src/Titano.Tools` | net10.0 exe | CLI: make-icon, i18n, xaml-lint, package-guard, selftest, diagnose, fixtures, changelog | +| `tests/Titano.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `Assert`, `TestContext`) | +| `tests/Titano.*.Tests` | exe | One test program per area; `dotnet run --project tests/X -- --junit out.xml` | + +## 2. Namespaces in Titano.Core + +| Folder / namespace | Content | +|---|---| +| `Imaging` | `ImageBuffer` (planar float, linear light), `ImageFileFormat`, `IImageDecoderProvider`, `ImageDecoder`, colour/geometry helpers, `FrameWindow` | +| `Metadata` (+ `Metadata.Tiff`, `Metadata.Bmff`, …) | Signature sniffing, TIFF/IFD (`TiffReader`), Exif/GPS/XMP/MakerNotes, ISO-BMFF, RIFF, RAF, PNG chunks, `MetadataReader`, `ExifWriter` | +| `Codecs` (`Codecs.Jpeg`, `Codecs.Png`, `Codecs.Tiff`, `Codecs.Dng`, `Codecs.Gif`, `Codecs.Ico`) | Pure managed image codecs | +| `Video` | `Mp4Muxer`, box writer, Annex-B/OBU parsing, MP4 inspector, AVI-MJPEG writer, managed encoder provider, encoder contracts | +| `Analysis` | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light/deep analysis | +| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabilisation, virtual camera, interpolation, stacking | +| `Math` | Splines (Fritsch–Carlson, Catmull-Rom, Bézier), robust local regression, statistics, solar position | +| `Render` | Render plan, pipeline, export presets | +| `Advisor` | Recommendation rules with localisable reasons, sequence presets | +| `Archive` | Archive layout, sidecars (`sequence.json`, `project.json`), scanner, rebuild, verify, duplicates, orphans, adopt | +| `Naming` | Folder/file templates and tokens | +| `Import` | Card/folder scan, session detection, import plan, hash-verified copy | +| `Model` | Domain entities (§5) shared by Data, Server and clients | +| `Localization`, `Diagnostics`, `IO`, `Hashing`, `Branding` | Infrastructure | + +## 3. Conventions + +- File-scoped namespaces, `sealed` by default, nullable on, warnings are errors. No `#pragma warning disable` + except narrowly around interop with a reason. +- No third-party packages, ever. If the BCL lacks it (CRC-32, Adler, JPEG, PNG decode…), write it. +- Parsers never throw on malformed input: they return partial results plus warnings. Every offset is + bounds-checked against the stream length; recursion and loops are capped. +- Never load a whole RAW to read metadata: windowed reads through `Stream` + `Seek`. +- Hot loops: `Span`, `System.Numerics.Vector`/`Vector256` where it measurably pays, no LINQ. + Parallelise per row/tile with `Parallel.For` only when work per item is large. +- Pixel math in linear light, `float`, Rec.709 primaries. Convert to sRGB/8-bit only at the edges. +- Every long operation takes a `CancellationToken` and reports progress through `IProgress`. +- Libraries use `ConfigureAwait(false)`. No `async void` except WPF event handlers. +- Logging through `Titano.Core.Diagnostics.Log` in Core; `ILogger` on the server. +- Public types and non-obvious members get a one-line `///` summary. Comments explain *why*, not *what*. +- Disk writes that must survive crashes use `AtomicFile` (temp → fsync → rename). +- IDs are UUIDv7 (`Guid.CreateVersion7()`); timestamps UTC; capture times are camera wall-clock with an + optional offset. + +## 4. Tests + +- Framework: `Titano.Testing`. Test classes are `public sealed`; constructor may take `TestContext` + (temp directories, cancellation, log). Use `[WindowsOnly]` for OS-specific tests and + `[RequiresEnvironment("TITANO_TEST_PG")]` for PostgreSQL integration tests. +- Put tests under `tests/Titano..Tests//Tests.cs`, mirroring the source folder. +- Fixtures are synthetic and generated in code wherever possible; tiny binary fixtures may go in + `tests/fixtures/` (< 50 KB each). Larger CC0 samples are fetched by `Titano.Tools fixtures` into + `tests/fixtures/external/` (git-ignored) and tests depending on them skip when absent. +- Fuzz tests: truncate and corrupt valid inputs at many offsets; assert no exception escapes. + +## 5. Localization + +- Keys: `Area.Group.Name`; area = file name. Areas: Common, Shell, Library, Editor, Import, Archive, + Jobs, Server, Settings, Tooltips, Errors, Advisor, Admin, Uploader, Setup. +- `en` is the source (`i18n/en/.resx`), `it` is mandatory (`i18n/it/.it.resx`). +- Labels ≤ 30 chars, tooltips/errors/advisor reasons ≤ 200 chars (one or two sentences). +- Plurals: `Key.one` / `Key.few` / `Key.many` / `Key.other`, resolved by `Loc.Plural("Key", n)`. + +## 6. Build and checks + +``` +dotnet build Titano.slnx -c Release +dotnet run --project tests/Titano.Core.Tests -c Release -- --junit out/core.xml +dotnet run --project src/Titano.Tools -- package-guard +dotnet run --project src/Titano.Tools -- i18n check +dotnet run --project src/Titano.Tools -- xaml-lint +``` diff --git a/docs/BRIEF.md b/docs/BRIEF.md new file mode 100644 index 00000000..6a5f2d75 --- /dev/null +++ b/docs/BRIEF.md @@ -0,0 +1,1346 @@ +# Titano — Build Brief for Claude Code + +> This document is the complete specification and standing instruction set for building the +> Titano time-lapse ecosystem from scratch. It is written to be read by Claude Code at the +> start of every session (via `CLAUDE.md`, see Appendix A) and to be the single source of +> truth for scope, architecture, constraints and delivery order. +> +> Working name: **Titano**. Three shipped programs — **Titano** (Windows desktop client), +> **Titano Server** (Linux/Docker and Windows), **Titano Uploader** (Windows) — sharing one +> engine. Target audience: photographers, astro/landscape shooters, construction and +> weather-cam operators, hobbyists worldwide. + +--- + +## 0. How to work on this project (operating rules for Claude Code) + +### 0.1 Kickoff message + +Paste this as the first message in Claude Code, from an empty repository that contains only +this file at `docs/BRIEF.md` and the prototype dump at `docs/reference/titano-prototype.md`: + +``` +Read docs/BRIEF.md completely before doing anything. It is the full specification for this +repository and it overrides your defaults. Then: +1. Create CLAUDE.md from Appendix A of the brief, and docs/DECISIONS.md, docs/CHANGELOG.md. +2. Execute Phase 0 exactly as described in §22, stopping at its phase gate. +At every phase gate, report: what was built, how to run it, test results on Windows and +Linux, open decisions. Do not ask questions before the gate unless a decision is +irreversible; otherwise decide, record it in docs/DECISIONS.md, and continue. +``` + +### 0.2 Standing rules + +1. **Zero third-party packages, everywhere.** No `` in any `.csproj`, + including tests, tools and build scripts. Anything that is not the .NET BCL, a Microsoft + shared framework that ships with the .NET SDK/runtime (`Microsoft.NETCore.App`, + `Microsoft.AspNetCore.App`, `Microsoft.WindowsDesktop.App`, the Windows SDK targeting + pack), or an operating-system API reached by P/Invoke or COM interop, is implemented + in-house. CI fails the build if a `PackageReference` appears (§19.2). The prototype in + `docs/reference/titano-prototype.md` proves this is workable: it decodes images with WIC, + encodes video with Media Foundation, parses EXIF/TIFF/XMP with its own parsers, and + writes its own MP4 container. +2. **No external processes.** No FFmpeg, no ExifTool, no ImageMagick, no PowerShell + scripts at runtime. The only OS executables/dialogs the product may invoke are listed in + §8.6 (format-volume dialog, shell "open with", browser launch for links). +3. **Cross-platform core, Windows-only presentation.** `Titano.Core`, `Titano.Data`, + `Titano.Protocol` and `Titano.Server` target `net10.0` and must build and pass tests on + Linux. Windows-only code lives in `*.Windows` projects or the desktop apps. +4. **English everywhere in the codebase**: identifiers, comments, commit messages, docs. + The prototype is written in Italian; port the algorithms, not the language. +5. **Every user-visible string is a resource.** No literal UI text in code or XAML. + English is the source language; Italian is the first translation; all other languages + follow in Phase 8 (§16). +6. **UI copy rules (mandatory):** labels ≤ 3 words when possible; no helper text or + paragraphs anywhere in the UI; explanations live only in tooltips (≤ 2 sentences); + every actionable control has a tooltip; empty states are one sentence plus one button; + errors are one sentence saying what happened plus one action. +7. **Decide, record, continue.** When the brief is silent, choose the option that is + simplest, safest for user data, and consistent with the constraints; write one line in + `docs/DECISIONS.md` (date, decision, alternative, reason). Ask the human only at phase + gates, or before any irreversible or data-destroying design choice. +8. **User data is sacred.** Never delete, move or format anything without (a) a verified + hash match of every copied file and (b) an explicit user action. Every destructive + operation is dry-run-able and shows its plan first. +9. **Definition of Done for every phase:** builds green on `windows-latest` and + `ubuntu-latest`; all tests green; no new warnings; `docs/DECISIONS.md` and + `docs/CHANGELOG.md` updated; a short "how to try it" note in the phase report; + localization completeness check passes for `en` and `it`. +10. **Commit style:** Conventional Commits (`feat(core): …`, `fix(server): …`), small + commits, one concern each. Never commit generated binaries, fixtures downloaded by + scripts, or secrets. +11. **Reference prototype:** `docs/reference/titano-prototype.md` is a Repomix dump of the + previous single-program prototype (C#/.NET 10, WinForms, zero packages). Its engine + (metadata parsing, deflicker, holy-grail transitions, optical flow, motion blur, + stabilization, virtual camera, time remap, stacking, Media Foundation encoding, MP4 + muxing, self-tests) was validated on real material. Port those algorithms faithfully + into the new structure, with English names and unit tests; do not copy its UI + (WinForms) or its file layout. Search it with grep; do not try to read it whole. + +--- + +## 1. Product vision + +Titano turns folders of photos (RAW, JPEG, HEIC…) into finished time-lapse videos and keeps +a lifetime archive of shoots organised, verified and searchable — on one PC or on a shared +server. + +- **Import** memory cards with per-card rules, session detection, renaming and hash + verification; import directly into a local archive or straight to a server. +- **Analyse** every sequence deeply (metadata + pixels) and let the advisor set frame + timing, motion blur, deflicker, transitions and export presets — with a reason for every + choice, visible in a tooltip. +- **Render** with the in-house engine and GPU encoders (H.264/HEVC/AV1 via Media + Foundation) to purpose-built presets, from 720p previews to 8K 10-bit archives. +- **Archive** hundreds of thousands of photos across years and cameras, on local or network + drives, with an index that can always be rebuilt from the files themselves. +- **Share** through Titano Server: central archive, users with logins, uploads from the + tiny Uploader, sync of projects, server-side jobs, render delegation to GPU-equipped + clients, and a web admin panel — deployable as a Docker container (Unraid template + included) or on Windows. + +### 1.1 Goals (measurable) + +- A first-time user imports a card, gets a recommended preset, and renders a 1080p preview + in under five interactions from launch. +- A library of 500,000 photos in 2,000 sequences: Library screen opens in < 1 s, scrolls at + 60 fps, filters respond in < 200 ms, full index rebuild from sidecars in < 10 min. +- Rendering quality equals or exceeds the prototype's measured results (§20.4 regression + thresholds), with hardware encoding used whenever a hardware MFT exists. +- Every feature reachable without reading any documentation; every control explained by + its tooltip; UI available in ≥ 30 languages with RTL support. +- Server: 10 concurrent clients uploading at line speed; resumable uploads; zero data loss + on crash (append-only ingest + manifest commit). + +### 1.2 Non-goals (v1) + +- Audio tracks (P2: mux an external AAC file), HDR/PQ output, colour-managed display. +- macOS/Linux desktop clients (server only), mobile apps, browser-based editing. +- Cloud object storage backends (S3 etc.), multi-server federation. +- General RAW *development* beyond what the render pipeline needs (no Lightroom clone). +- GPU compute for image processing (CPU SIMD only in v1; keep interfaces open). +- Real-time tethered capture, camera control. +- Plugin system. + +--- + +## 2. Hard constraints and allowed native surface + +### 2.1 Language and platform decision + +**C# on .NET 10 LTS** for every component. Reasons: one toolchain for a cross-platform +server and a first-class Windows desktop; WPF and ASP.NET Core ship with the SDK (no +packages); mature BCL for crypto, HTTP/2, WebSockets, JSON, compression and SIMD +(`System.Numerics.Vector`, `Vector256`); direct P/Invoke/COM interop to WIC, Media +Foundation and `winsqlite3.dll`; the validated engine is already C#. Alternatives were +rejected: Python (stdlib GUI is dated, no GPU encode, no PostgreSQL driver), C++ (UI and +server cost), Rust/Go (no standard GUI, no SQLite/PostgreSQL in std), Java (JavaFX is +external). + +Desktop UI: **WPF** with the built-in Fluent theme (`Application.ThemeMode`, available in +WPF since .NET 9, refined in .NET 10) for a Windows 11 look with dark/light/system modes and +system accent colour, plus in-house custom `FrameworkElement`s for charts, filmstrip, +curve editors and the virtualized photo grid. If the Fluent theme proves inadequate for any +control, restyle it with an in-house `ResourceDictionary` — never a package. Window chrome: +`WindowChrome` + `DwmSetWindowAttribute` (dark title bar, Mica/backdrop where available). + +### 2.2 Allowed native/OS surface (Windows) + +| Need | API (all OS components, no packages) | +|---|---| +| Image decoding incl. RAW/HEIC/WebP/AVIF when codecs installed | WIC (`IWICImagingFactory`… via COM interop) | +| Video encoding, hardware MFTs (NVENC/QSV/AMF) | Media Foundation (`MFStartup`, `MFTEnumEx`, `IMFTransform`, `ICodecAPI`) | +| Local database | `winsqlite3.dll` (ships with Windows 10 1709+ / Windows 11) via P/Invoke | +| Volume identity, device arrival | `GetVolumeInformationW`, `GetDriveTypeW`, `WM_DEVICECHANGE`, `SetupAPI` if needed | +| Format a card | `SHFormatDrive` (OS format dialog) | +| GPU name/VRAM for encoder capability display | DXGI (`CreateDXGIFactory1`, `IDXGIAdapter::GetDesc`) | +| Taskbar progress, toasts | `ITaskbarList3`; toasts via Windows SDK projection (`net10.0-windows10.0.19041.0` targeting pack) or in-house tray balloon | +| MTP cameras (P2) | Windows Portable Devices (COM) | +| Window chrome | `dwmapi.dll` | + +Linux (server): BCL only. No `libsqlite3`, no `libva`, no FFmpeg. PostgreSQL is reached +through the in-house wire-protocol client (§6.3). + +### 2.3 What this implies (and how the brief resolves it) + +- **RAW decoding** without libraw is tiered (§8.2): full in-house decode for DNG/TIFF/ + JPEG/PNG and a growing set of native RAW formats; embedded full-size JPEG previews as a + universal fallback (every major RAW format embeds one); on Windows, WIC with the free + Microsoft "Raw Image Extension" gives full decode of everything else. +- **Video encoding** on Linux has no OS encoder API; the server produces pure-managed + outputs (MJPEG-AVI, image sequences, GIF, APNG) itself and delegates MP4/H.264/HEVC/AV1 + jobs to **render nodes** — Titano clients that volunteer their GPU (§14.7). An in-house + intra-only H.264 encoder is a P2 universal fallback (§11.6). +- **Testing** uses an in-house runner (`Titano.Testing`, §20.1), not xUnit/NUnit. +- **HEIC/HEIF** cannot be decoded in-house (HEVC intra decoder is out of scope): Windows + clients decode via WIC (HEIF + HEVC extensions); the server stores originals and relies on + proxies produced by a Windows client or render node. + +--- + +## 3. Repository layout + +``` +titano/ (private GitHub repo) +├── CLAUDE.md operating rules (Appendix A) +├── Directory.Build.props version, LangVersion, nullable, warnings-as-errors, analyzers +├── Directory.Build.targets zero-package guard, resource generation hooks +├── Titano.slnx +├── global.json pins .NET 10 SDK +├── src/ +│ ├── Titano.Core/ net10.0 — engine: Metadata, Imaging, Codecs, Analysis, Motion, Video (container/muxers), Archive model, Naming, Localization runtime +│ ├── Titano.Core.Windows/ net10.0-windows — WIC decoder, Media Foundation encoder, DXGI, device APIs, winsqlite3 binding +│ ├── Titano.Data/ net10.0 — IDatabase abstraction, SQL dialects, migrations, repositories, Postgres wire client (Titano.Data.Postgres), SQLite driver surface (implemented by Core.Windows binding) +│ ├── Titano.Protocol/ net10.0 — API DTOs, JSON contexts (source-generated), chunked upload protocol, sync manifests, WebSocket event schema, version negotiation +│ ├── Titano.Server/ net10.0 — ASP.NET Core minimal API, auth, job engine, storage service, admin web UI (embedded static files), Docker entrypoint +│ ├── Titano.App/ net10.0-windows — WPF desktop client +│ ├── Titano.Uploader/ net10.0-windows — WPF uploader (tray-capable) +│ ├── Titano.Setup/ net10.0-windows — in-house installer/uninstaller (self-extracting, Add/Remove Programs, shortcuts, file associations) +│ └── Titano.Tools/ net10.0 — CLI: selftest, diagnose, make-icon, i18n export/check, fixtures fetch, changelog +├── tests/ +│ ├── Titano.Testing/ in-house test framework + runner (attributes, asserts, fixtures, JUnit XML) +│ ├── Titano.Core.Tests/ +│ ├── Titano.Data.Tests/ includes PostgreSQL integration tests (skipped without TITANO_TEST_PG) +│ ├── Titano.Server.Tests/ in-process Kestrel on a random port +│ ├── Titano.App.Tests/ view-model tests + XAML lint (tooltip/resource rules) + screenshot smoke (`--capture`) +│ └── fixtures/ tiny checked-in samples; larger CC0 RAW samples fetched by `Titano.Tools fixtures` +├── branding/ icon sources (SVG), generated ICO/PNG sets +├── i18n/ .resx sources (en) + translations, glossary, machine-translation notes +├── deploy/ +│ ├── docker/Dockerfile, docker-compose.yml, entrypoint +│ └── unraid/titano.xml +├── .github/workflows/ ci.yml, release.yml, docker.yml +└── docs/ BRIEF.md (this), DECISIONS.md, CHANGELOG.md, ARCHITECTURE.md (generated per phase), reference/titano-prototype.md +``` + +Project references: `App` → `Core`, `Core.Windows`, `Data`, `Protocol`. `Server` → `Core`, +`Data`, `Protocol`. `Uploader` → `Core` (hashing, metadata light), `Protocol`. `Core` and +`Data` never reference anything Windows-specific; CI builds them on Linux. + +--- + +## 4. Architecture + +### 4.1 Component diagram + +``` + ┌────────────────────────────────────────────────────────────────┐ + │ Titano (WPF client) │ + │ Library · Sequence editor · Import · Archive manager · Jobs │ + │ Local mode: SQLite + local/network archive │ + │ Server mode: REST/WS client, proxies cache, render node │ + └───────┬───────────────────────────────────────┬────────────────┘ + │ HTTPS REST + WebSocket │ Memory cards (USB/SD) + ▼ ▼ +┌───────────────────────────────────┐ ┌──────────────────────────┐ +│ Titano Server │ │ Titano Uploader (WPF) │ +│ Kestrel · API v1 · Auth · Jobs │◄───────────│ queue · watch folders │ +│ Storage service · Admin web panel │ HTTPS │ resumable chunk upload │ +│ Pure-managed encoders │ └──────────────────────────┘ +└──────┬──────────────────┬─────────┘ + │ │ + ▼ ▼ + PostgreSQL (Docker) Archive volume (/archive: originals, sidecars, proxies, renders) + or SQLite (Windows) +``` + +### 4.2 Shared engine + +`Titano.Core` is the same assembly on client and server: metadata parsing, image codecs, +analysis advisor, render pipeline, container writers. Only the *decoder/encoder providers* +differ per platform, behind two interfaces: + +```csharp +public interface IImageDecoderProvider { bool CanDecode(ImageFormatInfo f); DecodedImage Decode(DecodeRequest r); } +public interface IVideoEncoderProvider { IReadOnlyList Capabilities { get; } IVideoEncoderSession Open(EncodeSettings s); } +``` + +Registered providers, in priority order: client → `WicDecoderProvider`, then +`ManagedDecoderProvider`; server → `ManagedDecoderProvider` only. Encoders: client → +`MediaFoundationEncoderProvider` (hardware first, software H.264 fallback), then +`ManagedEncoderProvider` (MJPEG/AVI, sequences, GIF, APNG); server → managed only, plus +delegation to render nodes. + +### 4.3 Data flow: card → archive → render + +``` +Card ──scan(light metadata)──► Import plan (sessions, names) ──copy+hash──► originals/ + ──light analysis──► sequence.json sidecar + DB rows ──queue──► deep analysis job + ──► proxies + thumbs ──► advisor recommendations + suggested presets +User opens sequence ──► settings (project JSON) ──render──► exports/ + DB render row +``` + +Frames are streamed to the server by the client or uploader through chunked, resumable, +hash-verified uploads; the server commits the frame into the archive layout and updates the +sequence manifest atomically (write temp → fsync → rename). + +### 4.4 Modes of the client + +| Mode | Storage | Index | Who renders | +|---|---|---|---| +| Local | local or network drive archive | SQLite | this PC | +| Server-connected | server archive; local proxies/thumbs cache | server DB via API; local SQLite caches only | server (managed formats), render nodes (MP4), or this PC after downloading originals | +| Mixed | both; each sequence has an `origin` and a `sync state` | both | as above | + +--- + +## 5. Domain model + +Primary entities (identical concepts in SQLite and PostgreSQL; ids are UUIDv7 stored as +`TEXT`/`uuid`; timestamps UTC ISO-8601/`timestamptz`): + +- **Archive** — id, name, root path, layout templates, schema version, created, proxy policy. +- **Sequence** — id, archive id, title, folder (relative), camera make/model/serial, lens, + first/last capture, frame count, median interval, total bytes, status flags + (`analyzed_light`, `analyzed_deep`, `proxies_built`, `thumbs_built`, `rendered_count`, + `verified_at`), hero frame id, tags, rating, notes (short), settings JSON (project), + analysis report JSON (compact) + path to full report, origin (local/server), sync state, + version counters (`settings_version`, `frames_version`), owner user id (server). +- **Frame** — id, sequence id, index, relative path, file name, size, sha256, captured at + (with sub-second and source: EXIF/XMP/filesystem), exposure time, f-number, ISO, focal + length, exposure bias, white balance, orientation, width, height, format, embedded + preview info (offset/length), light stats (mean log-luminance, clip fractions) once + analysed, flags (missing, corrupt, duplicate, excluded). +- **Render** — id, sequence id, preset name, settings JSON, output relative path, codec, + width, height, fps, duration, bytes, created, produced by (client id / server / node). +- **Job** — id, kind (scan, rebuild, verify, light-analyse, deep-analyse, proxies, + thumbs, render, import, upload-commit, maintenance), target ids, state (queued, running, + paused, done, failed, cancelled), progress (done/total, fps, eta), log tail, created by, + node id, attempts, error. +- **MediaCard** (client) — id, volume serial, filesystem label, capacity, nickname, camera + identity (Make/Model/BodySerial from first file), profile JSON, first/last seen, import + history (job ids). +- **User** (server) — id, username, display name, password hash (PBKDF2), role (admin, + editor, uploader, viewer), permissions bitmask, quota bytes, used bytes, disabled, + must-change-password, created, last login. +- **Session/Token** (server) — token hash, user id, client name, created, expires, last + used, revoked. +- **RenderNode** (server) — id, user id, client name, capabilities JSON (codecs, hardware + encoder names, max resolution), last heartbeat, state. +- **Setting** — key/value (typed JSON), scope (app, archive, user). +- **Tag**, **SequenceTag** — normalised for filtering. +- **AuditLog** (server) — who did what to which sequence/user, when. + +Indexes: `frame(sequence_id, index)`, `frame(sha256)`, `frame(captured_at)`, +`sequence(archive_id, first_capture)`, `sequence(camera_model)`, tags, jobs by state. +Paging everywhere (keyset pagination on `(first_capture, id)`). + +--- + +## 6. Data layer + +### 6.1 `Titano.Data` abstraction + +```csharp +public interface IDatabase : IAsyncDisposable { + Dialect Dialect { get; } // Sqlite | Postgres + Task OpenAsync(CancellationToken ct); // connection from pool +} +public interface IDbSession : IAsyncDisposable { + Task ExecuteAsync(string sql, params DbParam[] p); + IAsyncEnumerable QueryAsync(string sql, params DbParam[] p); + Task BeginAsync(); + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows); // COPY on PG, multi-row INSERT on SQLite +} +``` + +Hand-written SQL in repositories (`SequenceRepository`, `FrameRepository`, …); no ORM. +Migrations: numbered `.sql` files per dialect in `Titano.Data/Migrations/{sqlite,postgres}/`, +applied at startup inside a transaction, recorded in `schema_migrations`. Dialect +differences (types, `RETURNING`, upserts) are confined to SQL files and a small `SqlDialect` +helper. + +### 6.2 SQLite (client, and Windows standalone server) + +- Binding: `Titano.Core.Windows/Sqlite/WinSqlite3.cs` P/Invoke to `winsqlite3.dll` + (`sqlite3_open_v2`, `prepare_v2`, `step`, `reset`, `finalize`, `bind_*`, `column_*`, + `exec`, `errmsg`, `last_insert_rowid`, `changes`, `busy_timeout`, `libversion`, + `extended_result_codes`). UTF-8 marshalling by hand. Check `sqlite3_libversion() ≥ 3.31` + at startup; probe `PRAGMA compile_options` and never depend on FTS/JSON extensions. +- Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, + `temp_store=MEMORY`, `cache_size=-65536`, `mmap_size=268435456`. +- Location: `%LOCALAPPDATA%\Titano\titano.db` (never Documents/OneDrive-synced folders — + SQLite in a synced folder corrupts). Portable mode: `portable.txt` next to the exe puts + everything under `.\data\`. +- Backups: `VACUUM INTO` nightly copy kept ×3; restore from Settings › Advanced. + +### 6.3 PostgreSQL client (`Titano.Data.Postgres`) — in-house wire protocol v3 + +- TCP + optional TLS via `SslStream` after `SSLRequest`; `sslmode` = disable | prefer | + require | verify-full. +- Startup (`user`, `database`, `application_name=titano-server`, `client_encoding=UTF8`, + `TimeZone=UTC`); authentication: SCRAM-SHA-256 (`Rfc2898DeriveBytes.Pbkdf2`, HMAC-SHA256, + channel binding not required), MD5, cleartext, trust. +- Simple query, extended query (Parse/Bind/Describe/Execute/Sync) with parameters in text + format except `bytea` (binary), prepared-statement cache per connection, transactions, + `COPY … FROM STDIN` for bulk inserts, `LISTEN/NOTIFY` (used for multi-instance job + wake-ups, optional), cancellation via `CancelRequest`. +- Type mapping: `text, varchar, int4, int8, float8, bool, bytea, timestamptz, uuid, jsonb, + numeric(as string)`; arrays not needed. +- Connection pool (min/max, health check `SELECT 1`, idle eviction), typed + `PostgresException` carrying SQLSTATE, retry on transient errors (57P01, 08xxx). +- Test suite runs against PostgreSQL 16 and 17 service containers in CI (§19). + +--- + +## 7. Archive format on disk + +The archive is the source of truth; the database is an index that can be rebuilt from it. + +``` +/ +├── .titano/ +│ ├── archive.json { id, name, schemaVersion, created, layoutTemplates, proxyPolicy } +│ ├── index-snapshot.bin optional accelerator for rebuild (all sidecars concatenated + hash); ignored if stale +│ └── locks/ lease files for concurrent writers (server + client on same share) +├── 2026/ +│ └── 2026-09-28 Canon EOS R5 - Harbour sunset/ folder = expanded FolderTemplate +│ ├── originals/ IMG_0001.CR2 … names = expanded FileTemplate +│ ├── proxies/ 0001.jpg … (JPEG, long edge per policy; optional, regenerable) +│ ├── exports/ 2026-09-28 Harbour sunset - 4K HEVC.mp4 … +│ └── .titano/ +│ ├── sequence.json sidecar manifest (below) +│ ├── analysis.json full deep-analysis report +│ ├── project.json render settings (the "project") +│ └── thumbs.pack packed thumbnails (one file per sequence, indexed; avoids 100k tiny files on SMB) +``` + +`sequence.json` (canonical, versioned, written atomically): +`{ id, title, camera, lens, frames: [{ i, file, size, sha256, capturedAt, exposure, fNumber, +iso, focal, bias, wb, orientation, w, h, format, previewOffset, previewLength, flags }], +tags, rating, notes, status, versions, createdBy, updatedAt }`. + +Rules: originals are immutable (never rewritten; edits are settings); every write of a +sidecar goes to a temp file, `fsync`, rename; the folder name is derived from templates at +import time and never auto-renamed afterwards (renaming is a user mass-operation that +updates sidecars and DB together). Network drives: UNC or mapped paths; long-path aware +(`\\?\` prefix); no `FileSystemWatcher` reliance — periodic polling by mtime/size plus manual +rescan; offline detection with graceful read-only state. + +### 7.1 Naming templates + +`FolderTemplate` default `{year}/{date} {camera}`; `FileTemplate` default +`{date}_{time}_{n:0000}`. Tokens (localised descriptions in resources): `year, month, day, +date, time, hm, session, sessionstart, camera, lens, iso, shutter, aperture, n, nsession, +name, ext, title`. `{token:format}` passes the format to the .NET formatter. Illegal +characters are replaced, never passed through; templates are validated live in the UI with a +preview of the first three names. + +--- + +## 8. Image pipeline + +### 8.1 Supported input formats + +| Family | Extensions | Metadata (in-house) | Pixels on Windows | Pixels on server (Linux) | +|---|---|---|---|---| +| JPEG | jpg jpeg jpe jfif | APP1 Exif/XMP, MPF | WIC or managed | managed (baseline + progressive) | +| PNG | png | eXIf, iTXt XMP | WIC or managed | managed | +| TIFF | tif tiff | IFDs | WIC or managed | managed (strips/tiles; none/PackBits/LZW/Deflate/JPEG) | +| DNG (smartphones: Apple ProRAW, Android, Samsung; DJI; Insta360; Leica; Pentax; Ricoh) | dng | IFDs, MakerNote | WIC (if Raw ext.) or managed full decode | managed full decode | +| Canon | cr2 cr3 | cr2: TIFF; cr3: ISO-BMFF `CMT1..4` | WIC (Raw ext.) → managed CR2 (P1) → embedded preview | managed CR2 (P1) → embedded full-size JPEG (CR3 track 1) | +| Nikon | nef nrw | TIFF | WIC → managed NEF (P1) → preview | managed NEF (P1) → preview | +| Sony | arw srf sr2 | TIFF | WIC → managed ARW (P1) → preview | idem | +| Fujifilm | raf | RAF header + TIFF | WIC → managed RAF uncompressed (P1) → preview | idem | +| Olympus/OM, Panasonic, Pentax, Samsung, Hasselblad, Phase One, Leica | orf rw2 raw pef srw 3fr fff iiq rwl | TIFF-like | WIC → managed (P1/P2) → preview | preview (P1: managed decoders as feasible) | +| GoPro | gpr (DNG+VC-5) + jpg sidecar | IFDs | preview/sidecar JPEG; VC-5 out of scope | sidecar JPEG | +| HEIF/HEIC/AVIF (iPhone, Samsung, DJI) | heic heif hif avif | ISO-BMFF `Exif` item | WIC (HEIF + HEVC/AV1 extensions) | metadata only; pixels via client-made proxies | +| WebP | webp | RIFF `EXIF` chunk | WIC (WebP ext.) | metadata only (P2: managed VP8L) | +| JPEG XL, JPEG XR, BMP, GIF (single frame) | jxl jxr bmp gif | minimal | WIC if a codec exists | not supported | + +Windows codec availability is enumerated at startup (`IWICImagingFactory:: +CreateComponentEnumerator`). Missing codecs are surfaced as a one-line notice with an +"Install" button opening the Microsoft Store page (Raw Image Extension, HEIF Image +Extension, HEVC Video Extensions, AV1 Video Extension, WebP Image Extension; verify product +IDs at implementation time). The format table in Settings › Formats shows, per format, +which tier will be used on this machine. + +### 8.2 Decode tiers (deterministic, logged per frame) + +1. **Native full decode** (in-house or WIC) at working resolution, 16-bit linear light. +2. **Embedded preview** (largest JPEG found: TIFF `JPEGInterchangeFormat`/SubIFD strips, + RAF preview, CR3 full-size JPEG track, MPF). Marked `PreviewOnly` on the frame; the + sequence shows a chip with the count and the advisor caps output resolution to the + preview size unless the user overrides. +3. **Unavailable** → frame flagged `Undecodable`; excluded from render; listed in the + sequence warnings. + +The in-house DNG pipeline (server and client): CFA/linear DNG, `Compression` 1/7 (lossless +JPEG SOF3)/8 (Deflate)/34892 (lossy JPEG), `LinearizationTable`, `BlackLevel` (+ repeat +dims, delta), `WhiteLevel`, `AsShotNeutral`/`AsShotWhiteXY`, `ColorMatrix1/2` + +`CameraCalibration`, `AnalogBalance`, Bradford adaptation to D65, demosaic **AHD** (default, +"perfect result" priority) with bilinear for Draft quality, highlight reconstruction (clip ++ desaturate), `ActiveArea`/`DefaultCrop*`, `Opcode` lists 1–3 (at least `GainMap`, +`WarpRectilinear`, `FixVignetteRadial`; unknown opcodes ignored with a warning), +`BaselineExposure`. Output: linear Rec.709/sRGB primaries float planes. + +### 8.3 Managed codecs (all in `Titano.Core/Codecs`, pure C#, SIMD where it pays) + +- `JpegDecoder` (baseline, progressive, restart intervals, 4:4:4/4:2:2/4:2:0/4:1:1/gray, + 12-bit optional, ICC ignored), `JpegEncoder` (baseline, quality 1–100, subsampling + choice, optimised Huffman tables optional, Exif/XMP APP1 embedding). +- `PngDecoder`/`PngEncoder` (all colour types, 8/16-bit, Adam7 decode, filters, zlib via + `System.IO.Compression.ZLibStream`). +- `TiffReader`/`TiffWriter` (as prototype: 16-bit TIFF, linear DNG writer with + `PhotometricInterpretation=34892`). +- `GifEncoder` (animated; median-cut palette + Floyd–Steinberg; frame differencing). +- `ApngEncoder`. +- `AviMjpegWriter` (RIFF AVI with `MJPG`, OpenDML index for > 2 GB). +- `Mp4Muxer` (port of prototype: streaming `ftyp`/`mdat`/`moov`, 90 kHz timescale, + variable durations, `avcC`/`hvcC`; add `av1C` + OBU handling in P1), `AnnexBParser`. +- `Bmff` reader (HEIF/CR3/AVIF boxes), `Riff` reader (WebP/AVI), `Raf` reader. + +### 8.4 Image buffers + +Port the prototype's `ImageBuffer`/`FrameBufferPool` (pooled float planes, linear light), +`FrameWindow` (sliding window, disk spill under a memory budget, read-ahead), and +`GeometryStage` (crop/aspect/affine with Catmull-Rom). Memory is governed by the window +size and budget, never by sequence length; the self-tests assert this. + +### 8.5 Thumbnails and proxies + +- Thumbnail: 320 px long edge JPEG q80, packed per sequence in `thumbs.pack` (header, + index table, entries), with an LRU in-memory cache and async loading for the UI. +- Proxy: JPEG at policy long edge (default 1920; options 1280/1920/2560/full), q92, Exif + orientation applied, capture time copied into Exif. Proxies are optional and regenerable; + they enable remote editing, server-side rendering of formats the server cannot decode, + and fast scrubbing. + +### 8.6 The only OS executables/dialogs the product may invoke + +`SHFormatDrive` (format card), `ShellExecute("open", url)` (links, Store pages), +`ShellExecute("explore", folder)` (reveal in Explorer). Nothing else. + +--- + +## 9. Metadata model and parsers (`Titano.Core/Metadata`) + +Port and extend the prototype's binary parsers: container detection by signature; JPEG +segment scan (APP1 Exif, APP1 XMP + extended XMP, APP2 MPF); TIFF/IFD walker with on-demand +window reads (never load a whole RAW to read tags), SubIFD selection of the main image, +`0x02BC` XMP; ISO-BMFF walker (`meta/iinf/iloc` Exif item, CR3 `CMT` boxes, `PRVW`/`THMB`, +track sample tables for the CR3 JPEG); RIFF; RAF; PNG chunks. MakerNote parsing only where +it adds value: Canon/Nikon/Sony/Fuji/Olympus/Panasonic body serial, shutter count, lens +name, exposure mode, image stabilisation flag, intervalometer hints, sRaw flags. + +Fields extracted per frame: DateTimeOriginal + SubSecTimeOriginal + OffsetTimeOriginal +(fallback: CreateDate, GPS time, file mtime — recorded with `TimestampSource`), ExposureTime, +FNumber, ISO, FocalLength (+35 mm equiv), ExposureBias, ExposureProgram, MeteringMode, +WhiteBalance mode + Kelvin if present, Flash, Orientation, dimensions, Make/Model/BodySerial, +Lens, GPS (lat/lon/alt), Artist/Copyright, Rating/Label from XMP, `Software`. All parsers +are fuzz-safe (no exception escapes; malformed input yields partial metadata + a warning). + +`ExifWriter` (prototype) is kept for proxies/exports: writes a minimal, valid Exif block. + +--- + +## 10. Analysis advisor + +Two passes; both deterministic, both explainable (every finding and every recommendation +carries a resource key + parameters that render as a localised reason in tooltips). + +### 10.1 Light analysis (at import/scan, metadata only, seconds per 10k frames) + +Cadence (median interval, jitter, gaps → session boundaries; `SessionGapMinutes` default +45, `MinimumSessionFrames` 8), total capture span, exposure series (EV = +log2(N²/t) − log2(ISO/100)), exposure step detection (ISO/shutter/aperture changes and +their EV amplitude), camera/lens identity, orientation consistency, resolution +consistency, timestamp sanity (clock resets, duplicates, non-monotonic), format tiers, +GPS → sunrise/sunset/civil twilight via an in-house solar-position calculation (NOAA +algorithm) → day/night/transition labelling. + +### 10.2 Deep analysis (background job after import; "speed is not an issue") + +Every frame decoded at analysis width (default half native, capped 2048): per-frame +trimmed log-luminance mean, histogram, clip fractions, per-channel means (WB drift), colour +temperature where applicable (McCamy with Planckian-locus validity check), sharpness +(Laplacian variance), noise estimate, phase-correlation shift vs previous frame (shake +magnitude, drift → panning), region mask (horizon by strongest row-luminance step, refined +per column; fallback by luminance), flicker spectrum (autocorrelation of luminance +residuals → deflicker window), exposure steps *as actually received* by the pixels, +star-field detection (small bright point density on night frames), cloud coverage estimate +(sky-region texture), scene-change detection (histogram distance), duplicate/black/white +frames, motion magnitude histogram (for motion-blur recommendation), suggested hero frame. +Results → `analysis.json` + compact summary in DB; charts in the Sequence editor. + +### 10.3 Recommendations (rules, each with reason and confidence) + +- Frame timing mode: Constant when jitter < tolerance; Adaptive when the intervalometer + paused deliberately; Interpolated when gaps are sparse and motion is smooth. +- Frame rate and time compression: choose 24/25/30/60 fps and duration targets from cadence + and motion magnitude; offer "fit to N seconds". +- Motion blur target shutter angle: from measured shutter angle (360×exposure/interval) and + motion magnitude; skip flow when exposure already exceeds the target. +- Deflicker window (4× flicker period), region deflicker when horizon confidence is high, + holy-grail transition length (half the typical distance between exposure steps), WB + smoothing, stabilization on/off (measured shake > 0.3 px) with crop cost, crop/aspect + suggestions from subject placement, output resolution cap from source/preview size and + codec level limits, quality profile. +- Auto-generated **sequence presets** ("Night sky — 4K 10-bit HEVC 24 fps, deflicker 41, + stabilise", "Holy grail sunset — 4K HEVC 30 fps, transitions 18", "Construction cam — + 1080p H.264 30 fps, adaptive timing", "Social vertical 1080×1920") = full project settings + + export preset; one click to apply; saveable as user presets. + +### 10.4 Auto vs manual + +Every deducible parameter shows an **Auto** indicator with the chosen value and a reason +tooltip; touching the control takes it manual; a small reset returns it to Auto. Per section +**Optimise** applies heavier decisions (module on/off) and reports what changed and why. Where +data is missing, the advisor says so and changes nothing. + +--- + +## 11. Rendering engine and export + +### 11.1 Render plan (port) + +The engine walks a list of output frames, each with a (possibly fractional) source position +and a duration; constant, adaptive, interpolated and remapped timings all produce this one +shape. Fractional positions synthesise frames from the motion field; motion blur scales +with `√(target² − real²)` shutter angle composition (prototype rule). + +### 11.2 Modules (port, keep the validated behaviour and its tests) + +Colour science (linear light, sRGB transfer), orientation detection (declared vs decoded +size), deflicker (weighted local linear regression with Tukey robustness blended by +surviving-window fraction), region deflicker (horizon/luminance masks), holy-grail exposure +step redistribution (only steps the pixels actually received), WB smoothing (channel +ratios), optical flow (pyramidal differential, median filtered), motion blur (gather +filter), stabilization (phase correlation, nine patches, similarity fit, texture gating, +smoothed path), virtual camera (Bézier eased pan/zoom keyframes, composed with +stabilization into one affine), non-linear time remap (Fritsch–Carlson monotone spline), +temporal stacking (median, progressive max with decay), geometry stage, codec level limits, +disk spill, cancellation semantics. + +### 11.3 Encoders and containers + +| Output | Client (Windows) | Server (Linux/Windows) | +|---|---|---| +| MP4 H.264 (Baseline/Main/High, 8-bit) | Media Foundation: hardware MFT (NVENC/QSV/AMF) else Microsoft software encoder | render node; P2 in-house intra-only encoder | +| MP4 HEVC Main / Main10 (10-bit, P010) | hardware MFT only | render node | +| MP4 AV1 | hardware MFT only (Windows 11 + AV1 encoder) | render node | +| AVI MJPEG | managed | managed | +| Image sequence JPEG / PNG / TIFF-16 / linear DNG | managed | managed | +| Animated GIF, APNG | managed | managed | + +Encoder session design as prototype: encoder MFT driven directly (not SinkWriter), NV12/P010 +conversion in-house, Annex-B → MP4 samples, streaming muxer; rate control (VBR/CBR/quality), +GOP, B-frames, profile/level via `ICodecAPI`. Capability discovery (`MFTEnumEx` hardware +flag, friendly names, DXGI adapter) is shown in Settings › Rendering and used to hide +unavailable codecs. + +### 11.4 Presets + +Presets bind resolution, aspect, codec, profile, bit depth, fps, bitrate (≈0.10 bpp/frame +H.264, 0.07 HEVC, 0.05 AV1; night-sky content is the most demanding), GOP and container. +Editing any value flips the name to "Custom"; matching values restore the preset name. + +Built-in presets: 8K UHD 10-bit HEVC archive · 4K UHD 10-bit HEVC archive · 4K UHD HEVC · +4K UHD H.264 compatible · DCI 4K HEVC 24 fps · Cinema 21:9 4K HEVC 24 fps · 4K 60 fps · +1440p H.264 · 1080p H.264 share · 1080p 60 · 1080×1920 vertical social · 1080×1350 4:5 · +1440×1440 square · 720p quick preview (GOP 1 s) · AV1 4K · MJPEG AVI intermediate · PNG +sequence · JPEG sequence · TIFF-16 sequence · GIF preview (480 px) · APNG. Resolutions: +720p/1080p/1440p/4K UHD/DCI 4K/5K/6K/8K/custom; aspects 16:9, 21:9, 4:3, 3:2, 1:1, 9:16, +4:5, source, custom; fps 23.976/24/25/29.97/30/48/50/59.94/60/120. + +### 11.5 Export UI behaviour + +Preview stays visible during encoding (optional live preview); single global progress bar +(frames, fps, elapsed, ETA) mirrored to the taskbar; cancel is always available and leaves +no partial files behind; output name from `{title} - {preset}` template; "Reveal in +Explorer" and "Render another preset" follow-ups; batch render of several presets in one +job; per-sequence render history. + +### 11.6 P2: in-house H.264 intra-only encoder + +Baseline profile, I-frames only, I_16x16/I_4x4 prediction, 4×4 integer transform, CAVLC, +fixed QP or simple rate control. Large files but universally playable; enables MP4 output +on a server without render nodes. Validate with the in-house MP4 inspector and a system +player smoke test on Windows CI. + +--- + +## 12. Titano desktop client — UI specification + +### 12.1 Shell + +``` +┌────┬─────────────────────────────────────────────────────────────────────────────┐ +│ ≡ │ ▮▮▮▮▮▮▮▮▮▮▮▮▮░░░░░░░ Building proxies · Harbour sunset · 1,240/3,600 · 12 fps · 3 min │ ⏹ │ ← global job bar, only while a job runs +│ ├─────────────────────────────────────────────────────────────────────────────┤ +│ ▤ │ │ +│Lib │ │ +│ ⬇ │ section content (edge to edge) │ +│Imp │ │ +│ ✎ │ commands of the section live INSIDE the section, in one row above the │ +│Seq │ content they act on; every command has a tooltip │ +│ ▣ │ │ +│Arch│ │ +│ ⚙ │ │ +│Jobs│ │ +│ ☁ │ │ +│Srv │ │ +│ │ │ +│ ⚙ │ │ +│Set │ │ +│ ⓘ ├─────────────────────────────────────────────────────────────────────────────┤ +│ │ 412 sequences · 618,204 photos · 9.4 TB · ☁ Connected to "Studio NAS" · 3 jobs │ ← status strip +└────┴─────────────────────────────────────────────────────────────────────────────┘ +``` + +- Left navigation rail (prototype pattern): full names, collapsible to icons (state saved), + badge counts (warnings, running jobs), hover tooltip with section description. +- Fluent theme, system/dark/light, system accent; density "comfortable"; 8 px grid; one + typeface (Segoe UI Variable, system fallback for CJK/Arabic/etc.). +- Window chrome custom (dark title bar), min size 1200×760; per-monitor DPI. +- Keyboard: standard shortcuts, listed in tooltips ("Render · Ctrl+R"). +- Notifications: unobtrusive toasts inside the window (bottom-right) for job completion, + card detected, server events; optional OS toast when minimised. +- Modals only for destructive confirmations and login. + +### 12.2 Library (home) + +``` +│ [🔍 Search title, camera, tag] [Year ▾] [Camera ▾] [Status ▾] [Tags ▾] [Sort ▾] [⊞][☰][▦] [⟳] │ +├──────────────────────────────────────────────────────────────────────────────────────────────┤ +│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ +│ │ hero thumb │ │ │ │ │ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ │ │ │ │ │ │ +│ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ ├────────────┤ │ +│ │Harbour sun…│ │2026-09-27 │ │… │ │ │ │ │ │ │ │ +│ │3,600 · R5 │ │1,020 · GoPr│ │ │ │ │ │ │ │ │ │ +│ │✓ ▣ ▶2 ☁ │ │✓ ▣ · ☁ │ │ │ │ │ │ │ │ │ │ +│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ +``` + +- Unit of the library = **sequence** (never a flat list of 600k photos). Views: grid + (default), list (sortable columns), timeline (year/month bands with density). +- Card: hero thumbnail, title (user title or `{date} {camera}`), count · camera · span, + status chips: `✓` analysed, `▣` proxies, `▶n` renders, `☁` synced/origin, `!` warnings. + Hover reveals quick actions: Open, Analyse, Render preset, Sync. +- Multi-select → mass actions bar (Analyse, Build proxies, Verify, Tag, Rate, Move, + Upload, Download, Delete, Export list as CSV). +- Filters are chips; saved views (e.g. "Night, 4K, not rendered"); search is instant + (indexed columns); everything virtualized (in-house `VirtualizingWrapPanel`). + +### 12.3 Sequence editor + +``` +│ ← Harbour sunset · 3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m [Analyse] [Optimise all] [Render ▾] │ +├──────────────────────────────────────────────────────────────────┬──────────────────────────────────┤ +│ ┌──────────────────────────────────────────────────────────────┐ │ Exposure │ +│ │ │ │ Deflicker [●] Auto 41 ⓘ │ +│ │ PREVIEW │ │ Strength ───●──── 0.8 │ +│ │ │ │ Regions [●] Auto horizon │ +│ │ [◧ compare] [⊹ vectors] [▭ regions] [▦ crop mask] [1:1] [⛶] │ │ Transitions [●] Auto 18 ⓘ │ +│ └──────────────────────────────────────────────────────────────┘ │ WB smoothing [●] Auto │ +│ ▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏▏ filmstrip + markers │ │ +│ [Frames] [Exposure] [Motion] [Camera] [Time] [Stack] [Export] │ [Optimise section] [Reset] │ +│ ┌──────────────────────────────────────────────────────────────┐ │ │ +│ │ measured (amber) vs target (accent) luminance chart, │ │ │ +│ │ exposure-step markers, region curves; click = seek preview │ │ │ +│ └──────────────────────────────────────────────────────────────┘ │ │ +``` + +- Preview always on top with tools: zoom/pan (1:1 shows raw pixels), wipe compare + original/corrected, motion-vector overlay, region boundary, crop mask ("what I lose" vs + "how it will look"), full-screen native-resolution window with collapsible shot data. +- Sections (tabs inside the editor; each with its measuring tool below the filmstrip and + its settings column on the right): **Frames** (virtualized table: index, time, exposure, + ISO, f, size, tier, flags; exclude/include; set hero; warnings list), **Exposure** + (deflicker, regions, holy-grail transitions, WB) with luminance/waveform charts, + **Motion** (blur, flow quality, stabilization) with shake path chart, **Camera** (crop, + aspect, virtual camera keyframes with a spline editor), **Time** (fps, timing mode, remap + curve, fit-to-duration, plan chart), **Stack** (median/max, trail length), **Export** + (preset, values, output name, batch list, render history, sponsor slot — Phase 9 only). +- Every deducible control shows Auto/manual state (§10.4); every control has a tooltip + with the reason and the effect of moving it the wrong way. +- While a job runs on this sequence, settings that would change the rules mid-render are + disabled; viewing tools stay live. + +### 12.4 Import (cards) + +``` +│ Devices │ Profile "EOS R5 · card A" (SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431) [Edit ▾] [New] │ +│ ● SD 128 GB EOS R5 card A ▲ │ Destination (•) Archive ( ) Folder [D:\Shoots …] ( ) Server ☁ "Studio NAS" │ +│ ● microSD 64 GB GoPro 12 │ Scan [✓] Subfolders Sessions [✓] gap [45] min · min [8] frames [✓] Verify hashes │ +│ ○ E:\ no DCIM │ Names {year}/{date} {camera} / {date}_{time}_{n:0000} → 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 │ +│ ○ Folder… │ On existing (•) Skip ( ) Rename ( ) Overwrite Convert (•) Copy ( ) TIFF-16 ( ) Linear DNG ( ) JPEG │ +│ │ After import (•) Keep card ( ) Delete imported ( ) Format card [✓] Eject [✓] Deep analysis │ +│ [✓] Import automatically when │ Plan 3 sessions · 4,812 photos · 96.2 GB · 12 min [Show plan] [ Import ▶ ] │ +│ a known card is inserted │ │ +``` + +- Devices list: removable volumes and any volume with `DCIM`; identity = volume serial + + label + capacity, camera identity from the first file; known cards show their nickname + and profile; unknown cards prompt for a nickname (one field). +- Plan before touching disk: sessions, folders to be created, first three file names, + duplicates already in the archive (by hash), disk space check. +- Copy with hash while streaming; verify by re-reading destination; only then delete or + format (OS dialog); eject via `IOCTL_STORAGE_EJECT_MEDIA` after `FSCTL_LOCK_VOLUME`. +- Destination "Server" streams frames through the client to the server (§14.4); the + server confirms each hash before the client counts it as imported. +- Auto-import on insertion (per card), with the OS toast "Card X detected — Import". + +### 12.5 Archive manager + +``` +│ [Archive: D:\TitanoArchive ▾] [Scan] [Rebuild index] [Verify] [Duplicates] [Orphans] [Adopt folder…] [Maintenance ▾] │ +├──────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ 618,204 photos · 412 sequences · 9.4 TB · 14 cameras · 2019–2026 │ +│ ▆▇█▅▂▁▃▆ photos per month (heatmap) ██████░░ storage by year ▉▉▉▍ by camera ▉▉▎ by format │ +│ Index health: ✓ sidecars 412/412 · ⚠ 3 sequences without proxies · ⚠ 1 unverified since 90 days │ +│ Recent maintenance: 2026-09-20 verify ✓ · 2026-09-01 vacuum ✓ │ +├──────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Mass operations on filtered set (412): [Analyse] [Proxies] [Thumbnails] [Verify] [Move] [Retag] [Export CSV] [Delete] │ +``` + +Operations: **Scan** (incremental, mtime/size), **Rebuild index** (from sidecars; falls +back to full metadata scan; never deletes originals), **Verify** (hashes; bit-rot report), +**Duplicates** (by hash across sequences), **Orphans** (files not indexed / rows without +files, with fix actions), **Adopt folder** (index an existing tree in place or copy into +the layout), **Merge/split sequences**, **Move archive** (relink), **Maintenance** +(SQLite vacuum/backup/restore, cache cleanup, proxy purge/rebuild, thumbnail pack +compaction, log rotation). Statistics drawn with in-house chart elements. Every operation +is a Job (resumable, cancellable, logged). + +### 12.6 Jobs + +Queue + history table: kind, target, progress, fps, ETA, node, state; pause/resume/cancel/ +retry; log tail on expand; filters. Global job bar mirrors the active job. + +### 12.7 Server (client side) + +``` +│ Server [https://nas.local:8443 ……] [Connect] Status ● Connected · v1.3 · TLS fingerprint 9A:… (trusted 2026-09-01) │ +│ Signed in as alberto · Editor · 2.1 TB of 5 TB used [Sign out] │ +│ [✓] Offer this PC as render node (NVENC HEVC/H.264, AV1) [✓] Keep proxies of synced sequences offline │ +├───────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Sequence Local Server State Action │ +│ Harbour sunset ✓ originals ✓ in sync — │ +│ Comet 2026-08-13 ✓ originals ✗ local only [Upload] │ +│ Construction cam wk 38 proxies ✓ remote [Download originals] [Open with proxies]│ +``` + +First connection shows the certificate fingerprint (trust-on-first-use); login modal; +per-sequence sync actions and states; conflict resolution only for settings JSON (keep +mine / take server / save both). + +### 12.8 Settings + +Sections (list on the left, controls on the right, no descriptions — tooltips only): +General (language, theme, startup, notifications), Archive (root, templates, proxy policy, +thumbnail size, network polling), Import (defaults, session rules, verify, post-actions), +Analysis (widths, thresholds, deep analysis auto-run), Rendering (quality profile, memory +budget, spill folder, parallelism, encoders detected, hardware preference), Formats (per +format tier on this PC, codec install links), Server (last servers, trusted fingerprints, +render node), Updates (check on start), Advanced (portable mode, logs, database backup/ +restore, reset). Import/export settings as JSON. + +### 12.9 About + +Version, build, licence/EULA link, third-party notice (none), diagnostics bundle button +(zips logs + environment report), update check. + +--- + +## 13. Card import — behaviour details + +- Detection: `WM_DEVICECHANGE` (`DBT_DEVICEARRIVAL`/`REMOVECOMPLETE`) + `DriveInfo` poll + fallback; card identity `{volumeSerial}-{label}-{capacity}`; camera identity from EXIF + Make/Model/BodySerial of the first image found. +- Card pool (`media_cards`): nickname, profile, history; profiles copyable; a card can + inherit a "camera profile" (rules shared by all cards of that camera). +- Session detection: gap > `SessionGapMinutes`; groups with < `MinimumSessionFrames` merge + into the previous session (test shots); each session becomes a sequence; the user can + merge/split in the plan. +- Duplicate handling: hash lookup against the archive index (skip/rename/overwrite); + "already imported" state remembered per card + file (path, size, mtime) for fast + re-inserts. +- Rename during import: templates (§7.1) with live preview; original name kept in the + sidecar. +- Post-actions: keep / delete imported files (only those verified) / format card (OS + dialog) / eject; run deep analysis automatically (default on, background, low priority). +- Failure handling: card removed mid-copy → partial files deleted, plan resumable on + re-insert; errors listed per file, never a modal per error. + +--- + +## 14. Titano Server + +### 14.1 Stack + +ASP.NET Core minimal API on Kestrel (`Microsoft.AspNetCore.App` shared framework, no +packages), `System.Text.Json` source-generated contexts from `Titano.Protocol`, WebSockets +for events, in-house structured file logging (`Microsoft.Extensions.Logging` abstractions +are part of the shared framework; the file provider is in-house), in-house rate limiting for +login and uploads, health endpoint, graceful shutdown (jobs checkpoint). + +### 14.2 Security + +- TLS: `auto` (self-signed cert generated at first start with `CertificateRequest`, stored + in `/data/tls`, fingerprint printed in logs and shown in admin), `pem` (cert + key + paths), `proxy` (HTTP behind a reverse proxy, `ForwardedHeaders` middleware, admin warns + if not local). +- Passwords: PBKDF2-SHA512, ≥ 210,000 iterations, 16-byte salt, versioned hash format; + minimum length 10; admin-created users get `mustChangePassword`. +- Tokens: 32 random bytes, stored as SHA-256, `Authorization: Bearer`; sliding expiry + (default 30 days), per-client name, revocation list; web admin uses an `HttpOnly; Secure; + SameSite=Strict` cookie session + double-submit CSRF token. +- Authorization: roles admin/editor/uploader/viewer + permission bits; sequence ownership; + admin-only management endpoints; path traversal impossible (ids → paths via DB only). +- Limits: max upload size, chunk size (default 8 MiB), per-user quota, request timeouts, + login rate limit (5/min/IP), audit log. + +### 14.3 API v1 (JSON; errors as `{ code, message, details }`; `X-Titano-Api: 1`) + +``` +POST /api/v1/auth/login {username,password,clientName} → {token,user,mustChangePassword} +POST /api/v1/auth/logout · POST /auth/password · GET /auth/me +GET /api/v1/server/info name, version, apiVersion, capabilities, tlsFingerprint, formats, limits +GET /health + +GET /api/v1/users · POST · GET/PATCH/DELETE /users/{id} · POST /users/{id}/reset-password (admin) + +GET /api/v1/sequences?year&camera&status&tag&q&cursor&limit +POST /api/v1/sequences create (title, camera hint) → id +GET /api/v1/sequences/{id} · PATCH (title, tags, rating, settings) · DELETE +GET /api/v1/sequences/{id}/manifest frames with hashes/sizes/versions (sync) +GET /api/v1/sequences/{id}/analysis · GET /stats · GET /renders +GET /api/v1/sequences/{id}/frames?cursor&limit +GET /api/v1/frames/{id}/original · /proxy · /thumb (streamed, Range supported) + +POST /api/v1/uploads {sequenceId|null, fileName, size, sha256, capturedAt?} → {uploadId, chunkSize, received[]} | 200 {alreadyExists} +PUT /api/v1/uploads/{id}/chunks/{n} body bytes (idempotent) → {received} +POST /api/v1/uploads/{id}/complete → frame id (server verifies sha256, commits into layout, updates manifest) +GET /api/v1/uploads/{id} resume state +DELETE /api/v1/uploads/{id} + +GET /api/v1/jobs?state · POST /jobs {kind, target, params} · GET /jobs/{id} · POST /jobs/{id}/cancel · /retry +WS /api/v1/events {type: jobProgress|jobState|sequenceChanged|cardEvent|nodeState, …} + +POST /api/v1/nodes/register · POST /nodes/{id}/heartbeat · POST /nodes/{id}/claim → job · POST /nodes/{id}/jobs/{jobId}/result (chunked upload of output) + +GET/PUT /api/v1/archive/settings · POST /archive/scan · /rebuild · /verify · GET /archive/stats · POST /archive/maintenance (admin) +GET /api/v1/i18n/{culture} strings for the web admin +``` + +### 14.4 Upload and ingest + +Client computes SHA-256 while reading; `POST /uploads` short-circuits if the hash exists; +chunks are written to `/data/uploads/{id}.part` with a received-bitmap; `complete` verifies +the hash, moves the file into `originals/` under the layout templates (temp → fsync → +rename), extracts metadata, appends to `sequence.json`, inserts the DB row, enqueues +thumbs/proxies/light analysis, emits `sequenceChanged`. Frames without a target sequence +are grouped by the same session rules (§13) into auto-created sequences. Card imports from +a connected client use exactly this path. + +### 14.5 Sync + +Manifest diff per sequence: originals are content-addressed (never conflict); settings and +tags carry version counters (last-writer-wins with an explicit conflict prompt in the +client when both changed); proxies/thumbs are regenerable and never synced upward; renders +are uploaded on request. "Edit with proxies, render where the originals are": a client can +open a remote sequence with proxies only and submit a render job to the server, which runs +it itself (managed formats) or hands it to a render node. + +### 14.6 Job engine + +Persistent queue in the DB; N worker threads (configurable, default = cores/2); job kinds +in §5; checkpoints every 5 s (progress + resumable cursor); crash-safe restart; priorities +(user-initiated > background analysis); cancellation cooperative; logs per job; retention +of history 90 days. + +### 14.7 Render nodes + +A Titano client with "Offer this PC as render node" registers its encoder capabilities +and polls/claims render jobs matching them, downloads what it needs (proxies or originals +per job settings), renders with its GPU, uploads the result as a render of the sequence. +Node state shown in admin › Jobs; the server falls back to managed formats when no node is +available and says so in the job log. + +### 14.8 Admin web panel (`/admin`, vanilla HTML/CSS/JS, ES modules, no build step, same API) + +``` +┌─────────────┬────────────────────────────────────────────────────────────────────────────┐ +│ Titano │ Dashboard │ +│ ● Dashboard │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ Users │ │ 9.4 TB │ │ 412 seq │ │ 3 jobs │ │ 2 nodes │ │ +│ Archive │ │ of 16 TB │ │ 618k pho │ │ running │ │ online │ │ +│ Jobs │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ Settings │ Storage by year ▁▂▃▅▇█ Uploads last 30 days ▂▁▃▆▇▅▂ │ +│ Logs │ Recent: alberto uploaded 1,020 frames · node "studio-pc" rendered 4K HEVC │ +│ About │ │ +└─────────────┴────────────────────────────────────────────────────────────────────────────┘ +``` + +Pages: Login · Dashboard · Users (table; create/edit/disable/reset/roles/quota) · Archive +(path, templates, proxy policy, scan/rebuild/verify, stats) · Jobs (queue/history/nodes, +cancel/retry) · Settings (server name, ports, TLS mode + fingerprint, discovery, limits, +language, retention) · Logs (tail, download) · About. Same UI rules: tooltips only, light/ +dark, localised via `/api/v1/i18n`, keyboard accessible. + +### 14.9 Configuration and Docker + +Environment variables (also readable from `/data/server.json`): +`TITANO_ADMIN_USER`, `TITANO_ADMIN_PASSWORD` (used only when no admin exists; forced change +at first login), `TITANO_ARCHIVE_PATH=/archive`, `TITANO_DATA_PATH=/data`, +`TITANO_DB=postgres|sqlite` (Linux: postgres only), `TITANO_DB_HOST`, `TITANO_DB_PORT=5432`, +`TITANO_DB_NAME`, `TITANO_DB_USER`, `TITANO_DB_PASSWORD`, `TITANO_DB_SSLMODE=prefer`, +`TITANO_HTTP_PORT=8080`, `TITANO_HTTPS_PORT=8443`, `TITANO_TLS_MODE=auto|pem|proxy`, +`TITANO_TLS_CERT`, `TITANO_TLS_KEY`, `TITANO_SERVER_NAME`, `TITANO_LANG=en`, +`TITANO_WORKERS`, `TITANO_DISCOVERY=true` (LAN UDP beacon), `PUID`, `PGID`, `TZ`. + +Dockerfile: multi-stage on `mcr.microsoft.com/dotnet/sdk:10.0` → `aspnet:10.0`, non-root +user via `PUID/PGID` entrypoint, volumes `/archive` and `/data`, `HEALTHCHECK` on +`/health`, `linux/amd64` + `linux/arm64`. `docker-compose.yml` with a PostgreSQL 17 service. +Windows: `Titano.Server.exe` runs as console or Windows Service (`sc create`), SQLite or +PostgreSQL. + +--- + +## 15. Titano Uploader + +Single small window (tray-capable), zero analysis: connect + sign in (token saved with +DPAPI), drop zone (files/folders/cards), queue with per-file state, pause/resume, bandwidth +limit, retry with backoff, resumable across restarts (queue persisted in a JSON file next to +the app data), hash verification, optional "delete source after server confirms" (off by +default, confirmation), watch folders (poll + `FileSystemWatcher` where reliable; upload +new files after they stop growing), run at startup, minimise to tray, per-session target +(auto-group / choose sequence / new sequence with title). P2: "make proxies here" toggle +for HEIC/RAW so the server can render without a node. + +``` +│ Titano Uploader ☁ https://nas.local:8443 · alberto · ● Connected [⚙] │ +│ ┌────────────────────────────────────────────────────────────────────────────────┐ │ +│ │ Drop photos, folders or a card here │ │ +│ └────────────────────────────────────────────────────────────────────────────────┘ │ +│ Target (•) Group into sessions automatically ( ) Sequence [Harbour sunset ▾] ( ) New │ +│ Queue 4,812 files · 96.2 GB · 38 MB/s · 41 min left [⏸] [⏹] Limit [50] MB/s │ +│ ▮▮▮▮▮▮▮▮▮▮▮▮▮▮░░░░░░░░░░░░░░░░ 2026-09-28_18-02-11_0413.CR2 │ +│ Watch folders D:\Cam\Roof (every 60 s) ● [+] │ +│ [✓] Delete source after verified upload [✓] Start with Windows │ +``` + +--- + +## 16. Localization + +- Source strings in `i18n/en/*.resx` (one file per area: `Shell`, `Library`, `Editor`, + `Import`, `Archive`, `Server`, `Settings`, `Tooltips`, `Errors`, `Advisor`, `Admin`). + Keys are stable identifiers (`Library.Filter.Year`), never English sentences. +- Runtime: `ResourceManager` + a `Loc` XAML markup extension and `L("key", args)` helper in + `Titano.Core/Localization`; culture switch at runtime without restart (rebinding via a + `LocalizationChanged` event); web admin receives `/api/v1/i18n/{culture}` generated from + the same resx by `Titano.Tools i18n export`. +- Plurals: an in-house minimal CLDR plural-rule table for the shipped languages + (`one/few/many/other`), keys with suffixes (`Photos.Count.one`, `.other`). +- Dates/numbers/units via `CultureInfo`; file sizes localised; RTL via `FlowDirection` + for `ar`, `he`, `fa`, `ur` (mirrored rail and icons where directional). +- Languages (Phase 8, all machine-translated by Claude Code with a glossary, marked as such + in About and open to community review via the public releases repo): `en` (source), `it`, + `de`, `fr`, `es`, `pt-BR`, `pt-PT`, `nl`, `pl`, `cs`, `sk`, `hu`, `ro`, `sv`, `da`, `nb`, + `fi`, `ru`, `uk`, `tr`, `el`, `bg`, `hr`, `sl`, `lt`, `lv`, `et`, `ja`, `zh-Hans`, + `zh-Hant`, `ko`, `ar`, `he`, `hi`, `id`, `ms`, `vi`, `th`. Add more if effort allows. +- `Titano.Tools i18n check` fails CI when a key is missing in `en` or `it`, when a + placeholder count differs between languages, or when a string exceeds the layout budget + (tooltips ≤ 200 chars, labels ≤ 30 chars unless flagged). +- UI is written to survive +40 % text expansion (German, Finnish): no fixed-width labels. + +--- + +## 17. Branding and icon + +- Mark: a **time-lapse aperture-clock** — a circle of 12 short arc segments increasing in + opacity clockwise (the sequence of frames) around a solid sun disc slightly off-centre, + reading as camera aperture, clock and sun path at once; single accent colour on a rounded + square (dark) tile; no text. Works at 16 px (segments merge into a ring; the disc + remains). +- Generated programmatically (`Titano.Tools make-icon`): in-house PNG encoder + ICO + container (16/20/24/32/48/64/128/256), SVG source kept in `branding/`; variants: Server + (mark + three horizontal bars badge), Uploader (mark + up-arrow badge). Also favicon + for the admin panel and a 1024 px PNG for listings. Prototype `IconGenerator` shows + the ICO writer approach. +- App name in title bar only; no splash screen; first-run screen is the empty Library + with one sentence and two buttons (Import a card · Open an archive). + +--- + +## 18. Installer, distribution and updates + +- Builds: `dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true + -p:PublishReadyToRun=true` for App, Uploader, Setup; server as framework-dependent + Docker image and a self-contained Windows zip/installer. (No trimming: WPF does not + support it.) +- `Titano.Setup` (in-house, WPF, ~one screen): choose components (Titano, Uploader, + Server for Windows), folder, shortcuts, file associations (`.titano` project bundles), + installs to `%LOCALAPPDATA%\Programs\Titano` per user (no admin) or `Program Files` + (elevated), registers Add/Remove Programs entry with uninstaller, silent mode + (`/S /DIR=`), upgrade in place, keeps user data. Payload appended to the setup exe as a + compressed archive (in-house format on `DeflateStream`) with a manifest and per-file + hashes. If the human later permits a build-time tool, Inno Setup/MSIX are acceptable + alternatives; default is in-house. +- Code signing hook in the release workflow (`signtool` from the Windows SDK) using + secrets when present; unsigned builds are still produced. +- Updates: on start (opt-out) the client calls the GitHub Releases API of the **public + releases repository** (§19.4) and shows a one-line notice with "Download" (P1: download + installer, verify SHA-256 from `SHA256SUMS`, run it). +- Distribution: installers and `SHA256SUMS` on the public releases repo; Docker images on + GHCR (public package); Unraid template in the public repo. + +--- + +## 19. CI/CD, Docker, Unraid + +### 19.1 `ci.yml` (push, PR) + +Matrix `windows-latest` / `ubuntu-latest`: `dotnet --info`, restore (no packages → fast), +build with warnings as errors, run `Titano.Testing` for all test projects (JUnit XML +uploaded and annotated), `dotnet format --verify-no-changes`, `Titano.Tools i18n check`, +XAML lint (App.Tests), zero-package guard, Docker build (no push) on ubuntu; PostgreSQL 16 +and 17 service containers for `Titano.Data.Tests`; CC0 RAW fixtures fetched by +`Titano.Tools fixtures` and cached (`actions/cache`). + +### 19.2 Zero-package guard + +`Directory.Build.targets` target `AssertNoPackageReferences` fails the build if any +`PackageReference` exists; CI also greps `**/*.csproj` and `**/*.props` and checks that +`obj/project.assets.json` lists no packages. Only `actions/*` and `docker/*` GitHub +Actions are used in workflows. + +### 19.3 `release.yml` (tag `v*`) + +Version from the tag → `Directory.Build.props`; publish self-contained binaries; build +`Titano-Setup-.exe`, `Titano-Uploader-Setup-.exe`, `Titano-Server-win-x64-.zip`; +sign if secrets present; generate `SHA256SUMS` and the changelog (`Titano.Tools changelog` +from Conventional Commits); build and push multi-arch Docker image to +`ghcr.io//titano-server:` and `:latest`; create the GitHub Release **in the +public releases repository** with `gh release create` (the `gh` CLI is preinstalled on +runners) using a fine-grained PAT stored as `RELEASES_TOKEN`; copy `deploy/unraid/ +titano.xml` and EULA there. + +### 19.4 Public releases repository + +Because release assets of a private repository are not publicly downloadable, a second, +public repository (`titano-releases`) holds only: README (what it is, screenshots, +requirements), EULA/LICENSE, release assets, `SHA256SUMS`, Unraid template, `i18n/` +translations for community review, and issues. The private repo publishes into it; nothing +is developed there. The GHCR package is set to public visibility. + +### 19.5 `docker.yml` + +Nightly build of `main` to `ghcr.io//titano-server:nightly`; `deploy/docker/ +docker-compose.yml` for users (server + PostgreSQL + volumes). + +### 19.6 Unraid template (`deploy/unraid/titano.xml`) + +Community Applications XML: repository `ghcr.io//titano-server:latest`, WebUI +`http://[IP]:[PORT:8080]/admin`, ports 8080/8443, paths `/archive` → `/mnt/user/Timelapse`, +`/data` → `/mnt/user/appdata/titano`, variables from §14.9 (admin user/password, DB +host/port/name/user/password, TLS mode, PUID/PGID, TZ), icon URL from the public repo, +support/project links, description ≤ 2 sentences. Document (in the public README) how to +add the template repository URL in Unraid and to pair with the official PostgreSQL +template. + +--- + +## 20. Testing and quality + +### 20.1 `Titano.Testing` (in-house) + +Attributes `[Test]`, `[Theory]` + `[Case(...)]`, `[Skip(reason)]`, `[Timeout(ms)]`, +`[Category]`; assertions with expressive messages (`Assert.Equal`, `Approximately`, +`Throws`, `SequenceEqual`, `Monotonic`, `Within(px)`); fixtures (temp dirs, synthetic +sequences, in-process server, database per test); parallel execution; filters by name/ +category; console output + JUnit XML; exit codes; `dotnet run --project tests/X -- --junit +out.xml --filter core`. + +### 20.2 Test layers + +- Unit: parsers (fuzz corpus: truncated/garbage files must not throw), codecs (round-trip + PSNR thresholds), analysis rules (synthetic sequences with known answers — port the + prototype's 63-check self-test as tests), naming templates, SQL repositories (SQLite + in-memory), PostgreSQL wire client (against service container), protocol (chunk resume, + hash mismatch, idempotency), advisor recommendations (golden JSON). +- Integration: import a synthetic card folder → archive layout + sidecars + DB; rebuild + index from sidecars equals original DB; verify detects a flipped byte; server ingest via + API; sync round trip; render node claim/complete; job resume after simulated crash. +- Windows: WIC decode of fixtures, Media Foundation encode smoke (software H.264) + + in-house MP4 inspector + `MediaPlayer` playback check; `--capture` screenshots of every + screen for visual regression (pixel-diff tolerance) and for the phase report. +- Fixtures: tiny synthetic files checked in; CC0 RAW samples (one per major format, from a + public CC0 sample set) fetched by `Titano.Tools fixtures` into `tests/fixtures/external` + (git-ignored, CI-cached). + +### 20.3 Static rules + +Warnings as errors; nullable enabled; `dotnet format`; XAML lint: every `Button`, +`ToggleButton`, `Slider`, `ComboBox`, `CheckBox`, `MenuItem` has a `ToolTip`; no literal +`Content="…"`/`Text="…"` outside resources; no `PackageReference`; no Windows APIs in +`Titano.Core`/`Titano.Data`/`Titano.Protocol`/`Titano.Server` (checked by building them on +Linux); public API of `Titano.Protocol` versioned. + +### 20.4 Quality gates carried over from the prototype (regression thresholds) + +Deflicker: flicker reduction ≥ 60 % on the synthetic ramp sequence with the ramp preserved +within 0.05 EV; region deflicker: landscape residual ≤ 25 % of the global-curve residual; +phase correlation: sub-pixel error ≤ 0.10 px; stabilization on a textureless frame: shake +≤ 0.1 px (texture gating); holy grail: no step > 0.3 EV in the target curve; time remap +monotonic; star-trail luminance non-decreasing on ≥ 99 % of steps; memory: peak RSS +independent of sequence length for a fixed window; cancellation: no partial output, no +unobserved exceptions, spill file removed. + +--- + +## 21. Monetization — absolute final step (Phase 9; do not start before every gate passed) + +- In-house ad delivery, no SDK, no tracking by default: the client fetches a signed + campaign manifest (JSON: id, image URL, link, weight, languages, countries, start/end, + minimum version) from `https://.github.io/titano-releases/ads/manifest.json` + (or a URL set by the human), caches creatives, renders them natively in one slot — the + Export section while a render runs (prototype rationale: the only moment an ad takes + nothing from anyone) — and optionally a small footer slot in Library. Clicks open the + browser. Manifest signature: ECDSA P-256 with an embedded public key. +- Consent: first-run one-line choice for anonymous impression counting (off by default); + when on, a daily aggregated ping (version, language, country from OS locale, counts) — + no identifiers. Privacy policy link in About and EULA. +- Ad-free: "Titano Pro" licence key (ECDSA-signed, offline validation, tied to a display + name and edition, no phone-home) entered in Settings › Licence; a server licence makes + all its connected clients ad-free (team scenario). Fallback content when the manifest + is empty: internal tips about the program. +- Everything above is a toggle in Settings for the human's own builds; the feature ships + disabled by default until the human flips a build property `TitanoAdsEnabled=true`. + +--- + +## 22. Phased delivery plan + +Each phase ends with the Definition of Done (§0.2 rule 9) and a phase report. Phases may be +split into sub-phases; order inside a phase is Claude Code's choice. + +### Phase 0 — Bootstrap (repo, rules, shells) +Solution, `Directory.Build.*`, `global.json`, `CLAUDE.md`, `DECISIONS.md`, `CHANGELOG.md`; +`Titano.Testing`; zero-package guard; `ci.yml`; i18n infrastructure with `en` + `it`; +WPF shell (rail, theme, job bar, status strip, settings skeleton, tooltip lint); server +skeleton (Kestrel, `/health`, `/server/info`, login page, admin shell); Dockerfile builds; +branding mark + ICO generator. +*Gate:* both apps start, server container answers `/health`, CI green on both OSes. + +### Phase 1 — Metadata and imaging core +Parsers (§9), managed codecs (§8.3), WIC provider, decode tiers, thumbnails/proxies, +`ImageBuffer`/`FrameWindow` port, fixtures tool, fuzz tests, DNG full pipeline. +*Gate:* every fixture decodes at the expected tier on Windows and Linux; PSNR/round-trip +tests green; `Titano.Tools diagnose ` reports per-file tier and metadata. + +### Phase 2 — Data layer and archive +SQLite binding, PostgreSQL wire client, migrations, repositories, archive layout, sidecars, +scanner, rebuild, verify, duplicates, orphans, adopt folder, naming templates. +*Gate:* import synthetic 100k-frame archive; rebuild equals original; verify detects +corruption; PG tests green against 16 and 17. + +### Phase 3 — Client Library and Archive manager +Virtualized grid/list/timeline, filters, saved views, mass operations, jobs screen, stats +charts, maintenance, settings screens, `--capture` screenshots. +*Gate:* 500k-photo synthetic library meets §1.1 timings. + +### Phase 4 — Card import +Device detection, card pool and profiles, plan preview, sessions, hash-verified copy, +post-actions (delete/format/eject), auto-import, direct-to-server destination stub. +*Gate:* end-to-end import from a simulated card folder; destructive actions gated by +verification; screenshots. + +### Phase 5 — Analysis advisor +Light + deep analysis, reports, charts, recommendations with reasons, auto presets, +Auto/manual controls, Optimise. +*Gate:* golden recommendations for synthetic sequences; every recommendation has a +localised reason; deep analysis of 10k frames completes unattended. + +### Phase 6 — Engine, encoding and Sequence editor +6a modules port with regression thresholds (§20.4); 6b Media Foundation encoder, MP4 muxer +(H.264/HEVC/AV1), managed encoders (AVI/GIF/APNG/sequences), presets; 6c preview tools, +section charts, spline editor, export UI, batch render. +*Gate:* self-test suite green; renders play in Windows Media Player and the in-house +inspector validates containers; hardware MFT used when present (logged). + +### Phase 7 — Server, sync, uploader +Full API, auth, uploads/ingest, sync, jobs, render nodes, admin panel, Docker + compose, +client server mode, Uploader app, LAN discovery. +*Gate:* two clients + uploader against a Docker server: upload, sync, render via node and +via server; crash-restart resumes jobs; audit log complete. + +### Phase 8 — Worldwide release readiness +All languages (§16), RTL pass, installer, `release.yml`, public releases repo bootstrap +(README, EULA draft, template), Unraid template, update check, diagnostics bundle, +accessibility pass, performance pass, docs. +*Gate:* tagged pre-release published end-to-end from CI; install/uninstall/upgrade tested; +Unraid template validated. + +### Phase 9 — Monetization (§21) +*Gate:* human explicitly approves start; feature behind build property; privacy text done. + +--- + +## 23. Assumptions and open decisions (for the human; do not block on these) + +1. Product name **Titano** kept from the prototype — rename before Phase 0 if desired + (repo-wide rename later is costly). +2. Linux server MP4 output relies on render nodes (and P2 intra-only encoder). If an + FFmpeg subprocess were ever allowed as an *optional, opt-in* backend, it would be a + single `IVideoEncoderProvider`; not planned unless the human approves. +3. HEIC pixels are only decodable on Windows (WIC); server-side rendering of HEIC-only + sequences requires proxies from a client/node. +4. Native RAW decoders beyond DNG are phased (CR2, NEF, ARW, PEF, ORF, RW2, RAF + uncompressed first); until then those formats render from full-size embedded previews + on the server and via WIC + Raw Image Extension on Windows. +5. Windows 10 21H2+/Windows 11, x64 only (ARM64 later); `winsqlite3.dll` presence assumed. +6. Tests use the in-house runner to keep the zero-package rule absolute; xUnit would be + acceptable only if the human relaxes the rule for test projects. +7. Installer is in-house; Inno Setup/MSIX acceptable if the human allows build-time tools. +8. Ads and licence keys are designed but disabled by build property until Phase 9. + +--- + +## Appendix A — `CLAUDE.md` content (create verbatim in Phase 0, keep updated) + +```markdown +# Titano — working rules +Read docs/BRIEF.md when in doubt; it wins over these notes. +- Zero . Anything not in the .NET BCL / Microsoft shared frameworks / OS APIs is written here. +- No external processes at runtime (no ffmpeg, exiftool, powershell). Only OS dialogs listed in BRIEF §8.6. +- Titano.Core / Data / Protocol / Server target net10.0 and build on Linux; Windows-only code lives in *.Windows or the desktop apps. +- English identifiers, comments, commits (Conventional Commits). Prototype in docs/reference is Italian: port algorithms, not language. +- Every UI string is a resource (en source, it translation). Labels ≤ 3 words; explanations only in tooltips; every actionable control has a tooltip; no helper paragraphs. +- Destructive operations: dry-run plan first, hash verification, explicit user action. +- When the brief is silent: choose the simplest safe option, log it in docs/DECISIONS.md, continue. Ask only at phase gates or before irreversible choices. +- Definition of Done per phase: green on windows-latest + ubuntu-latest, tests green, no new warnings, DECISIONS + CHANGELOG updated, i18n check green, phase report with "how to try it". +- Build: dotnet build -c Release; tests: dotnet run --project tests/ -- --junit out.xml; tools: dotnet run --project src/Titano.Tools -- . +- Current phase and next steps: see docs/STATUS.md (update at every gate). +``` + +## Appendix B — Prototype module map (grep targets in `docs/reference/titano-prototype.md`) + +| Prototype (Italian) | New home | Notes | +|---|---|---| +| `Metadata/TiffDirectory, TiffPrimitives, MetadataReader, XmpScanner, FrameMetadata` | `Core/Metadata` | extend with BMFF/RIFF/RAF walkers, MakerNotes | +| `Imaging/WicInterop, ImageDecoder` | `Core.Windows/Wic` | keep pull-based scaling chain | +| `Imaging/ImageBuffer, ColorSpace, GeometryStage, RasterWriter, OrientationDetector` | `Core/Imaging` | RasterWriter → `Codecs/TiffWriter`, `LinearDngWriter` | +| `Analysis/*` (LuminanceAnalyzer, DeflickerEngine, RegionSegmenter, HolyGrailEngine, ExposureProcessor, ColorScience) | `Core/Analysis` | keep validated behaviour + tests | +| `Motion/*` (Fourier, PhaseCorrelator, GrayPyramid, OpticalFlowEngine, MotionField, MotionBlurRenderer, Stabilizer, VirtualCamera, TemporalStacker, FrameInterpolator) | `Core/Motion` | | +| `Core/Spline, LocalRegression, TimelapseSequence, FrameRecord` | `Core/Math`, `Core/Sequences` | | +| `Pipeline/RenderPlan, RenderPipeline, FrameWindow, AutoDirector, AutoOptimizer, SequenceWarnings` | `Core/Render`, `Core/Advisor` | AutoDirector/Optimizer → advisor rules with reasons | +| `Pipeline/MediaImporter, PathTemplate` | `Core/Import`, `Core/Naming` | tokens translated to English | +| `Video/MediaFoundationInterop, VideoEncoderSession, Nv12Converter, CodecLimits` | `Core.Windows/MediaFoundation` | add P010, AV1, capability enumeration | +| `Video/Mp4Muxer, BoxWriter, AnnexBParser, ExportPresets, ExportSettings` | `Core/Video`, `Core/Export` | add `av1C`, new presets | +| `Diagnostics/SelfTest, SyntheticSequence, SequenceDiagnostics, Mp4Inspector, Mp4Playback, AdvancedModuleTests, ExifWriter, IconGenerator, CrashGuard` | `tests/*`, `Titano.Tools`, `Core/Diagnostics` | 63 checks → tests | +| `UI/*` (WinForms) | not ported | reuse only the interaction ideas (rail, preview tools, Auto indicator, presets) | +| `UI/SponsorPanel` | Phase 9 only | | + +## Appendix C — Glossary + +Sequence (a shoot: one folder of frames = one project) · Frame (one photo) · Hero frame +(thumbnail of the sequence) · Light/Deep analysis · Advisor (rule engine producing +recommendations with reasons) · Tier (how a frame's pixels are obtained) · Proxy (JPEG +stand-in) · Sidecar (`sequence.json` manifest) · Render (an exported video) · Preset +(bundle of export values) · Sequence preset (project settings + export preset produced by +the advisor) · Render node (client lending its GPU to the server) · Job (any long +operation, resumable) · Card profile (import rules for a memory card). diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 00000000..88a030af --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes. Format: Keep a Changelog; versions follow SemVer; commits follow Conventional Commits. + +## [Unreleased] + +### Added +- Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin. +- `Titano.Testing`: in-house test framework and runner with JUnit XML output. +- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages) and `i18n check/export`. +- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon`. +- Core contracts: image buffers and decoder providers, video encoder providers, domain model, atomic file writes. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 00000000..4b79c26f --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,16 @@ +# Decisions + +One line per decision: date · decision · alternative · reason. + +| Date | Decision | Alternative | Reason | +|---|---|---|---| +| 2026-10-02 | The prototype dump `docs/reference/titano-prototype.md` was not supplied; algorithms are implemented from the brief's descriptions and the cited literature, with the §20.4 thresholds as acceptance tests. | Wait for the dump | Not available in the repository or uploads; the brief fully specifies behaviour and gates. | +| 2026-10-02 | Custom WPF theme dictionaries (`Titano.Ui/Themes`) implementing DESIGN.md tokens instead of `Application.ThemeMode` Fluent. | Fluent theme + overrides | DESIGN.md fixes exact colours/sizes; Fluent is still flagged experimental (WPF0001) and would need restyling of most controls anyway (§2.1 permits in-house dictionaries). | +| 2026-10-02 | Added shared WPF library `src/Titano.Ui` (theme, icons, controls, `Loc` markup extension) used by App, Uploader and Setup. | Duplicate resources per app | One visual system for three programs. | +| 2026-10-02 | Added `tests/Titano.Core.Windows.Tests` for WIC / Media Foundation / DXGI tests. | Put them in App.Tests | Keeps engine interop tests independent of the WPF app. | +| 2026-10-02 | Localization areas extended with `Common`, `Jobs`, `Uploader`, `Setup`. | Fold into `Shell` | Smaller, owned files; same key scheme. | +| 2026-10-02 | Resources live in `i18n//[.].resx`, embedded into `Titano.Core` (satellite assemblies), base name `Titano.Core.i18n.`. Keys marked `invariant` need no translation. | Raw XML loader | Uses `ResourceManager` as the brief requires; satellites bundle into single-file publishes. | +| 2026-10-02 | Program icons (ICO) are generated at build time into `artifacts/icons` by `Titano.Tools make-icon`, invoked from `Directory.Build.targets`. | Commit generated ICO files | Brief forbids committing generated binaries and raster sources. | +| 2026-10-02 | In-house CRC-32 (`Titano.Core.Hashing.Crc32`). | System.IO.Hashing | That assembly is a NuGet package, not part of the shared framework. | +| 2026-10-02 | Windows projects target `net10.0-windows` (platform version 7.0) without a Windows SDK projection TFM; Windows 10 APIs are reached by P/Invoke/COM. | `net10.0-windows10.0.19041.0` | Avoids the CsWinRT projection; toasts use the in-window toast host plus tray balloon. | +| 2026-10-02 | Test projects use an explicit `TestMain` entry point. | Top-level statements | Avoids the `Program` type clash with the server's top-level program. | diff --git a/docs/STATUS.md b/docs/STATUS.md new file mode 100644 index 00000000..992f99a0 --- /dev/null +++ b/docs/STATUS.md @@ -0,0 +1,5 @@ +# Status + +Current phase: **Phase 0 — Bootstrap** (in progress). + +See docs/BRIEF.md §22 for the phase plan. diff --git a/docs/ui/DESIGN.md b/docs/ui/DESIGN.md new file mode 100644 index 00000000..6bcfbea5 --- /dev/null +++ b/docs/ui/DESIGN.md @@ -0,0 +1,119 @@ +# Titano — Design reference for Claude Code + +Companion to `docs/BRIEF.md` §12 (UI spec). Suggested repo placement: +`docs/ui/DESIGN.md` (this file), `docs/ui/mockups/*.html` (open in any browser; +each file is one screen at its natural size, links between screens work), `branding/` +(icon sources). The mockups are the visual target; where a mockup and the brief disagree +on behaviour, the brief wins; where they disagree on looks, the mockup wins. + +## 1. Tokens → WPF resource dictionary (`Titano.App/Themes/Dark.xaml`, `Light.xaml`) + +| Key (SolidColorBrush) | Dark | Light | Use | +|---|---|---|---| +| `Brush.Bg` | #1F1F23 | #F3F3F3 | window background | +| `Brush.Chrome` | #1A1A1E | #FFFFFF | title bar, rail, status bar, web sidebar | +| `Brush.Surface` | #26262C | #FFFFFF | panels, toolbars, dialogs | +| `Brush.Card` | #2F3038 | #FFFFFF | cards, inputs, buttons, hovered rows | +| `Brush.Stroke` | #3E404A | #E5E5E5 | 1 px borders and dividers | +| `Brush.Text` | #F2F3F5 | #1A1A1A | primary text | +| `Brush.TextMuted` | #A9AEB9 | #616161 | secondary text, labels | +| `Brush.TextFaint` | #7B818E | #9E9E9E | hints, column headers, disabled | +| `Brush.Accent` | #4CC2FF | #0067C0 | primary button, active rail edge, links, Auto | +| `Brush.OnAccent` | #0B1B24 | #FFFFFF | text on accent | +| `Brush.AccentSelected` | rgba(76,194,255,.25) | #E8F1FA | selection glow / selected nav | +| `Brush.Sun` | #F5A524 | #E08A1E | manual slider track, uploader accent, icon sun | +| `Brush.Success` | #35C48F | #0F7B4F | analysed, in sync, done | +| `Brush.Warning` | #E8B339 | #9A6700 | warnings, destructive outline | +| `Brush.Error` | #F0625D | #C42B1C | errors, failed | +| `Brush.Region` | #5AD1C8 | #1A9E95 | sky/landscape region masks only | + +Dark is the client default; Light follows the OS setting; the web admin is Light-only. +Never use colour alone to carry state: pair it with a glyph (● ○ ◐ ▲ ✕ ▶) or a word. + +## 2. Type (Segoe UI Variable, fallback Segoe UI; `FontSize` keys) + +`Text.PageTitle` 18/600 · `Text.Title` 16/600 · `Text.Section` 14/600 · `Text.Body` 13/400 +· `Text.Secondary` 12/400 muted · `Text.Chip` 11/400. Line heights 24/22/20/18/16/14. +Numbers in tables use tabular figures (`Typography.NumeralAlignment="Tabular"`). +Layout must survive +40 % text width (de, fi): no fixed-width labels, `MinWidth` only. + +## 3. Spacing, radii, sizes + +Spacing scale 4 · 8 · 12 · 16 · 20 (`Thickness` keys `Space.1`…`Space.5`). +Radii: 6 controls · 8 cards/panels · 12 pills · 12 modal dialogs. +Controls 32 px tall, 44 px minimum width, 12 px horizontal padding; compact row buttons 26–28 px. +Rail 128 px (collapses to 48 px icons); title bar 34; job bar 40; toolbar 56; status bar 30; +table rows 36–40 (52 in the web admin); side panels 320 px; settings section list 200 px. +Label column left of controls: 116 px in panels, 180 px in Settings. + +## 4. Controls and states (see `Components.html`) + +- **Button**: Card fill, Stroke border. Hover +6 % lightness, pressed −6 %, focus = 2 px + Accent ring outside. **Primary** (Accent fill, OnAccent text, 600) — one per screen. + **Destructive** = Warning outline, transparent fill, never a primary. **Subtle** = no border + until hover. **Toggled** = Accent text + Accent border. **Disabled** = 40 % opacity and the + tooltip says why. Icon-only buttons carry `AutomationProperties.Name` and a tooltip. +- **Inputs**: Card fill, Stroke border, Accent border on focus, Error border when invalid with + the message in the tooltip (never a line of text under the field). Enter commits, Esc reverts. +- **Slider — Auto/manual** (brief §10.4): Auto state = Accent track, dimmed thumb, an `Auto · 41` + pill at the right whose tooltip gives the advisor's reason; touching it turns the track Sun + (manual), shows the value, and a `⟲` reset button returns to Auto. Not applicable = greyed + value "n/a" with the reason in its tooltip. +- **Status glyphs**: `●` green Analysed · `○` faint Not analysed · `●` Proxies · `▶ n` rendered + · `●` accent Synced/Remote · `◐` amber Analysing · `▲ n` warnings · `✕ n` errors. +- **Chips**: 24 px pills, Card fill, Stroke border; selected/recommended = Accent border and text. +- **Progress**: 6 px bar, Accent fill, text to the right; indeterminate = sliding highlight. +- **Tooltip**: light on dark (#F2F3F5 on dark, #1A1A1A text), 12 px, one line: action + cost + + shortcut ("Read every frame again · about 6 min · Ctrl+Shift+A"); 400 ms delay; ≤ 200 chars. + Every interactive element has one. There is no other explanatory text in the UI. +- **Dialog**: Surface fill, Stroke border, radius 12, 24 px shadow, two buttons maximum, safe + action left and default, destructive on the right with typed confirmation for formatting. +- **Toast**: bottom-right, 420 px, Card fill with a 3 px Accent left edge, one action button, + 8 s, hover pauses. Used for card insertion, render done, server messages. +- **Job bar**: 40 px strip under the title bar in every client screen: current job, progress, + time left, pause; hidden when idle only in the editor (it shows "Ready" elsewhere). +- **Rail item**: 36 px; active = Card fill + 3 px Accent left edge; badge = Accent pill with + the count of things needing attention. +- **Cards** (Library): 236 px wide, thumbnail 16:9, count badge top-right, checkbox top-left on + hover/selection, selected = Accent border + `AccentSelected` glow; hover scrubs the thumbnail. +- **Tables**: header 11 px faint, sortable; rows Card fill on hover; numbers right-aligned, + tabular; virtualised beyond 200 rows; row actions are 26 px buttons revealed on the row. + +## 5. Icons + +16 px, 1.5 px strokes, round caps and joins, `currentColor`, drawn as `PathGeometry` / +`DrawingImage` resources in `Titano.App/Icons/Icons.xaml` (source SVGs in `branding/ui-icons/` +if generated by a tool). No icon fonts, no emoji in shipped UI (the mockups use a few glyphs +only as placeholders: replace ⟳ ▾ ✕ ■ ❚❚ ≡ with drawn icons). Directional icons mirror in RTL. + +## 6. App icon (`branding/`) + +`titano.svg` is the master: 256 plate radius 56 #1A1A1E, ring r 92, 12 ticks of 12° with 18° +gaps, stroke 20 round caps, opacity 0.14 → 1.0 clockwise from 12 o'clock, sun disc at +(152,104) r 30 #F5A524. Variants: `titano-server.svg` (rack badge), `titano-uploader.svg` +(up-arrow badge), `titano-mono.svg` (white, no plate, for the tray). PNG renders at +16/32/48/64/128/256 are reference output; `Titano.Tools make-icon` must regenerate ICO/PNG +from the SVG geometry (no raster assets checked in as sources). Badges only at ≥ 48 px. + +## 7. Screen-by-screen notes (mockup → brief section) + +| Mockup | Brief | Notes | +|---|---|---| +| `Main.html` | §12.2 Library | grid/list, year·camera·status filters, selection panel | +| `Editor.html` | §12.3 Sequence editor | Exposure tab, wipe compare, curves, advisor Auto pills | +| `Export.html` | §12.3 / §11.4 | preset cards with size/time estimate, Output panel, batch | +| `Import.html` | §12.4 / §13 | card profile, sessions, plan, verification, after-import actions | +| `Archive.html` | §12.5 | tree, mass operations, stats, verify/rebuild, maintenance | +| `Jobs.html` | §12.6 | filters, queue order, expandable log, retry/open/folder | +| `Server.html` | §12.7 / §14 | connection with TOFU fingerprint, account and quota, render node, sync table, conflicts | +| `Settings.html` | §12.8 | section list, Rendering section, encoder table, self-test | +| `Welcome.html` | §12.1 | first run: local archive / adopt folder / connect; consent line; card toast | +| `Admin.html` | §14.7 | dashboard | +| `AdminUsers.html` | §14.7 | users table, roles, quotas, temporary password, render-node right | +| `Uploader.html` | §15 | single window, watch folder, queue, tray | +| `Components.html` | §12.1 | the control kit above, with hex values and state rules | +| `Icon.html` | §17 | construction, sizes, variants, wordmark | + +Missing on purpose (build from the brief and this kit): About, Login dialog, the other editor +tabs (Frames, Motion, Camera, Time, Stack), Import "Show plan", Archive rebuild dialog, the +admin Archive/Jobs/Settings/Logs pages. Reuse the shell and the kit; do not invent new colours. diff --git a/docs/ui/mockups/Admin.html b/docs/ui/mockups/Admin.html new file mode 100644 index 00000000..fe0ac6f5 --- /dev/null +++ b/docs/ui/mockups/Admin.html @@ -0,0 +1,118 @@ + + + + +Titano Server — Admin dashboard + + + +
+ +
+
+ Dashboard + up 12 d 4 h · PostgreSQL 17 · TLS auto · discovery on + + + + +
+
+
+
+ Storage + 9.4 TBof 16 TB +
+ 6.6 TB free · exports 210 GB · proxies 610 GB +
+
+ Archive + 412sequences + 618,204 photos · 14 cameras · last scan 07:12 + 3 sequences without proxies +
+
+ Jobs + 3running + 12 queued · 41 done today · 0 failed + workers 4 of 4 busy +
+
+ Render nodes + 2online + studio-pc · NVENC HEVC/H.264/AV1 · busy + laptop-alb · QSV HEVC/H.264 · idle +
+
+
+
+ Storage by year + +
+
+
Uploads · last 30 daysframes per day · 96,410 total · peak 12,400
+ +
+
+
+
+
Recent activityAll logs
+
+ 09:41alberto uploaded 1,020 frames to Construction cam · week 38 + 09:12studio-pc rendered Milan skyline dusk · 4K HEVC · 2 min 41 s + 08:55uploader roof-cam signed in from 192.168.1.44 + 08:30admin set export retention to 180 days + 07:12scheduled scan finished · 412 sequences · 0 changes + 06:00database backup · /data/backups/2026-09-30.sql.gz · 190 MB + 23:04admin created user giulia · Editor · quota 2 TB +
+
+
+ +
+ KindTargetNodeProgressState + RenderHarbour sunset → 4K 10-bit HEVCstudio-pc
62 %
running + Deep analysisConstruction cam · week 38server
28 %
running + ProxiesComet over the ridgeserver
91 %
running + VerifyArchive · 2024server
—
queued + RenderAurora, Tromsø → 1080p share H.264laptop-alb
—
queued +
+
+
+
+
+
+ + diff --git a/docs/ui/mockups/AdminUsers.html b/docs/ui/mockups/AdminUsers.html new file mode 100644 index 00000000..faffd14d --- /dev/null +++ b/docs/ui/mockups/AdminUsers.html @@ -0,0 +1,76 @@ + + + + +Titano Server — Users + + + +
+ +
+
+ Users + 6 accounts · 5 active · roles: admin, editor, uploader, viewer + + + + +
+
+
+
UserRoleQuotaLast seenUploads 30 dStatus
+
AadminAdministrator · created at first startAdmin—now · 192.168.1.100● Active
+
AalbertoAlberto · render node studio-pcEditor
2.1 of 5 TB
10:15 · client 1.3.014,208● Active
+
GgiuliaGiulia · must change passwordEditor
0.1 of 2 TB
09:20 · client 1.3.0640● Active
+
Rroof-camUploader on the roof PC · watch folderUploader
0.6 of 1 TB
08:55 · uploader 1.3.081,320● Active
+
MmarcoMarco · clientViewer—2026-09-140● Active
+
SsimoneSimone · disabled 2026-08-30Editor
0.4 of 2 TB
2026-08-290○ Disabled
+ +
Passwords: PBKDF2-SHA512, 12 characters minimum · tokens expire after 30 days idleSign-in log
+
+ +
+
+
+ + diff --git a/docs/ui/mockups/Archive.html b/docs/ui/mockups/Archive.html new file mode 100644 index 00000000..8837fc49 --- /dev/null +++ b/docs/ui/mockups/Archive.html @@ -0,0 +1,142 @@ + + + + +Titano — Archive manager + + + +
+
+ + Titano — Archive + + —▢✕ +
+
+ +
+
+
+ Verify · 6.7 of 9.4 TB · 410 MB/s · 1 h 52 min left · 0 errors + +
+
+
+ + + + + + + + + + + Last scan 2026-09-29 07:12 · 14 min +
+
+
618,204photos
+
412sequences · 1,309 loose photos
+
9.4 TBoriginals · 610 GB proxies · 1.8 GB thumbnails
+
14cameras · 9 formats
+
2019 – 2026316 rendered · 84 never rendered · 12 not analysed
+
+
+
+
Photos per month021k
+ +
+
+ Storage by year + +
+
+ By camera + +
+
+ By format + +
+
+
+
+ Index health +
Sidecars 412 / 412 · database matches the disk
+
3 sequences without proxies
+
1 sequence not verified in 90 days
+
Database 214 MB · thumbnail pack 1.8 GB · 0 orphans · 0 duplicates
+
Network root reachable · SMB · 118 MB/s read
+
+
+
Recent maintenance
+
+ 2026-09-29Verify · running71 % + 2026-09-20Verify · 9.4 TB0 errors + 2026-09-01Vacuum · 231 → 214 MBdone + 2026-08-14Rebuild index · 412 sidecarsdone + 2026-08-02Backup · D:\Backups\titano-2026-08-02.dbdone +
+
+
+
+ Filtered set + + + + + + + + + + + +
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"1 job +
+
+
+
+ + diff --git a/docs/ui/mockups/Components.html b/docs/ui/mockups/Components.html new file mode 100644 index 00000000..7dfa392c --- /dev/null +++ b/docs/ui/mockups/Components.html @@ -0,0 +1,193 @@ + + + + +Titano — UI kit + + + +
+
+ COLOURS · CLIENT (DARK, DEFAULT) +
+
Bg #1F1F23
+
Chrome #1A1A1E
+
Surface #26262C
+
Card #2F3038
+
Stroke #3E404A
+
Text #F2F3F5
+
Muted #A9AEB9
+
Faint #7B818E
+
Accent #4CC2FF
+
On accent #0B1B24
+
Sun #F5A524
+
Success #35C48F
+
Warning #E8B339
+
Error #F0625D
+
+ Region teal #5AD1C8 only for sky/landscape masks · one accent per screen · never colour alone: pair with a shape or a word +
+
+ COLOURS · LIGHT THEME & WEB ADMIN +
+
Bg #F3F3F3
+
Card #FFFFFF
+
Stroke #E5E5E5
+
Text #1A1A1A
+
Muted #616161
+
Accent #0067C0
+
+ Selected nav #E8F1FA · sun #E08A1E · success #0F7B4F · warning #9A6700 · error #C42B1C +
+
+ TYPE · SPACING · RADII + Page title 18 / 600 + Sequence title 16 / 600 + Section 14 / 600 + Body and controls 13 / 400 + Secondary 12 / 400 muted + Chips and axis labels 11 / 400 +
+ + 4 · 8 · 12 · 16 · 20 px + + 6 control · 8 card · 12 pill +
+
+
+ BUTTONS · 32 PX · MIN WIDTH 44 +
+ + + +
+
+ + + + +
+
+ + +
+ Hover +6 % lightness · pressed −6 % · focus ring 2 px accent outside · every button has a tooltip +
+
+ INPUTS · SELECTION + +
+ + + +
+ +
+ + + + + +
+ Labels left of the control, 116 px column · placeholder never replaces a label · Enter commits, Esc reverts +
+
+ SLIDERS · AUTO / MANUAL +
+
+ +
+
+
0.80
+ +
+
Colour temperaturen/a
+ Accent track = Auto · sun track = manual · greyed with reason = not applicable · values edit on double-click +
+
+ STATUS · PROGRESS · TOOLTIP +
+ ● Analysed○ Not analysed● Proxies▶ 2 rendered● Synced● Remote◐ Analysing▲ 1 warning✕ 2 errors +
+
+ sunset ✕ + holy grail ✕ + Recommended +
+
Determinate 6 px · text to the right, never inside
+
Indeterminate: sliding highlight
+
+ +
Read every frame again and refresh the analysis · about 6 min · Ctrl+Shift+A
+
+ Tooltip: one line, action + cost + shortcut · shows after 400 ms · light on dark +
+
+ DIALOG · DESTRUCTIVE CONFIRM +
+ Format EOS R5 · card A? + 4,812 photos were copied and verified. Formatting removes everything on the card. + +
+ + +
+
+ Two buttons max · safe action left and default · destructive never primary · Esc = safe +
+
+ TOAST · JOB BAR · RAIL +
+ + EOS R5 · card A inserted4,812 photos · 96.2 GB · 3 sessions + + +
+
+
+ Building proxies · 1,240 / 3,600 · 3 min left + +
+
+
+ Library + Import + Jobs2 +
+ Rail 128 px, collapses to 48 px icons · active = card fill + 3 px accent edge · badge = count needing attention · toast bottom-right, 8 s, hover pauses +
+
+
+ EMPTY STATE · SEQUENCE CARD · TABLE ROW +
+
+ + No sequences yet +
+ + + +
+
+
+
+
3,600
+
Harbour sunsetCanon EOS R5 · 2 h 00 m
● Analysed● Proxies▶ 2
+
+ Selected card: accent border + glow · thumbnail is the first analysed keyframe, hover scrubs +
+
+
SequenceCameraFramesState
+
Harbour sunsetCanon EOS R53,600● ok
+
Comet over the ridgeGoPro HERO81,005▲ 1
+
Aurora, TromsøNikon Z 81,860● sync
+ Rows 36 px · hover = card fill · numbers right-aligned in real tables · sortable headers · virtualised past 200 rows +
+
+
+
+ + diff --git a/docs/ui/mockups/Editor.html b/docs/ui/mockups/Editor.html new file mode 100644 index 00000000..3e013a8f --- /dev/null +++ b/docs/ui/mockups/Editor.html @@ -0,0 +1,114 @@ + + + + +Titano — Sequence editor + + + +
+
+ + Titano — Harbour sunset + + —▢✕ +
+
+ +
+
+ ← + Harbour sunset + 3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings + + + + +
+
+
+
+
+
+
+
original | corrected
+
+ + + + + + +
+
0413 / 3,600 · 18:02:11 · 1/8 s · f/8 · ISO 400 · 24 mm
+
+
+
▼▼▼▼
+
+
+
+
+
+ + + + + + + +
+
+
— measured luminance— target curve- - sky region▼ exposure steps as receivedflicker −67 % · max step 0.21 EV
+ +
+
+ +
+
+
+
+ + diff --git a/docs/ui/mockups/Export.html b/docs/ui/mockups/Export.html new file mode 100644 index 00000000..16814484 --- /dev/null +++ b/docs/ui/mockups/Export.html @@ -0,0 +1,102 @@ + + + + +Titano — Sequence editor · Export + + + +
+
+ + Titano — Harbour sunset + + —▢✕ +
+
+ +
+
+ ← + Harbour sunset + 3,600 frames · 24 fps · 2 min 30 s · 3840×2160 source 8192×5464 + + + + +
+
+
+
+
+
+ + + +
+
0413 / 3,600 · 00:17.2 of 02:30 · output 3840×2160
+
+
+
+
+
+ + + + + + + +
+
+ + + + + + + + +
+
+ +
+
+
+
+ + diff --git a/docs/ui/mockups/Icon.html b/docs/ui/mockups/Icon.html new file mode 100644 index 00000000..b45593f5 --- /dev/null +++ b/docs/ui/mockups/Icon.html @@ -0,0 +1,80 @@ + + + + +Titano — Icon + + + +
+ + + + + + + + + + + + + + + + + + + + + + plate 256 · radius 56 · ring r 92 · stroke 20 · sun (152,104) r 30 + + 12 ticks of 12°, 18° gaps, round caps — a clock face and an intervalometer at once. + Opacity 0.14 → 1.0 clockwise from 12 o'clock: time accumulating, exposure ramping. + The sun sits off-centre, north-east, the way it does in every sunset shot. + Two colours only: accent #4CC2FF on plate #1A1A1E, sun #F5A524. No gradients, no text. + Generated by `Titano.Tools make-icon` into ICO (16–256), PNG, and the WPF DrawingImage. + + + ON DARK + + + + + + 12864483216 + + + ON LIGHT + + + + + + + VARIANTS + + + + Titano ServerTitano UploaderTray · monochrome · no plate + + WORDMARK · Segoe UI Variable Display Semibold, tracking −1 %, cap height aligned to the ring + + Titano + + Titano Server + + Titano Uploader + + Clear space around the mark: one tick length (40/256) on every side. Never rotate, recolour or add a drop shadow. + Badges only at 48 px and above; below that the Server and Uploader use the plain mark and their window title. + Installer, Store listing, GitHub social preview and the Unraid template icon all use the 256 px PNG. + + +
+ + diff --git a/docs/ui/mockups/Import.html b/docs/ui/mockups/Import.html new file mode 100644 index 00000000..3f1f14da --- /dev/null +++ b/docs/ui/mockups/Import.html @@ -0,0 +1,154 @@ + + + + +Titano — Import + + + +
+
+ + Titano — Import + + —▢✕ +
+
+ +
+
+
+ Ready · 0 jobs queued +
+
+ +
+
+ EOS R5 · card A + SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431 · last import 2026-09-21 + + + +
+
+ Destination +
+ + + + + + Studio NAS +
+ Scan +
+ + + gap min + min frames + +
+ Names +
+
+ + / + + +
+ → 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 +
+ On existing +
+ + + +
+ Convert +
+ + + + +
+ After import +
+ + + + + + +
+
+
+
+ Plan + 3 sessions · 4,812 photos · 96.2 GB · about 12 min + + 0 duplicates + 2.1 TB free after import +
+
+ SessionFrames · intervalSizeCameraSequence + 2026-09-28 · 18:02 → 20:043,600 · 2 s72.4 GBEOS R5new · 2026-09-28 Canon EOS R5 + 2026-09-27 · 05:41 → 06:571,140 · 4 s22.6 GBEOS R5new · 2026-09-27 Canon EOS R5 + 2026-09-26 · 21:10 → 23:3472 · 120 s1.2 GBEOS R5loose photos +
+ +
+ + + +
+
+
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"0 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Jobs.html b/docs/ui/mockups/Jobs.html new file mode 100644 index 00000000..9a391d65 --- /dev/null +++ b/docs/ui/mockups/Jobs.html @@ -0,0 +1,80 @@ + + + + +Titano — Jobs + + + +
+
+ + Titano — Jobs + + —▢✕ +
+
+ +
+
+
+ Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left + +
+
+ + + + + + + + + + Workers 4 / 4 · GPU NVENC busy + + +
+
+
KindTargetProgressSpeedLeftWhereState
+
RenderHarbour sunset → 4K 10-bit HEVC · 24 fps
62 %
11.3 fps2 minthis PC · NVENCrunning
+
+
10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames
+
10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %
+
10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48
+
10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget
+
+
Deep analysisConstruction cam · week 38
28 %
41 fps6 minthis PCrunning
+
UploadComet over the ridge → Studio NAS
46 %
38 MB/s4 minnetworkrunning
+
ProxiesComet over the ridge
91 %
118 fps8 sthis PCrunning
+
RenderAurora, Tromsø → 1080p share H.264
—
—after 1this PCqueued
+
VerifyArchive · 2024
—
—after 2this PCqueued
+
VerifyStar trails, Colle del Nivolet
100 %
—09:58this PCfailed · 2
+
RenderMilan skyline dusk → 4K HEVC
100 %
14.8 fps09:12studio-pcdone · 2:41
+
ImportEOS R5 · card A → Archive · 4,812 photos
100 %
410 MB/s08:41this PCdone · 11:52
+
Thumbnails2026-09-27 Sony ILCE-7M4
100 %
2,300 fps08:42this PCdone · 0:01
+ +
History keeps 90 days · 1,412 jobsFailed jobs retry automatically 3× with backoff, then wait for youRendering settings
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"4 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Main.html b/docs/ui/mockups/Main.html new file mode 100644 index 00000000..ba11bd8a --- /dev/null +++ b/docs/ui/mockups/Main.html @@ -0,0 +1,101 @@ + + + + +Titano — Library + + + +
+
+ + Titano + + —▢✕ +
+
+ +
+
+
+ Building proxies · Harbour sunset · 1,240 / 3,600 · 12 fps · 3 min left + +
+
+ + + + + + + + + + + + +
+
+
+
+
Harbour sunset3,600 · Canon EOS R5 · 2 h 00 m
● Analysed● Proxies▶ 2● Synced
+
+
+
+
Comet over the ridge1,005 · GoPro HERO8 · 5 h 34 m
● Analysed● Proxies▲ 1
+
+
+
+
2026-09-27 Sony ILCE-7M42,140 · Sony A7 IV · 1 h 11 m
● Analysed○ Proxies
+
+
+
+
Aurora, Tromsø1,860 · Nikon Z 8 · 4 h 08 m
● Analysed● Proxies● Synced
+
+
+
+
Construction cam · week 388,920 · Brinno · 7 d
◐ Analysing● Remote
+
+
+
+
Milan skyline dusk2,400 · iPhone 16 Pro · 1 h 20 m
● Analysed● Proxies▶ 1
+
+
+
+
Clouds over the Langhe1,320 · Canon EOS R5 · 44 m
○ Analysed○ Proxies
+
+
+
+
Star trails, Colle del Nivolet640 · Sony A7 IV · 5 h 20 m
● Analysed● Proxies▶ 3
+
+
+
+
Fog lifting, Asti980 · DJI Osmo Action 5 · 1 h 38 m
● Analysed○ Proxies
+
+
+
+
Holy grail · Monviso1,720 · Nikon Z 8 · 3 h 02 m
● Analysed● Proxies▶ 1● Synced
+
+
+
+ 412 sequences618,204 photos9.4 TBConnected to "Studio NAS"3 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Server.html b/docs/ui/mockups/Server.html new file mode 100644 index 00000000..f865587e --- /dev/null +++ b/docs/ui/mockups/Server.html @@ -0,0 +1,112 @@ + + + + +Titano — Server + + + +
+
+ + Titano — Server + + —▢✕ +
+
+ +
+
+
+ Upload · Comet over the ridge · 46 % · 38 MB/s · 4 min left + +
+
+
+
+
+ + + + +
+
+ Status + Connected + ·Studio NAS · v1.3.0 · 14 ms + ·TLS 9A:3C:71:E0:… trusted 2026-09-01 + +
+
+ Account + A + alberto·Editor· +
2.1 TB of 5 TB + + + +
+
+ + NVENC HEVC · H.264 · AV1 + + + +
+
+
+
Render nodeBusy
+ Rendering Harbour sunset → 4K 10-bit HEVC for the server · 62 % · 11.3 fps +
+
Today3 jobs · 41 min GPU timeQueue1 waiting on the serverAvailabilitywhen idle for 2 min · never on battery
+ +
Node settings
+
+
+
+
+ Sequences + + + + + + + + +
+
SequenceThis PCServerState
+
Holy grail · Monvisooriginals · proxiesoriginals · proxies▲ settings differ
+
Harbour sunsetoriginals · proxiesoriginals · proxies● in sync
rendering on this PC as a node
+
Comet over the ridgeoriginals · proxies46 % received● uploading
+
Clouds over the Langheoriginals—local only
+
Construction cam · week 38proxiesoriginals · proxies● remote
+
Aurora, Tromsøoriginals · proxiesoriginals · proxies● in sync
+
Star trails, Colle del Nivoletoriginals · proxiesoriginals · proxies · 3 exports● in sync
+
Milan skyline dusk—originals · proxies · 1 export● remote
+ +
Last sync 10:15 · manifest diff 0.4 sServer archive 9.4 TB · 412 sequences · 6 usersOpen admin panel
+
+
+
+ 418 sequences640,118 photos9.4 TBConnected to "Studio NAS"2 jobs +
+
+
+
+ + diff --git a/docs/ui/mockups/Settings.html b/docs/ui/mockups/Settings.html new file mode 100644 index 00000000..6991a8d5 --- /dev/null +++ b/docs/ui/mockups/Settings.html @@ -0,0 +1,83 @@ + + + + +Titano — Settings + + + +
+
+ + Titano — Settings + + —▢✕ +
+
+ +
+
+ + + General + Archive + Import + Analysis + Rendering + Formats + Server + Updates + Licence + Advanced + + + +
+
+
RenderingChanges apply to the next job
+
+ Quality profile +
Best · Balanced · Fast
+ +
8 GBof 32 GB installed
+ Cache folder +
1.4 GB used · SSD · 612 GB free
+ Parallelism +
of 16 logical cores
+ Hardware encoding +
+
+
+
Encoders on this PCNVIDIA GeForce RTX 4070 · driver 560.94 · Media Foundation 10.0.26100
+
+
CodecEncoder10-bitMaxSelf-testUsed for
+
HEVCNVIDIA NVENC (hardware)Main108192×8192✓ 142 fps · ok4K archive · 4K HEVC · 1440p · cinema
+
H.264NVIDIA NVENC (hardware)—4096×4096✓ 188 fps · ok1080p share · social · square · 720p
+
AV1NVIDIA NVENC (hardware)10-bit8192×8192✓ 96 fps · oknot in any preset · available in Custom
+
H.264Microsoft (software)—4096×2304✓ 21 fps · okfallback for every H.264 preset
+
MJPEG · AVITitano (built in)—no limit✓ 64 fps · oklossless-ish intermediate
+
GIF · APNGTitano (built in)—1080p✓ okpreviews, social loops
+
+ Intel QSV and AMD AMF appear here on PCs that have them. HEVC and AV1 exist only as hardware encoders: without one, those presets fall back to H.264 and say so in the preset list. +
+
+
+
+
+
+ + diff --git a/docs/ui/mockups/Uploader.html b/docs/ui/mockups/Uploader.html new file mode 100644 index 00000000..653dc74e --- /dev/null +++ b/docs/ui/mockups/Uploader.html @@ -0,0 +1,70 @@ + + + + +Titano Uploader + + + +
+
+ + Titano Uploader + + —✕ +
+
+ + https://nas.local:8443 + · + alberto + · + Connected + + 1.9 TB free of 5 TB + +
+
+
+ + Drop photos, folders or a card here + +
+
+ Target + + + + +
+
+ Queue + 4,812 files · 96.2 GB · 38 MB/s · 41 min left + + + + Limit MB/s +
+
+
+
2026-09-28_18-02-11_0413.CR22,214 of 4,812 sent · 2,201 verified by the server · 0 retries
+
+
+ Watch folders + D:\Cam\Roof · every 60 s + \\garage-pi\cam · every 5 min + +
+ +
+ + + +
+
+
+ + diff --git a/docs/ui/mockups/Welcome.html b/docs/ui/mockups/Welcome.html new file mode 100644 index 00000000..83c9d379 --- /dev/null +++ b/docs/ui/mockups/Welcome.html @@ -0,0 +1,81 @@ + + + + +Titano — First run + + + +
+
+ + Titano + + —▢✕ +
+
+ +
+
Ready
+
+ + Year ▾ + Camera ▾ + Status ▾ +
+
No sequences yet
+
0 sequences0 photosNo archiveNot connected
+
+
+
+
+
+ + Welcome to TitanoWhere should your time-lapses live? + +
+
+ + + +
+
+ + + +
+
+
+ + New card inserted · SD 128 GBCanon EOS R5 · 4,812 photos · not yet known to Titano + + +
+
+ + diff --git a/global.json b/global.json new file mode 100644 index 00000000..d46d21e5 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx new file mode 100644 index 00000000..dd4fb457 --- /dev/null +++ b/i18n/en/Shell.resx @@ -0,0 +1,10 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Titano + {0:N0} photo + {0:N0} photos + diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx new file mode 100644 index 00000000..7d948680 --- /dev/null +++ b/i18n/it/Shell.it.resx @@ -0,0 +1,9 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0:N0} foto + {0:N0} foto + diff --git a/src/Titano.App/App.xaml b/src/Titano.App/App.xaml new file mode 100644 index 00000000..fa7e5103 --- /dev/null +++ b/src/Titano.App/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs new file mode 100644 index 00000000..83019998 --- /dev/null +++ b/src/Titano.App/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.App; + +public partial class App : Application +{ +} diff --git a/src/Titano.App/Titano.App.csproj b/src/Titano.App/Titano.App.csproj new file mode 100644 index 00000000..5b3bf883 --- /dev/null +++ b/src/Titano.App/Titano.App.csproj @@ -0,0 +1,21 @@ + + + WinExe + net10.0-windows + true + Titano.App + Titano + app.manifest + titano + + + + + + + + + + + + diff --git a/src/Titano.App/app.manifest b/src/Titano.App/app.manifest new file mode 100644 index 00000000..aa6ecd8b --- /dev/null +++ b/src/Titano.App/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/src/Titano.Core.Windows/Titano.Core.Windows.csproj b/src/Titano.Core.Windows/Titano.Core.Windows.csproj new file mode 100644 index 00000000..a70192ff --- /dev/null +++ b/src/Titano.Core.Windows/Titano.Core.Windows.csproj @@ -0,0 +1,13 @@ + + + net10.0-windows + Titano.Core.Windows + + + + + + + + + diff --git a/src/Titano.Core.Windows/WindowsPlatform.cs b/src/Titano.Core.Windows/WindowsPlatform.cs new file mode 100644 index 00000000..c7dcd4a1 --- /dev/null +++ b/src/Titano.Core.Windows/WindowsPlatform.cs @@ -0,0 +1,7 @@ +namespace Titano.Core.Windows; + +/// Windows-only providers (WIC, Media Foundation, DXGI, devices). +public static class WindowsPlatform +{ + public static bool IsSupported => OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17763); +} diff --git a/src/Titano.Core/Branding/BrandMark.cs b/src/Titano.Core/Branding/BrandMark.cs new file mode 100644 index 00000000..f7a15f02 --- /dev/null +++ b/src/Titano.Core/Branding/BrandMark.cs @@ -0,0 +1,204 @@ +namespace Titano.Core.Branding; + +public enum BrandVariant +{ + /// Titano desktop client: plate, ring, sun. + App, + + /// Titano Server: App mark plus the three-bar rack badge (≥ 48 px). + Server, + + /// Titano Uploader: App mark plus the up-arrow badge (≥ 48 px). + Uploader, + + /// White mark without plate, for the tray. + Mono, +} + +/// +/// The time-lapse aperture-clock mark (BRIEF §17, DESIGN §6), defined as geometry on a 256-unit canvas +/// and rasterised with analytic anti-aliasing from signed distance fields. Single source of truth for +/// the ICO/PNG sets, the admin favicon and the WPF DrawingImage. +/// +public static class BrandMark +{ + public const double Canvas = 256; + public const double PlateRadius = 56; + public const double RingRadius = 92; + public const double StrokeWidth = 20; + public const int TickCount = 12; + public const double TickSweepDegrees = 12; + public const double TickPitchDegrees = 30; + public const double FirstTickStartDegrees = 9; + public const double SunX = 152, SunY = 104, SunRadius = 30; + + public static readonly Rgb Plate = new(0x1A, 0x1A, 0x1E); + public static readonly Rgb Accent = new(0x4C, 0xC2, 0xFF); + public static readonly Rgb Sun = new(0xF5, 0xA5, 0x24); + public static readonly Rgb White = new(0xFF, 0xFF, 0xFF); + + /// Opacity of tick (0 = first clockwise from 12 o'clock). + public static double TickOpacity(int i) => Math.Round(0.14 + (1.0 - 0.14) * i / (TickCount - 1), 2); + + /// Start and end angle of tick in degrees, clockwise from 12 o'clock. + public static (double Start, double End) TickAngles(int i) + { + var start = FirstTickStartDegrees + i * TickPitchDegrees; + return (start, start + TickSweepDegrees); + } + + /// Renders the mark as straight-alpha RGBA8 (row-major, top-down). + public static byte[] Render(BrandVariant variant, int size) + { + ArgumentOutOfRangeException.ThrowIfLessThan(size, 8); + var scale = size / Canvas; + // Below 32 px the stroke would vanish; keep it at least ~1.3 px wide. + var stroke = Math.Max(StrokeWidth, 1.3 / scale); + var badge = size >= 48 && variant is BrandVariant.Server or BrandVariant.Uploader; + var ringColor = variant == BrandVariant.Mono ? White : Accent; + var sunColor = variant == BrandVariant.Mono ? White : Sun; + + var pixels = new byte[size * size * 4]; + var px = 1.0 / scale; // one pixel in canvas units + for (var y = 0; y < size; y++) + { + for (var x = 0; x < size; x++) + { + var cx = (x + 0.5) * px; + var cy = (y + 0.5) * px; + var c = new Rgba(0, 0, 0, 0); + + if (variant != BrandVariant.Mono) + c = Over(c, Plate, Coverage(RoundedBox(cx, cy, 0, 0, Canvas, Canvas, PlateRadius), px)); + + for (var i = 0; i < TickCount; i++) + { + var (a0, a1) = TickAngles(i); + var d = ArcStroke(cx, cy, 128, 128, RingRadius, a0, a1, stroke); + if (d < px) c = Over(c, ringColor, Coverage(d, px) * TickOpacity(i)); + } + + c = Over(c, sunColor, Coverage(Circle(cx, cy, SunX, SunY, SunRadius), px)); + + if (badge) + { + var badgeColor = variant == BrandVariant.Server ? Accent : Sun; + // Badge disc in plate colour with a 6-unit outline. + c = Over(c, Plate, Coverage(Circle(cx, cy, 204, 204, 43), px)); + c = Over(c, badgeColor, Coverage(Math.Abs(Circle(cx, cy, 204, 204, 40)) - 3, px)); + if (variant == BrandVariant.Server) + { + c = Over(c, badgeColor, Coverage(RoundedBox(cx, cy, 185, 188, 38, 12, 4), px)); + c = Over(c, badgeColor, Coverage(RoundedBox(cx, cy, 185, 208, 38, 12, 4), px)); + } + else + { + var arrow = Math.Min( + Segment(cx, cy, 204, 226, 204, 186), + Math.Min(Segment(cx, cy, 188, 202, 204, 186), Segment(cx, cy, 204, 186, 220, 202))) - 4; + c = Over(c, badgeColor, Coverage(arrow, px)); + } + } + + var o = (y * size + x) * 4; + pixels[o] = ToByte(c.R); + pixels[o + 1] = ToByte(c.G); + pixels[o + 2] = ToByte(c.B); + pixels[o + 3] = ToByte(c.A); + } + } + return pixels; + } + + /// The master SVG for a variant (identical geometry to ). + public static string ToSvg(BrandVariant variant) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + var sb = new System.Text.StringBuilder(); + sb.Append("\n"); + var ring = variant == BrandVariant.Mono ? "#ffffff" : Accent.Hex; + if (variant != BrandVariant.Mono) sb.Append("\n"); + for (var i = 0; i < TickCount; i++) + { + var (a0, a1) = TickAngles(i); + var (x0, y0) = Polar(a0); + var (x1, y1) = Polar(a1); + sb.Append(inv, $"\n"); + } + sb.Append("\n"); + if (variant == BrandVariant.Server) + sb.Append("\n"); + if (variant == BrandVariant.Uploader) + sb.Append("\n"); + sb.Append("\n"); + return sb.ToString(); + } + + /// Point on the ring at clockwise from 12 o'clock. + public static (double X, double Y) Polar(double degrees, double radius = RingRadius) + { + var a = degrees * Math.PI / 180; + return (128 + radius * Math.Sin(a), 128 - radius * Math.Cos(a)); + } + + private static double Coverage(double signedDistance, double pixel) => Math.Clamp(0.5 - signedDistance / pixel, 0, 1); + + private static double Circle(double x, double y, double cx, double cy, double r) => Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) - r; + + private static double RoundedBox(double x, double y, double left, double top, double w, double h, double r) + { + var hx = w / 2 - r; + var hy = h / 2 - r; + var qx = Math.Abs(x - (left + w / 2)) - hx; + var qy = Math.Abs(y - (top + h / 2)) - hy; + var outside = Math.Sqrt(Math.Max(qx, 0) * Math.Max(qx, 0) + Math.Max(qy, 0) * Math.Max(qy, 0)); + return outside + Math.Min(Math.Max(qx, qy), 0) - r; + } + + private static double Segment(double x, double y, double ax, double ay, double bx, double by) + { + double px = x - ax, py = y - ay, dx = bx - ax, dy = by - ay; + var t = Math.Clamp((px * dx + py * dy) / (dx * dx + dy * dy), 0, 1); + var ex = px - dx * t; + var ey = py - dy * t; + return Math.Sqrt(ex * ex + ey * ey); + } + + private static double ArcStroke(double x, double y, double cx, double cy, double r, double startDeg, double endDeg, double width) + { + var dx = x - cx; + var dy = y - cy; + var angle = Math.Atan2(dx, -dy) * 180 / Math.PI; + if (angle < 0) angle += 360; + double d; + if (angle >= startDeg && angle <= endDeg) + { + d = Math.Abs(Math.Sqrt(dx * dx + dy * dy) - r); + } + else + { + var (sx, sy) = Polar(startDeg, r); + var (ex, ey) = Polar(endDeg, r); + d = Math.Min(Math.Sqrt((x - sx) * (x - sx) + (y - sy) * (y - sy)), Math.Sqrt((x - ex) * (x - ex) + (y - ey) * (y - ey))); + } + return d - width / 2; + } + + private static Rgba Over(Rgba dst, Rgb src, double alpha) + { + if (alpha <= 0) return dst; + var a = alpha + dst.A * (1 - alpha); + if (a <= 0) return new Rgba(0, 0, 0, 0); + double Mix(double s, double d) => (s * alpha + d * dst.A * (1 - alpha)) / a; + return new Rgba(Mix(src.R / 255.0, dst.R), Mix(src.G / 255.0, dst.G), Mix(src.B / 255.0, dst.B), a); + } + + private static byte ToByte(double v) => (byte)Math.Clamp((int)Math.Round(v * 255), 0, 255); + + private readonly record struct Rgba(double R, double G, double B, double A); + + public readonly record struct Rgb(byte R, byte G, byte B) + { + public string Hex => $"#{R:x2}{G:x2}{B:x2}"; + } +} diff --git a/src/Titano.Core/Codecs/Ico/IcoWriter.cs b/src/Titano.Core/Codecs/Ico/IcoWriter.cs new file mode 100644 index 00000000..e0586938 --- /dev/null +++ b/src/Titano.Core/Codecs/Ico/IcoWriter.cs @@ -0,0 +1,78 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Png; + +namespace Titano.Core.Codecs.Ico; + +/// +/// Writes Windows ICO files. Sizes ≥ 64 px are stored as PNG; smaller sizes as 32-bit DIBs with an AND +/// mask, which every shell version renders crisply. +/// +public static class IcoWriter +{ + /// Straight-alpha RGBA8 square images keyed by size. + public static byte[] Write(IReadOnlyList<(int Size, byte[] Rgba)> images) + { + var payloads = images.Select(i => i.Size >= 64 + ? PngEncoder.Encode(i.Rgba, i.Size, i.Size, PngColorType.Rgba) + : Dib(i.Rgba, i.Size)).ToList(); + + using var ms = new MemoryStream(); + Span header = stackalloc byte[6]; + BinaryPrimitives.WriteUInt16LittleEndian(header, 0); + BinaryPrimitives.WriteUInt16LittleEndian(header[2..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(header[4..], (ushort)images.Count); + ms.Write(header); + + var offset = 6 + 16 * images.Count; + Span entry = stackalloc byte[16]; + for (var i = 0; i < images.Count; i++) + { + var size = images[i].Size; + entry.Clear(); + entry[0] = (byte)(size >= 256 ? 0 : size); + entry[1] = (byte)(size >= 256 ? 0 : size); + BinaryPrimitives.WriteUInt16LittleEndian(entry[4..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(entry[6..], 32); + BinaryPrimitives.WriteInt32LittleEndian(entry[8..], payloads[i].Length); + BinaryPrimitives.WriteInt32LittleEndian(entry[12..], offset); + ms.Write(entry); + offset += payloads[i].Length; + } + foreach (var p in payloads) ms.Write(p); + return ms.ToArray(); + } + + private static byte[] Dib(byte[] rgba, int size) + { + var maskStride = ((size + 31) / 32) * 4; + var data = new byte[40 + size * size * 4 + maskStride * size]; + var span = data.AsSpan(); + BinaryPrimitives.WriteInt32LittleEndian(span, 40); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[8..], size * 2); // XOR + AND masks + BinaryPrimitives.WriteUInt16LittleEndian(span[12..], 1); + BinaryPrimitives.WriteUInt16LittleEndian(span[14..], 32); + BinaryPrimitives.WriteInt32LittleEndian(span[20..], size * size * 4); + var o = 40; + for (var y = size - 1; y >= 0; y--) + { + for (var x = 0; x < size; x++) + { + var s = (y * size + x) * 4; + data[o++] = rgba[s + 2]; + data[o++] = rgba[s + 1]; + data[o++] = rgba[s]; + data[o++] = rgba[s + 3]; + } + } + for (var y = size - 1; y >= 0; y--) + { + for (var x = 0; x < size; x++) + { + if (rgba[(y * size + x) * 4 + 3] == 0) data[o + (x >> 3)] |= (byte)(0x80 >> (x & 7)); + } + o += maskStride; + } + return data; + } +} diff --git a/src/Titano.Core/Codecs/Png/PngEncoder.cs b/src/Titano.Core/Codecs/Png/PngEncoder.cs new file mode 100644 index 00000000..6c9273fc --- /dev/null +++ b/src/Titano.Core/Codecs/Png/PngEncoder.cs @@ -0,0 +1,133 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Hashing; + +namespace Titano.Core.Codecs.Png; + +/// PNG colour types written by . +public enum PngColorType : byte +{ + Gray = 0, + Rgb = 2, + GrayAlpha = 4, + Rgba = 6, +} + +/// PNG encoder (8/16-bit, gray/RGB with or without alpha), adaptive filtering, zlib via the BCL. +public static class PngEncoder +{ + private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + /// Encodes interleaved pixels. 16-bit samples are big-endian in . + public static byte[] Encode(ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize) + { + using var ms = new MemoryStream(); + Encode(ms, pixels, width, height, colorType, bitDepth, level); + return ms.ToArray(); + } + + public static void Encode(Stream output, ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null) + { + if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth)); + var channels = colorType switch + { + PngColorType.Gray => 1, + PngColorType.GrayAlpha => 2, + PngColorType.Rgb => 3, + _ => 4, + }; + var bpp = channels * bitDepth / 8; + var stride = width * bpp; + if (pixels.Length < stride * height) throw new ArgumentException("Pixel buffer too small", nameof(pixels)); + + output.Write(Signature); + Span ihdr = stackalloc byte[13]; + BinaryPrimitives.WriteInt32BigEndian(ihdr, width); + BinaryPrimitives.WriteInt32BigEndian(ihdr[4..], height); + ihdr[8] = (byte)bitDepth; + ihdr[9] = (byte)colorType; + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + WriteChunk(output, "IHDR", ihdr); + + if (extraChunks is not null) + { + foreach (var (type, data) in extraChunks) WriteChunk(output, type, data); + } + + WriteChunk(output, "IDAT", Compress(pixels, height, stride, bpp, level)); + WriteChunk(output, "IEND", []); + } + + /// Filters every row (adaptive, minimum sum of absolute differences) and deflates the result. + public static byte[] Compress(ReadOnlySpan pixels, int height, int stride, int bpp, CompressionLevel level) + { + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, level, leaveOpen: true)) + { + var filtered = new byte[stride + 1]; + var best = new byte[stride + 1]; + for (var y = 0; y < height; y++) + { + var row = pixels.Slice(y * stride, stride); + var prev = y > 0 ? pixels.Slice((y - 1) * stride, stride) : default; + var bestScore = long.MaxValue; + for (byte f = 0; f <= 4; f++) + { + filtered[0] = f; + long score = 0; + for (var i = 0; i < stride; i++) + { + int a = i >= bpp ? row[i - bpp] : 0; + int b = y > 0 ? prev[i] : 0; + int c = i >= bpp && y > 0 ? prev[i - bpp] : 0; + var v = f switch + { + 0 => row[i], + 1 => row[i] - a, + 2 => row[i] - b, + 3 => row[i] - ((a + b) >> 1), + _ => row[i] - Paeth(a, b, c), + }; + var bv = (byte)v; + filtered[i + 1] = bv; + score += bv < 128 ? bv : 256 - bv; + } + if (score < bestScore) + { + bestScore = score; + filtered.CopyTo(best, 0); + } + } + z.Write(best); + } + } + return ms.ToArray(); + } + + public static void WriteChunk(Stream output, string type, ReadOnlySpan data) + { + Span header = stackalloc byte[8]; + BinaryPrimitives.WriteInt32BigEndian(header, data.Length); + for (var i = 0; i < 4; i++) header[4 + i] = (byte)type[i]; + output.Write(header); + output.Write(data); + var crc = new Crc32(); + crc.Append(header[4..]); + crc.Append(data); + Span trailer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(trailer, crc.GetCurrentHashAsUInt32()); + output.Write(trailer); + } + + internal static int Paeth(int a, int b, int c) + { + var p = a + b - c; + var pa = Math.Abs(p - a); + var pb = Math.Abs(p - b); + var pc = Math.Abs(p - c); + if (pa <= pb && pa <= pc) return a; + return pb <= pc ? b : c; + } +} diff --git a/src/Titano.Core/Diagnostics/Log.cs b/src/Titano.Core/Diagnostics/Log.cs new file mode 100644 index 00000000..0aa6da57 --- /dev/null +++ b/src/Titano.Core/Diagnostics/Log.cs @@ -0,0 +1,116 @@ +using System.Globalization; + +namespace Titano.Core.Diagnostics; + +public enum LogLevel +{ + Trace, + Debug, + Info, + Warning, + Error, +} + +/// Destination for engine log events (file logger on desktop, ILogger bridge on the server). +public interface ILogSink +{ + void Write(LogLevel level, string category, string message, Exception? exception); +} + +/// Tiny engine-wide logger. Core code logs through it; hosts plug in a sink. +public static class Log +{ + private static ILogSink _sink = new ConsoleSink(); + + public static LogLevel MinimumLevel { get; set; } = LogLevel.Info; + + public static void SetSink(ILogSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + + public static void Debug(string category, string message) => Write(LogLevel.Debug, category, message, null); + public static void Info(string category, string message) => Write(LogLevel.Info, category, message, null); + public static void Warning(string category, string message, Exception? ex = null) => Write(LogLevel.Warning, category, message, ex); + public static void Error(string category, string message, Exception? ex = null) => Write(LogLevel.Error, category, message, ex); + + public static void Write(LogLevel level, string category, string message, Exception? exception) + { + if (level < MinimumLevel) return; + try + { + _sink.Write(level, category, message, exception); + } + catch (IOException) + { + // Logging must never take the process down. + } + } + + private sealed class ConsoleSink : ILogSink + { + public void Write(LogLevel level, string category, string message, Exception? exception) + { + var line = string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}"); + if (exception is not null) line += Environment.NewLine + exception; + Console.Error.WriteLine(line); + } + } +} + +/// Appends log lines to rotating files (one per day, kept for retainDays). +public sealed class FileLogSink : ILogSink, IDisposable +{ + private readonly string _directory; + private readonly string _prefix; + private readonly int _retainDays; + private readonly Lock _gate = new(); + private StreamWriter? _writer; + private DateOnly _day; + + public FileLogSink(string directory, string prefix, int retainDays = 14) + { + _directory = directory; + _prefix = prefix; + _retainDays = retainDays; + Directory.CreateDirectory(directory); + } + + public string CurrentPath => Path.Combine(_directory, $"{_prefix}-{_day:yyyyMMdd}.log"); + + public void Write(LogLevel level, string category, string message, Exception? exception) + { + lock (_gate) + { + var today = DateOnly.FromDateTime(DateTime.UtcNow); + if (_writer is null || today != _day) + { + _writer?.Dispose(); + _day = today; + _writer = new StreamWriter(new FileStream(CurrentPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { AutoFlush = true }; + Prune(); + } + _writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}")); + if (exception is not null) _writer.WriteLine(exception.ToString()); + } + } + + private void Prune() + { + foreach (var file in Directory.EnumerateFiles(_directory, _prefix + "-*.log")) + { + if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddDays(-_retainDays)) + { + try + { + File.Delete(file); + } + catch (IOException) + { + } + } + } + } + + public void Dispose() + { + lock (_gate) _writer?.Dispose(); + } +} diff --git a/src/Titano.Core/Hashing/Crc32.cs b/src/Titano.Core/Hashing/Crc32.cs new file mode 100644 index 00000000..65504080 --- /dev/null +++ b/src/Titano.Core/Hashing/Crc32.cs @@ -0,0 +1,47 @@ +namespace Titano.Core.Hashing; + +/// CRC-32 (IEEE 802.3, reflected 0xEDB88320) as used by PNG, ZIP and gzip. Slicing-by-8. +public sealed class Crc32 +{ + private static readonly uint[] Table = BuildTable(); + private uint _crc = 0xFFFFFFFFu; + + public void Append(ReadOnlySpan data) => _crc = Update(_crc, data); + + public uint GetCurrentHashAsUInt32() => ~_crc; + + public void Reset() => _crc = 0xFFFFFFFFu; + + public static uint Compute(ReadOnlySpan data) => ~Update(0xFFFFFFFFu, data); + + private static uint Update(uint crc, ReadOnlySpan data) + { + var t = Table; + var i = 0; + for (; i + 8 <= data.Length; i += 8) + { + var one = (uint)(data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24) ^ crc; + var two = (uint)(data[i + 4] | data[i + 5] << 8 | data[i + 6] << 16 | data[i + 7] << 24); + crc = t[7 * 256 + (one & 0xFF)] ^ t[6 * 256 + ((one >> 8) & 0xFF)] ^ t[5 * 256 + ((one >> 16) & 0xFF)] ^ t[4 * 256 + (one >> 24)] + ^ t[3 * 256 + (two & 0xFF)] ^ t[2 * 256 + ((two >> 8) & 0xFF)] ^ t[256 + ((two >> 16) & 0xFF)] ^ t[two >> 24]; + } + for (; i < data.Length; i++) crc = t[(crc ^ data[i]) & 0xFF] ^ (crc >> 8); + return crc; + } + + private static uint[] BuildTable() + { + var t = new uint[8 * 256]; + for (uint n = 0; n < 256; n++) + { + var c = n; + for (var k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1; + t[n] = c; + } + for (var s = 1; s < 8; s++) + { + for (var n = 0; n < 256; n++) t[s * 256 + n] = t[(s - 1) * 256 + n] >> 8 ^ t[t[(s - 1) * 256 + n] & 0xFF]; + } + return t; + } +} diff --git a/src/Titano.Core/IO/AtomicFile.cs b/src/Titano.Core/IO/AtomicFile.cs new file mode 100644 index 00000000..ed8e7b8b --- /dev/null +++ b/src/Titano.Core/IO/AtomicFile.cs @@ -0,0 +1,81 @@ +using System.Text; + +namespace Titano.Core.IO; + +/// +/// Crash-safe writes: content goes to a temporary sibling, is flushed to disk, then renamed over the +/// target (BRIEF §7 "temp → fsync → rename"). +/// +public static class AtomicFile +{ + public static void WriteAllBytes(string path, ReadOnlySpan content) + { + var temp = TempPathFor(path); + try + { + using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.WriteThrough)) + { + fs.Write(content); + fs.Flush(flushToDisk: true); + } + File.Move(temp, path, overwrite: true); + } + catch + { + TryDelete(temp); + throw; + } + } + + public static void WriteAllText(string path, string content) => WriteAllBytes(path, new UTF8Encoding(false).GetBytes(content)); + + /// Streams content produced by and commits it atomically. + public static async Task WriteAsync(string path, Func write, CancellationToken cancellationToken = default) + { + var temp = TempPathFor(path); + try + { + await using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous)) + { + await write(fs, cancellationToken).ConfigureAwait(false); + await fs.FlushAsync(cancellationToken).ConfigureAwait(false); + fs.Flush(flushToDisk: true); + } + File.Move(temp, path, overwrite: true); + } + catch + { + TryDelete(temp); + throw; + } + } + + /// Commits an already-written temporary file over after flushing it. + public static void Commit(string tempPath, string path) + { + using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + fs.Flush(flushToDisk: true); + File.Move(tempPath, path, overwrite: true); + } + + public static string TempPathFor(string path) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? "."; + Directory.CreateDirectory(dir); + return Path.Combine(dir, "." + Path.GetFileName(path) + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp"); + } + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) File.Delete(path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} diff --git a/src/Titano.Core/IO/LongPath.cs b/src/Titano.Core/IO/LongPath.cs new file mode 100644 index 00000000..8d3cbb5b --- /dev/null +++ b/src/Titano.Core/IO/LongPath.cs @@ -0,0 +1,23 @@ +namespace Titano.Core.IO; + +/// Helpers for UNC and long paths on Windows network archives (BRIEF §7). +public static class LongPath +{ + /// Adds the \\?\ prefix on Windows when a path exceeds MAX_PATH. + public static string Normalize(string path) + { + if (!OperatingSystem.IsWindows()) return path; + var full = Path.GetFullPath(path); + if (full.Length < 248 || full.StartsWith(@"\\?\", StringComparison.Ordinal)) return full; + return full.StartsWith(@"\\", StringComparison.Ordinal) + ? @"\\?\UNC\" + full[2..] + : @"\\?\" + full; + } + + /// Relative path with forward slashes, as stored in sidecars and the database. + public static string ToPortableRelative(string root, string path) => + Path.GetRelativePath(root, path).Replace('\\', '/'); + + public static string FromPortableRelative(string root, string relative) => + Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); +} diff --git a/src/Titano.Core/Imaging/Decoding.cs b/src/Titano.Core/Imaging/Decoding.cs new file mode 100644 index 00000000..98f5f519 --- /dev/null +++ b/src/Titano.Core/Imaging/Decoding.cs @@ -0,0 +1,112 @@ +namespace Titano.Core.Imaging; + +/// How a frame's pixels were obtained (BRIEF §8.2). Logged per frame. +public enum DecodeTier +{ + /// Full-resolution decode of the main image (in-house or WIC). + Native = 1, + + /// Largest embedded JPEG preview; output resolution is capped to its size. + EmbeddedPreview = 2, + + /// No decoder could produce pixels; the frame is excluded from renders. + Unavailable = 3, +} + +public enum DecodePurpose +{ + Thumbnail, + Analysis, + Proxy, + Render, +} + +/// A request to decode one file. +/// Absolute path of the source file. +/// Maximum long edge of the result in pixels; 0 = native size. +/// Lets providers trade quality for speed (e.g. bilinear demosaic for thumbnails). +/// Rotate/flip according to the Exif orientation. +/// Accept the embedded-preview tier when native decode is impossible. +/// Use the embedded preview even when native decode is possible (fast paths). +public sealed record DecodeRequest( + string Path, + int MaxLongEdge = 0, + DecodePurpose Purpose = DecodePurpose.Render, + bool ApplyOrientation = true, + bool AllowPreview = true, + bool ForcePreview = false); + +/// Decoded pixels plus how they were produced. Dispose to return the buffer to the pool. +public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string decoder, int sourceWidth, int sourceHeight) : IDisposable +{ + public ImageBuffer Pixels { get; } = pixels; + public DecodeTier Tier { get; } = tier; + + /// Short provider/decoder name for logs ("wic", "managed-jpeg", "managed-dng"). + public string Decoder { get; } = decoder; + + /// Dimensions of the full-resolution source (before scaling), oriented. + public int SourceWidth { get; } = sourceWidth; + + public int SourceHeight { get; } = sourceHeight; + + public void Dispose() => Pixels.Dispose(); +} + +/// A platform image decoder (WIC on Windows, managed codecs everywhere). +public interface IImageDecoderProvider +{ + /// Short name for logs and the Settings › Formats table. + string Name { get; } + + /// The best tier this provider can deliver for the format on this machine, or null. + DecodeTier? TierFor(ImageFileFormat format); + + bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null; + + /// Decodes or returns null when this provider cannot handle the specific file. + DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default); +} + +/// Tries providers in priority order and applies the tier rules of BRIEF §8.2. +public sealed class ImageDecoder(IReadOnlyList providers) +{ + public IReadOnlyList Providers { get; } = providers; + + /// Best tier available for across all providers. + public DecodeTier TierFor(ImageFileFormat format) + { + var best = DecodeTier.Unavailable; + foreach (var p in Providers) + { + if (p.TierFor(format) is { } t && t < best) best = t; + } + return best; + } + + /// Decodes with the first provider that succeeds; null means . + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + var format = ImageFormatInfo.FromPath(request.Path); + List? errors = null; + foreach (var provider in Providers.OrderBy(p => p.TierFor(format.Format) ?? DecodeTier.Unavailable)) + { + if (provider.TierFor(format.Format) is null) continue; + cancellationToken.ThrowIfCancellationRequested(); + try + { + var result = provider.Decode(request, cancellationToken); + if (result is not null) return result; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or NotSupportedException or FormatException or InvalidOperationException or System.Runtime.InteropServices.COMException) + { + (errors ??= []).Add(ex); + } + } + return null; + } +} diff --git a/src/Titano.Core/Imaging/ImageBuffer.cs b/src/Titano.Core/Imaging/ImageBuffer.cs new file mode 100644 index 00000000..4e78ebfc --- /dev/null +++ b/src/Titano.Core/Imaging/ImageBuffer.cs @@ -0,0 +1,74 @@ +using System.Buffers; + +namespace Titano.Core.Imaging; + +/// +/// Planar 32-bit float image in linear light (Rec.709/sRGB primaries). Channel 0..2 = R, G, B +/// (or a single luminance channel). Nominal range 0..1; highlights may exceed 1. +/// Storage is rented from and returned on . +/// +public sealed class ImageBuffer : IDisposable +{ + private float[]? _data; + + public ImageBuffer(int width, int height, int channels = 3, bool clear = true) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (channels is not (1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(channels), "1, 3 or 4 channels"); + Width = width; + Height = height; + Channels = channels; + var length = checked(width * height * channels); + _data = ArrayPool.Shared.Rent(length); + if (clear) Array.Clear(_data, 0, length); + } + + public int Width { get; } + public int Height { get; } + public int Channels { get; } + public int PlaneLength => Width * Height; + + /// All planes, channel-major: plane c starts at c * Width * Height. + public Span Data => Storage.AsSpan(0, PlaneLength * Channels); + + public Span Plane(int channel) + { + if ((uint)channel >= (uint)Channels) throw new ArgumentOutOfRangeException(nameof(channel)); + return Storage.AsSpan(channel * PlaneLength, PlaneLength); + } + + public Span Row(int channel, int y) => Plane(channel).Slice(y * Width, Width); + + public float this[int channel, int x, int y] + { + get => Storage[channel * PlaneLength + y * Width + x]; + set => Storage[channel * PlaneLength + y * Width + x] = value; + } + + /// Underlying array (may be longer than the image). Exposed for SIMD kernels. + public float[] Storage => _data ?? throw new ObjectDisposedException(nameof(ImageBuffer)); + + public ImageBuffer Clone() + { + var copy = new ImageBuffer(Width, Height, Channels, clear: false); + Data.CopyTo(copy.Data); + return copy; + } + + public void CopyTo(ImageBuffer target) + { + if (target.Width != Width || target.Height != Height || target.Channels != Channels) + throw new ArgumentException("Dimensions differ", nameof(target)); + Data.CopyTo(target.Data); + } + + /// Approximate managed memory held by the buffer, in bytes. + public long ByteSize => (long)PlaneLength * Channels * sizeof(float); + + public void Dispose() + { + var data = Interlocked.Exchange(ref _data, null); + if (data is not null) ArrayPool.Shared.Return(data); + } +} diff --git a/src/Titano.Core/Imaging/ImageFileFormat.cs b/src/Titano.Core/Imaging/ImageFileFormat.cs new file mode 100644 index 00000000..aceda4d7 --- /dev/null +++ b/src/Titano.Core/Imaging/ImageFileFormat.cs @@ -0,0 +1,109 @@ +namespace Titano.Core.Imaging; + +/// Container/file formats recognised by signature and extension (BRIEF §8.1). +public enum ImageFileFormat +{ + Unknown = 0, + Jpeg, + Png, + Tiff, + Dng, + Cr2, + Cr3, + Crw, + Nef, + Nrw, + Arw, + Srf, + Sr2, + Raf, + Orf, + Rw2, + Raw, + Pef, + Srw, + ThreeFr, + Fff, + Iiq, + Rwl, + Gpr, + Heif, + Avif, + WebP, + JpegXl, + JpegXr, + Bmp, + Gif, +} + +public enum ImageFamily +{ + Unknown, + Jpeg, + Png, + Tiff, + Dng, + CameraRaw, + Heif, + WebP, + Other, +} + +/// Static facts about a format: family, extensions, whether it is a camera RAW. +public sealed record ImageFormatInfo(ImageFileFormat Format, ImageFamily Family, IReadOnlyList Extensions) +{ + public bool IsRaw => Family is ImageFamily.CameraRaw or ImageFamily.Dng; + + private static readonly ImageFormatInfo[] All = + [ + new(ImageFileFormat.Jpeg, ImageFamily.Jpeg, ["jpg", "jpeg", "jpe", "jfif"]), + new(ImageFileFormat.Png, ImageFamily.Png, ["png"]), + new(ImageFileFormat.Tiff, ImageFamily.Tiff, ["tif", "tiff"]), + new(ImageFileFormat.Dng, ImageFamily.Dng, ["dng"]), + new(ImageFileFormat.Cr2, ImageFamily.CameraRaw, ["cr2"]), + new(ImageFileFormat.Cr3, ImageFamily.CameraRaw, ["cr3"]), + new(ImageFileFormat.Crw, ImageFamily.CameraRaw, ["crw"]), + new(ImageFileFormat.Nef, ImageFamily.CameraRaw, ["nef"]), + new(ImageFileFormat.Nrw, ImageFamily.CameraRaw, ["nrw"]), + new(ImageFileFormat.Arw, ImageFamily.CameraRaw, ["arw"]), + new(ImageFileFormat.Srf, ImageFamily.CameraRaw, ["srf"]), + new(ImageFileFormat.Sr2, ImageFamily.CameraRaw, ["sr2"]), + new(ImageFileFormat.Raf, ImageFamily.CameraRaw, ["raf"]), + new(ImageFileFormat.Orf, ImageFamily.CameraRaw, ["orf"]), + new(ImageFileFormat.Rw2, ImageFamily.CameraRaw, ["rw2"]), + new(ImageFileFormat.Raw, ImageFamily.CameraRaw, ["raw"]), + new(ImageFileFormat.Pef, ImageFamily.CameraRaw, ["pef"]), + new(ImageFileFormat.Srw, ImageFamily.CameraRaw, ["srw"]), + new(ImageFileFormat.ThreeFr, ImageFamily.CameraRaw, ["3fr"]), + new(ImageFileFormat.Fff, ImageFamily.CameraRaw, ["fff"]), + new(ImageFileFormat.Iiq, ImageFamily.CameraRaw, ["iiq"]), + new(ImageFileFormat.Rwl, ImageFamily.CameraRaw, ["rwl"]), + new(ImageFileFormat.Gpr, ImageFamily.CameraRaw, ["gpr"]), + new(ImageFileFormat.Heif, ImageFamily.Heif, ["heic", "heif", "hif"]), + new(ImageFileFormat.Avif, ImageFamily.Heif, ["avif"]), + new(ImageFileFormat.WebP, ImageFamily.WebP, ["webp"]), + new(ImageFileFormat.JpegXl, ImageFamily.Other, ["jxl"]), + new(ImageFileFormat.JpegXr, ImageFamily.Other, ["jxr", "wdp", "hdp"]), + new(ImageFileFormat.Bmp, ImageFamily.Other, ["bmp"]), + new(ImageFileFormat.Gif, ImageFamily.Other, ["gif"]), + ]; + + private static readonly Dictionary ByExtension = + All.SelectMany(i => i.Extensions.Select(e => (e, i))).ToDictionary(p => p.e, p => p.i, StringComparer.OrdinalIgnoreCase); + + public static IReadOnlyList Known => All; + + public static ImageFormatInfo Unknown { get; } = new(ImageFileFormat.Unknown, ImageFamily.Unknown, []); + + public static ImageFormatInfo Of(ImageFileFormat format) => All.FirstOrDefault(i => i.Format == format) ?? Unknown; + + /// Format implied by a file name's extension (signature sniffing lives in Metadata). + public static ImageFormatInfo FromPath(string path) + { + var ext = Path.GetExtension(path).TrimStart('.'); + return ByExtension.TryGetValue(ext, out var info) ? info : Unknown; + } + + /// True when the extension is one Titano imports as a photo. + public static bool IsSupportedExtension(string path) => FromPath(path).Format != ImageFileFormat.Unknown; +} diff --git a/src/Titano.Core/Localization/Languages.cs b/src/Titano.Core/Localization/Languages.cs new file mode 100644 index 00000000..349197bf --- /dev/null +++ b/src/Titano.Core/Localization/Languages.cs @@ -0,0 +1,39 @@ +using System.Globalization; + +namespace Titano.Core.Localization; + +/// Languages shipped with Titano (BRIEF §16). English is the source. +public static class Languages +{ + public static readonly IReadOnlyList Shipped = + [ + "en", "it", "de", "fr", "es", "pt-BR", "pt-PT", "nl", "pl", "cs", "sk", "hu", "ro", "sv", "da", "nb", + "fi", "ru", "uk", "tr", "el", "bg", "hr", "sl", "lt", "lv", "et", "ja", "zh-Hans", "zh-Hant", "ko", + "ar", "he", "hi", "id", "ms", "vi", "th", + ]; + + /// Languages whose UI layout is mirrored. + public static readonly IReadOnlySet RightToLeft = new HashSet(StringComparer.OrdinalIgnoreCase) { "ar", "he", "fa", "ur" }; + + /// The shipped language that best matches , falling back to English. + public static CultureInfo BestMatch(CultureInfo culture) + { + for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent) + { + var hit = Shipped.FirstOrDefault(s => s.Equals(c.Name, StringComparison.OrdinalIgnoreCase)); + if (hit is not null) return CultureInfo.GetCultureInfo(hit); + } + if (culture.TwoLetterISOLanguageName == "pt") return CultureInfo.GetCultureInfo("pt-PT"); + if (culture.TwoLetterISOLanguageName == "zh") return CultureInfo.GetCultureInfo("zh-Hans"); + if (culture.TwoLetterISOLanguageName is "no" or "nn") return CultureInfo.GetCultureInfo("nb"); + return CultureInfo.GetCultureInfo("en"); + } + + /// Native display name ("Italiano", "日本語"). + public static string NativeName(string code) + { + var c = CultureInfo.GetCultureInfo(code); + var name = c.NativeName; + return name.Length > 0 ? char.ToUpper(name[0], c) + name[1..] : code; + } +} diff --git a/src/Titano.Core/Localization/Loc.cs b/src/Titano.Core/Localization/Loc.cs new file mode 100644 index 00000000..feb4352c --- /dev/null +++ b/src/Titano.Core/Localization/Loc.cs @@ -0,0 +1,114 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Resources; + +namespace Titano.Core.Localization; + +/// +/// Runtime string catalog. Keys are stable identifiers of the form Area.Group.Name; the first +/// segment selects the resource file i18n/<culture>/<Area>.resx. English is the source. +/// +public static class Loc +{ + private const string BaseNamePrefix = "Titano.Core.i18n."; + private static readonly ConcurrentDictionary Managers = new(StringComparer.Ordinal); + private static CultureInfo _culture = CultureInfo.CurrentUICulture; + + /// Raised after so bound UI can refresh without restart. + public static event EventHandler? CultureChanged; + + /// Raised once per missing key (used by tests and diagnostics). + public static event Action? MissingKey; + + public static CultureInfo Culture => _culture; + + /// Text direction of the current culture. + public static bool IsRightToLeft => _culture.TextInfo.IsRightToLeft; + + public static void SetCulture(CultureInfo culture) + { + ArgumentNullException.ThrowIfNull(culture); + if (Equals(culture, _culture)) return; + _culture = culture; + CultureChanged?.Invoke(null, EventArgs.Empty); + } + + /// Returns the localized string for in the current culture. + public static string L(string key) => Get(key, _culture) ?? Missing(key); + + /// Returns the localized composite format for filled with . + public static string L(string key, params object?[] args) + { + var format = Get(key, _culture); + if (format is null) return Missing(key); + return args.Length == 0 ? format : string.Format(_culture, format, args); + } + + /// + /// Plural-aware lookup: resolves key.one, key.few, key.many or key.other + /// using CLDR rules of the current language; {0} receives the count. + /// + public static string Plural(string key, long count, params object?[] args) + { + var category = PluralRules.Select(_culture, count); + var format = Get(key + "." + PluralRules.Suffix(category), _culture) ?? Get(key + ".other", _culture); + if (format is null) return Missing(key); + var all = new object?[args.Length + 1]; + all[0] = count; + Array.Copy(args, 0, all, 1, args.Length); + return string.Format(_culture, format, all); + } + + /// Looks a key up in a specific culture (falls back to parents and English); null when absent. + public static string? Get(string key, CultureInfo culture) + { + var dot = key.IndexOf('.', StringComparison.Ordinal); + if (dot <= 0) return null; + var area = key[..dot]; + var manager = Managers.GetOrAdd(area, static a => new ResourceManager(BaseNamePrefix + a, typeof(Loc).Assembly)); + try + { + return manager.GetString(key, culture); + } + catch (MissingManifestResourceException) + { + return null; + } + } + + /// Every key and English value of an area, for tooling and the web admin export. + public static IReadOnlyDictionary GetArea(string area, CultureInfo culture) + { + var manager = Managers.GetOrAdd(area, static a => new ResourceManager(BaseNamePrefix + a, typeof(Loc).Assembly)); + var result = new Dictionary(StringComparer.Ordinal); + // Walk from invariant to specific so the most specific value wins. + var chain = new List(); + for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent) chain.Add(c); + chain.Add(CultureInfo.InvariantCulture); + chain.Reverse(); + foreach (var c in chain) + { + ResourceSet? set; + try + { + set = manager.GetResourceSet(c, createIfNotExists: true, tryParents: false); + } + catch (MissingManifestResourceException) + { + continue; + } + if (set is null) continue; + foreach (System.Collections.DictionaryEntry entry in set) + { + if (entry.Key is string k && entry.Value is string v) result[k] = v; + } + } + return result; + } + + private static string Missing(string key) + { + MissingKey?.Invoke(key); + return "⟦" + key + "⟧"; + } +} diff --git a/src/Titano.Core/Localization/PluralRules.cs b/src/Titano.Core/Localization/PluralRules.cs new file mode 100644 index 00000000..fd6d1926 --- /dev/null +++ b/src/Titano.Core/Localization/PluralRules.cs @@ -0,0 +1,103 @@ +using System.Globalization; + +namespace Titano.Core.Localization; + +public enum PluralCategory +{ + One, + Few, + Many, + Other, +} + +/// +/// Minimal CLDR cardinal plural rules for the shipped languages (integers only, which is all the UI needs). +/// +public static class PluralRules +{ + public static string Suffix(PluralCategory c) => c switch + { + PluralCategory.One => "one", + PluralCategory.Few => "few", + PluralCategory.Many => "many", + _ => "other", + }; + + public static PluralCategory Select(CultureInfo culture, long count) + { + var n = Math.Abs(count); + var lang = culture.TwoLetterISOLanguageName; + long mod10 = n % 10, mod100 = n % 100; + switch (lang) + { + // No plural distinction. + case "ja" or "zh" or "ko" or "vi" or "th" or "id" or "ms": + return PluralCategory.Other; + + // one: 0 and 1. + case "fr" or "hi": + return n is 0 or 1 ? PluralCategory.One : PluralCategory.Other; + + case "pt" when culture.Name.Equals("pt-BR", StringComparison.OrdinalIgnoreCase): + return n is 0 or 1 ? PluralCategory.One : PluralCategory.Other; + + // East Slavic. + case "ru" or "uk": + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Many; + + case "pl": + if (n == 1) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Many; + + case "cs" or "sk": + if (n == 1) return PluralCategory.One; + if (n is >= 2 and <= 4) return PluralCategory.Few; + return PluralCategory.Other; + + case "hr" or "sr" or "bs": + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + if (mod10 is >= 2 and <= 4 && mod100 is < 12 or > 14) return PluralCategory.Few; + return PluralCategory.Other; + + case "sl": + if (mod100 == 1) return PluralCategory.One; + if (mod100 == 2) return PluralCategory.Few; // CLDR "two", folded into few + if (mod100 is 3 or 4) return PluralCategory.Few; + return PluralCategory.Other; + + case "lt": + if (mod10 == 1 && mod100 is < 11 or > 19) return PluralCategory.One; + if (mod10 is >= 2 and <= 9 && mod100 is < 11 or > 19) return PluralCategory.Few; + return PluralCategory.Other; + + case "lv": + if (mod10 == 0 || mod100 is >= 11 and <= 19) return PluralCategory.Many; // CLDR "zero" + if (mod10 == 1 && mod100 != 11) return PluralCategory.One; + return PluralCategory.Other; + + case "ro": + if (n == 1) return PluralCategory.One; + if (n == 0 || mod100 is >= 2 and <= 19) return PluralCategory.Few; + return PluralCategory.Other; + + case "ar": + if (n == 1) return PluralCategory.One; + if (n == 2) return PluralCategory.Few; // CLDR "two", folded + if (mod100 is >= 3 and <= 10) return PluralCategory.Few; + if (mod100 is >= 11 and <= 99) return PluralCategory.Many; + return PluralCategory.Other; + + case "he": + if (n == 1) return PluralCategory.One; + if (n == 2) return PluralCategory.Few; // CLDR "two", folded + return PluralCategory.Other; + + // Default Germanic/Romance rule: one for exactly 1. + default: + return n == 1 ? PluralCategory.One : PluralCategory.Other; + } + } +} diff --git a/src/Titano.Core/Metadata/FrameMetadata.cs b/src/Titano.Core/Metadata/FrameMetadata.cs new file mode 100644 index 00000000..e38d2714 --- /dev/null +++ b/src/Titano.Core/Metadata/FrameMetadata.cs @@ -0,0 +1,71 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Core.Metadata; + +public enum PreviewKind +{ + Thumbnail, + Preview, + FullSize, +} + +/// An embedded JPEG inside a RAW/TIFF/HEIF/JPEG(MPF) container. +public sealed record EmbeddedPreview(long Offset, long Length, int Width, int Height, PreviewKind Kind); + +public sealed record GpsPosition(double Latitude, double Longitude, double? Altitude, DateTime? UtcTimestamp); + +/// Everything Titano reads from one photo's metadata (BRIEF §9). Never throws while parsing: +/// malformed input yields partial data plus . +public sealed record FrameMetadata +{ + public ImageFileFormat Format { get; init; } + public string? Make { get; init; } + public string? Model { get; init; } + public string? BodySerial { get; init; } + public string? LensModel { get; init; } + public string? Software { get; init; } + public string? Artist { get; init; } + public string? Copyright { get; init; } + + /// Camera wall-clock time including sub-seconds (DateTimeKind.Unspecified). + public DateTime? CapturedAt { get; init; } + + public int? UtcOffsetMinutes { get; init; } + public TimestampSource TimestampSource { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? FocalLength { get; init; } + public double? FocalLength35 { get; init; } + public double? ExposureBias { get; init; } + public int? ExposureProgram { get; init; } + public int? MeteringMode { get; init; } + public int? WhiteBalanceMode { get; init; } + public int? ColorTemperature { get; init; } + public int? Flash { get; init; } + + /// Exif orientation 1–8. + public int Orientation { get; init; } = 1; + + /// Dimensions of the main (largest) image as stored, before orientation. + public int Width { get; init; } + + public int Height { get; init; } + public int? BitsPerSample { get; init; } + public GpsPosition? Gps { get; init; } + public int? Rating { get; init; } + public string? Label { get; init; } + public long? ShutterCount { get; init; } + public bool? ImageStabilization { get; init; } + + /// Embedded JPEGs, largest first. + public IReadOnlyList Previews { get; init; } = []; + + public IReadOnlyList Warnings { get; init; } = []; + + /// Width/height after applying orientation 5–8 (90° rotations). + public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height); + + public EmbeddedPreview? LargestPreview => Previews.Count > 0 ? Previews[0] : null; +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffReader.cs b/src/Titano.Core/Metadata/Tiff/TiffReader.cs new file mode 100644 index 00000000..112a5874 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffReader.cs @@ -0,0 +1,251 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Metadata.Tiff; + +/// One IFD entry. Small values (≤ 4 bytes) are inline; larger ones live at . +public readonly record struct IfdEntry(ushort Tag, TiffType Type, uint Count, uint ValueOffset, long EntryPosition) +{ + public long ByteLength => (long)Count * TiffTypeInfo.Size(Type); + public bool IsInline => ByteLength <= 4; + + /// Absolute file position of the value bytes (inline values sit inside the entry). + public long ValuePosition(long tiffBase) => IsInline ? EntryPosition + 8 : tiffBase + ValueOffset; +} + +/// An image file directory: its entries and the offset of the next IFD (0 = none). +public sealed class Ifd(long position, IReadOnlyDictionary entries, uint nextOffset) +{ + public long Position { get; } = position; + public IReadOnlyDictionary Entries { get; } = entries; + public uint NextOffset { get; } = nextOffset; + public bool Has(ushort tag) => Entries.ContainsKey(tag); +} + +/// +/// Fuzz-safe TIFF structure reader over a seekable stream. Reads only the bytes it needs (never the whole +/// file), validates every offset against the stream length, caps entry counts and detects IFD loops. +/// Also used for TIFF structures embedded at a base offset (Exif APP1, RAF, CR3 CMT boxes, MakerNotes). +/// +public sealed class TiffReader +{ + public const int MaxEntriesPerIfd = 4096; + public const int MaxIfdChain = 64; + public const long MaxValueBytes = 64L * 1024 * 1024; + + private readonly Stream _stream; + private readonly List _warnings = []; + + private TiffReader(Stream stream, long tiffBase, bool littleEndian, uint firstIfdOffset) + { + _stream = stream; + Base = tiffBase; + LittleEndian = littleEndian; + FirstIfdOffset = firstIfdOffset; + } + + /// Absolute position of the TIFF header ("II*\0"/"MM\0*"); IFD offsets are relative to it. + public long Base { get; } + + public bool LittleEndian { get; } + public uint FirstIfdOffset { get; } + public IReadOnlyList Warnings => _warnings; + public long StreamLength => _stream.Length; + + /// Opens a TIFF header at ; null when the bytes are not a TIFF header. + /// Accepts the ORF ("IIRO"/"IIRS") and RW2 ("IIU\0") header variants. + public static TiffReader? Open(Stream stream, long tiffBase = 0) + { + if (!stream.CanSeek || tiffBase < 0 || tiffBase + 8 > stream.Length) return null; + Span h = stackalloc byte[8]; + stream.Position = tiffBase; + if (stream.ReadAtLeast(h, 8, throwOnEndOfStream: false) < 8) return null; + bool le; + if (h[0] == 'I' && h[1] == 'I') le = true; + else if (h[0] == 'M' && h[1] == 'M') le = false; + else return null; + var magic = le ? BinaryPrimitives.ReadUInt16LittleEndian(h[2..]) : BinaryPrimitives.ReadUInt16BigEndian(h[2..]); + if (magic is not (42 or 0x4F52 or 0x5352 or 0x0055)) return null; + var first = le ? BinaryPrimitives.ReadUInt32LittleEndian(h[4..]) : BinaryPrimitives.ReadUInt32BigEndian(h[4..]); + return new TiffReader(stream, tiffBase, le, first); + } + + /// Creates a reader for an IFD structure without a header (e.g. maker notes) with a known byte order. + public static TiffReader ForEmbedded(Stream stream, long tiffBase, bool littleEndian) => new(stream, tiffBase, littleEndian, 0); + + /// Reads the chain of top-level IFDs (IFD0, IFD1, …). + public IReadOnlyList ReadChain() + { + var list = new List(); + var seen = new HashSet(); + var offset = FirstIfdOffset; + while (offset != 0 && list.Count < MaxIfdChain) + { + var ifd = ReadIfd(offset, seen); + if (ifd is null) break; + list.Add(ifd); + offset = ifd.NextOffset; + } + return list; + } + + /// Reads one IFD at a base-relative offset; null if out of bounds or already visited. + public Ifd? ReadIfd(uint offset, HashSet? visited = null) + { + var pos = Base + offset; + if (pos + 2 > _stream.Length || pos < 0) + { + Warn($"IFD offset {offset} beyond end of file"); + return null; + } + if (visited is not null && !visited.Add(pos)) + { + Warn($"IFD loop at {offset}"); + return null; + } + Span two = stackalloc byte[2]; + if (!ReadAt(pos, two)) return null; + var count = U16(two); + if (count == 0 || count > MaxEntriesPerIfd) + { + Warn($"IFD at {offset} has {count} entries"); + return null; + } + var bytes = new byte[count * 12 + 4]; + var available = (int)Math.Min(bytes.Length, _stream.Length - (pos + 2)); + if (!ReadAt(pos + 2, bytes.AsSpan(0, available))) return null; + var entries = new Dictionary(count); + var complete = available / 12; + for (var i = 0; i < Math.Min(count, complete); i++) + { + var e = bytes.AsSpan(i * 12, 12); + var tag = U16(e); + var type = (TiffType)U16(e[2..]); + var n = U32(e[4..]); + var value = U32(e[8..]); + if (TiffTypeInfo.Size(type) == 0) continue; + entries.TryAdd(tag, new IfdEntry(tag, type, n, value, pos + 2 + i * 12)); + } + if (complete < count) Warn($"IFD at {offset} truncated"); + var next = available >= count * 12 + 4 ? U32(bytes.AsSpan(count * 12)) : 0u; + return new Ifd(pos, entries, next); + } + + /// Raw value bytes of an entry (bounded by ); null when invalid. + public byte[]? ReadBytes(IfdEntry e, long maxBytes = MaxValueBytes) + { + var length = e.ByteLength; + if (length <= 0 || length > maxBytes) return null; + var pos = e.ValuePosition(Base); + if (pos < 0 || pos + length > _stream.Length) + { + Warn($"Tag 0x{e.Tag:X4} value outside file"); + return null; + } + var buffer = new byte[length]; + return ReadAt(pos, buffer) ? buffer : null; + } + + public uint? GetUInt(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) is { Length: > 0 } v ? v[0] : null : null; + + public uint[]? GetUInts(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetUInts(e) : null; + + /// Integer values of BYTE/SHORT/LONG/IFD (and signed variants) entries. + public uint[]? GetUInts(IfdEntry e) + { + var raw = ReadBytes(e); + if (raw is null) return null; + var size = TiffTypeInfo.Size(e.Type); + var result = new uint[e.Count]; + for (var i = 0; i < e.Count; i++) + { + var s = raw.AsSpan(i * size); + result[i] = e.Type switch + { + TiffType.Byte or TiffType.Undefined or TiffType.Ascii => s[0], + TiffType.SByte => (uint)(sbyte)s[0], + TiffType.Short => U16(s), + TiffType.SShort => (uint)(short)U16(s), + TiffType.Long or TiffType.Ifd or TiffType.SLong => U32(s), + _ => 0, + }; + } + return result; + } + + public double? GetDouble(Ifd ifd, ushort tag) => GetDoubles(ifd, tag) is { Length: > 0 } v ? v[0] : null; + + public double[]? GetDoubles(Ifd ifd, ushort tag) => ifd.Entries.TryGetValue(tag, out var e) ? GetDoubles(e) : null; + + /// Numeric values of any numeric type as doubles (rationals divided; 0-denominator → NaN skipped as 0). + public double[]? GetDoubles(IfdEntry e) + { + var raw = ReadBytes(e); + if (raw is null) return null; + var size = TiffTypeInfo.Size(e.Type); + var result = new double[e.Count]; + for (var i = 0; i < e.Count; i++) + { + var s = raw.AsSpan(i * size); + result[i] = e.Type switch + { + TiffType.Rational => U32(s[4..]) == 0 ? 0 : (double)U32(s) / U32(s[4..]), + TiffType.SRational => (int)U32(s[4..]) == 0 ? 0 : (double)(int)U32(s) / (int)U32(s[4..]), + TiffType.Float => BitConverter.Int32BitsToSingle((int)U32(s)), + TiffType.Double => BitConverter.Int64BitsToDouble((long)U64(s)), + TiffType.Byte or TiffType.Undefined => s[0], + TiffType.SByte => (sbyte)s[0], + TiffType.Short => U16(s), + TiffType.SShort => (short)U16(s), + TiffType.Long or TiffType.Ifd => U32(s), + TiffType.SLong => (int)U32(s), + _ => 0, + }; + } + return result; + } + + /// ASCII/UTF-8 string value with trailing NULs and spaces trimmed; null when empty. + public string? GetString(Ifd ifd, ushort tag) + { + if (!ifd.Entries.TryGetValue(tag, out var e)) return null; + var raw = ReadBytes(e, 1 << 20); + if (raw is null) return null; + var end = Array.IndexOf(raw, (byte)0); + var s = Encoding.UTF8.GetString(raw, 0, end < 0 ? raw.Length : end).Trim(); + return s.Length == 0 ? null : s; + } + + /// Reads arbitrary bytes at a base-relative offset (bounds-checked). + public byte[]? ReadRelative(long offset, int length) + { + if (length <= 0 || length > MaxValueBytes) return null; + var pos = Base + offset; + if (pos < 0 || pos + length > _stream.Length) return null; + var buffer = new byte[length]; + return ReadAt(pos, buffer) ? buffer : null; + } + + public ushort U16(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(s) : BinaryPrimitives.ReadUInt16BigEndian(s); + public uint U32(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt32LittleEndian(s) : BinaryPrimitives.ReadUInt32BigEndian(s); + public ulong U64(ReadOnlySpan s) => LittleEndian ? BinaryPrimitives.ReadUInt64LittleEndian(s) : BinaryPrimitives.ReadUInt64BigEndian(s); + + public void Warn(string message) + { + if (_warnings.Count < 32) _warnings.Add(message); + } + + private bool ReadAt(long position, Span buffer) + { + try + { + _stream.Position = position; + return _stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length; + } + catch (IOException ex) + { + Warn("I/O error: " + ex.Message); + return false; + } + } +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffTags.cs b/src/Titano.Core/Metadata/Tiff/TiffTags.cs new file mode 100644 index 00000000..e279e5a1 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffTags.cs @@ -0,0 +1,126 @@ +namespace Titano.Core.Metadata.Tiff; + +/// Tag numbers used across TIFF, Exif, GPS and DNG. +public static class TiffTags +{ + // Baseline TIFF + public const ushort NewSubfileType = 0x00FE; + public const ushort ImageWidth = 0x0100; + public const ushort ImageLength = 0x0101; + public const ushort BitsPerSample = 0x0102; + public const ushort Compression = 0x0103; + public const ushort PhotometricInterpretation = 0x0106; + public const ushort ImageDescription = 0x010E; + public const ushort Make = 0x010F; + public const ushort Model = 0x0110; + public const ushort StripOffsets = 0x0111; + public const ushort Orientation = 0x0112; + public const ushort SamplesPerPixel = 0x0115; + public const ushort RowsPerStrip = 0x0116; + public const ushort StripByteCounts = 0x0117; + public const ushort XResolution = 0x011A; + public const ushort YResolution = 0x011B; + public const ushort PlanarConfiguration = 0x011C; + public const ushort ResolutionUnit = 0x0128; + public const ushort Software = 0x0131; + public const ushort DateTime = 0x0132; + public const ushort Artist = 0x013B; + public const ushort Predictor = 0x013D; + public const ushort TileWidth = 0x0142; + public const ushort TileLength = 0x0143; + public const ushort TileOffsets = 0x0144; + public const ushort TileByteCounts = 0x0145; + public const ushort SubIfds = 0x014A; + public const ushort ExtraSamples = 0x0152; + public const ushort SampleFormat = 0x0153; + public const ushort JpegTables = 0x015B; + public const ushort JpegInterchangeFormat = 0x0201; + public const ushort JpegInterchangeFormatLength = 0x0202; + public const ushort YCbCrSubSampling = 0x0212; + public const ushort Rating = 0x4746; + public const ushort Xmp = 0x02BC; + public const ushort Copyright = 0x8298; + public const ushort ExifIfd = 0x8769; + public const ushort GpsIfd = 0x8825; + public const ushort InteropIfd = 0xA005; + + // Exif + public const ushort ExposureTime = 0x829A; + public const ushort FNumber = 0x829D; + public const ushort ExposureProgram = 0x8822; + public const ushort IsoSpeedRatings = 0x8827; + public const ushort SensitivityType = 0x8830; + public const ushort RecommendedExposureIndex = 0x8832; + public const ushort ExifVersion = 0x9000; + public const ushort DateTimeOriginal = 0x9003; + public const ushort DateTimeDigitized = 0x9004; + public const ushort OffsetTime = 0x9010; + public const ushort OffsetTimeOriginal = 0x9011; + public const ushort OffsetTimeDigitized = 0x9012; + public const ushort ShutterSpeedValue = 0x9201; + public const ushort ApertureValue = 0x9202; + public const ushort ExposureBiasValue = 0x9204; + public const ushort MeteringMode = 0x9207; + public const ushort Flash = 0x9209; + public const ushort FocalLength = 0x920A; + public const ushort MakerNote = 0x927C; + public const ushort SubSecTime = 0x9290; + public const ushort SubSecTimeOriginal = 0x9291; + public const ushort SubSecTimeDigitized = 0x9292; + public const ushort ColorSpace = 0xA001; + public const ushort PixelXDimension = 0xA002; + public const ushort PixelYDimension = 0xA003; + public const ushort WhiteBalance = 0xA403; + public const ushort FocalLengthIn35mmFilm = 0xA405; + public const ushort BodySerialNumber = 0xA431; + public const ushort LensSpecification = 0xA432; + public const ushort LensMake = 0xA433; + public const ushort LensModel = 0xA434; + + // GPS + public const ushort GpsLatitudeRef = 0x0001; + public const ushort GpsLatitude = 0x0002; + public const ushort GpsLongitudeRef = 0x0003; + public const ushort GpsLongitude = 0x0004; + public const ushort GpsAltitudeRef = 0x0005; + public const ushort GpsAltitude = 0x0006; + public const ushort GpsTimeStamp = 0x0007; + public const ushort GpsDateStamp = 0x001D; + + // DNG + public const ushort CfaRepeatPatternDim = 0x828D; + public const ushort CfaPattern = 0x828E; + public const ushort DngVersion = 0xC612; + public const ushort DngBackwardVersion = 0xC613; + public const ushort UniqueCameraModel = 0xC614; + public const ushort CfaPlaneColor = 0xC616; + public const ushort CfaLayout = 0xC617; + public const ushort LinearizationTable = 0xC618; + public const ushort BlackLevelRepeatDim = 0xC619; + public const ushort BlackLevel = 0xC61A; + public const ushort BlackLevelDeltaH = 0xC61B; + public const ushort BlackLevelDeltaV = 0xC61C; + public const ushort WhiteLevel = 0xC61D; + public const ushort DefaultScale = 0xC61E; + public const ushort DefaultCropOrigin = 0xC61F; + public const ushort DefaultCropSize = 0xC620; + public const ushort ColorMatrix1 = 0xC621; + public const ushort ColorMatrix2 = 0xC622; + public const ushort CameraCalibration1 = 0xC623; + public const ushort CameraCalibration2 = 0xC624; + public const ushort AnalogBalance = 0xC627; + public const ushort AsShotNeutral = 0xC628; + public const ushort AsShotWhiteXy = 0xC629; + public const ushort BaselineExposure = 0xC62A; + public const ushort CameraSerialNumber = 0xC62F; + public const ushort LensInfo = 0xC630; + public const ushort ActiveArea = 0xC68D; + public const ushort CalibrationIlluminant1 = 0xC65A; + public const ushort CalibrationIlluminant2 = 0xC65B; + public const ushort OpcodeList1 = 0xC740; + public const ushort OpcodeList2 = 0xC741; + public const ushort OpcodeList3 = 0xC74E; + public const ushort ForwardMatrix1 = 0xC714; + public const ushort ForwardMatrix2 = 0xC715; + public const ushort NewRawImageDigest = 0xC7A7; +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffType.cs b/src/Titano.Core/Metadata/Tiff/TiffType.cs new file mode 100644 index 00000000..fafd8605 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/TiffType.cs @@ -0,0 +1,32 @@ +namespace Titano.Core.Metadata.Tiff; + +/// TIFF 6.0 field types (plus IFD = 13). +public enum TiffType : ushort +{ + Byte = 1, + Ascii = 2, + Short = 3, + Long = 4, + Rational = 5, + SByte = 6, + Undefined = 7, + SShort = 8, + SLong = 9, + SRational = 10, + Float = 11, + Double = 12, + Ifd = 13, +} + +public static class TiffTypeInfo +{ + /// Size in bytes of one value; 0 for unknown types. + public static int Size(TiffType type) => type switch + { + TiffType.Byte or TiffType.Ascii or TiffType.SByte or TiffType.Undefined => 1, + TiffType.Short or TiffType.SShort => 2, + TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd => 4, + TiffType.Rational or TiffType.SRational or TiffType.Double => 8, + _ => 0, + }; +} diff --git a/src/Titano.Core/Model/Entities.cs b/src/Titano.Core/Model/Entities.cs new file mode 100644 index 00000000..2ba34ddc --- /dev/null +++ b/src/Titano.Core/Model/Entities.cs @@ -0,0 +1,238 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Model; + +/// A rooted folder tree that holds originals, sidecars, proxies and exports (BRIEF §7). +public sealed record Archive +{ + public required Guid Id { get; init; } + public required string Name { get; init; } + public required string RootPath { get; init; } + public string FolderTemplate { get; init; } = Naming.TemplateDefaults.Folder; + public string FileTemplate { get; init; } = Naming.TemplateDefaults.File; + public int SchemaVersion { get; init; } = 1; + public DateTimeOffset Created { get; init; } + + /// Proxy long edge in pixels; 0 = full size, -1 = proxies disabled. + public int ProxyLongEdge { get; init; } = 1920; +} + +/// One shoot: a folder of frames that becomes one project (BRIEF §5). +public sealed record Sequence +{ + public required Guid Id { get; init; } + public required Guid ArchiveId { get; init; } + public string? Title { get; init; } + + /// Folder relative to the archive root, forward slashes. + public required string Folder { get; init; } + + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? Lens { get; init; } + public DateTime? FirstCapture { get; init; } + public DateTime? LastCapture { get; init; } + public int FrameCount { get; init; } + + /// Median capture interval in seconds. + public double? MedianInterval { get; init; } + + public long TotalBytes { get; init; } + public SequenceStatus Status { get; init; } + public int RenderedCount { get; init; } + public DateTimeOffset? VerifiedAt { get; init; } + public Guid? HeroFrameId { get; init; } + public IReadOnlyList Tags { get; init; } = []; + public int Rating { get; init; } + public string? Notes { get; init; } + + /// Render settings ("project") as JSON. + public string? SettingsJson { get; init; } + + /// Compact analysis summary as JSON; the full report lives in .titano/analysis.json. + public string? AnalysisJson { get; init; } + + public SequenceOrigin Origin { get; init; } + public SyncState SyncState { get; init; } + public int SettingsVersion { get; init; } + public int FramesVersion { get; init; } + public Guid? OwnerUserId { get; init; } + public int WarningCount { get; init; } + public DateTimeOffset UpdatedAt { get; init; } + + /// User title or "{date} {camera}". + public string DisplayTitle => !string.IsNullOrWhiteSpace(Title) + ? Title! + : $"{FirstCapture:yyyy-MM-dd} {CameraModel}".Trim(); +} + +/// One photo of a sequence. +public sealed record Frame +{ + public required Guid Id { get; init; } + public required Guid SequenceId { get; init; } + public required int Index { get; init; } + + /// Path relative to the archive root, forward slashes. + public required string RelativePath { get; init; } + + public required string FileName { get; init; } + public string? OriginalFileName { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 of the original file. + public string? Sha256 { get; init; } + + /// Camera wall-clock time including sub-seconds (unspecified kind). + public DateTime? CapturedAt { get; init; } + + /// UTC offset of when known, in minutes. + public int? UtcOffsetMinutes { get; init; } + + public TimestampSource TimestampSource { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? FocalLength { get; init; } + public double? ExposureBias { get; init; } + public int? WhiteBalance { get; init; } + public int Orientation { get; init; } = 1; + public int Width { get; init; } + public int Height { get; init; } + public ImageFileFormat Format { get; init; } + public long? PreviewOffset { get; init; } + public long? PreviewLength { get; init; } + + /// Mean log2 luminance once analysed. + public double? MeanLogLuminance { get; init; } + + public double? ClipLow { get; init; } + public double? ClipHigh { get; init; } + public FrameFlags Flags { get; init; } + + /// Exposure value at ISO 100: log2(N²/t) − log2(ISO/100). + public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0 + ? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso ?? 100) / 100.0) + : null; +} + +/// An exported video or image sequence. +public sealed record Render +{ + public required Guid Id { get; init; } + public required Guid SequenceId { get; init; } + public required string PresetName { get; init; } + public string? SettingsJson { get; init; } + public required string OutputPath { get; init; } + public string? Codec { get; init; } + public int Width { get; init; } + public int Height { get; init; } + public double Fps { get; init; } + public double DurationSeconds { get; init; } + public long Bytes { get; init; } + public DateTimeOffset Created { get; init; } + public string? ProducedBy { get; init; } +} + +/// Any long operation: resumable, cancellable, logged (BRIEF §5, §14.6). +public sealed record Job +{ + public required Guid Id { get; init; } + public required JobKind Kind { get; init; } + public IReadOnlyList TargetIds { get; init; } = []; + + /// Human-readable target ("Harbour sunset", "Archive · 2024"). + public string? TargetLabel { get; init; } + + public string? ParametersJson { get; init; } + public JobState State { get; init; } + public JobPriority Priority { get; init; } = JobPriority.Normal; + public long ProgressDone { get; init; } + public long ProgressTotal { get; init; } + public double? ItemsPerSecond { get; init; } + public TimeSpan? Eta { get; init; } + + /// Opaque resume cursor written at checkpoints. + public string? Checkpoint { get; init; } + + public string? LogTail { get; init; } + public Guid? CreatedBy { get; init; } + public string? NodeId { get; init; } + public int Attempts { get; init; } + public string? Error { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset? Started { get; init; } + public DateTimeOffset? Finished { get; init; } +} + +/// A memory card known to this client (BRIEF §13). +public sealed record MediaCard +{ + public required Guid Id { get; init; } + + /// {volumeSerial}-{label}-{capacity}. + public required string Identity { get; init; } + + public uint VolumeSerial { get; init; } + public string? Label { get; init; } + public long Capacity { get; init; } + public string? Nickname { get; init; } + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? ProfileJson { get; init; } + public bool AutoImport { get; init; } + public DateTimeOffset FirstSeen { get; init; } + public DateTimeOffset LastSeen { get; init; } +} + +public sealed record User +{ + public required Guid Id { get; init; } + public required string Username { get; init; } + public string? DisplayName { get; init; } + public required string PasswordHash { get; init; } + public UserRole Role { get; init; } + public Permissions Permissions { get; init; } + public long QuotaBytes { get; init; } + public long UsedBytes { get; init; } + public bool Disabled { get; init; } + public bool MustChangePassword { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset? LastLogin { get; init; } +} + +public sealed record SessionToken +{ + public required string TokenHash { get; init; } + public required Guid UserId { get; init; } + public string? ClientName { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset Expires { get; init; } + public DateTimeOffset LastUsed { get; init; } + public bool Revoked { get; init; } +} + +public sealed record RenderNode +{ + public required Guid Id { get; init; } + public required Guid UserId { get; init; } + public required string ClientName { get; init; } + public string? CapabilitiesJson { get; init; } + public DateTimeOffset LastHeartbeat { get; init; } + public string State { get; init; } = "idle"; +} + +public sealed record AuditEntry +{ + public required Guid Id { get; init; } + public DateTimeOffset At { get; init; } + public Guid? UserId { get; init; } + public string? Username { get; init; } + public required string Action { get; init; } + public string? TargetKind { get; init; } + public string? TargetId { get; init; } + public string? Details { get; init; } + public string? RemoteAddress { get; init; } +} diff --git a/src/Titano.Core/Model/Enums.cs b/src/Titano.Core/Model/Enums.cs new file mode 100644 index 00000000..a032754e --- /dev/null +++ b/src/Titano.Core/Model/Enums.cs @@ -0,0 +1,126 @@ +namespace Titano.Core.Model; + +/// Where a capture timestamp came from. +public enum TimestampSource +{ + Unknown = 0, + ExifOriginal, + ExifCreate, + Xmp, + QuickTime, + Gps, + FileSystem, +} + +[Flags] +public enum FrameFlags +{ + None = 0, + Missing = 1, + Corrupt = 2, + Duplicate = 4, + Excluded = 8, + PreviewOnly = 16, + Undecodable = 32, + Black = 64, + White = 128, +} + +[Flags] +public enum SequenceStatus +{ + None = 0, + AnalyzedLight = 1, + AnalyzedDeep = 2, + ProxiesBuilt = 4, + ThumbsBuilt = 8, + Verified = 16, + HasWarnings = 32, + HasErrors = 64, +} + +public enum SequenceOrigin +{ + Local, + Server, +} + +public enum SyncState +{ + LocalOnly, + InSync, + LocalAhead, + ServerAhead, + Conflict, + RemoteOnly, +} + +public enum JobKind +{ + Scan, + Rebuild, + Verify, + LightAnalyse, + DeepAnalyse, + Proxies, + Thumbs, + Render, + Import, + UploadCommit, + Maintenance, + Duplicates, + Orphans, + Adopt, + Move, +} + +public enum JobState +{ + Queued, + Running, + Paused, + Done, + Failed, + Cancelled, +} + +public enum JobPriority +{ + Background = 0, + Normal = 1, + User = 2, +} + +public enum UserRole +{ + Viewer, + Uploader, + Editor, + Admin, +} + +[Flags] +public enum Permissions : long +{ + None = 0, + Read = 1, + Upload = 2, + Edit = 4, + Delete = 8, + Render = 16, + RenderNode = 32, + ManageArchive = 64, + ManageUsers = 128, + All = Read | Upload | Edit | Delete | Render | RenderNode | ManageArchive | ManageUsers, +} + +public static class RolePermissions +{ + public static Permissions Default(UserRole role) => role switch + { + UserRole.Admin => Permissions.All, + UserRole.Editor => Permissions.Read | Permissions.Upload | Permissions.Edit | Permissions.Delete | Permissions.Render | Permissions.RenderNode, + UserRole.Uploader => Permissions.Read | Permissions.Upload, + _ => Permissions.Read, + }; +} diff --git a/src/Titano.Core/Naming/TemplateDefaults.cs b/src/Titano.Core/Naming/TemplateDefaults.cs new file mode 100644 index 00000000..23b2577d --- /dev/null +++ b/src/Titano.Core/Naming/TemplateDefaults.cs @@ -0,0 +1,8 @@ +namespace Titano.Core.Naming; + +/// Default naming templates (BRIEF §7.1). +public static class TemplateDefaults +{ + public const string Folder = "{year}/{date} {camera}"; + public const string File = "{date}_{time}_{n:0000}"; +} diff --git a/src/Titano.Core/Titano.Core.csproj b/src/Titano.Core/Titano.Core.csproj new file mode 100644 index 00000000..0a91bf3a --- /dev/null +++ b/src/Titano.Core/Titano.Core.csproj @@ -0,0 +1,11 @@ + + + net10.0 + Titano.Core + true + + + + + + diff --git a/src/Titano.Core/Video/Encoding.cs b/src/Titano.Core/Video/Encoding.cs new file mode 100644 index 00000000..e3e1bb42 --- /dev/null +++ b/src/Titano.Core/Video/Encoding.cs @@ -0,0 +1,134 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Video; + +public enum VideoCodec +{ + H264, + Hevc, + Av1, + Mjpeg, + JpegSequence, + PngSequence, + Tiff16Sequence, + LinearDngSequence, + Gif, + Apng, +} + +public enum ContainerFormat +{ + Mp4, + Avi, + ImageSequence, + Gif, + Apng, +} + +public enum RateControl +{ + Vbr, + Cbr, + Quality, +} + +public enum CodecProfile +{ + Auto, + H264Baseline, + H264Main, + H264High, + HevcMain, + HevcMain10, + Av1Main, +} + +public static class VideoCodecInfo +{ + public static ContainerFormat DefaultContainer(VideoCodec codec) => codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => ContainerFormat.Mp4, + VideoCodec.Mjpeg => ContainerFormat.Avi, + VideoCodec.Gif => ContainerFormat.Gif, + VideoCodec.Apng => ContainerFormat.Apng, + _ => ContainerFormat.ImageSequence, + }; + + /// True for codecs every platform can produce without an OS encoder. + public static bool IsManaged(VideoCodec codec) => codec is not (VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1); + + public static string FileExtension(VideoCodec codec) => codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => ".mp4", + VideoCodec.Mjpeg => ".avi", + VideoCodec.Gif => ".gif", + VideoCodec.Apng => ".png", + VideoCodec.JpegSequence => ".jpg", + VideoCodec.PngSequence => ".png", + VideoCodec.Tiff16Sequence => ".tif", + VideoCodec.LinearDngSequence => ".dng", + _ => ".bin", + }; +} + +/// What an encoder on this machine can do (shown in Settings › Rendering). +public sealed record EncoderCapability( + VideoCodec Codec, + string Name, + bool Hardware, + int MaxWidth, + int MaxHeight, + bool SupportsTenBit, + string? Vendor = null); + +/// Complete parameters of one encode. +public sealed record EncodeSettings +{ + public required string OutputPath { get; init; } + public required VideoCodec Codec { get; init; } + public required int Width { get; init; } + public required int Height { get; init; } + public required Rational FrameRate { get; init; } + public CodecProfile Profile { get; init; } = CodecProfile.Auto; + public int BitDepth { get; init; } = 8; + public RateControl RateControl { get; init; } = RateControl.Vbr; + + /// Average bit rate in bits per second (VBR/CBR). + public long BitRate { get; init; } + + /// 0–100 quality for , JPEG/MJPEG and GIF. + public int Quality { get; init; } = 90; + + /// Distance between key frames in frames; 0 = encoder default (≈ 1 s). + public int GopLength { get; init; } + + public int BFrames { get; init; } = 2; + public bool PreferHardware { get; init; } = true; + + /// Optional specific encoder name from . + public string? EncoderName { get; init; } +} + +/// One open encode. Frames are linear-light buffers at the output size. +public interface IVideoEncoderSession : IDisposable +{ + /// Encoder actually used ("NVIDIA NVENC H.264", "Managed MJPEG"). + string EncoderName { get; } + + bool IsHardware { get; } + + /// Appends a frame shown for ticks of a 90 kHz clock. + void WriteFrame(ImageBuffer frame, long duration90k); + + /// Flushes and closes the output. Without it, deletes the partial file. + void Complete(); +} + +/// A family of encoders (Media Foundation on Windows, managed everywhere). +public interface IVideoEncoderProvider +{ + string Name { get; } + IReadOnlyList Capabilities { get; } + bool CanEncode(EncodeSettings settings); + IVideoEncoderSession Open(EncodeSettings settings); +} diff --git a/src/Titano.Core/Video/Rational.cs b/src/Titano.Core/Video/Rational.cs new file mode 100644 index 00000000..cd2372e2 --- /dev/null +++ b/src/Titano.Core/Video/Rational.cs @@ -0,0 +1,29 @@ +using System.Globalization; + +namespace Titano.Core.Video; + +/// An exact frame rate such as 24000/1001. +public readonly record struct Rational(int Numerator, int Denominator) +{ + public double Value => (double)Numerator / Denominator; + + public static Rational Fps23976 { get; } = new(24000, 1001); + public static Rational Fps2997 { get; } = new(30000, 1001); + public static Rational Fps5994 { get; } = new(60000, 1001); + + public static Rational FromFps(double fps) + { + if (Math.Abs(fps - 23.976) < 0.01) return Fps23976; + if (Math.Abs(fps - 29.97) < 0.01) return Fps2997; + if (Math.Abs(fps - 59.94) < 0.01) return Fps5994; + if (Math.Abs(fps - Math.Round(fps)) < 1e-6) return new((int)Math.Round(fps), 1); + return new((int)Math.Round(fps * 1000), 1000); + } + + /// Duration of one frame in 90 kHz ticks (MP4 timescale used by Titano). + public long FrameTicks90k => (long)Math.Round(90000.0 * Denominator / Numerator); + + public override string ToString() => Denominator == 1 + ? Numerator.ToString(CultureInfo.InvariantCulture) + : Value.ToString("0.###", CultureInfo.InvariantCulture); +} diff --git a/src/Titano.Data/Dialect.cs b/src/Titano.Data/Dialect.cs new file mode 100644 index 00000000..4fe4f2fc --- /dev/null +++ b/src/Titano.Data/Dialect.cs @@ -0,0 +1,8 @@ +namespace Titano.Data; + +/// SQL dialect of an IDatabase. +public enum Dialect +{ + Sqlite, + Postgres, +} diff --git a/src/Titano.Data/Titano.Data.csproj b/src/Titano.Data/Titano.Data.csproj new file mode 100644 index 00000000..ee1ac377 --- /dev/null +++ b/src/Titano.Data/Titano.Data.csproj @@ -0,0 +1,13 @@ + + + net10.0 + Titano.Data + + + + + + + + + diff --git a/src/Titano.Protocol/ApiVersion.cs b/src/Titano.Protocol/ApiVersion.cs new file mode 100644 index 00000000..9eb139fd --- /dev/null +++ b/src/Titano.Protocol/ApiVersion.cs @@ -0,0 +1,8 @@ +namespace Titano.Protocol; + +/// API version negotiated through the X-Titano-Api header. +public static class ApiVersion +{ + public const int Current = 1; + public const string Header = "X-Titano-Api"; +} diff --git a/src/Titano.Protocol/Titano.Protocol.csproj b/src/Titano.Protocol/Titano.Protocol.csproj new file mode 100644 index 00000000..085fb7f3 --- /dev/null +++ b/src/Titano.Protocol/Titano.Protocol.csproj @@ -0,0 +1,6 @@ + + + net10.0 + Titano.Protocol + + diff --git a/src/Titano.Server/Admin/web/index.html b/src/Titano.Server/Admin/web/index.html new file mode 100644 index 00000000..7c26771a --- /dev/null +++ b/src/Titano.Server/Admin/web/index.html @@ -0,0 +1 @@ +Titano diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs new file mode 100644 index 00000000..14d0787d --- /dev/null +++ b/src/Titano.Server/Program.cs @@ -0,0 +1,4 @@ +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); +app.MapGet("/health", () => Results.Ok(new { status = "ok" })); +app.Run(); diff --git a/src/Titano.Server/Titano.Server.csproj b/src/Titano.Server/Titano.Server.csproj new file mode 100644 index 00000000..804605ea --- /dev/null +++ b/src/Titano.Server/Titano.Server.csproj @@ -0,0 +1,23 @@ + + + net10.0 + Titano.Server + Titano.Server + $(TitanoIconDir)titano-server.ico + true + false + + + + + + + + + + + + + + + diff --git a/src/Titano.Setup/App.xaml b/src/Titano.Setup/App.xaml new file mode 100644 index 00000000..f0e5e815 --- /dev/null +++ b/src/Titano.Setup/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.Setup/App.xaml.cs b/src/Titano.Setup/App.xaml.cs new file mode 100644 index 00000000..24976df3 --- /dev/null +++ b/src/Titano.Setup/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.Setup; + +public partial class App : Application +{ +} diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj new file mode 100644 index 00000000..4aa167fd --- /dev/null +++ b/src/Titano.Setup/Titano.Setup.csproj @@ -0,0 +1,15 @@ + + + WinExe + net10.0-windows + true + Titano.Setup + Titano.Setup + app.manifest + titano + + + + + + diff --git a/src/Titano.Setup/app.manifest b/src/Titano.Setup/app.manifest new file mode 100644 index 00000000..a25dd8ee --- /dev/null +++ b/src/Titano.Setup/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs new file mode 100644 index 00000000..2c835d93 --- /dev/null +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -0,0 +1,203 @@ +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using Titano.Core.Localization; + +namespace Titano.Tools.Commands; + +/// +/// i18n check: completeness of en and it, placeholder parity, length budgets and that +/// every key used in code/XAML/admin JS exists (BRIEF §16). +/// i18n export --out dir: one JSON per culture for the web admin. +/// +internal sealed partial class I18nCommand : ICommand +{ + private static readonly string[] RequiredCultures = ["en", "it"]; + private static readonly HashSet SentenceAreas = new(StringComparer.Ordinal) { "Tooltips", "Errors", "Advisor" }; + + public string Name => "i18n"; + public string Summary => "check | export --out (resource completeness and web export)"; + + public Task RunAsync(string[] args) + { + var a = new Args(args); + var sub = a.Positional.FirstOrDefault() ?? "check"; + var root = Args.RepoRoot(); + var catalog = Catalog.Load(Path.Combine(root, "i18n")); + return Task.FromResult(sub switch + { + "check" => Check(root, catalog), + "export" => Export(catalog, a.Get("out") ?? throw new ToolException("--out required")), + "missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture required")), + _ => throw new ToolException($"Unknown i18n subcommand '{sub}'"), + }); + } + + private static int Check(string root, Catalog catalog) + { + var errors = new List(); + var warnings = new List(); + if (!catalog.Cultures.TryGetValue("en", out var en)) throw new ToolException("i18n/en missing"); + + foreach (var (key, entry) in en) + { + var area = key.Split('.')[0]; + if (!entry.File.Equals(area, StringComparison.Ordinal)) + errors.Add($"en: key {key} lives in {entry.File}.resx but its area is {area}"); + var limit = Limit(key, area, entry.Comment); + if (entry.Value.Length > limit) + errors.Add($"en: {key} is {entry.Value.Length} chars (budget {limit})"); + if (string.IsNullOrWhiteSpace(entry.Value)) + errors.Add($"en: {key} is empty"); + } + + foreach (var (culture, strings) in catalog.Cultures) + { + if (culture == "en") continue; + var required = RequiredCultures.Contains(culture); + var missing = 0; + foreach (var (key, entry) in en) + { + if (entry.Comment is not null && entry.Comment.Contains("invariant", StringComparison.OrdinalIgnoreCase)) continue; + if (!strings.TryGetValue(key, out var translated)) + { + if (required) errors.Add($"{culture}: missing {key}"); + else missing++; + continue; + } + var p1 = Placeholders(entry.Value); + var p2 = Placeholders(translated.Value); + if (!p1.SetEquals(p2)) + errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}"); + var area = key.Split('.')[0]; + var limit = (int)(Limit(key, area, entry.Comment) * 1.6); + if (translated.Value.Length > limit) + warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})"); + } + if (missing > 0) warnings.Add($"{culture}: {missing} key(s) not translated yet"); + foreach (var key in strings.Keys.Where(k => !en.ContainsKey(k))) + errors.Add($"{culture}: orphan key {key}"); + } + + foreach (var (file, key) in UsedKeys(root)) + { + if (en.ContainsKey(key)) continue; + // Plural lookups reference the stem; any suffix satisfies them. + if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue; + errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}"); + } + + foreach (var w in warnings.Take(50)) Console.WriteLine("warning: " + w); + if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more"); + foreach (var e in errors) Console.Error.WriteLine("error: " + e); + Console.WriteLine($"i18n: {en.Count} keys, {catalog.Cultures.Count} cultures, {errors.Count} error(s), {warnings.Count} warning(s)"); + return errors.Count == 0 ? 0 : 1; + } + + private static int Missing(Catalog catalog, string culture) + { + var en = catalog.Cultures["en"]; + catalog.Cultures.TryGetValue(culture, out var target); + foreach (var (key, entry) in en.OrderBy(k => k.Key, StringComparer.Ordinal)) + { + if (target is null || !target.ContainsKey(key)) Console.WriteLine($"{key}\t{entry.Value}"); + } + return 0; + } + + private static int Limit(string key, string area, string? comment) + { + if (comment is not null && comment.Contains("long", StringComparison.OrdinalIgnoreCase)) return 200; + if (SentenceAreas.Contains(area) || key.EndsWith(".Tip", StringComparison.Ordinal)) return 200; + return 30; + } + + private static int Export(Catalog catalog, string outDir) + { + Directory.CreateDirectory(outDir); + var en = catalog.Cultures["en"]; + foreach (var (culture, strings) in catalog.Cultures) + { + var merged = new SortedDictionary(StringComparer.Ordinal); + foreach (var (k, v) in en) merged[k] = strings.TryGetValue(k, out var t) ? t.Value : v.Value; + var json = JsonSerializer.Serialize(merged, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + File.WriteAllText(Path.Combine(outDir, culture + ".json"), json, new UTF8Encoding(false)); + } + Console.WriteLine($"Exported {catalog.Cultures.Count} cultures to {outDir}"); + return 0; + } + + private static HashSet Placeholders(string s) => + [.. PlaceholderRegex().Matches(s).Select(m => m.Groups[1].Value)]; + + /// Keys referenced from C# (L("…"), Plural("…"), Loc.Get("…")), XAML ({l:Loc …}) and admin JS (t("…")). + private static IEnumerable<(string File, string Key)> UsedKeys(string root) + { + var src = Path.Combine(root, "src"); + foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories)) + { + if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + || file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue; + var ext = Path.GetExtension(file); + Regex? regex = ext switch + { + ".cs" => CsKeyRegex(), + ".xaml" => XamlKeyRegex(), + ".js" or ".html" => JsKeyRegex(), + _ => null, + }; + if (regex is null) continue; + var text = File.ReadAllText(file); + foreach (Match m in regex.Matches(text)) yield return (file, m.Groups[1].Value); + } + } + + [GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")] + private static partial Regex PlaceholderRegex(); + + [GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")] + private static partial Regex CsKeyRegex(); + + [GeneratedRegex(@"\{(?:l|loc):Loc\s+(?:Key=)?([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")] + private static partial Regex XamlKeyRegex(); + + [GeneratedRegex(@"(?:\bt\(\s*['""]|data-i18n(?:-[a-z]+)?=['""])([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)")] + private static partial Regex JsKeyRegex(); + + [GeneratedRegex(@"^(one|few|many|other)$")] + private static partial Regex PluralSuffix(); + + internal sealed record Entry(string File, string Value, string? Comment); + + internal sealed class Catalog + { + public Dictionary> Cultures { get; } = new(StringComparer.OrdinalIgnoreCase); + + public static Catalog Load(string dir) + { + var c = new Catalog(); + foreach (var cultureDir in Directory.EnumerateDirectories(dir)) + { + var culture = Path.GetFileName(cultureDir); + var strings = new Dictionary(StringComparer.Ordinal); + foreach (var file in Directory.EnumerateFiles(cultureDir, "*.resx")) + { + var area = Path.GetFileName(file).Split('.')[0]; + var doc = XDocument.Load(file); + foreach (var data in doc.Root!.Elements("data")) + { + var name = (string?)data.Attribute("name") ?? throw new ToolException($"{file}: data without name"); + var value = (string?)data.Element("value") ?? string.Empty; + if (!strings.TryAdd(name, new Entry(area, value, (string?)data.Element("comment")))) + throw new ToolException($"{file}: duplicate key {name}"); + } + } + c.Cultures[culture] = strings; + } + foreach (var code in Languages.Shipped.Where(s => !c.Cultures.ContainsKey(s))) + c.Cultures.TryAdd(code, new Dictionary(StringComparer.Ordinal)); + return c; + } + } +} diff --git a/src/Titano.Tools/Commands/MakeIconCommand.cs b/src/Titano.Tools/Commands/MakeIconCommand.cs new file mode 100644 index 00000000..a2fbea23 --- /dev/null +++ b/src/Titano.Tools/Commands/MakeIconCommand.cs @@ -0,0 +1,51 @@ +using Titano.Core.Branding; +using Titano.Core.Codecs.Ico; +using Titano.Core.Codecs.Png; + +namespace Titano.Tools.Commands; + +/// Generates ICO/PNG sets and SVG masters from geometry. +internal sealed class MakeIconCommand : ICommand +{ + private static readonly int[] IcoSizes = [16, 20, 24, 32, 48, 64, 128, 256]; + + public string Name => "make-icon"; + public string Summary => "Generate ICO/PNG/SVG brand assets (--out dir, --svg dir to refresh masters)"; + + public Task RunAsync(string[] args) + { + var a = new Args(args); + var outDir = Path.GetFullPath(a.Get("out", Path.Combine(Args.RepoRoot(), "artifacts", "icons"))); + Directory.CreateDirectory(outDir); + + foreach (var (variant, name) in new[] + { + (BrandVariant.App, "titano"), + (BrandVariant.Server, "titano-server"), + (BrandVariant.Uploader, "titano-uploader"), + (BrandVariant.Mono, "titano-mono"), + }) + { + var images = IcoSizes.Select(s => (s, BrandMark.Render(variant, s))).ToList(); + File.WriteAllBytes(Path.Combine(outDir, name + ".ico"), IcoWriter.Write(images)); + foreach (var size in new[] { 16, 32, 48, 64, 128, 256, 512, 1024 }) + { + var rgba = BrandMark.Render(variant, size); + File.WriteAllBytes(Path.Combine(outDir, $"{name}-{size}.png"), PngEncoder.Encode(rgba, size, size, PngColorType.Rgba)); + } + File.WriteAllText(Path.Combine(outDir, name + ".svg"), BrandMark.ToSvg(variant)); + } + + if (a.Get("svg") is { } svgDir) + { + Directory.CreateDirectory(svgDir); + File.WriteAllText(Path.Combine(svgDir, "titano.svg"), BrandMark.ToSvg(BrandVariant.App)); + File.WriteAllText(Path.Combine(svgDir, "titano-server.svg"), BrandMark.ToSvg(BrandVariant.Server)); + File.WriteAllText(Path.Combine(svgDir, "titano-uploader.svg"), BrandMark.ToSvg(BrandVariant.Uploader)); + File.WriteAllText(Path.Combine(svgDir, "titano-mono.svg"), BrandMark.ToSvg(BrandVariant.Mono)); + } + + Console.WriteLine($"Icons written to {outDir}"); + return Task.FromResult(0); + } +} diff --git a/src/Titano.Tools/Commands/PackageGuardCommand.cs b/src/Titano.Tools/Commands/PackageGuardCommand.cs new file mode 100644 index 00000000..44fa2cc8 --- /dev/null +++ b/src/Titano.Tools/Commands/PackageGuardCommand.cs @@ -0,0 +1,45 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Titano.Tools.Commands; + +/// BRIEF §19.2: no PackageReference anywhere and no restored packages in project.assets.json. +internal sealed partial class PackageGuardCommand : ICommand +{ + public string Name => "package-guard"; + public string Summary => "Fail when any project references or restores a package"; + + public Task RunAsync(string[] args) + { + var root = Args.RepoRoot(); + var failures = new List(); + foreach (var file in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories) + .Where(f => f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".props", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".targets", StringComparison.OrdinalIgnoreCase)) + .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))) + { + var text = File.ReadAllText(file); + if (PackageReference().IsMatch(text)) failures.Add($"{Path.GetRelativePath(root, file)}: PackageReference"); + } + + foreach (var assets in Directory.EnumerateFiles(root, "project.assets.json", SearchOption.AllDirectories)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(assets)); + if (doc.RootElement.TryGetProperty("libraries", out var libs)) + { + foreach (var lib in libs.EnumerateObject()) + { + if (lib.Value.TryGetProperty("type", out var type) && type.GetString() == "package") + failures.Add($"{Path.GetRelativePath(root, assets)}: restored package {lib.Name}"); + } + } + } + + foreach (var f in failures) Console.Error.WriteLine(f); + Console.WriteLine(failures.Count == 0 ? "Zero packages: OK" : $"{failures.Count} package violation(s)"); + return Task.FromResult(failures.Count == 0 ? 0 : 1); + } + + [GeneratedRegex(@"<\s*PackageReference\b", RegexOptions.IgnoreCase)] + private static partial Regex PackageReference(); +} diff --git a/src/Titano.Tools/Commands/XamlLintCommand.cs b/src/Titano.Tools/Commands/XamlLintCommand.cs new file mode 100644 index 00000000..bf4c1f2e --- /dev/null +++ b/src/Titano.Tools/Commands/XamlLintCommand.cs @@ -0,0 +1,74 @@ +using System.Xml.Linq; + +namespace Titano.Tools.Commands; + +/// +/// BRIEF §20.3 / DESIGN §4: every actionable control carries a tooltip and no visible text is a literal. +/// Elements inside ControlTemplates are template parts and exempt from the tooltip rule. +/// +internal sealed class XamlLintCommand : ICommand +{ + private static readonly HashSet Actionable = new(StringComparer.Ordinal) + { + "Button", "ToggleButton", "RepeatButton", "Slider", "ComboBox", "CheckBox", "RadioButton", "MenuItem", + "AutoSlider", "IconButton", "SplitButton", + }; + + private static readonly string[] TextAttributes = ["Content", "Text", "Header", "ToolTip", "Title", "Tag"]; + + public string Name => "xaml-lint"; + public string Summary => "Check tooltips and literal text in all XAML under src/"; + + public Task RunAsync(string[] args) + { + var root = Args.RepoRoot(); + var problems = new List(); + var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.xaml", SearchOption.AllDirectories) + .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .ToList(); + + foreach (var file in files) + { + var doc = XDocument.Load(file, LoadOptions.SetLineInfo); + foreach (var el in doc.Descendants()) + { + var line = ((System.Xml.IXmlLineInfo)el).LineNumber; + var where = $"{Path.GetRelativePath(root, file)}:{line}"; + var name = el.Name.LocalName; + var inTemplate = el.Ancestors().Any(a => a.Name.LocalName is "ControlTemplate" or "Setter" or "Style"); + + if (Actionable.Contains(name) && !inTemplate && !HasToolTip(el) && !IsExempt(el)) + problems.Add($"{where}: <{name}> has no ToolTip"); + + foreach (var attrName in TextAttributes) + { + var attr = el.Attribute(attrName); + if (attr is null) continue; + var v = attr.Value; + if (v.Length == 0 || v.StartsWith('{')) continue; + if (attrName == "Tag" || (attrName == "Content" && inTemplate)) continue; + if (v.Any(char.IsLetter)) + problems.Add($"{where}: literal {attrName}=\"{v}\" on <{name}> (use {{l:Loc …}})"); + } + + // Literal element content such as Hello or Hi. + if (name is "TextBlock" or "Run" or "Label" or "Button" && !el.HasElements && el.Value.Any(char.IsLetter)) + problems.Add($"{where}: literal text in <{name}>"); + } + } + + foreach (var p in problems) Console.Error.WriteLine(p); + Console.WriteLine($"xaml-lint: {files.Count} file(s), {problems.Count} problem(s)"); + return Task.FromResult(problems.Count == 0 ? 0 : 1); + } + + private static bool HasToolTip(XElement el) => + el.Attribute("ToolTip") is not null + || el.Elements().Any(c => c.Name.LocalName.EndsWith(".ToolTip", StringComparison.Ordinal)) + || el.Attributes().Any(a => a.Name.LocalName == "TipKey"); + + /// Opt-out for controls whose tooltip is applied by a style (marked explicitly in XAML). + private static bool IsExempt(XElement el) => + el.Attributes().Any(a => a.Name.LocalName == "ToolTipFromStyle" && a.Value == "True"); +} diff --git a/src/Titano.Tools/ICommand.cs b/src/Titano.Tools/ICommand.cs new file mode 100644 index 00000000..b5767027 --- /dev/null +++ b/src/Titano.Tools/ICommand.cs @@ -0,0 +1,61 @@ +namespace Titano.Tools; + +internal interface ICommand +{ + string Name { get; } + string Summary { get; } + Task RunAsync(string[] args); +} + +internal sealed class ToolException(string message) : Exception(message); + +/// Minimal option parser: --key value, --flag, positional arguments. +internal sealed class Args +{ + private readonly Dictionary _options = new(StringComparer.OrdinalIgnoreCase); + + public Args(string[] args, params string[] flags) + { + for (var i = 0; i < args.Length; i++) + { + var a = args[i]; + if (a.StartsWith("--", StringComparison.Ordinal)) + { + var key = a[2..]; + if (flags.Contains(key, StringComparer.OrdinalIgnoreCase) || i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + _options[key] = null; + else + _options[key] = args[++i]; + } + else + { + Positional.Add(a); + } + } + } + + public List Positional { get; } = []; + + public bool Has(string key) => _options.ContainsKey(key); + + public string? Get(string key) => _options.TryGetValue(key, out var v) ? v : null; + + public string Get(string key, string fallback) => Get(key) ?? fallback; + + public static string RepoRoot() + { + var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + throw new ToolException("Repository root (Titano.slnx) not found."); + } +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs new file mode 100644 index 00000000..5d569615 --- /dev/null +++ b/src/Titano.Tools/Program.cs @@ -0,0 +1,34 @@ +using Titano.Tools; +using Titano.Tools.Commands; + +var commands = new ICommand[] +{ + new MakeIconCommand(), + new I18nCommand(), + new XamlLintCommand(), + new PackageGuardCommand(), +}; + +if (args.Length == 0 || args[0] is "-h" or "--help" or "help") +{ + Console.WriteLine("Titano.Tools [options]"); + foreach (var c in commands) Console.WriteLine($" {c.Name,-14} {c.Summary}"); + return args.Length == 0 ? 2 : 0; +} + +var command = commands.FirstOrDefault(c => c.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase)); +if (command is null) +{ + Console.Error.WriteLine($"Unknown command '{args[0]}'. Run with --help."); + return 2; +} + +try +{ + return await command.RunAsync(args[1..]); +} +catch (ToolException ex) +{ + Console.Error.WriteLine(ex.Message); + return 2; +} diff --git a/src/Titano.Tools/Titano.Tools.csproj b/src/Titano.Tools/Titano.Tools.csproj new file mode 100644 index 00000000..167ccda0 --- /dev/null +++ b/src/Titano.Tools/Titano.Tools.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + Titano.Tools + Titano.Tools + + + + + + + diff --git a/src/Titano.Ui/Titano.Ui.csproj b/src/Titano.Ui/Titano.Ui.csproj new file mode 100644 index 00000000..fba00245 --- /dev/null +++ b/src/Titano.Ui/Titano.Ui.csproj @@ -0,0 +1,10 @@ + + + net10.0-windows + true + Titano.Ui + + + + + diff --git a/src/Titano.Ui/UiAssembly.cs b/src/Titano.Ui/UiAssembly.cs new file mode 100644 index 00000000..70b27ca4 --- /dev/null +++ b/src/Titano.Ui/UiAssembly.cs @@ -0,0 +1,6 @@ +namespace Titano.Ui; + +/// Shared WPF theme, controls and localization bindings for Titano desktop programs. +public static class UiAssembly +{ +} diff --git a/src/Titano.Uploader/App.xaml b/src/Titano.Uploader/App.xaml new file mode 100644 index 00000000..6e70f617 --- /dev/null +++ b/src/Titano.Uploader/App.xaml @@ -0,0 +1,4 @@ + + diff --git a/src/Titano.Uploader/App.xaml.cs b/src/Titano.Uploader/App.xaml.cs new file mode 100644 index 00000000..67a0cc99 --- /dev/null +++ b/src/Titano.Uploader/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace Titano.Uploader; + +public partial class App : Application +{ +} diff --git a/src/Titano.Uploader/Titano.Uploader.csproj b/src/Titano.Uploader/Titano.Uploader.csproj new file mode 100644 index 00000000..abfba7d6 --- /dev/null +++ b/src/Titano.Uploader/Titano.Uploader.csproj @@ -0,0 +1,16 @@ + + + WinExe + net10.0-windows + true + Titano.Uploader + Titano.Uploader + app.manifest + titano-uploader + + + + + + + diff --git a/src/Titano.Uploader/app.manifest b/src/Titano.Uploader/app.manifest new file mode 100644 index 00000000..0890c857 --- /dev/null +++ b/src/Titano.Uploader/app.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + true + + + + + + + + diff --git a/tests/Titano.App.Tests/Program.cs b/tests/Titano.App.Tests/Program.cs new file mode 100644 index 00000000..e4838431 --- /dev/null +++ b/tests/Titano.App.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.App.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.App.Tests/Titano.App.Tests.csproj b/tests/Titano.App.Tests/Titano.App.Tests.csproj new file mode 100644 index 00000000..43859d50 --- /dev/null +++ b/tests/Titano.App.Tests/Titano.App.Tests.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0-windows + true + Titano.App.Tests + + + + + + + diff --git a/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs b/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs new file mode 100644 index 00000000..2116fd20 --- /dev/null +++ b/tests/Titano.Core.Tests/Branding/BrandMarkTests.cs @@ -0,0 +1,62 @@ +using Titano.Core.Branding; +using Titano.Core.Codecs.Ico; +using Titano.Testing; + +namespace Titano.Core.Tests.Branding; + +public sealed class BrandMarkTests +{ + [Test] + public void TickOpacityRampsFromDimToFull() + { + Assert.Approximately(0.14, BrandMark.TickOpacity(0), 1e-9); + Assert.Approximately(1.0, BrandMark.TickOpacity(11), 1e-9); + Assert.Monotonic(Enumerable.Range(0, 12).Select(BrandMark.TickOpacity), strict: true); + } + + [Test] + public void SunPixelIsSunColour() + { + var rgba = BrandMark.Render(BrandVariant.App, 256); + var o = (104 * 256 + 152) * 4; + Assert.Equal(BrandMark.Sun.R, rgba[o]); + Assert.Equal(BrandMark.Sun.G, rgba[o + 1]); + Assert.Equal(BrandMark.Sun.B, rgba[o + 2]); + Assert.Equal((byte)255, rgba[o + 3]); + } + + [Test] + public void CornersOutsideRoundedPlateAreTransparent() + { + var rgba = BrandMark.Render(BrandVariant.App, 64); + Assert.Equal((byte)0, rgba[3]); + Assert.Equal((byte)255, rgba[(32 * 64 + 32) * 4 + 3]); + } + + [Test] + public void MonoHasNoPlate() + { + var rgba = BrandMark.Render(BrandVariant.Mono, 64); + Assert.Equal((byte)0, rgba[(4 * 64 + 32) * 4 + 3]); + } + + [Test] + public void SvgMatchesDesignMaster() + { + var master = File.ReadAllText(Path.Combine(TestContext.RepositoryRoot, "branding", "titano.svg")).Replace("\r", "", StringComparison.Ordinal); + Assert.Equal(master.Trim(), BrandMark.ToSvg(BrandVariant.App).Trim()); + } + + [Test] + public void IcoHasAllSizes() + { + var sizes = new[] { 16, 32, 48, 256 }; + var ico = IcoWriter.Write(sizes.Select(s => (s, BrandMark.Render(BrandVariant.App, s))).ToList()); + Assert.Equal((byte)0, ico[0]); + Assert.Equal((byte)1, ico[2]); + Assert.Equal(sizes.Length, ico[4] | ico[5] << 8); + // 256 px entry stored as PNG. + var lastOffset = BitConverter.ToInt32(ico, 6 + 16 * 3 + 12); + Assert.Equal((byte)0x89, ico[lastOffset]); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs b/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs new file mode 100644 index 00000000..62d1d6fb --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/AtomicFileTests.cs @@ -0,0 +1,33 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class AtomicFileTests(TestContext context) +{ + [Test] + public void ReplacesContentAndLeavesNoTemporaryFiles() + { + var dir = context.CreateTempDirectory(); + var path = Path.Combine(dir, "sequence.json"); + AtomicFile.WriteAllText(path, "one"); + AtomicFile.WriteAllText(path, "two"); + Assert.Equal("two", File.ReadAllText(path)); + Assert.Count(1, Directory.GetFiles(dir)); + } + + [Test] + public async Task FailedWriteKeepsPreviousContent() + { + var dir = context.CreateTempDirectory(); + var path = Path.Combine(dir, "project.json"); + AtomicFile.WriteAllText(path, "stable"); + await Assert.ThrowsAsync(() => AtomicFile.WriteAsync(path, async (s, ct) => + { + await s.WriteAsync("partial"u8.ToArray(), ct); + throw new InvalidOperationException("boom"); + })); + Assert.Equal("stable", File.ReadAllText(path)); + Assert.Count(1, Directory.GetFiles(dir)); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs b/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs new file mode 100644 index 00000000..fb77be68 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/Crc32Tests.cs @@ -0,0 +1,25 @@ +using System.Text; +using Titano.Core.Hashing; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class Crc32Tests +{ + [Test] + public void CheckValueMatchesStandard() => Assert.Equal(0xCBF43926u, Crc32.Compute("123456789"u8)); + + [Test] + public void IncrementalEqualsOneShot() + { + var data = Encoding.ASCII.GetBytes(new string('x', 1000) + "titano"); + var crc = new Crc32(); + crc.Append(data.AsSpan(0, 7)); + crc.Append(data.AsSpan(7, 500)); + crc.Append(data.AsSpan(507)); + Assert.Equal(Crc32.Compute(data), crc.GetCurrentHashAsUInt32()); + } + + [Test] + public void EmptyInputIsZero() => Assert.Equal(0u, Crc32.Compute([])); +} diff --git a/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs b/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs new file mode 100644 index 00000000..4a922ef6 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/ImageBufferTests.cs @@ -0,0 +1,44 @@ +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class ImageBufferTests +{ + [Test] + public void PlanesAreIndependentAndClearedByDefault() + { + using var image = new ImageBuffer(4, 3); + Assert.Equal(12, image.PlaneLength); + Assert.True(image.Data.ToArray().All(v => v == 0)); + image[1, 2, 1] = 0.5f; + Assert.Equal(0.5f, image.Plane(1)[1 * 4 + 2]); + Assert.Equal(0f, image.Plane(0)[1 * 4 + 2]); + } + + [Test] + public void CloneCopiesPixels() + { + using var image = new ImageBuffer(2, 2, 1); + image[0, 1, 1] = 3f; + using var clone = image.Clone(); + image[0, 1, 1] = 0f; + Assert.Equal(3f, clone[0, 1, 1]); + } + + [Test] + public void DisposedBufferThrows() + { + var image = new ImageBuffer(1, 1); + image.Dispose(); + Assert.Throws(() => _ = image.Storage); + } + + [Theory] + [Case("IMG_0001.CR2", ImageFileFormat.Cr2)] + [Case("a.jpeg", ImageFileFormat.Jpeg)] + [Case("photo.HEIC", ImageFileFormat.Heif)] + [Case("notes.txt", ImageFileFormat.Unknown)] + public void FormatFromExtension(string name, ImageFileFormat expected) => + Assert.Equal(expected, ImageFormatInfo.FromPath(name).Format); +} diff --git a/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs b/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs new file mode 100644 index 00000000..e14bfcd4 --- /dev/null +++ b/tests/Titano.Core.Tests/Localization/PluralRulesTests.cs @@ -0,0 +1,38 @@ +using System.Globalization; +using Titano.Core.Localization; +using Titano.Testing; + +namespace Titano.Core.Tests.Localization; + +public sealed class PluralRulesTests +{ + [Theory] + [Case("en", 1L, PluralCategory.One)] + [Case("en", 0L, PluralCategory.Other)] + [Case("fr", 0L, PluralCategory.One)] + [Case("ru", 21L, PluralCategory.One)] + [Case("ru", 22L, PluralCategory.Few)] + [Case("ru", 11L, PluralCategory.Many)] + [Case("ru", 25L, PluralCategory.Many)] + [Case("pl", 12L, PluralCategory.Many)] + [Case("pl", 23L, PluralCategory.Few)] + [Case("cs", 3L, PluralCategory.Few)] + [Case("ja", 1L, PluralCategory.Other)] + [Case("ar", 11L, PluralCategory.Many)] + public void SelectsCldrCategory(string culture, long count, PluralCategory expected) => + Assert.Equal(expected, PluralRules.Select(CultureInfo.GetCultureInfo(culture), count)); + + [Test] + public void BestMatchFallsBackToEnglish() + { + Assert.Equal("it", Languages.BestMatch(CultureInfo.GetCultureInfo("it-CH")).Name); + Assert.Equal("pt-BR", Languages.BestMatch(CultureInfo.GetCultureInfo("pt-BR")).Name); + Assert.Equal("en", Languages.BestMatch(CultureInfo.GetCultureInfo("sw")).Name); + } + + [Test] + public void EveryShippedLanguageIsAKnownCulture() + { + foreach (var code in Languages.Shipped) Assert.NotNull(CultureInfo.GetCultureInfo(code)); + } +} diff --git a/tests/Titano.Core.Tests/Program.cs b/tests/Titano.Core.Tests/Program.cs new file mode 100644 index 00000000..905d7a45 --- /dev/null +++ b/tests/Titano.Core.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Core.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Core.Tests/Titano.Core.Tests.csproj b/tests/Titano.Core.Tests/Titano.Core.Tests.csproj new file mode 100644 index 00000000..2a01ce7b --- /dev/null +++ b/tests/Titano.Core.Tests/Titano.Core.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Core.Tests + + + + + + + diff --git a/tests/Titano.Core.Windows.Tests/Program.cs b/tests/Titano.Core.Windows.Tests/Program.cs new file mode 100644 index 00000000..09bb9745 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Core.Windows.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj b/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj new file mode 100644 index 00000000..0da39c1c --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Titano.Core.Windows.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0-windows + Titano.Core.Windows.Tests + + + + + + diff --git a/tests/Titano.Data.Tests/Program.cs b/tests/Titano.Data.Tests/Program.cs new file mode 100644 index 00000000..92339124 --- /dev/null +++ b/tests/Titano.Data.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Data.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Data.Tests/Titano.Data.Tests.csproj b/tests/Titano.Data.Tests/Titano.Data.Tests.csproj new file mode 100644 index 00000000..7d259b6f --- /dev/null +++ b/tests/Titano.Data.Tests/Titano.Data.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Data.Tests + + + + + + + diff --git a/tests/Titano.Server.Tests/Program.cs b/tests/Titano.Server.Tests/Program.cs new file mode 100644 index 00000000..58b57f8d --- /dev/null +++ b/tests/Titano.Server.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Server.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Server.Tests/Titano.Server.Tests.csproj b/tests/Titano.Server.Tests/Titano.Server.Tests.csproj new file mode 100644 index 00000000..5bbe584c --- /dev/null +++ b/tests/Titano.Server.Tests/Titano.Server.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + Titano.Server.Tests + + + + + + + diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs new file mode 100644 index 00000000..8530989f --- /dev/null +++ b/tests/Titano.Testing/Assert.cs @@ -0,0 +1,251 @@ +using System.Collections; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace Titano.Testing; + +/// Assertions with messages that state expected and actual values. +public static class Assert +{ + public static void True(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + { + if (!condition) Fail(message ?? $"Expected true: {expression}"); + } + + public static void False(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + { + if (condition) Fail(message ?? $"Expected false: {expression}"); + } + + public static void Null(object? value, [CallerArgumentExpression(nameof(value))] string? expression = null) + { + if (value is not null) Fail($"Expected null: {expression} was {Format(value)}"); + } + + public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class + { + if (value is null) Fail($"Expected non-null: {expression}"); + return value!; + } + + public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct + { + if (value is null) Fail($"Expected non-null: {expression}"); + return value!.Value; + } + + public static void Equal(T expected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + Fail(Prefix(message) + $"{expression}: expected {Format(expected)}, actual {Format(actual)}"); + } + + public static void NotEqual(T unexpected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (EqualityComparer.Default.Equals(unexpected, actual)) + Fail(Prefix(message) + $"{expression}: did not expect {Format(unexpected)}"); + } + + public static void Same(object? expected, object? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!ReferenceEquals(expected, actual)) Fail($"{expression}: expected the same instance"); + } + + /// |expected − actual| ≤ tolerance. + public static void Approximately(double expected, double actual, double tolerance, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (double.IsNaN(actual) || Math.Abs(expected - actual) > tolerance) + Fail(Prefix(message) + $"{expression}: expected {F(expected)} ± {F(tolerance)}, actual {F(actual)} (diff {F(Math.Abs(expected - actual))})"); + } + + /// Distance between two points ≤ . + public static void Within(double expectedX, double expectedY, double actualX, double actualY, double pixels, string? message = null) + { + var d = Math.Sqrt((expectedX - actualX) * (expectedX - actualX) + (expectedY - actualY) * (expectedY - actualY)); + if (!(d <= pixels)) + Fail(Prefix(message) + $"expected ({F(expectedX)}, {F(expectedY)}) within {F(pixels)} px, actual ({F(actualX)}, {F(actualY)}) at {F(d)} px"); + } + + public static void InRange(double actual, double min, double max, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual >= min && actual <= max)) + Fail(Prefix(message) + $"{expression}: expected in [{F(min)}, {F(max)}], actual {F(actual)}"); + } + + public static void Greater(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual > bound)) Fail(Prefix(message) + $"{expression}: expected > {F(bound)}, actual {F(actual)}"); + } + + public static void GreaterOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual >= bound)) Fail(Prefix(message) + $"{expression}: expected ≥ {F(bound)}, actual {F(actual)}"); + } + + public static void Less(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual < bound)) Fail(Prefix(message) + $"{expression}: expected < {F(bound)}, actual {F(actual)}"); + } + + public static void LessOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (!(actual <= bound)) Fail(Prefix(message) + $"{expression}: expected ≤ {F(bound)}, actual {F(actual)}"); + } + + public static void SequenceEqual(IEnumerable expected, IEnumerable actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + var e = expected.ToList(); + var a = actual.ToList(); + var n = Math.Min(e.Count, a.Count); + for (var i = 0; i < n; i++) + { + if (!EqualityComparer.Default.Equals(e[i], a[i])) + Fail(Prefix(message) + $"{expression}: first difference at [{i}]: expected {Format(e[i])}, actual {Format(a[i])}"); + } + if (e.Count != a.Count) + Fail(Prefix(message) + $"{expression}: expected {e.Count} items, actual {a.Count}"); + } + + public static void BytesEqual(ReadOnlySpan expected, ReadOnlySpan actual, string? message = null) + { + var n = Math.Min(expected.Length, actual.Length); + for (var i = 0; i < n; i++) + { + if (expected[i] != actual[i]) + Fail(Prefix(message) + $"bytes differ at offset {i}: expected 0x{expected[i]:X2}, actual 0x{actual[i]:X2}"); + } + if (expected.Length != actual.Length) + Fail(Prefix(message) + $"expected {expected.Length} bytes, actual {actual.Length}"); + } + + /// Every element is ≥ (or > when strict) the previous one. + public static void Monotonic(IEnumerable values, bool strict = false, bool decreasing = false, string? message = null) + { + var i = 0; + double? previous = null; + foreach (var v in values) + { + if (previous is { } p) + { + var ok = decreasing + ? (strict ? v < p : v <= p) + : (strict ? v > p : v >= p); + if (!ok) Fail(Prefix(message) + $"not monotonic at [{i}]: {F(p)} then {F(v)}"); + } + previous = v; + i++; + } + } + + public static void Contains(T expected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + if (!collection.Contains(expected)) Fail($"{expression}: does not contain {Format(expected)}"); + } + + public static void DoesNotContain(T unexpected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + if (collection.Contains(unexpected)) Fail($"{expression}: unexpectedly contains {Format(unexpected)}"); + } + + public static void Contains(string expected, string? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null) + { + if (actual is null || !actual.Contains(expected, StringComparison.Ordinal)) + Fail($"{expression}: expected to contain \"{expected}\", actual {Format(actual)}"); + } + + public static void Empty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + foreach (var item in collection) Fail($"{expression}: expected empty, first item {Format(item)}"); + } + + public static void NotEmpty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + foreach (var _ in collection) return; + Fail($"{expression}: expected at least one item"); + } + + public static void Count(int expected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) + { + var n = 0; + foreach (var _ in collection) n++; + if (n != expected) Fail($"{expression}: expected {expected} items, actual {n}"); + } + + public static TException Throws(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception + { + try + { + action(); + } + catch (TException ex) + { + return ex; + } + catch (Exception ex) + { + Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}"); + } + Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown"); + return null!; + } + + public static async Task ThrowsAsync(Func action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception + { + try + { + await action().ConfigureAwait(false); + } + catch (TException ex) + { + return ex; + } + catch (Exception ex) + { + Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}"); + } + Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown"); + return null!; + } + + public static void DoesNotThrow(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null) + { + try + { + action(); + } + catch (Exception ex) + { + Fail($"{expression}: unexpected {ex.GetType().Name}: {ex.Message}"); + } + } + + public static void FileExists(string path) + { + if (!File.Exists(path)) Fail($"File not found: {path}"); + } + + public static void FileMissing(string path) + { + if (File.Exists(path)) Fail($"File should not exist: {path}"); + } + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Fail(string message) => throw new AssertionException(message); + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Inconclusive(string reason) => throw new SkipException(reason); + + private static string Prefix(string? message) => string.IsNullOrEmpty(message) ? string.Empty : message + ": "; + + private static string F(double v) => v.ToString("G6", CultureInfo.InvariantCulture); + + internal static string Format(object? value) => value switch + { + null => "null", + string s => "\"" + s + "\"", + double d => F(d), + float f => F(f), + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() ?? value.GetType().Name, + }; +} diff --git a/tests/Titano.Testing/AssertionException.cs b/tests/Titano.Testing/AssertionException.cs new file mode 100644 index 00000000..b2a951c0 --- /dev/null +++ b/tests/Titano.Testing/AssertionException.cs @@ -0,0 +1,7 @@ +namespace Titano.Testing; + +/// Raised by when an expectation is not met. +public sealed class AssertionException(string message) : Exception(message); + +/// Raised by or to skip at run time. +public sealed class SkipException(string reason) : Exception(reason); diff --git a/tests/Titano.Testing/Attributes.cs b/tests/Titano.Testing/Attributes.cs new file mode 100644 index 00000000..a87e0a30 --- /dev/null +++ b/tests/Titano.Testing/Attributes.cs @@ -0,0 +1,55 @@ +namespace Titano.Testing; + +/// Marks a public method as a test. The method may be sync or return /. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class TestAttribute : Attribute; + +/// Marks a parameterised test; each is one execution. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class TheoryAttribute : Attribute; + +/// One set of arguments for a test. +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public sealed class CaseAttribute(params object?[] arguments) : Attribute +{ + public object?[] Arguments { get; } = arguments ?? [null]; + + /// Optional display name for the case. + public string? Name { get; init; } +} + +/// Skips a test (or every test of a class) with a reason. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class SkipAttribute(string reason) : Attribute +{ + public string Reason { get; } = reason; +} + +/// Fails the test when it runs longer than the given number of milliseconds. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class TimeoutAttribute(int milliseconds) : Attribute +{ + public int Milliseconds { get; } = milliseconds; +} + +/// Tags a test or class; filters accept category:name. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] +public sealed class CategoryAttribute(string name) : Attribute +{ + public string Name { get; } = name; +} + +/// Runs only on Windows; skipped elsewhere. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +public sealed class WindowsOnlyAttribute : Attribute; + +/// Runs only when the environment variable is set and non-empty; skipped otherwise. +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] +public sealed class RequiresEnvironmentAttribute(string variable) : Attribute +{ + public string Variable { get; } = variable; +} + +/// Tests of this class never run concurrently with any other test. +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public sealed class SerialAttribute : Attribute; diff --git a/tests/Titano.Testing/ConsoleReporter.cs b/tests/Titano.Testing/ConsoleReporter.cs new file mode 100644 index 00000000..d9828784 --- /dev/null +++ b/tests/Titano.Testing/ConsoleReporter.cs @@ -0,0 +1,64 @@ +using System.Globalization; + +namespace Titano.Testing; + +internal sealed class ConsoleReporter(bool verbose) : IDisposable +{ + private readonly Lock _gate = new(); + + public void Report(TestResult r) + { + lock (_gate) + { + switch (r.Outcome) + { + case TestOutcome.Failed: + Write(ConsoleColor.Red, "FAIL "); + Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); + Console.WriteLine(" " + r.Message); + if (r.StackTrace is not null) Console.WriteLine(Indent(r.StackTrace)); + if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log)); + break; + case TestOutcome.Skipped when verbose: + Write(ConsoleColor.Yellow, "SKIP "); + Console.WriteLine($"{r.Test.FullName} — {r.Message}"); + break; + case TestOutcome.Passed when verbose: + Write(ConsoleColor.Green, "PASS "); + Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); + if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log)); + break; + } + } + } + + public void Summary(string suite, int passed, int failed, int skipped, TimeSpan elapsed, IReadOnlyList results) + { + lock (_gate) + { + Console.WriteLine(); + var slowest = results.Where(r => r.Outcome == TestOutcome.Passed).OrderByDescending(r => r.Duration).Take(3).ToList(); + if (verbose && slowest.Count > 0) + { + Console.WriteLine("Slowest:"); + foreach (var r in slowest) Console.WriteLine($" {Ms(r.Duration),9} {r.Test.FullName}"); + } + Write(failed > 0 ? ConsoleColor.Red : ConsoleColor.Green, failed > 0 ? "FAILED" : "PASSED"); + Console.WriteLine($" {suite}: {passed} passed, {failed} failed, {skipped} skipped in {elapsed.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)} s"); + } + } + + public void Dispose() => Console.Out.Flush(); + + private static string Ms(TimeSpan t) => t.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture) + " ms"; + + private static string Indent(string s) => string.Join(Environment.NewLine, s.TrimEnd().Split('\n').Select(l => " " + l.TrimEnd('\r'))); + + private static void Write(ConsoleColor color, string text) + { + var redirected = Console.IsOutputRedirected; + if (!redirected) Console.ForegroundColor = color; + Console.Write(text); + if (!redirected) Console.ResetColor(); + } +} diff --git a/tests/Titano.Testing/TestCase.cs b/tests/Titano.Testing/TestCase.cs new file mode 100644 index 00000000..3b079725 --- /dev/null +++ b/tests/Titano.Testing/TestCase.cs @@ -0,0 +1,59 @@ +using System.Reflection; + +namespace Titano.Testing; + +/// One discovered executable test (a method, or one case of a theory). +public sealed class TestCase +{ + internal TestCase(Type type, MethodInfo method, object?[]? arguments, string? caseName) + { + Type = type; + Method = method; + Arguments = arguments; + var suffix = arguments is null ? string.Empty : "(" + (caseName ?? string.Join(", ", arguments.Select(Assert.Format))) + ")"; + FullName = $"{type.FullName}.{method.Name}{suffix}"; + Categories = type.GetCustomAttributes() + .Concat(method.GetCustomAttributes()) + .Select(c => c.Name) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + TimeoutMs = method.GetCustomAttribute()?.Milliseconds + ?? type.GetCustomAttribute()?.Milliseconds + ?? 300_000; + Serial = type.GetCustomAttribute() is not null; + StaticSkipReason = ComputeSkipReason(type, method); + } + + public Type Type { get; } + public MethodInfo Method { get; } + public object?[]? Arguments { get; } + public string FullName { get; } + public IReadOnlyList Categories { get; } + public int TimeoutMs { get; } + public bool Serial { get; } + public string? StaticSkipReason { get; } + + private static string? ComputeSkipReason(Type type, MethodInfo method) + { + var skip = method.GetCustomAttribute() ?? type.GetCustomAttribute(); + if (skip is not null) return skip.Reason; + if ((method.GetCustomAttribute() ?? type.GetCustomAttribute()) is not null + && !OperatingSystem.IsWindows()) + return "Windows only"; + foreach (var env in type.GetCustomAttributes().Concat(method.GetCustomAttributes())) + { + if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(env.Variable))) + return $"{env.Variable} not set"; + } + return null; + } +} + +public enum TestOutcome +{ + Passed, + Failed, + Skipped, +} + +public sealed record TestResult(TestCase Test, TestOutcome Outcome, TimeSpan Duration, string? Message, string? StackTrace, string Log); diff --git a/tests/Titano.Testing/TestContext.cs b/tests/Titano.Testing/TestContext.cs new file mode 100644 index 00000000..3c31cc3d --- /dev/null +++ b/tests/Titano.Testing/TestContext.cs @@ -0,0 +1,96 @@ +using System.Collections.Concurrent; +using System.Text; + +namespace Titano.Testing; + +/// +/// Per-test services. A test class may take a in its constructor; +/// one context is created for every test execution and disposed after it. +/// +public sealed class TestContext : IDisposable +{ + private readonly ConcurrentQueue _log = new(); + private readonly List _tempDirectories = []; + private readonly Lock _gate = new(); + + internal TestContext(string testName, CancellationToken cancellation) + { + TestName = testName; + Cancellation = cancellation; + } + + public string TestName { get; } + + /// Signalled when the test times out or the run is aborted. + public CancellationToken Cancellation { get; } + + /// Repository root (the directory that holds Titano.slnx), or the working directory. + public static string RepositoryRoot { get; } = FindRepositoryRoot(); + + /// tests/fixtures under the repository root. + public static string FixturesDirectory => Path.Combine(RepositoryRoot, "tests", "fixtures"); + + /// Creates an empty directory that is deleted when the test ends. + public string CreateTempDirectory(string? hint = null) + { + var path = Path.Combine(Path.GetTempPath(), "titano-tests", $"{Sanitize(hint ?? TestName)}-{Guid.NewGuid():N}"); + Directory.CreateDirectory(path); + lock (_gate) _tempDirectories.Add(path); + return path; + } + + /// Lines written here are printed only when the test fails or in verbose mode. + public void Log(string message) => _log.Enqueue(message); + + public string LogText + { + get + { + var sb = new StringBuilder(); + foreach (var line in _log) sb.AppendLine(line); + return sb.ToString(); + } + } + + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + public static void Skip(string reason) => throw new SkipException(reason); + + public void Dispose() + { + lock (_gate) + { + foreach (var dir in _tempDirectories) + { + try + { + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + } + catch (IOException) + { + // Best effort: a file still open by the OS indexer must not fail the test. + } + catch (UnauthorizedAccessException) + { + } + } + _tempDirectories.Clear(); + } + } + + private static string Sanitize(string s) + { + var chars = s.Select(c => char.IsLetterOrDigit(c) ? c : '-').Take(48).ToArray(); + return new string(chars); + } + + private static string FindRepositoryRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Titano.slnx"))) return dir.FullName; + dir = dir.Parent; + } + return Directory.GetCurrentDirectory(); + } +} diff --git a/tests/Titano.Testing/TestRunner.cs b/tests/Titano.Testing/TestRunner.cs new file mode 100644 index 00000000..1745aad5 --- /dev/null +++ b/tests/Titano.Testing/TestRunner.cs @@ -0,0 +1,319 @@ +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Text; +using System.Xml; + +namespace Titano.Testing; + +/// +/// Discovers and runs tests in an assembly. Test projects are console apps whose entry point is +/// return await TestRunner.RunAsync(args, typeof(Program).Assembly);. +/// +/// +/// Arguments: --filter text (substring of the full name, or category:name; repeatable, OR-combined), +/// --exclude text, --junit path, --parallel n, --list, --verbose. +/// Exit codes: 0 all passed, 1 failures, 2 usage error or no tests matched. +/// +public static class TestRunner +{ + public static async Task RunAsync(string[] args, Assembly assembly) + { + CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; + CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; + + Options options; + try + { + options = Options.Parse(args); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine(ex.Message); + return 2; + } + + var all = Discover(assembly); + var selected = all.Where(options.Matches).ToList(); + if (options.List) + { + foreach (var t in selected) Console.WriteLine(t.FullName); + return 0; + } + if (selected.Count == 0) + { + Console.Error.WriteLine("No tests matched."); + return 2; + } + + var stopwatch = Stopwatch.StartNew(); + var results = new List(selected.Count); + var resultsGate = new Lock(); + using var console = new ConsoleReporter(options.Verbose); + + void Record(TestResult r) + { + lock (resultsGate) results.Add(r); + console.Report(r); + } + + var parallel = selected.Where(t => !t.Serial).GroupBy(t => t.Type).ToList(); + var serial = selected.Where(t => t.Serial).ToList(); + + // Classes run in parallel; tests inside a class run in declaration order. + await Parallel.ForEachAsync( + parallel, + new ParallelOptions { MaxDegreeOfParallelism = options.Parallelism }, + async (group, _) => + { + foreach (var test in group) Record(await ExecuteAsync(test).ConfigureAwait(false)); + }).ConfigureAwait(false); + + foreach (var test in serial) Record(await ExecuteAsync(test).ConfigureAwait(false)); + + stopwatch.Stop(); + var passed = results.Count(r => r.Outcome == TestOutcome.Passed); + var failed = results.Count(r => r.Outcome == TestOutcome.Failed); + var skipped = results.Count(r => r.Outcome == TestOutcome.Skipped); + console.Summary(assembly.GetName().Name ?? "tests", passed, failed, skipped, stopwatch.Elapsed, results); + + if (options.JUnitPath is { } junit) + WriteJUnit(junit, assembly.GetName().Name ?? "tests", results, stopwatch.Elapsed); + + return failed > 0 ? 1 : 0; + } + + public static IReadOnlyList Discover(Assembly assembly) + { + var list = new List(); + Type[] types; + try + { + types = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + types = ex.Types.Where(t => t is not null).ToArray()!; + } + + foreach (var type in types.Where(t => t is { IsClass: true, IsPublic: true } && !t.IsAbstract).OrderBy(t => t.FullName, StringComparer.Ordinal)) + { + foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(m => m.MetadataToken)) + { + if (method.GetCustomAttribute() is not null) + { + list.Add(new TestCase(type, method, null, null)); + } + else if (method.GetCustomAttribute() is not null) + { + foreach (var c in method.GetCustomAttributes()) + list.Add(new TestCase(type, method, c.Arguments, c.Name)); + } + } + } + return list; + } + + private static async Task ExecuteAsync(TestCase test) + { + if (test.StaticSkipReason is { } reason) + return new TestResult(test, TestOutcome.Skipped, TimeSpan.Zero, reason, null, string.Empty); + + using var cts = new CancellationTokenSource(); + using var context = new TestContext(test.FullName, cts.Token); + var sw = Stopwatch.StartNew(); + try + { + var run = Task.Run(() => InvokeAsync(test, context), CancellationToken.None); + var finished = await Task.WhenAny(run, Task.Delay(test.TimeoutMs, CancellationToken.None)).ConfigureAwait(false); + if (finished != run) + { + await cts.CancelAsync().ConfigureAwait(false); + // Give cooperative code a moment to observe cancellation before reporting. + await Task.WhenAny(run, Task.Delay(2000, CancellationToken.None)).ConfigureAwait(false); + return new TestResult(test, TestOutcome.Failed, sw.Elapsed, $"Timed out after {test.TimeoutMs} ms", null, context.LogText); + } + await run.ConfigureAwait(false); + return new TestResult(test, TestOutcome.Passed, sw.Elapsed, null, null, context.LogText); + } + catch (SkipException ex) + { + return new TestResult(test, TestOutcome.Skipped, sw.Elapsed, ex.Message, null, context.LogText); + } + catch (Exception ex) + { + var message = ex is AssertionException ? ex.Message : $"{ex.GetType().FullName}: {ex.Message}"; + return new TestResult(test, TestOutcome.Failed, sw.Elapsed, message, ex.StackTrace, context.LogText); + } + } + + private static async Task InvokeAsync(TestCase test, TestContext context) + { + object? instance = null; + try + { + if (!test.Method.IsStatic) + { + var ctor = test.Type.GetConstructor([typeof(TestContext)]); + instance = ctor is not null + ? ctor.Invoke([context]) + : Activator.CreateInstance(test.Type); + } + + var parameters = test.Method.GetParameters(); + var args = BuildArguments(test, parameters, context); + object? returned; + try + { + returned = test.Method.Invoke(instance, args); + } + catch (TargetInvocationException tie) when (tie.InnerException is not null) + { + ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); + throw; + } + + switch (returned) + { + case Task task: + await task.ConfigureAwait(false); + break; + case ValueTask valueTask: + await valueTask.ConfigureAwait(false); + break; + } + } + finally + { + switch (instance) + { + case IAsyncDisposable ad: + await ad.DisposeAsync().ConfigureAwait(false); + break; + case IDisposable d: + d.Dispose(); + break; + } + } + } + + private static object?[] BuildArguments(TestCase test, ParameterInfo[] parameters, TestContext context) + { + var supplied = test.Arguments ?? []; + var result = new object?[parameters.Length]; + var next = 0; + for (var i = 0; i < parameters.Length; i++) + { + var p = parameters[i]; + if (p.ParameterType == typeof(TestContext)) + { + result[i] = context; + continue; + } + if (p.ParameterType == typeof(CancellationToken)) + { + result[i] = context.Cancellation; + continue; + } + if (next >= supplied.Length) + throw new InvalidOperationException($"{test.FullName}: missing argument for parameter '{p.Name}'"); + result[i] = Convert(supplied[next++], p.ParameterType); + } + if (next != supplied.Length) + throw new InvalidOperationException($"{test.FullName}: {supplied.Length - next} unused case argument(s)"); + return result; + } + + private static object? Convert(object? value, Type target) + { + if (value is null) return null; + var underlying = Nullable.GetUnderlyingType(target) ?? target; + if (underlying.IsInstanceOfType(value)) return value; + if (underlying.IsEnum) return Enum.ToObject(underlying, value); + return System.Convert.ChangeType(value, underlying, CultureInfo.InvariantCulture); + } + + private static void WriteJUnit(string path, string suiteName, IReadOnlyList results, TimeSpan elapsed) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) }; + using var w = XmlWriter.Create(path, settings); + w.WriteStartDocument(); + w.WriteStartElement("testsuites"); + w.WriteStartElement("testsuite"); + w.WriteAttributeString("name", suiteName); + w.WriteAttributeString("tests", results.Count.ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("failures", results.Count(r => r.Outcome == TestOutcome.Failed).ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("skipped", results.Count(r => r.Outcome == TestOutcome.Skipped).ToString(CultureInfo.InvariantCulture)); + w.WriteAttributeString("time", elapsed.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); + foreach (var r in results.OrderBy(r => r.Test.FullName, StringComparer.Ordinal)) + { + w.WriteStartElement("testcase"); + w.WriteAttributeString("classname", r.Test.Type.FullName); + w.WriteAttributeString("name", r.Test.FullName[(r.Test.Type.FullName!.Length + 1)..]); + w.WriteAttributeString("time", r.Duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); + if (r.Outcome == TestOutcome.Failed) + { + w.WriteStartElement("failure"); + w.WriteAttributeString("message", Clean(r.Message ?? "failed")); + w.WriteString(Clean((r.StackTrace ?? string.Empty) + Environment.NewLine + r.Log)); + w.WriteEndElement(); + } + else if (r.Outcome == TestOutcome.Skipped) + { + w.WriteStartElement("skipped"); + w.WriteAttributeString("message", Clean(r.Message ?? string.Empty)); + w.WriteEndElement(); + } + w.WriteEndElement(); + } + w.WriteEndElement(); + w.WriteEndElement(); + w.WriteEndDocument(); + } + + private static string Clean(string s) => new(s.Where(XmlConvert.IsXmlChar).ToArray()); + + private sealed class Options + { + public List Filters { get; } = []; + public List Excludes { get; } = []; + public string? JUnitPath { get; private set; } + public int Parallelism { get; private set; } = Math.Max(1, Environment.ProcessorCount); + public bool List { get; private set; } + public bool Verbose { get; private set; } + + public static Options Parse(string[] args) + { + var o = new Options(); + for (var i = 0; i < args.Length; i++) + { + string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"Missing value after {args[i]}"); + switch (args[i]) + { + case "--filter": o.Filters.Add(Next()); break; + case "--exclude": o.Excludes.Add(Next()); break; + case "--junit": o.JUnitPath = Next(); break; + case "--parallel": o.Parallelism = Math.Max(1, int.Parse(Next(), CultureInfo.InvariantCulture)); break; + case "--list": o.List = true; break; + case "--verbose": o.Verbose = true; break; + default: throw new ArgumentException($"Unknown argument {args[i]}. Use --filter, --exclude, --junit, --parallel, --list, --verbose."); + } + } + return o; + } + + public bool Matches(TestCase t) + { + if (Excludes.Any(f => Match(t, f))) return false; + return Filters.Count == 0 || Filters.Any(f => Match(t, f)); + } + + private static bool Match(TestCase t, string filter) => + filter.StartsWith("category:", StringComparison.OrdinalIgnoreCase) + ? t.Categories.Contains(filter["category:".Length..], StringComparer.OrdinalIgnoreCase) + : t.FullName.Contains(filter, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/Titano.Testing/Titano.Testing.csproj b/tests/Titano.Testing/Titano.Testing.csproj new file mode 100644 index 00000000..3feaef79 --- /dev/null +++ b/tests/Titano.Testing/Titano.Testing.csproj @@ -0,0 +1,6 @@ + + + net10.0 + Titano.Testing + + From 800843d2aeb7cabf14471fdf054ff5a29bd52f5f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:01:53 +0000 Subject: [PATCH 002/188] feat(core): add sRGB transfer and luminance helpers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Imaging/ColorSpace.cs | 99 +++++++++++++++++++ .../Foundation/ColorSpaceTests.cs | 36 +++++++ 2 files changed, 135 insertions(+) create mode 100644 src/Titano.Core/Imaging/ColorSpace.cs create mode 100644 tests/Titano.Core.Tests/Foundation/ColorSpaceTests.cs diff --git a/src/Titano.Core/Imaging/ColorSpace.cs b/src/Titano.Core/Imaging/ColorSpace.cs new file mode 100644 index 00000000..bcfd7bef --- /dev/null +++ b/src/Titano.Core/Imaging/ColorSpace.cs @@ -0,0 +1,99 @@ +using System.Runtime.CompilerServices; + +namespace Titano.Core.Imaging; + +/// +/// sRGB/Rec.709 transfer functions and luminance. Titano processes in linear light with Rec.709 primaries; +/// encoded (gamma) values appear only at codec and display edges. +/// +public static class ColorSpace +{ + /// Rec.709 / sRGB luminance weights for linear RGB. + public const float LumaR = 0.2126f, LumaG = 0.7152f, LumaB = 0.0722f; + + private const int EncodeLutSize = 4096; + private static readonly float[] Decode8 = BuildDecodeLut(256); + private static readonly float[] Decode16 = BuildDecodeLut(65536); + private static readonly float[] EncodeLut = BuildEncodeLut(); + + /// Exact sRGB EOTF: encoded 0..1 → linear 0..1. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double SrgbToLinear(double v) => v <= 0.04045 ? v / 12.92 : Math.Pow((v + 0.055) / 1.055, 2.4); + + /// Exact inverse sRGB EOTF: linear 0..1 → encoded 0..1 (values outside are clamped). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double LinearToSrgb(double v) + { + if (v <= 0) return 0; + if (v >= 1) return 1; + return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.Pow(v, 1 / 2.4) - 0.055; + } + + /// 8-bit sRGB code value → linear (table lookup). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Linear8(byte code) => Decode8[code]; + + /// 16-bit sRGB code value → linear (table lookup). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Linear16(ushort code) => Decode16[code]; + + /// Fast linear → encoded sRGB (0..1) with a 4096-entry table and linear interpolation; + /// max error below 1/65535 above the toe. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float EncodeFast(float linear) + { + if (!(linear > 0f)) return 0f; + if (linear >= 1f) return 1f; + // Index in the square-root domain spreads table entries into the shadows where sRGB is steep. + var t = MathF.Sqrt(linear) * (EncodeLutSize - 1); + var i = (int)t; + var f = t - i; + return EncodeLut[i] + (EncodeLut[i + 1] - EncodeLut[i]) * f; + } + + /// Linear → 8-bit sRGB code with rounding. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte Encode8(float linear) => (byte)(EncodeFast(linear) * 255f + 0.5f); + + /// Linear → 16-bit sRGB code with rounding. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort Encode16(float linear) => (ushort)(EncodeFast(linear) * 65535f + 0.5f); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Luminance(float r, float g, float b) => LumaR * r + LumaG * g + LumaB * b; + + /// Writes Rec.709 linear luminance of an RGB buffer into . + public static void Luminance(ImageBuffer rgb, Span destination) + { + if (rgb.Channels == 1) + { + rgb.Plane(0).CopyTo(destination); + return; + } + var r = rgb.Plane(0); + var g = rgb.Plane(1); + var b = rgb.Plane(2); + for (var i = 0; i < destination.Length; i++) destination[i] = LumaR * r[i] + LumaG * g[i] + LumaB * b[i]; + } + + /// Exposure value difference in stops between two linear luminances. + public static double Stops(double from, double to) => Math.Log2(Math.Max(to, 1e-12) / Math.Max(from, 1e-12)); + + private static float[] BuildDecodeLut(int size) + { + var lut = new float[size]; + for (var i = 0; i < size; i++) lut[i] = (float)SrgbToLinear(i / (double)(size - 1)); + return lut; + } + + private static float[] BuildEncodeLut() + { + var lut = new float[EncodeLutSize + 1]; + for (var i = 0; i <= EncodeLutSize; i++) + { + var s = Math.Min(1.0, i / (double)(EncodeLutSize - 1)); + lut[i] = (float)LinearToSrgb(s * s); + } + return lut; + } +} diff --git a/tests/Titano.Core.Tests/Foundation/ColorSpaceTests.cs b/tests/Titano.Core.Tests/Foundation/ColorSpaceTests.cs new file mode 100644 index 00000000..2b05fdb8 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/ColorSpaceTests.cs @@ -0,0 +1,36 @@ +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +public sealed class ColorSpaceTests +{ + [Test] + public void EightBitRoundTripIsExact() + { + for (var i = 0; i < 256; i++) Assert.Equal((byte)i, ColorSpace.Encode8(ColorSpace.Linear8((byte)i))); + } + + [Test] + public void SixteenBitRoundTripWithinOneCode() + { + for (var i = 0; i < 65536; i += 7) + { + var back = ColorSpace.Encode16(ColorSpace.Linear16((ushort)i)); + Assert.InRange(back, i - 1, i + 1); + } + } + + [Test] + public void FastEncodeMatchesExact() + { + for (var i = 1; i <= 10000; i++) + { + var v = i / 10000f; + Assert.Approximately(ColorSpace.LinearToSrgb(v), ColorSpace.EncodeFast(v), 2e-5); + } + } + + [Test] + public void MiddleGreyIsAbout118() => Assert.InRange(ColorSpace.Encode8(0.18f), 117, 119); +} From bda76ccff2da7c0946a54d239d9c21d2b64ff97d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:19:18 +0000 Subject: [PATCH 003/188] =?UTF-8?q?feat(motion):=20add=20FFT=20plans=20and?= =?UTF-8?q?=20Kuglin=E2=80=93Hines=20phase=20correlation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Radix-2 Cooley–Tukey with SIMD butterflies and Bluestein chirp-z for arbitrary lengths, cached plans, parallel 2D transforms, real-input half-length transforms and Tukey/Hann windows. Phase correlation packs both patches into one complex FFT, normalises the cross-power spectrum with a Gaussian low-pass and refines the peak with a log-parabola fit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/FftPlan.cs | 276 ++++++++++++++++++ src/Titano.Core/Motion/Fourier.cs | 269 +++++++++++++++++ src/Titano.Core/Motion/PhaseCorrelator.cs | 273 +++++++++++++++++ .../Titano.Core.Tests/Motion/FourierTests.cs | 176 +++++++++++ .../Motion/PhaseCorrelatorTests.cs | 83 ++++++ .../Motion/SyntheticImages.cs | 122 ++++++++ 6 files changed, 1199 insertions(+) create mode 100644 src/Titano.Core/Motion/FftPlan.cs create mode 100644 src/Titano.Core/Motion/Fourier.cs create mode 100644 src/Titano.Core/Motion/PhaseCorrelator.cs create mode 100644 tests/Titano.Core.Tests/Motion/FourierTests.cs create mode 100644 tests/Titano.Core.Tests/Motion/PhaseCorrelatorTests.cs create mode 100644 tests/Titano.Core.Tests/Motion/SyntheticImages.cs diff --git a/src/Titano.Core/Motion/FftPlan.cs b/src/Titano.Core/Motion/FftPlan.cs new file mode 100644 index 00000000..412da884 --- /dev/null +++ b/src/Titano.Core/Motion/FftPlan.cs @@ -0,0 +1,276 @@ +using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Titano.Core.Motion; + +/// +/// Precomputed complex DFT of one length on split real/imaginary arrays: iterative radix-2 +/// Cooley–Tukey (1965) for powers of two, Bluestein (1970) chirp-z convolution otherwise. +/// Forward uses e^(−2πikn/N); is normalised by 1/N. +/// Immutable and thread-safe; obtain shared instances from . +/// +public sealed class FftPlan +{ + private readonly int[]? _bitReverse; + // Stage-major twiddles: the stage with half-size h occupies [h − 1, 2h − 1), so SIMD loads are contiguous. + private readonly double[]? _twiddleRe, _twiddleIm; + private readonly FftPlan? _convolution; + private readonly double[]? _chirpRe, _chirpIm; + private readonly double[]? _kernelRe, _kernelIm; + + internal FftPlan(int length) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length); + Length = length; + IsPowerOfTwo = BitOperations.IsPow2(length); + + // e^(−iπk/N), k = 0..N: the post-processing twiddles of a real transform of length 2N. + HalfTwiddleRe = new double[length + 1]; + HalfTwiddleIm = new double[length + 1]; + for (var k = 0; k <= length; k++) + { + var (s, c) = double.SinCos(double.Pi * k / length); + HalfTwiddleRe[k] = c; + HalfTwiddleIm[k] = -s; + } + + if (IsPowerOfTwo) + { + var bits = BitOperations.Log2((uint)length); + _bitReverse = new int[length]; + for (var i = 0; i < length; i++) + _bitReverse[i] = bits == 0 ? 0 : (int)(ReverseBits((uint)i) >> (32 - bits)); + _twiddleRe = new double[int.Max(1, length - 1)]; + _twiddleIm = new double[_twiddleRe.Length]; + for (var h = 1; h < length; h <<= 1) + { + for (var k = 0; k < h; k++) + { + var (s, c) = double.SinCos(double.Pi * k / h); + _twiddleRe[h - 1 + k] = c; + _twiddleIm[h - 1 + k] = -s; + } + } + return; + } + + // Bluestein: X_k = c_k · Σ_n (x_n c_n) · conj(c_(k−n)), c_k = e^(−iπk²/N), as a power-of-two circular convolution. + var m = (int)BitOperations.RoundUpToPowerOf2((uint)(2 * length - 1)); + _convolution = Fourier.Plan(m); + ScratchLength = 2 * m; + _chirpRe = new double[length]; + _chirpIm = new double[length]; + _kernelRe = new double[m]; + _kernelIm = new double[m]; + for (var k = 0; k < length; k++) + { + // k² mod 2N keeps the angle argument small and exact for large N. + var q = (long)k * k % (2L * length); + var (s, c) = double.SinCos(double.Pi * q / length); + _chirpRe[k] = c; + _chirpIm[k] = -s; + _kernelRe[k] = c; + _kernelIm[k] = s; + if (k > 0) + { + _kernelRe[m - k] = c; + _kernelIm[m - k] = s; + } + } + _convolution.Radix2(_kernelRe, _kernelIm); + var scale = 1.0 / m; + for (var i = 0; i < m; i++) + { + _kernelRe[i] *= scale; + _kernelIm[i] *= scale; + } + } + + /// Transform length N. + public int Length { get; } + + /// True when the radix-2 path is used. + public bool IsPowerOfTwo { get; } + + /// Doubles of scratch the scratch-taking overloads need (0 for powers of two). + public int ScratchLength { get; } + + internal double[] HalfTwiddleRe { get; } + + internal double[] HalfTwiddleIm { get; } + + /// In-place forward DFT. Bluestein lengths rent their scratch from the shared pool. + public void Forward(Span re, Span im) + { + if (ScratchLength == 0) + { + Forward(re, im, Span.Empty); + return; + } + var scratch = ArrayPool.Shared.Rent(ScratchLength); + try + { + Forward(re, im, scratch); + } + finally + { + ArrayPool.Shared.Return(scratch); + } + } + + /// In-place forward DFT using caller-provided scratch of at least doubles. + public void Forward(Span re, Span im, Span scratch) + { + CheckLengths(re, im, scratch); + if (IsPowerOfTwo) Radix2(re, im); + else Bluestein(re, im, scratch); + } + + /// In-place inverse DFT, normalised by 1/N. + public void Inverse(Span re, Span im) + { + // Swapping the real and imaginary parts turns a forward DFT into an unnormalised inverse one. + Forward(im, re); + Scale(re, im, 1.0 / Length); + } + + /// In-place inverse DFT (normalised by 1/N) using caller-provided scratch. + public void Inverse(Span re, Span im, Span scratch) + { + Forward(im, re, scratch); + Scale(re, im, 1.0 / Length); + } + + /// Unnormalised radix-2 transform; the caller guarantees a power-of-two length. + internal void Radix2(Span re, Span im) + { + var n = Length; + var rev = _bitReverse!; + for (var i = 0; i < n; i++) + { + var j = rev[i]; + if (j <= i) continue; + (re[i], re[j]) = (re[j], re[i]); + (im[i], im[j]) = (im[j], im[i]); + } + + ref var r0 = ref MemoryMarshal.GetReference(re); + ref var i0 = ref MemoryMarshal.GetReference(im); + ref var wr0 = ref MemoryMarshal.GetArrayDataReference(_twiddleRe!); + ref var wi0 = ref MemoryMarshal.GetArrayDataReference(_twiddleIm!); + var vc = Vector.Count; + for (var h = 1; h < n; h <<= 1) + { + ref var wr = ref Unsafe.Add(ref wr0, h - 1); + ref var wi = ref Unsafe.Add(ref wi0, h - 1); + for (var start = 0; start < n; start += h << 1) + { + ref var ar = ref Unsafe.Add(ref r0, start); + ref var ai = ref Unsafe.Add(ref i0, start); + ref var br = ref Unsafe.Add(ref r0, start + h); + ref var bi = ref Unsafe.Add(ref i0, start + h); + var k = 0; + if (Vector.IsHardwareAccelerated && h >= vc) + { + // h and vc are powers of two, so h is a multiple of vc: no remainder loop needed. + for (; k < h; k += vc) + { + var u = (nuint)k; + var cr = Vector.LoadUnsafe(ref wr, u); + var ci = Vector.LoadUnsafe(ref wi, u); + var xr = Vector.LoadUnsafe(ref br, u); + var xi = Vector.LoadUnsafe(ref bi, u); + var tr = xr * cr - xi * ci; + var ti = xr * ci + xi * cr; + var yr = Vector.LoadUnsafe(ref ar, u); + var yi = Vector.LoadUnsafe(ref ai, u); + (yr - tr).StoreUnsafe(ref br, u); + (yi - ti).StoreUnsafe(ref bi, u); + (yr + tr).StoreUnsafe(ref ar, u); + (yi + ti).StoreUnsafe(ref ai, u); + } + } + for (; k < h; k++) + { + var cr = Unsafe.Add(ref wr, k); + var ci = Unsafe.Add(ref wi, k); + ref var xr = ref Unsafe.Add(ref br, k); + ref var xi = ref Unsafe.Add(ref bi, k); + ref var yr = ref Unsafe.Add(ref ar, k); + ref var yi = ref Unsafe.Add(ref ai, k); + var tr = xr * cr - xi * ci; + var ti = xr * ci + xi * cr; + xr = yr - tr; + xi = yi - ti; + yr += tr; + yi += ti; + } + } + } + } + + private void Bluestein(Span re, Span im, Span scratch) + { + var n = Length; + var conv = _convolution!; + var m = conv.Length; + var ar = scratch[..m]; + var ai = scratch.Slice(m, m); + var cr = _chirpRe!; + var ci = _chirpIm!; + for (var k = 0; k < n; k++) + { + ar[k] = re[k] * cr[k] - im[k] * ci[k]; + ai[k] = re[k] * ci[k] + im[k] * cr[k]; + } + ar[n..].Clear(); + ai[n..].Clear(); + + conv.Radix2(ar, ai); + var kr = _kernelRe!; + var ki = _kernelIm!; + for (var k = 0; k < m; k++) + { + var xr = ar[k]; + var xi = ai[k]; + ar[k] = xr * kr[k] - xi * ki[k]; + ai[k] = xr * ki[k] + xi * kr[k]; + } + // Unnormalised inverse via the real/imaginary swap; 1/M is folded into the kernel. + conv.Radix2(ai, ar); + + for (var k = 0; k < n; k++) + { + re[k] = ar[k] * cr[k] - ai[k] * ci[k]; + im[k] = ar[k] * ci[k] + ai[k] * cr[k]; + } + } + + private void CheckLengths(Span re, Span im, Span scratch) + { + if (re.Length != Length || im.Length != Length) + throw new ArgumentException($"Expected {Length} samples, got {re.Length} and {im.Length}."); + if (scratch.Length < ScratchLength) + throw new ArgumentException($"Scratch must hold {ScratchLength} doubles.", nameof(scratch)); + } + + private static void Scale(Span re, Span im, double factor) + { + for (var i = 0; i < re.Length; i++) + { + re[i] *= factor; + im[i] *= factor; + } + } + + private static uint ReverseBits(uint v) + { + v = ((v >> 1) & 0x55555555u) | ((v & 0x55555555u) << 1); + v = ((v >> 2) & 0x33333333u) | ((v & 0x33333333u) << 2); + v = ((v >> 4) & 0x0F0F0F0Fu) | ((v & 0x0F0F0F0Fu) << 4); + v = ((v >> 8) & 0x00FF00FFu) | ((v & 0x00FF00FFu) << 8); + return (v >> 16) | (v << 16); + } +} diff --git a/src/Titano.Core/Motion/Fourier.cs b/src/Titano.Core/Motion/Fourier.cs new file mode 100644 index 00000000..f4448008 --- /dev/null +++ b/src/Titano.Core/Motion/Fourier.cs @@ -0,0 +1,269 @@ +using System.Buffers; +using System.Collections.Concurrent; + +namespace Titano.Core.Motion; + +/// +/// Discrete Fourier transforms on split real/imaginary arrays: cached +/// s (twiddles computed once per length), separable 2D transforms (rows then +/// columns, parallel for large images), real-input transforms through the half-length packing trick, +/// and analysis windows. +/// +public static class Fourier +{ + // Below this many samples a 2D transform is cheaper than the Parallel.For overhead. + private const int ParallelThreshold = 1 << 15; + + private static readonly ConcurrentDictionary Plans = new(); + + /// Shared, thread-safe plan for the given length. + public static FftPlan Plan(int length) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length); + return Plans.GetOrAdd(length, static n => new FftPlan(n)); + } + + /// In-place forward DFT of any length. + public static void Forward(Span re, Span im) => Plan(re.Length).Forward(re, im); + + /// In-place inverse DFT of any length, normalised by 1/N. + public static void Inverse(Span re, Span im) => Plan(re.Length).Inverse(re, im); + + /// In-place forward 2D DFT of a row-major × array. + public static void Forward2D(double[] re, double[] im, int width, int height) => Transform2D(re, im, width, height, inverse: false); + + /// In-place inverse 2D DFT, normalised by 1/(width·height). + public static void Inverse2D(double[] re, double[] im, int width, int height) => Transform2D(re, im, width, height, inverse: true); + + /// + /// Spectrum bins 0..N/2 of a real signal. Even lengths run one complex transform of length N/2 + /// (even samples as real part, odd samples as imaginary part) and split it with the standard + /// post-processing butterflies; odd lengths fall back to a full complex transform. + /// + public static void ForwardReal(ReadOnlySpan signal, Span re, Span im) + { + var n = signal.Length; + ArgumentOutOfRangeException.ThrowIfZero(n, nameof(signal)); + var bins = n / 2 + 1; + if (re.Length < bins || im.Length < bins) throw new ArgumentException($"Spectrum spans must hold {bins} bins."); + if (n == 1) + { + re[0] = signal[0]; + im[0] = 0; + return; + } + if ((n & 1) != 0) + { + var buffer = ArrayPool.Shared.Rent(2 * n); + try + { + var fr = buffer.AsSpan(0, n); + var fi = buffer.AsSpan(n, n); + signal.CopyTo(fr); + fi.Clear(); + Plan(n).Forward(fr, fi); + fr[..bins].CopyTo(re); + fi[..bins].CopyTo(im); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + return; + } + + var m = n / 2; + for (var j = 0; j < m; j++) + { + re[j] = signal[2 * j]; + im[j] = signal[2 * j + 1]; + } + var plan = Plan(m); + plan.Forward(re[..m], im[..m]); + re[m] = re[0]; + im[m] = im[0]; + var wr = plan.HalfTwiddleRe; + var wi = plan.HalfTwiddleIm; + for (var k = 0; k <= m / 2; k++) + { + var k2 = m - k; + double zr = re[k], zi = im[k], yr = re[k2], yi = im[k2]; + // E = (Z_k + conj Z_(m−k)) / 2 is the even-sample spectrum, O = (Z_k − conj Z_(m−k)) / 2i the odd one. + var er = 0.5 * (zr + yr); + var ei = 0.5 * (zi - yi); + var or = 0.5 * (zi + yi); + var oi = -0.5 * (zr - yr); + re[k] = er + wr[k] * or - wi[k] * oi; + im[k] = ei + wr[k] * oi + wi[k] * or; + // X_(m−k) = conj E + W^(m−k) conj O. + re[k2] = er + wr[k2] * or + wi[k2] * oi; + im[k2] = -ei + wi[k2] * or - wr[k2] * oi; + } + } + + /// Inverse of : real signal of length signal.Length from bins 0..N/2. + public static void InverseReal(ReadOnlySpan re, ReadOnlySpan im, Span signal) + { + var n = signal.Length; + ArgumentOutOfRangeException.ThrowIfZero(n, nameof(signal)); + var bins = n / 2 + 1; + if (re.Length < bins || im.Length < bins) throw new ArgumentException($"Spectrum spans must hold {bins} bins."); + if (n == 1) + { + signal[0] = re[0]; + return; + } + + var odd = (n & 1) != 0; + var buffer = ArrayPool.Shared.Rent(odd ? 2 * n : n); + try + { + if (odd) + { + var fr = buffer.AsSpan(0, n); + var fi = buffer.AsSpan(n, n); + for (var k = 0; k < bins; k++) + { + fr[k] = re[k]; + fi[k] = im[k]; + if (k == 0) continue; + fr[n - k] = re[k]; + fi[n - k] = -im[k]; + } + Plan(n).Inverse(fr, fi); + fr.CopyTo(signal); + return; + } + + var m = n / 2; + var zr = buffer.AsSpan(0, m); + var zi = buffer.AsSpan(m, m); + var plan = Plan(m); + var wr = plan.HalfTwiddleRe; + var wi = plan.HalfTwiddleIm; + for (var k = 0; k < m; k++) + { + // E = (X_k + conj X_(m−k)) / 2, O = (X_k − conj X_(m−k)) · conj(W^k) / 2, Z = E + iO. + double xr = re[k], xi = im[k], yr = re[m - k], yi = -im[m - k]; + var er = 0.5 * (xr + yr); + var ei = 0.5 * (xi + yi); + var dr = 0.5 * (xr - yr); + var di = 0.5 * (xi - yi); + var or = dr * wr[k] + di * wi[k]; + var oi = di * wr[k] - dr * wi[k]; + zr[k] = er - oi; + zi[k] = ei + or; + } + plan.Inverse(zr, zi); + for (var j = 0; j < m; j++) + { + signal[2 * j] = zr[j]; + signal[2 * j + 1] = zi[j]; + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Symmetric Hann window (zero at both ends). + public static void Hann(Span window) => Tukey(window, 1.0); + + /// + /// Symmetric Tukey (tapered cosine) window: flat top with raised-cosine flanks covering a fraction + /// of the length; 0 is rectangular, 1 is Hann. + /// + public static void Tukey(Span window, double alpha) + { + ArgumentOutOfRangeException.ThrowIfLessThan(alpha, 0.0); + ArgumentOutOfRangeException.ThrowIfGreaterThan(alpha, 1.0); + var n = window.Length; + if (n == 1 || alpha == 0) + { + window.Fill(1.0); + return; + } + var half = alpha / 2; + for (var i = 0; i < n; i++) + { + var x = i / (double)(n - 1); + var edge = double.Min(x, 1 - x); + window[i] = edge >= half ? 1.0 : 0.5 * (1 - double.Cos(double.Pi * edge / half)); + } + } + + private static void Transform2D(double[] re, double[] im, int width, int height, bool inverse) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + var length = checked(width * height); + if (re.Length < length || im.Length < length) throw new ArgumentException($"Arrays must hold {length} samples."); + + // The inverse is the forward transform with real and imaginary parts swapped, then scaled. + var (a, b) = inverse ? (im, re) : (re, im); + var rows = Plan(width); + var columns = Plan(height); + if (length < ParallelThreshold) + { + var scratch = ArrayPool.Shared.Rent(int.Max(rows.ScratchLength, 2 * height + columns.ScratchLength)); + try + { + for (var y = 0; y < height; y++) rows.Forward(a.AsSpan(y * width, width), b.AsSpan(y * width, width), scratch); + for (var x = 0; x < width; x++) TransformColumn(a, b, width, height, x, columns, scratch); + } + finally + { + ArrayPool.Shared.Return(scratch); + } + } + else + { + Parallel.For( + 0, + height, + () => ArrayPool.Shared.Rent(int.Max(1, rows.ScratchLength)), + (y, _, scratch) => + { + rows.Forward(a.AsSpan(y * width, width), b.AsSpan(y * width, width), scratch); + return scratch; + }, + scratch => ArrayPool.Shared.Return(scratch)); + Parallel.For( + 0, + width, + () => ArrayPool.Shared.Rent(2 * height + columns.ScratchLength), + (x, _, scratch) => + { + TransformColumn(a, b, width, height, x, columns, scratch); + return scratch; + }, + scratch => ArrayPool.Shared.Return(scratch)); + } + + if (!inverse) return; + var scale = 1.0 / length; + for (var i = 0; i < length; i++) + { + re[i] *= scale; + im[i] *= scale; + } + } + + private static void TransformColumn(double[] re, double[] im, int width, int height, int x, FftPlan plan, double[] scratch) + { + var cr = scratch.AsSpan(0, height); + var ci = scratch.AsSpan(height, height); + for (int y = 0, i = x; y < height; y++, i += width) + { + cr[y] = re[i]; + ci[y] = im[i]; + } + plan.Forward(cr, ci, scratch.AsSpan(2 * height)); + for (int y = 0, i = x; y < height; y++, i += width) + { + re[i] = cr[y]; + im[i] = ci[y]; + } + } +} diff --git a/src/Titano.Core/Motion/PhaseCorrelator.cs b/src/Titano.Core/Motion/PhaseCorrelator.cs new file mode 100644 index 00000000..12e9027a --- /dev/null +++ b/src/Titano.Core/Motion/PhaseCorrelator.cs @@ -0,0 +1,273 @@ +namespace Titano.Core.Motion; + +/// +/// Translation between two patches. moving(x, y) ≈ reference(x − Dx, y − Dy): content moved by +/// (+Dx, +Dy) pixels from the reference to the moving patch. is the peak +/// sharpness ratio 1 − second/primary peak, in [0, 1]; is the correlation peak height +/// (1 for a perfect translation, near 0 for unrelated content). +/// +public readonly record struct PhaseCorrelation(double Dx, double Dy, double Confidence, double Peak); + +/// Tuning for . +public sealed record PhaseCorrelatorOptions +{ + /// Tukey taper fraction of the analysis window (1 = Hann). Suppresses the patch-border discontinuity. + public double WindowTaper { get; init; } = 0.5; + + /// + /// Spatial σ (px) of the Gaussian low-pass applied to the normalised cross-power spectrum. It shapes the + /// correlation peak into a sampled Gaussian, which makes the log-parabola sub-pixel fit unbiased, and + /// attenuates the noisiest high frequencies. + /// + public double PeakSigma { get; init; } = 1.0; + + /// Largest |shift| searched per axis (px); 0 searches the whole surface. + public int MaxShift { get; init; } + + /// Default options. + public static PhaseCorrelatorOptions Default { get; } = new(); +} + +/// +/// Kuglin & Hines (1975) phase correlation between two equally sized luminance patches: weighted-mean +/// removal, Tukey window, one complex FFT carrying both real patches (reference as real part, moving as +/// imaginary part), normalised cross-power spectrum with a relative epsilon and a Gaussian low-pass, +/// inverse FFT, integer peak search and a separable Gaussian (log-parabola) sub-pixel fit. +/// Holds its working buffers, so one instance must not be used by two threads at once. +/// +public sealed class PhaseCorrelator +{ + // Relative regulariser of |cross power|: keeps empty bins from being amplified to unit magnitude. + private const double SpectrumEpsilon = 1e-6; + + private readonly double[] _window; + private readonly double[] _lowPass; + private readonly double[] _re; + private readonly double[] _im; + private readonly int _maxShiftX; + private readonly int _maxShiftY; + private readonly int _exclusion; + private readonly double _windowSum; + + public PhaseCorrelator(int width, int height, PhaseCorrelatorOptions? options = null) + { + ArgumentOutOfRangeException.ThrowIfLessThan(width, 4); + ArgumentOutOfRangeException.ThrowIfLessThan(height, 4); + Options = options ?? PhaseCorrelatorOptions.Default; + Width = width; + Height = height; + var n = width * height; + _re = new double[n]; + _im = new double[n]; + + var wxArray = new double[width]; + var wyArray = new double[height]; + Fourier.Tukey(wxArray, Options.WindowTaper); + Fourier.Tukey(wyArray, Options.WindowTaper); + _window = new double[n]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var w = wyArray[y] * wxArray[x]; + _window[y * width + x] = w; + _windowSum += w; + } + } + + // Gaussian of spatial σ in the frequency domain: exp(−2π²σ²|f|²), f in cycles per pixel. + _lowPass = new double[n]; + var sigma = Options.PeakSigma; + var k = -2.0 * double.Pi * double.Pi * sigma * sigma; + for (var v = 0; v < height; v++) + { + var fy = Signed(v, height) / (double)height; + for (var u = 0; u < width; u++) + { + var fx = Signed(u, width) / (double)width; + _lowPass[v * width + u] = sigma > 0 ? double.Exp(k * (fx * fx + fy * fy)) : 1.0; + } + } + _lowPass[0] = 0; // DC carries no shift information. + double sum = 0; + foreach (var g in _lowPass) sum += g; + // Normalise so that a perfect translation produces a unit peak. + var norm = n / sum; + for (var i = 0; i < n; i++) _lowPass[i] *= norm; + + var limitX = width / 2 - 1; + var limitY = height / 2 - 1; + _maxShiftX = Options.MaxShift > 0 ? int.Min(Options.MaxShift, limitX) : limitX; + _maxShiftY = Options.MaxShift > 0 ? int.Min(Options.MaxShift, limitY) : limitY; + _exclusion = int.Max(2, (int)double.Ceiling(3 * double.Max(sigma, 0.5))); + } + + public int Width { get; } + + public int Height { get; } + + public PhaseCorrelatorOptions Options { get; } + + /// Correlates two row-major patches of × samples. + public PhaseCorrelation Correlate(ReadOnlySpan reference, ReadOnlySpan moving) => + Correlate(reference, moving, Width, 0, 0); + + /// + /// Correlates the patches at (, ) of two equally sized planes + /// with row stride . + /// + public PhaseCorrelation Correlate(ReadOnlySpan referencePlane, ReadOnlySpan movingPlane, int planeWidth, int x0, int y0) + { + var w = Width; + var h = Height; + if (x0 < 0 || y0 < 0 || x0 + w > planeWidth) throw new ArgumentOutOfRangeException(nameof(x0), "Patch outside the plane."); + var last = (y0 + h - 1) * planeWidth + x0 + w; + if (last > referencePlane.Length || last > movingPlane.Length) throw new ArgumentOutOfRangeException(nameof(y0), "Patch outside the plane."); + + // Window-weighted means, so the windowed patches have exactly zero DC. + double ma = 0, mb = 0; + for (var y = 0; y < h; y++) + { + var ra = referencePlane.Slice((y0 + y) * planeWidth + x0, w); + var rb = movingPlane.Slice((y0 + y) * planeWidth + x0, w); + var win = _window.AsSpan(y * w, w); + for (var x = 0; x < w; x++) + { + ma += win[x] * ra[x]; + mb += win[x] * rb[x]; + } + } + ma /= _windowSum; + mb /= _windowSum; + for (var y = 0; y < h; y++) + { + var ra = referencePlane.Slice((y0 + y) * planeWidth + x0, w); + var rb = movingPlane.Slice((y0 + y) * planeWidth + x0, w); + var o = y * w; + for (var x = 0; x < w; x++) + { + _re[o + x] = (ra[x] - ma) * _window[o + x]; + _im[o + x] = (rb[x] - mb) * _window[o + x]; + } + } + + Fourier.Forward2D(_re, _im, w, h); + CrossPowerSpectrum(); + Fourier.Inverse2D(_re, _im, w, h); + return LocatePeak(); + } + + /// + /// Replaces the packed spectrum Z = A + iB with the normalised, low-passed cross power conj(A)·B / |conj(A)·B|. + /// A and B are recovered from Hermitian symmetry: A_k = (Z_k + conj Z_−k)/2, B_k = (Z_k − conj Z_−k)/2i. + /// + private void CrossPowerSpectrum() + { + var w = Width; + var h = Height; + var re = _re; + var im = _im; + double magnitudeSum = 0; + for (var v = 0; v < h; v++) + { + var mv = v == 0 ? 0 : h - v; + for (var u = 0; u < w; u++) + { + var i = v * w + u; + var j = mv * w + (u == 0 ? 0 : w - u); + if (j < i) continue; + double zr = re[i], zi = im[i], yr = re[j], yi = im[j]; + var ar = 0.5 * (zr + yr); + var ai = 0.5 * (zi - yi); + var br = 0.5 * (zi + yi); + var bi = -0.5 * (zr - yr); + // conj(A)·B; the mirrored bin holds its conjugate because the correlation is real. + var cr = ar * br + ai * bi; + var ci = ar * bi - ai * br; + re[i] = cr; + im[i] = ci; + re[j] = cr; + im[j] = -ci; + var mag = double.Sqrt(cr * cr + ci * ci); + magnitudeSum += i == j ? mag : 2 * mag; + } + } + + var epsilon = SpectrumEpsilon * magnitudeSum / (w * h) + double.Epsilon; + var lowPass = _lowPass; + for (var i = 0; i < re.Length; i++) + { + var mag = double.Sqrt(re[i] * re[i] + im[i] * im[i]); + var f = lowPass[i] / (mag + epsilon); + re[i] *= f; + im[i] *= f; + } + } + + private PhaseCorrelation LocatePeak() + { + var w = Width; + var h = Height; + var c = _re; + int px = 0, py = 0; + var best = double.NegativeInfinity; + for (var dy = -_maxShiftY; dy <= _maxShiftY; dy++) + { + var row = Wrap(dy, h) * w; + for (var dx = -_maxShiftX; dx <= _maxShiftX; dx++) + { + var value = c[row + Wrap(dx, w)]; + if (value > best) + { + best = value; + px = dx; + py = dy; + } + } + } + + double At(int dx, int dy) => c[Wrap(dy, h) * w + Wrap(dx, w)]; + var fx = SubPixel(At(px - 1, py), best, At(px + 1, py)); + var fy = SubPixel(At(px, py - 1), best, At(px, py + 1)); + + // Second peak: the largest value outside the main lobe (wrap-aware Chebyshev distance). + var second = double.NegativeInfinity; + for (var dy = -_maxShiftY; dy <= _maxShiftY; dy++) + { + var row = Wrap(dy, h) * w; + var nearY = int.Abs(dy - py) <= _exclusion; + for (var dx = -_maxShiftX; dx <= _maxShiftX; dx++) + { + if (nearY && int.Abs(dx - px) <= _exclusion) continue; + var value = c[row + Wrap(dx, w)]; + if (value > second) second = value; + } + } + + var confidence = best > 0 ? double.Clamp(1 - double.Max(second, 0) / best, 0, 1) : 0; + return new PhaseCorrelation(px + fx, py + fy, confidence, double.Max(best, 0)); + } + + /// Vertex of the parabola through log values (exact for a sampled Gaussian), or of the plain + /// parabola when a neighbour is not positive; clamped to ±0.5 px. + private static double SubPixel(double left, double centre, double right) + { + double offset; + if (left > 0 && centre > 0 && right > 0) + { + double l = double.Log(left), c = double.Log(centre), r = double.Log(right); + var d = l - 2 * c + r; + offset = d < 0 ? 0.5 * (l - r) / d : 0; + } + else + { + var d = left - 2 * centre + right; + offset = d < 0 ? 0.5 * (left - right) / d : 0; + } + return double.Clamp(offset, -0.5, 0.5); + } + + private static int Signed(int index, int length) => index <= length / 2 ? index : index - length; + + private static int Wrap(int index, int length) => index < 0 ? index + length : index; +} diff --git a/tests/Titano.Core.Tests/Motion/FourierTests.cs b/tests/Titano.Core.Tests/Motion/FourierTests.cs new file mode 100644 index 00000000..621d1fd6 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/FourierTests.cs @@ -0,0 +1,176 @@ +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class FourierTests +{ + [Theory] + [Case(1)] + [Case(2)] + [Case(64)] + [Case(1024)] + [Case(4096)] + public void PowerOfTwoRoundTrip(int n) + { + var (re, im) = RandomSignal(n, seed: n); + var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone()); + Fourier.Forward(re, im); + Fourier.Inverse(re, im); + Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5); + } + + [Theory] + [Case(3)] + [Case(7)] + [Case(13)] + [Case(97)] + [Case(251)] + [Case(1009)] + public void BluesteinMatchesDirectDftForPrimes(int n) + { + var (re, im) = RandomSignal(n, seed: n); + var (er, ei) = Dft(re, im); + Fourier.Forward(re, im); + var scale = double.Sqrt(n); + Assert.LessOrEqual(MaxError(er, ei, re, im) / scale, 1e-9); + } + + [Theory] + [Case(12)] + [Case(100)] + [Case(1000)] + public void CompositeLengthsRoundTrip(int n) + { + var (re, im) = RandomSignal(n, seed: 3 * n); + var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone()); + Fourier.Forward(re, im); + Fourier.Inverse(re, im); + Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5); + } + + [Theory] + [Case(64)] + [Case(100)] + [Case(15)] + public void RealTransformMatchesComplexAndRoundTrips(int n) + { + var (signal, _) = RandomSignal(n, seed: 11 * n); + var bins = n / 2 + 1; + var hr = new double[bins]; + var hi = new double[bins]; + Fourier.ForwardReal(signal, hr, hi); + + var re = (double[])signal.Clone(); + var im = new double[n]; + Fourier.Forward(re, im); + Assert.LessOrEqual(MaxError(re.AsSpan(0, bins).ToArray(), im.AsSpan(0, bins).ToArray(), hr, hi), 1e-9); + + var back = new double[n]; + Fourier.InverseReal(hr, hi, back); + for (var i = 0; i < n; i++) Assert.Approximately(signal[i], back[i], 1e-9); + } + + [Theory] + [Case(64, 64)] + [Case(48, 36)] + [Case(256, 160)] + public void TwoDimensionalRoundTripAndShiftTheorem(int width, int height) + { + var (re, im) = RandomSignal(width * height, seed: width + height); + var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone()); + Fourier.Forward2D(re, im, width, height); + // A unit impulse at (1, 0) transforms to e^(−2πiu/W) on every row: check one bin of a separate impulse. + var dr = new double[width * height]; + var di = new double[width * height]; + dr[1] = 1; + Fourier.Forward2D(dr, di, width, height); + var (s, c) = double.SinCos(-2 * double.Pi * 3 / width); + Assert.Approximately(c, dr[2 * width + 3], 1e-12); + Assert.Approximately(s, di[2 * width + 3], 1e-12); + + Fourier.Inverse2D(re, im, width, height); + Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5); + } + + [Test] + public void ParsevalHolds() + { + const int n = 512; + var (re, im) = RandomSignal(n, seed: 5); + double time = 0, freq = 0; + for (var i = 0; i < n; i++) time += re[i] * re[i] + im[i] * im[i]; + Fourier.Forward(re, im); + for (var i = 0; i < n; i++) freq += re[i] * re[i] + im[i] * im[i]; + Assert.Approximately(time, freq / n, 1e-9 * time); + } + + [Test] + public void WindowsHaveExpectedShape() + { + var hann = new double[9]; + Fourier.Hann(hann); + Assert.Approximately(0, hann[0], 1e-15); + Assert.Approximately(1, hann[4], 1e-15); + Assert.Approximately(0.5, hann[2], 1e-12); + Assert.Approximately(hann[1], hann[7], 1e-15); + + var rect = new double[9]; + Fourier.Tukey(rect, 0); + Assert.True(rect.All(v => v == 1)); + + var tukey = new double[101]; + Fourier.Tukey(tukey, 0.5); + Assert.Approximately(0, tukey[0], 1e-15); + Assert.Equal(1.0, tukey[25]); + Assert.Equal(1.0, tukey[75]); + // Mid-taper (x = 0.125) is at half height; the flanks rise monotonically and mirror each other. + Assert.InRange(tukey[12], 0.45, 0.5); + Assert.InRange(tukey[13], 0.5, 0.55); + Assert.Monotonic(tukey.Take(26).ToArray()); + for (var i = 0; i < 101; i++) Assert.Approximately(tukey[i], tukey[100 - i], 1e-15); + } + + [Test] + public void PlansAreCached() => Assert.Same(Fourier.Plan(96), Fourier.Plan(96)); + + private static (double[] Re, double[] Im) RandomSignal(int n, int seed) + { + var random = new Random(seed); + var re = new double[n]; + var im = new double[n]; + for (var i = 0; i < n; i++) + { + re[i] = random.NextDouble() * 2 - 1; + im[i] = random.NextDouble() * 2 - 1; + } + return (re, im); + } + + private static (double[] Re, double[] Im) Dft(double[] re, double[] im) + { + var n = re.Length; + var or = new double[n]; + var oi = new double[n]; + for (var k = 0; k < n; k++) + { + double sr = 0, si = 0; + for (var t = 0; t < n; t++) + { + var (s, c) = double.SinCos(-2 * double.Pi * ((long)k * t % n) / n); + sr += re[t] * c - im[t] * s; + si += re[t] * s + im[t] * c; + } + or[k] = sr; + oi[k] = si; + } + return (or, oi); + } + + private static double MaxError(double[] ar, double[] ai, double[] br, double[] bi) + { + double max = 0; + for (var i = 0; i < ar.Length; i++) max = double.Max(max, double.Max(double.Abs(ar[i] - br[i]), double.Abs(ai[i] - bi[i]))); + return max; + } +} diff --git a/tests/Titano.Core.Tests/Motion/PhaseCorrelatorTests.cs b/tests/Titano.Core.Tests/Motion/PhaseCorrelatorTests.cs new file mode 100644 index 00000000..c268c527 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/PhaseCorrelatorTests.cs @@ -0,0 +1,83 @@ +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class PhaseCorrelatorTests +{ + private const int Size = 256; + private const int Patch = 128; + + private readonly TestContext _context; + + public PhaseCorrelatorTests(TestContext context) => _context = context; + + [Theory] + [Case("noise", 3.25, -1.6)] + [Case("noise", 0.5, 0.5)] + [Case("noise", -7.8, 2.1)] + [Case("noise", 0.0, 0.0)] + [Case("natural", 3.25, -1.6)] + [Case("natural", 0.5, 0.5)] + [Case("natural", -7.8, 2.1)] + [Case("natural", 12.3, -9.45)] + public void SubPixelErrorWithinTenthOfPixel(string texture, double dx, double dy) + { + var image = texture == "noise" ? SyntheticImages.Noise(Size, 0.8, seed: 7) : SyntheticImages.Natural(Size, seed: 7); + var shifted = SyntheticImages.Shift(image, Size, dx, dy); + var reference = SyntheticImages.Crop(image, Size, 64, 64, Patch, Patch); + var moving = SyntheticImages.Crop(shifted, Size, 64, 64, Patch, Patch); + + var result = new PhaseCorrelator(Patch, Patch).Correlate(reference, moving); + var error = double.Hypot(result.Dx - dx, result.Dy - dy); + _context.Log($"{texture} ({dx}, {dy}) → ({result.Dx:F4}, {result.Dy:F4}) error {error:F4} px, confidence {result.Confidence:F3}, peak {result.Peak:F3}"); + Assert.LessOrEqual(error, 0.10); + Assert.Greater(result.Confidence, 0.5); + } + + [Test] + public void NonPowerOfTwoPatchesUseBluestein() + { + var image = SyntheticImages.Natural(Size, seed: 3); + var shifted = SyntheticImages.Shift(image, Size, -2.4, 1.3); + var reference = SyntheticImages.Crop(image, Size, 60, 70, 96, 80); + var moving = SyntheticImages.Crop(shifted, Size, 60, 70, 96, 80); + var result = new PhaseCorrelator(96, 80).Correlate(reference, moving); + Assert.Within(-2.4, 1.3, result.Dx, result.Dy, 0.10); + } + + [Test] + public void PatchesAreReadFromLargerPlanes() + { + var image = SyntheticImages.Noise(Size, 1.0, seed: 9); + var shifted = SyntheticImages.Shift(image, Size, 1.75, -0.25); + var a = SyntheticImages.Crop(image, Size, 0, 0, Size, Size); + var b = SyntheticImages.Crop(shifted, Size, 0, 0, Size, Size); + var result = new PhaseCorrelator(64, 64).Correlate(a, b, Size, 100, 40); + Assert.Within(1.75, -0.25, result.Dx, result.Dy, 0.10); + } + + [Test] + public void UnrelatedContentHasLowConfidence() + { + var a = SyntheticImages.Crop(SyntheticImages.Noise(Size, 0.8, seed: 1), Size, 0, 0, Patch, Patch); + var b = SyntheticImages.Crop(SyntheticImages.Noise(Size, 0.8, seed: 2), Size, 0, 0, Patch, Patch); + var result = new PhaseCorrelator(Patch, Patch).Correlate(a, b); + _context.Log($"confidence {result.Confidence:F3}, peak {result.Peak:F3}"); + Assert.Less(result.Confidence, 0.4); + Assert.Less(result.Peak, 0.2); + } + + [Test] + public void MaxShiftLimitsTheSearch() + { + var image = SyntheticImages.Noise(Size, 0.8, seed: 4); + var shifted = SyntheticImages.Shift(image, Size, 20, 0); + var a = SyntheticImages.Crop(image, Size, 64, 64, Patch, Patch); + var b = SyntheticImages.Crop(shifted, Size, 64, 64, Patch, Patch); + var free = new PhaseCorrelator(Patch, Patch).Correlate(a, b); + Assert.Within(20, 0, free.Dx, free.Dy, 0.10); + var limited = new PhaseCorrelator(Patch, Patch, new PhaseCorrelatorOptions { MaxShift = 8 }).Correlate(a, b); + Assert.LessOrEqual(double.Abs(limited.Dx), 8.5); + } +} diff --git a/tests/Titano.Core.Tests/Motion/SyntheticImages.cs b/tests/Titano.Core.Tests/Motion/SyntheticImages.cs new file mode 100644 index 00000000..921c8d9d --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/SyntheticImages.cs @@ -0,0 +1,122 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; + +namespace Titano.Core.Tests.Motion; + +/// Deterministic synthetic textures (periodic, band-limited) and exact sub-pixel shifts by Fourier phase ramp. +internal static class SyntheticImages +{ + /// Gaussian-filtered white noise: spectral envelope exp(−2π²σ²|f|²), mean 0.5, standard deviation 0.15. + public static double[] Noise(int size, double sigma, int seed) => + Synthesize(size, seed, f => double.Exp(-2 * double.Pi * double.Pi * sigma * sigma * f * f)); + + /// Natural-image-like texture: amplitude ∝ 1/f^1.4 with a soft high-frequency roll-off. + public static double[] Natural(int size, int seed) => + Synthesize(size, seed, f => f == 0 ? 0 : double.Pow(f * size, -1.4) * double.Exp(-f * f / (2 * 0.2 * 0.2))); + + /// Periodic shift with sub-pixel accuracy: result(x, y) = image(x − dx, y − dy). + public static double[] Shift(double[] image, int size, double dx, double dy) + { + var re = (double[])image.Clone(); + var im = new double[re.Length]; + Fourier.Forward2D(re, im, size, size); + for (var v = 0; v < size; v++) + { + for (var u = 0; u < size; u++) + { + var (s, c) = double.SinCos(-2 * double.Pi * (Signed(u, size) * dx + Signed(v, size) * dy) / size); + var i = v * size + u; + (re[i], im[i]) = (re[i] * c - im[i] * s, re[i] * s + im[i] * c); + } + } + Fourier.Inverse2D(re, im, size, size); + return re; + } + + /// Copies a rectangle of a square periodic image into a float plane. + public static float[] Crop(double[] image, int size, int x0, int y0, int width, int height) + { + var plane = new float[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) plane[y * width + x] = (float)image[((y0 + y) % size) * size + (x0 + x) % size]; + } + return plane; + } + + /// Single-channel buffer from a plane. + public static ImageBuffer ToBuffer(float[] plane, int width, int height) + { + var buffer = new ImageBuffer(width, height, 1, clear: false); + plane.AsSpan().CopyTo(buffer.Plane(0)); + return buffer; + } + + /// RGB buffer whose channels are scaled copies of a plane (distinct but correlated colours). + public static ImageBuffer ToRgb(float[] plane, int width, int height) + { + var buffer = new ImageBuffer(width, height, 3, clear: false); + for (var c = 0; c < 3; c++) + { + var dst = buffer.Plane(c); + var gain = 0.6f + 0.2f * c; + for (var i = 0; i < plane.Length; i++) dst[i] = plane[i] * gain; + } + return buffer; + } + + /// Peak signal-to-noise ratio in dB for unit peak over the window [x0, x1)×[y0, y1). + public static double Psnr(ReadOnlySpan a, ReadOnlySpan b, int width, int x0, int y0, int x1, int y1) + { + double sum = 0; + var n = 0; + for (var y = y0; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var d = a[y * width + x] - (double)b[y * width + x]; + sum += d * d; + n++; + } + } + var mse = sum / n; + return mse == 0 ? double.PositiveInfinity : 10 * double.Log10(1 / mse); + } + + private static double[] Synthesize(int size, int seed, Func envelope) + { + var random = new Random(seed); + var re = new double[size * size]; + var im = new double[size * size]; + for (var v = 0; v < size; v++) + { + for (var u = 0; u < size; u++) + { + // Nyquist bins stay empty so the phase-ramp shift is exact for a real image. + if (u == size / 2 || v == size / 2) continue; + double fx = Signed(u, size) / (double)size, fy = Signed(v, size) / (double)size; + var a = envelope(double.Sqrt(fx * fx + fy * fy)); + re[v * size + u] = a * Gaussian(random); + im[v * size + u] = a * Gaussian(random); + } + } + re[0] = im[0] = 0; + Fourier.Inverse2D(re, im, size, size); + double mean = 0, sq = 0; + foreach (var x in re) mean += x; + mean /= re.Length; + foreach (var x in re) sq += (x - mean) * (x - mean); + var scale = 0.15 / double.Sqrt(sq / re.Length); + for (var i = 0; i < re.Length; i++) re[i] = 0.5 + (re[i] - mean) * scale; + return re; + } + + private static double Gaussian(Random random) + { + var u1 = 1.0 - random.NextDouble(); + var u2 = random.NextDouble(); + return double.Sqrt(-2 * double.Log(u1)) * double.Cos(2 * double.Pi * u2); + } + + private static int Signed(int index, int length) => index <= length / 2 ? index : index - length; +} From 0b459bd108ef0edb15dd2950f0dbf569d45ec03f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:22:36 +0000 Subject: [PATCH 004/188] feat(geometry): add affine maps, aspect crop-fit and Catmull-Rom geometry stage Affine2D (compose, invert, apply, similarity decomposition), RectD and AspectRatio presets with largest-centred crop fitting and offsets, and a single-pass geometry stage composing crop, aspect, output size and warp, resampled with Keys cubic convolution (a = -0.5): Vector128 4x4 interior path, widened kernel when minifying, clamp or transparent borders. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Imaging/Geometry/Affine2D.cs | 82 +++++ .../Imaging/Geometry/AspectRatio.cs | 117 +++++++ .../Imaging/Geometry/GeometryStage.cs | 320 ++++++++++++++++++ .../Geometry/Affine2DTests.cs | 56 +++ .../Geometry/AspectRatioTests.cs | 54 +++ .../Geometry/GeometryStageTests.cs | 133 ++++++++ 6 files changed, 762 insertions(+) create mode 100644 src/Titano.Core/Imaging/Geometry/Affine2D.cs create mode 100644 src/Titano.Core/Imaging/Geometry/AspectRatio.cs create mode 100644 src/Titano.Core/Imaging/Geometry/GeometryStage.cs create mode 100644 tests/Titano.Core.Tests/Geometry/Affine2DTests.cs create mode 100644 tests/Titano.Core.Tests/Geometry/AspectRatioTests.cs create mode 100644 tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs diff --git a/src/Titano.Core/Imaging/Geometry/Affine2D.cs b/src/Titano.Core/Imaging/Geometry/Affine2D.cs new file mode 100644 index 00000000..70198191 --- /dev/null +++ b/src/Titano.Core/Imaging/Geometry/Affine2D.cs @@ -0,0 +1,82 @@ +namespace Titano.Core.Imaging.Geometry; + +/// +/// 2D affine map x' = M11·x + M12·y + Tx, y' = M21·x + M22·y + Ty. Image transforms use +/// pixel-centre coordinates: pixel (i, j) sits at (i, j) and an image of width W spans [−0.5, W − 0.5]. +/// a * b applies b first, then a. +/// +public readonly record struct Affine2D(double M11, double M12, double M21, double M22, double Tx, double Ty) +{ + public static Affine2D Identity { get; } = new(1, 0, 0, 1, 0, 0); + + public static Affine2D Translation(double tx, double ty) => new(1, 0, 0, 1, tx, ty); + + public static Affine2D Scaling(double sx, double sy) => new(sx, 0, 0, sy, 0, 0); + + /// Counter-clockwise rotation in a y-up frame (clockwise on screen, where y points down). + public static Affine2D Rotation(double radians) + { + var (s, c) = double.SinCos(radians); + return new Affine2D(c, -s, s, c, 0, 0); + } + + /// Similarity x' = scale · R(radians) · x + (tx, ty). + public static Affine2D Similarity(double scale, double radians, double tx, double ty) + { + var (s, c) = double.SinCos(radians); + return new Affine2D(scale * c, -scale * s, scale * s, scale * c, tx, ty); + } + + /// The linear part of applied about the pivot (cx, cy) instead of the origin. + public static Affine2D About(Affine2D map, double cx, double cy) => Translation(cx, cy) * map * Translation(-cx, -cy); + + public double Determinant => M11 * M22 - M12 * M21; + + /// Uniform scale of the linear part, √|det|. + public double Scale => double.Sqrt(double.Abs(Determinant)); + + /// Rotation angle (radians) of the closest similarity. + public double Angle => double.Atan2(M21 - M12, M11 + M22); + + public (double X, double Y) Apply(double x, double y) => (M11 * x + M12 * y + Tx, M21 * x + M22 * y + Ty); + + /// Applies the linear part only (for displacement vectors). + public (double X, double Y) ApplyVector(double x, double y) => (M11 * x + M12 * y, M21 * x + M22 * y); + + /// This map followed by . + public Affine2D Then(Affine2D next) => next * this; + + public static Affine2D operator *(Affine2D outer, Affine2D inner) => new( + outer.M11 * inner.M11 + outer.M12 * inner.M21, + outer.M11 * inner.M12 + outer.M12 * inner.M22, + outer.M21 * inner.M11 + outer.M22 * inner.M21, + outer.M21 * inner.M12 + outer.M22 * inner.M22, + outer.M11 * inner.Tx + outer.M12 * inner.Ty + outer.Tx, + outer.M21 * inner.Tx + outer.M22 * inner.Ty + outer.Ty); + + public bool TryInvert(out Affine2D inverse) + { + var det = Determinant; + var norm = double.Abs(M11) + double.Abs(M12) + double.Abs(M21) + double.Abs(M22); + if (!(double.Abs(det) > 1e-14 * norm * norm)) + { + inverse = default; + return false; + } + var r = 1 / det; + var a = M22 * r; + var b = -M12 * r; + var c = -M21 * r; + var d = M11 * r; + inverse = new Affine2D(a, b, c, d, -(a * Tx + b * Ty), -(c * Tx + d * Ty)); + return true; + } + + /// Inverse map; throws for a singular matrix. + public Affine2D Invert() => TryInvert(out var inverse) ? inverse : throw new InvalidOperationException("The affine map is singular."); + + /// True when every coefficient is within of the identity. + public bool IsIdentity(double tolerance = 1e-12) => + double.Abs(M11 - 1) <= tolerance && double.Abs(M12) <= tolerance && double.Abs(M21) <= tolerance + && double.Abs(M22 - 1) <= tolerance && double.Abs(Tx) <= tolerance && double.Abs(Ty) <= tolerance; +} diff --git a/src/Titano.Core/Imaging/Geometry/AspectRatio.cs b/src/Titano.Core/Imaging/Geometry/AspectRatio.cs new file mode 100644 index 00000000..ae92435f --- /dev/null +++ b/src/Titano.Core/Imaging/Geometry/AspectRatio.cs @@ -0,0 +1,117 @@ +using System.Globalization; + +namespace Titano.Core.Imaging.Geometry; + +/// Axis-aligned rectangle in edge coordinates (a W×H image is (0, 0, W, H)). +public readonly record struct RectD(double X, double Y, double Width, double Height) +{ + public double Right => X + Width; + + public double Bottom => Y + Height; + + public double CenterX => X + Width / 2; + + public double CenterY => Y + Height / 2; + + public static RectD FromSize(double width, double height) => new(0, 0, width, height); +} + +/// +/// Output aspect ratio: a named preset, a custom W:H, or (the source frame's own ratio). +/// +public readonly record struct AspectRatio +{ + private AspectRatio(int width, int height) + { + Width = width; + Height = height; + } + + /// Ratio numerator; 0 for . + public int Width { get; } + + /// Ratio denominator; 0 for . + public int Height { get; } + + public bool IsSource => Width == 0; + + public static AspectRatio Source => default; + + public static AspectRatio Widescreen { get; } = new(16, 9); + + public static AspectRatio Cinema { get; } = new(21, 9); + + public static AspectRatio Standard { get; } = new(4, 3); + + public static AspectRatio Photo { get; } = new(3, 2); + + public static AspectRatio Square { get; } = new(1, 1); + + public static AspectRatio Vertical { get; } = new(9, 16); + + public static AspectRatio Portrait { get; } = new(4, 5); + + /// The presets offered to users, first. + public static IReadOnlyList Presets { get; } = [Source, Widescreen, Cinema, Standard, Photo, Square, Vertical, Portrait]; + + /// A custom W:H ratio (reduced to lowest terms). + public static AspectRatio Custom(int width, int height) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + var g = Gcd(width, height); + return new AspectRatio(width / g, height / g); + } + + /// Width / height, using the source size when this is . + public double Resolve(double sourceWidth, double sourceHeight) => IsSource ? sourceWidth / sourceHeight : Width / (double)Height; + + /// Parses "16:9", "16/9" or "source". + public static bool TryParse(string? text, out AspectRatio ratio) + { + ratio = Source; + if (string.IsNullOrWhiteSpace(text)) return false; + text = text.Trim(); + if (text.Equals("source", StringComparison.OrdinalIgnoreCase)) return true; + var separator = text.IndexOfAny([':', '/', 'x']); + if (separator <= 0 + || !int.TryParse(text.AsSpan(0, separator), NumberStyles.None, CultureInfo.InvariantCulture, out var w) + || !int.TryParse(text.AsSpan(separator + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var h) + || w <= 0 || h <= 0) + return false; + ratio = Custom(w, h); + return true; + } + + public override string ToString() => IsSource ? "source" : string.Create(CultureInfo.InvariantCulture, $"{Width}:{Height}"); + + /// + /// Largest crop of aspect (width / height) inside . + /// The offsets place it within the leftover slack: −1 = left/top, 0 = centred, +1 = right/bottom (clamped). + /// + public static RectD FitCrop(RectD bounds, double ratio, double offsetX = 0, double offsetY = 0) + { + if (!(ratio > 0) || double.IsInfinity(ratio)) throw new ArgumentOutOfRangeException(nameof(ratio)); + if (!(bounds.Width > 0 && bounds.Height > 0)) throw new ArgumentOutOfRangeException(nameof(bounds)); + double width, height; + if (bounds.Width >= bounds.Height * ratio) + { + height = bounds.Height; + width = height * ratio; + } + else + { + width = bounds.Width; + height = width / ratio; + } + var fx = (1 + double.Clamp(offsetX, -1, 1)) / 2; + var fy = (1 + double.Clamp(offsetY, -1, 1)) / 2; + return new RectD(bounds.X + (bounds.Width - width) * fx, bounds.Y + (bounds.Height - height) * fy, width, height); + } + + private static int Gcd(int a, int b) + { + while (b != 0) (a, b) = (b, a % b); + return a; + } +} diff --git a/src/Titano.Core/Imaging/Geometry/GeometryStage.cs b/src/Titano.Core/Imaging/Geometry/GeometryStage.cs new file mode 100644 index 00000000..c9e70682 --- /dev/null +++ b/src/Titano.Core/Imaging/Geometry/GeometryStage.cs @@ -0,0 +1,320 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace Titano.Core.Imaging.Geometry; + +/// How samples that fall outside the source are treated. +public enum BorderMode +{ + /// Replicate the nearest edge pixel. + Clamp, + + /// Outside is transparent black; the destination carries premultiplied colour and alpha coverage. + Transparent, +} + +/// Crop, aspect, output size and warp of one frame, applied in a single resampling pass. +public sealed record GeometrySettings +{ + /// Region of the working space to show (edge coordinates); null = the whole frame. + public RectD? Crop { get; init; } + + /// + /// Output aspect; the largest crop of this aspect inside is used. + /// takes the ratio of the output size when both dimensions are given, else that of the source frame. + /// + public AspectRatio Aspect { get; init; } = AspectRatio.Source; + + /// Placement of the fitted crop within the slack, −1..1 per axis (0 = centred). + public double OffsetX { get; init; } + + public double OffsetY { get; init; } + + /// Output width in pixels; 0 derives it from the height and aspect, or from the crop. + public int OutputWidth { get; init; } + + /// Output height in pixels; 0 derives it from the width and aspect, or from the crop. + public int OutputHeight { get; init; } + + /// Maps working-space pixel-centre coordinates to source pixel-centre coordinates + /// (e.g. virtual camera composed with the inverse stabilisation correction). + public Affine2D Warp { get; init; } = Affine2D.Identity; + + public BorderMode Border { get; init; } = BorderMode.Clamp; +} + +/// Resolved geometry: output size and the output→source pixel-centre mapping. +public readonly record struct GeometryPlan(int OutputWidth, int OutputHeight, RectD Crop, Affine2D OutputToSource, BorderMode Border); + +/// +/// Geometry stage: crop rectangle, aspect fit, output size and affine warp composed into one output→source +/// map and resampled once with Catmull-Rom (Keys 1981 cubic convolution, a = −0.5). Magnification and 1:1 +/// use the 4×4 kernel (Vector128 rows in the interior); minification widens the kernel by the footprint +/// scale so downsizing does not alias. Rows run in parallel. +/// +public static class GeometryStage +{ + private const int ParallelThreshold = 1 << 16; + + /// Resolves crop, aspect and output size against a source of the given size. + public static GeometryPlan Plan(int sourceWidth, int sourceHeight, GeometrySettings settings) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight); + ArgumentOutOfRangeException.ThrowIfNegative(settings.OutputWidth); + ArgumentOutOfRangeException.ThrowIfNegative(settings.OutputHeight); + var bounds = settings.Crop ?? RectD.FromSize(sourceWidth, sourceHeight); + var ratio = settings.Aspect.IsSource && settings.OutputWidth > 0 && settings.OutputHeight > 0 + ? settings.OutputWidth / (double)settings.OutputHeight + : settings.Aspect.Resolve(sourceWidth, sourceHeight); + var crop = AspectRatio.FitCrop(bounds, ratio, settings.OffsetX, settings.OffsetY); + + int width = settings.OutputWidth, height = settings.OutputHeight; + if (width == 0 && height == 0) + { + width = (int)double.Round(crop.Width); + height = (int)double.Round(crop.Height); + } + else if (height == 0) + { + height = (int)double.Round(width / ratio); + } + else if (width == 0) + { + width = (int)double.Round(height * ratio); + } + width = int.Max(1, width); + height = int.Max(1, height); + + // Output pixel centre u ↦ crop edge coordinate X + (u + ½)·Wc/Wout ↦ working pixel centre (−½). + var sx = crop.Width / width; + var sy = crop.Height / height; + var toWorking = new Affine2D(sx, 0, 0, sy, crop.X - 0.5 + 0.5 * sx, crop.Y - 0.5 + 0.5 * sy); + return new GeometryPlan(width, height, crop, settings.Warp * toWorking, settings.Border); + } + + /// Plans and renders into a new buffer (4 channels when the border is transparent). + public static ImageBuffer Apply(ImageBuffer source, GeometrySettings settings, CancellationToken cancellationToken = default) + { + var plan = Plan(source.Width, source.Height, settings); + var channels = plan.Border == BorderMode.Transparent ? 4 : source.Channels; + var destination = new ImageBuffer(plan.OutputWidth, plan.OutputHeight, channels, clear: false); + try + { + Warp(source, destination, plan.OutputToSource, plan.Border, cancellationToken); + return destination; + } + catch + { + destination.Dispose(); + throw; + } + } + + /// + /// Fills by sampling at + /// (x, y) for every destination pixel centre. With + /// both buffers have the same channel count; with + /// the destination has 4 channels (alpha last, colour premultiplied) + /// and the source 3 (opaque) or 4 (premultiplied). + /// + public static void Warp(ImageBuffer source, ImageBuffer destination, Affine2D outputToSource, BorderMode border = BorderMode.Clamp, CancellationToken cancellationToken = default) + { + var transparent = border == BorderMode.Transparent; + if (transparent ? destination.Channels != 4 || source.Channels < 3 : destination.Channels != source.Channels) + throw new ArgumentException("Destination channels must match the source (Clamp) or be 4 with a colour source (Transparent).", nameof(destination)); + + // Source-axis footprint of one output pixel; > 1 means minification and a widened kernel. + var footprintX = double.Max(1, double.Hypot(outputToSource.M11, outputToSource.M12)); + var footprintY = double.Max(1, double.Hypot(outputToSource.M21, outputToSource.M22)); + var job = new WarpJob(source, destination, outputToSource, transparent, footprintX, footprintY); + var rows = destination.Height; + if ((long)destination.Width * rows < ParallelThreshold) + { + for (var y = 0; y < rows; y++) + { + cancellationToken.ThrowIfCancellationRequested(); + job.Row(y); + } + } + else + { + Parallel.For(0, rows, new ParallelOptions { CancellationToken = cancellationToken }, job.Row); + } + } + + /// Catmull-Rom weights for taps at offsets −1, 0, 1, 2 from floor(x), with t = x − floor(x). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Vector128 CatmullRomWeights(float t) + { + var t2 = t * t; + var t3 = t2 * t; + return Vector128.Create( + 0.5f * (-t3 + 2 * t2 - t), + 0.5f * (3 * t3 - 5 * t2 + 2), + 0.5f * (-3 * t3 + 4 * t2 + t), + 0.5f * (t3 - t2)); + } + + /// Catmull-Rom kernel value at distance x (support ±2). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static double CatmullRom(double x) + { + x = double.Abs(x); + if (x < 1) return (1.5 * x - 2.5) * x * x + 1; + if (x < 2) return ((-0.5 * x + 2.5) * x - 4) * x + 2; + return 0; + } + + private sealed class WarpJob(ImageBuffer source, ImageBuffer destination, Affine2D map, bool transparent, double footprintX, double footprintY) + { + private readonly int _sw = source.Width; + private readonly int _sh = source.Height; + private readonly int _colourChannels = transparent ? 3 : source.Channels; + private readonly bool _sourceAlpha = transparent && source.Channels == 4; + private readonly bool _wide = footprintX > 1 || footprintY > 1; + + public void Row(int y) + { + if (_wide) WideRow(y); + else CubicRow(y); + } + + private void CubicRow(int y) + { + var src = source.Storage; + var plane = source.PlaneLength; + var dst = destination.Storage; + var dplane = destination.PlaneLength; + var w = _sw; + var h = _sh; + var outWidth = destination.Width; + var channels = transparent ? 4 : _colourChannels; + Span values = stackalloc float[4]; + for (var x = 0; x < outWidth; x++) + { + var (sx, sy) = map.Apply(x, y); + var fx = double.Floor(sx); + var fy = double.Floor(sy); + var o = y * outWidth + x; + if (!(double.Abs(fx) < 1e9 && double.Abs(fy) < 1e9)) + { + WriteOutside(dst, dplane, o, channels); + continue; + } + var ix = (int)fx; + var iy = (int)fy; + var wx = CatmullRomWeights((float)(sx - fx)); + var wy = CatmullRomWeights((float)(sy - fy)); + if (ix >= 1 && iy >= 1 && ix + 2 < w && iy + 2 < h) + { + ref var s0 = ref MemoryMarshal.GetArrayDataReference(src); + var offset = (nuint)((iy - 1) * w + ix - 1); + var stride = (nuint)w; + for (var c = 0; c < channels; c++) + { + if (transparent && c == 3 && !_sourceAlpha) + { + dst[c * dplane + o] = 1f; + continue; + } + var p = offset + (nuint)(c * plane); + var acc = Vector128.LoadUnsafe(ref s0, p) * wy.GetElement(0) + + Vector128.LoadUnsafe(ref s0, p + stride) * wy.GetElement(1) + + Vector128.LoadUnsafe(ref s0, p + 2 * stride) * wy.GetElement(2) + + Vector128.LoadUnsafe(ref s0, p + 3 * stride) * wy.GetElement(3); + dst[c * dplane + o] = Vector128.Dot(acc, wx); + } + continue; + } + + // Border: clamp indices, or drop outside taps and accumulate coverage. + values.Clear(); + float coverage = 0; + for (var j = 0; j < 4; j++) + { + var yy = iy - 1 + j; + var weightY = wy.GetElement(j); + if (transparent && (uint)yy >= (uint)h) continue; + yy = int.Clamp(yy, 0, h - 1); + for (var i = 0; i < 4; i++) + { + var xx = ix - 1 + i; + if (transparent && (uint)xx >= (uint)w) continue; + xx = int.Clamp(xx, 0, w - 1); + var weight = weightY * wx.GetElement(i); + var s = yy * w + xx; + for (var c = 0; c < _colourChannels; c++) values[c] += weight * src[c * plane + s]; + if (_sourceAlpha) values[3] += weight * src[3 * plane + s]; + coverage += weight; + } + } + for (var c = 0; c < _colourChannels; c++) dst[c * dplane + o] = values[c]; + if (transparent) dst[3 * dplane + o] = float.Clamp(_sourceAlpha ? values[3] : coverage, 0f, 1f); + } + } + + private void WideRow(int y) + { + var src = source.Storage; + var plane = source.PlaneLength; + var dst = destination.Storage; + var dplane = destination.PlaneLength; + var w = _sw; + var h = _sh; + var outWidth = destination.Width; + var channels = transparent ? 4 : _colourChannels; + var maxX = (int)double.Ceiling(4 * footprintX) + 2; + var maxY = (int)double.Ceiling(4 * footprintY) + 2; + Span wxs = maxX <= 256 ? stackalloc double[maxX] : new double[maxX]; + Span wys = maxY <= 256 ? stackalloc double[maxY] : new double[maxY]; + Span values = stackalloc double[4]; + for (var x = 0; x < outWidth; x++) + { + var (sx, sy) = map.Apply(x, y); + var o = y * outWidth + x; + if (!(double.Abs(sx) < 1e9 && double.Abs(sy) < 1e9)) + { + WriteOutside(dst, dplane, o, channels); + continue; + } + var x0 = (int)double.Ceiling(sx - 2 * footprintX); + var y0 = (int)double.Ceiling(sy - 2 * footprintY); + var nx = int.Min(maxX, (int)double.Floor(sx + 2 * footprintX) - x0 + 1); + var ny = int.Min(maxY, (int)double.Floor(sy + 2 * footprintY) - y0 + 1); + double sumX = 0, sumY = 0; + for (var i = 0; i < nx; i++) sumX += wxs[i] = CatmullRom((x0 + i - sx) / footprintX); + for (var j = 0; j < ny; j++) sumY += wys[j] = CatmullRom((y0 + j - sy) / footprintY); + var norm = 1 / (sumX * sumY); + + values.Clear(); + double coverage = 0; + for (var j = 0; j < ny; j++) + { + var yy = y0 + j; + if (transparent && (uint)yy >= (uint)h) continue; + var row = int.Clamp(yy, 0, h - 1) * w; + for (var i = 0; i < nx; i++) + { + var xx = x0 + i; + if (transparent && (uint)xx >= (uint)w) continue; + var s = row + int.Clamp(xx, 0, w - 1); + var weight = wys[j] * wxs[i]; + for (var c = 0; c < _colourChannels; c++) values[c] += weight * src[c * plane + s]; + if (_sourceAlpha) values[3] += weight * src[3 * plane + s]; + coverage += weight; + } + } + for (var c = 0; c < _colourChannels; c++) dst[c * dplane + o] = (float)(values[c] * norm); + if (transparent) dst[3 * dplane + o] = (float)double.Clamp((_sourceAlpha ? values[3] : coverage) * norm, 0, 1); + } + } + + private void WriteOutside(float[] dst, int dplane, int o, int channels) + { + // Non-finite or absurd coordinates: transparent, or the clamped corner colour for Clamp. + for (var c = 0; c < channels; c++) dst[c * dplane + o] = transparent ? 0f : source.Storage[c * source.PlaneLength]; + } + } +} diff --git a/tests/Titano.Core.Tests/Geometry/Affine2DTests.cs b/tests/Titano.Core.Tests/Geometry/Affine2DTests.cs new file mode 100644 index 00000000..357b1cd9 --- /dev/null +++ b/tests/Titano.Core.Tests/Geometry/Affine2DTests.cs @@ -0,0 +1,56 @@ +using Titano.Core.Imaging.Geometry; +using Titano.Testing; + +namespace Titano.Core.Tests.Geometry; + +public sealed class Affine2DTests +{ + [Test] + public void CompositionAppliesInnerFirst() + { + var scale = Affine2D.Scaling(2, 3); + var move = Affine2D.Translation(5, -1); + var (x, y) = (move * scale).Apply(1, 1); + Assert.Approximately(7, x, 1e-15); + Assert.Approximately(2, y, 1e-15); + Assert.Equal(move * scale, scale.Then(move)); + } + + [Test] + public void InverseUndoesTheMap() + { + var map = Affine2D.Similarity(1.3, 0.4, 12, -7) * Affine2D.Scaling(1, 0.8); + var inverse = map.Invert(); + Assert.True((inverse * map).IsIdentity(1e-12)); + Assert.True((map * inverse).IsIdentity(1e-12)); + var (x, y) = map.Apply(3.5, -2.25); + var (bx, by) = inverse.Apply(x, y); + Assert.Within(3.5, -2.25, bx, by, 1e-12); + } + + [Test] + public void SingularMapsDoNotInvert() + { + Assert.False(new Affine2D(1, 2, 2, 4, 0, 0).TryInvert(out _)); + Assert.Throws(() => Affine2D.Scaling(0, 1).Invert()); + } + + [Test] + public void RotationAboutPivotKeepsThePivot() + { + var map = Affine2D.About(Affine2D.Rotation(0.7), 40, 30); + var (x, y) = map.Apply(40, 30); + Assert.Within(40, 30, x, y, 1e-12); + var (vx, vy) = map.ApplyVector(1, 0); + Assert.Within(double.Cos(0.7), double.Sin(0.7), vx, vy, 1e-15); + } + + [Test] + public void SimilarityDecomposes() + { + var map = Affine2D.Similarity(1.25, -0.3, 4, 5); + Assert.Approximately(1.25, map.Scale, 1e-12); + Assert.Approximately(-0.3, map.Angle, 1e-12); + Assert.Approximately(1.25 * 1.25, map.Determinant, 1e-12); + } +} diff --git a/tests/Titano.Core.Tests/Geometry/AspectRatioTests.cs b/tests/Titano.Core.Tests/Geometry/AspectRatioTests.cs new file mode 100644 index 00000000..797553a6 --- /dev/null +++ b/tests/Titano.Core.Tests/Geometry/AspectRatioTests.cs @@ -0,0 +1,54 @@ +using Titano.Core.Imaging.Geometry; +using Titano.Testing; + +namespace Titano.Core.Tests.Geometry; + +public sealed class AspectRatioTests +{ + [Theory] + [Case(1920.0, 1080.0, 1, 1, 420.0, 0.0, 1080.0, 1080.0)] + [Case(1920.0, 1080.0, 9, 16, 656.25, 0.0, 607.5, 1080.0)] + [Case(4000.0, 3000.0, 16, 9, 0.0, 375.0, 4000.0, 2250.0)] + [Case(6000.0, 4000.0, 3, 2, 0.0, 0.0, 6000.0, 4000.0)] + [Case(1080.0, 1920.0, 4, 5, 0.0, 285.0, 1080.0, 1350.0)] + [Case(3840.0, 2160.0, 21, 9, 0.0, 257.142857142857, 3840.0, 1645.71428571429)] + public void FitCropCentresTheLargestCrop(double bw, double bh, int w, int h, double x, double y, double cw, double ch) + { + var crop = AspectRatio.FitCrop(RectD.FromSize(bw, bh), AspectRatio.Custom(w, h).Resolve(bw, bh)); + Assert.Approximately(x, crop.X, 1e-9); + Assert.Approximately(y, crop.Y, 1e-9); + Assert.Approximately(cw, crop.Width, 1e-9); + Assert.Approximately(ch, crop.Height, 1e-9); + } + + [Theory] + [Case(-1.0, 100.0)] + [Case(0.0, 280.0)] + [Case(1.0, 460.0)] + [Case(5.0, 460.0)] + [Case(-0.5, 190.0)] + public void FitCropOffsetMovesWithinTheSlack(double offset, double expectedX) + { + var crop = AspectRatio.FitCrop(new RectD(100, 50, 720, 360), 1.0, offset, offset); + Assert.Approximately(expectedX, crop.X, 1e-9); + Assert.Approximately(50, crop.Y, 1e-9); + Assert.Approximately(360, crop.Width, 1e-9); + } + + [Test] + public void PresetsAndParsing() + { + Assert.Equal(AspectRatio.Widescreen, AspectRatio.Custom(32, 18)); + Assert.Equal("16:9", AspectRatio.Widescreen.ToString()); + Assert.Equal("9:16", AspectRatio.Vertical.ToString()); + Assert.Equal(8, AspectRatio.Presets.Count); + Assert.Approximately(1.5, AspectRatio.Source.Resolve(6000, 4000), 1e-15); + Assert.Approximately(21.0 / 9, AspectRatio.Cinema.Resolve(6000, 4000), 1e-15); + Assert.True(AspectRatio.TryParse("4/5", out var portrait)); + Assert.Equal(AspectRatio.Portrait, portrait); + Assert.True(AspectRatio.TryParse("source", out var source)); + Assert.True(source.IsSource); + Assert.False(AspectRatio.TryParse("16:0", out _)); + Assert.False(AspectRatio.TryParse("wide", out _)); + } +} diff --git a/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs b/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs new file mode 100644 index 00000000..4d98c6c9 --- /dev/null +++ b/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs @@ -0,0 +1,133 @@ +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Tests.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Geometry; + +public sealed class GeometryStageTests +{ + private const int Size = 128; + + private readonly TestContext _context; + + public GeometryStageTests(TestContext context) => _context = context; + + [Test] + public void IdentityWarpReproducesTheImage() + { + using var source = Texture(sigma: 1.0); + using var output = GeometryStage.Apply(source, new GeometrySettings()); + Assert.Equal(Size, output.Width); + Assert.Equal(3, output.Channels); + var psnr = SyntheticImages.Psnr(source.Plane(1), output.Plane(1), Size, 0, 0, Size, Size); + _context.Log($"identity PSNR {psnr:F1} dB"); + Assert.GreaterOrEqual(psnr, 60); + Assert.True(source.Data.SequenceEqual(output.Data)); + } + + [Test] + public void HalfPixelShiftAndBackStaysWithinBounds() + { + using var source = Texture(sigma: 2.0); + using var shifted = new ImageBuffer(Size, Size); + using var back = new ImageBuffer(Size, Size); + GeometryStage.Warp(source, shifted, Affine2D.Translation(0.5, 0.5)); + GeometryStage.Warp(shifted, back, Affine2D.Translation(-0.5, -0.5)); + var psnr = SyntheticImages.Psnr(source.Plane(0), back.Plane(0), Size, 4, 4, Size - 4, Size - 4); + _context.Log($"0.5 px round trip PSNR {psnr:F1} dB"); + Assert.GreaterOrEqual(psnr, 40); + } + + [Test] + public void LinearRampsAreReproducedUnderSubPixelWarps() + { + using var ramp = new ImageBuffer(64, 64, 1); + for (var y = 0; y < 64; y++) + for (var x = 0; x < 64; x++) + ramp[0, x, y] = 0.01f * x + 0.005f * y; + using var output = new ImageBuffer(64, 64, 1); + var map = Affine2D.About(Affine2D.Similarity(0.8, 0.2, 0, 0), 32, 32); + GeometryStage.Warp(ramp, output, map); + for (var y = 8; y < 56; y++) + { + for (var x = 8; x < 56; x++) + { + var (sx, sy) = map.Apply(x, y); + Assert.Approximately(0.01 * sx + 0.005 * sy, output[0, x, y], 2e-6); + } + } + } + + [Test] + public void TransparentBordersCarryCoverage() + { + using var source = Texture(sigma: 1.0); + using var output = GeometryStage.Apply(source, new GeometrySettings + { + Warp = Affine2D.Translation(-10, 0), + Border = BorderMode.Transparent, + }); + Assert.Equal(4, output.Channels); + for (var y = 0; y < Size; y += 7) + { + Assert.Equal(0f, output[3, 3, y]); + Assert.Equal(0f, output[0, 3, y]); + Assert.Equal(1f, output[3, 40, y]); + Assert.Equal(source[1, 30, y], output[1, 40, y]); + } + } + + [Test] + public void ClampReplicatesEdges() + { + using var source = Texture(sigma: 1.0); + using var output = GeometryStage.Apply(source, new GeometrySettings { Warp = Affine2D.Translation(-10, 0) }); + for (var y = 0; y < Size; y += 5) Assert.Approximately(source[2, 0, y], output[2, 2, y], 1e-6); + } + + [Test] + public void PlanFitsAspectAndMapsPixelCentres() + { + var plan = GeometryStage.Plan(1920, 1080, new GeometrySettings { Aspect = AspectRatio.Square, OutputWidth = 540 }); + Assert.Equal(540, plan.OutputWidth); + Assert.Equal(540, plan.OutputHeight); + Assert.Equal(new RectD(420, 0, 1080, 1080), plan.Crop); + var (x, y) = plan.OutputToSource.Apply(0, 0); + Assert.Within(420.5, 0.5, x, y, 1e-12); + + var cropped = GeometryStage.Plan(800, 600, new GeometrySettings { Crop = new RectD(100, 50, 200, 100), OutputWidth = 400, OutputHeight = 200 }); + Assert.Equal(new RectD(100, 50, 200, 100), cropped.Crop); + var (cx, cy) = cropped.OutputToSource.Apply(0, 0); + Assert.Within(99.75, 49.75, cx, cy, 1e-12); + + var vertical = GeometryStage.Plan(1920, 1080, new GeometrySettings { Aspect = AspectRatio.Vertical, OutputHeight = 1920 }); + Assert.Equal(1080, vertical.OutputWidth); + } + + [Test] + public void DownscalingDoesNotAlias() + { + using var checker = new ImageBuffer(256, 256, 1); + for (var y = 0; y < 256; y++) + for (var x = 0; x < 256; x++) + checker[0, x, y] = (x + y) % 2 == 0 ? 1f : 0f; + using var small = GeometryStage.Apply(checker, new GeometrySettings { OutputWidth = 64 }); + Assert.Equal(64, small.Height); + for (var y = 2; y < 62; y++) + for (var x = 2; x < 62; x++) + Assert.Approximately(0.5, small[0, x, y], 0.02); + } + + [Test] + public void CancellationStopsTheWarp() + { + using var source = Texture(sigma: 1.0); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + Assert.Throws(() => GeometryStage.Apply(source, new GeometrySettings(), cts.Token)); + } + + private static ImageBuffer Texture(double sigma) => + SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Noise(Size, sigma, seed: 21), Size, 0, 0, Size, Size), Size, Size); +} From bb7bc6490dfd1b969a1edacca4a0b8846d62e6fc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:24:38 +0000 Subject: [PATCH 005/188] feat(video): add bitstream readers for Annex-B, H.264/HEVC SPS and AV1 OBUs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Video/Bitstream/AnnexBParser.cs | 214 ++++++++++++ .../Video/Bitstream/Av1ObuParser.cs | 321 +++++++++++++++++ src/Titano.Core/Video/Bitstream/BitReader.cs | 113 ++++++ src/Titano.Core/Video/Bitstream/BitWriter.cs | 80 +++++ .../Video/Bitstream/H264SpsParser.cs | 230 +++++++++++++ .../Video/Bitstream/HevcSpsParser.cs | 120 +++++++ .../Titano.Core.Tests/Video/BitstreamTests.cs | 229 +++++++++++++ .../Video/SyntheticStreams.cs | 323 ++++++++++++++++++ 8 files changed, 1630 insertions(+) create mode 100644 src/Titano.Core/Video/Bitstream/AnnexBParser.cs create mode 100644 src/Titano.Core/Video/Bitstream/Av1ObuParser.cs create mode 100644 src/Titano.Core/Video/Bitstream/BitReader.cs create mode 100644 src/Titano.Core/Video/Bitstream/BitWriter.cs create mode 100644 src/Titano.Core/Video/Bitstream/H264SpsParser.cs create mode 100644 src/Titano.Core/Video/Bitstream/HevcSpsParser.cs create mode 100644 tests/Titano.Core.Tests/Video/BitstreamTests.cs create mode 100644 tests/Titano.Core.Tests/Video/SyntheticStreams.cs diff --git a/src/Titano.Core/Video/Bitstream/AnnexBParser.cs b/src/Titano.Core/Video/Bitstream/AnnexBParser.cs new file mode 100644 index 00000000..3d43665e --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/AnnexBParser.cs @@ -0,0 +1,214 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Video.Bitstream; + +/// H.264 nal_unit_type values (ITU-T H.264 Table 7-1). +public enum H264NalUnitType : byte +{ + Unspecified = 0, + NonIdrSlice = 1, + SliceDataPartitionA = 2, + SliceDataPartitionB = 3, + SliceDataPartitionC = 4, + IdrSlice = 5, + Sei = 6, + Sps = 7, + Pps = 8, + AccessUnitDelimiter = 9, + EndOfSequence = 10, + EndOfStream = 11, + FillerData = 12, + SpsExtension = 13, + PrefixNal = 14, + SubsetSps = 15, +} + +/// HEVC nal_unit_type values (ITU-T H.265 Table 7-1). +public enum HevcNalUnitType : byte +{ + TrailN = 0, + TrailR = 1, + TsaN = 2, + TsaR = 3, + StsaN = 4, + StsaR = 5, + RadlN = 6, + RadlR = 7, + RaslN = 8, + RaslR = 9, + BlaWLp = 16, + BlaWRadl = 17, + BlaNLp = 18, + IdrWRadl = 19, + IdrNLp = 20, + Cra = 21, + Vps = 32, + Sps = 33, + Pps = 34, + AccessUnitDelimiter = 35, + EndOfSequence = 36, + EndOfBitstream = 37, + FillerData = 38, + PrefixSei = 39, + SuffixSei = 40, +} + +/// Location of one NAL unit (header included, start code or length prefix excluded) inside a buffer. +public readonly record struct NalUnit(int Offset, int Length) +{ + public ReadOnlySpan Slice(ReadOnlySpan buffer) => buffer.Slice(Offset, Length); +} + +/// Annex-B byte streams and ISO/IEC 14496-15 length-prefixed samples of H.264/HEVC NAL units. +public static class AnnexBParser +{ + private static ReadOnlySpan StartCode => [0, 0, 1]; + + /// True when the data begins with a 3- or 4-byte start code. + public static bool StartsWithStartCode(ReadOnlySpan data) => + data.Length >= 3 && data[0] == 0 && data[1] == 0 && (data[2] == 1 || (data.Length >= 4 && data[2] == 0 && data[3] == 1)); + + /// + /// Splits an Annex-B stream at 3/4-byte start codes. Bytes before the first start code are ignored and + /// trailing zero bytes (trailing_zero_8bits, the leading zero of a 4-byte start code) are not part of a unit. + /// + public static List Split(ReadOnlySpan data) + { + var units = new List(); + var first = data.IndexOf(StartCode); + if (first < 0) return units; + var start = first + 3; + while (true) + { + var next = data[start..].IndexOf(StartCode); + var end = next < 0 ? data.Length : start + next; + var nalEnd = end; + while (nalEnd > start && data[nalEnd - 1] == 0) nalEnd--; + if (nalEnd > start) units.Add(new NalUnit(start, nalEnd - start)); + if (next < 0) return units; + start = end + 3; + } + } + + /// + /// Splits big-endian length-prefixed NAL units. Returns false (with the units read so far) when a length + /// is zero, runs past the end or the buffer does not end exactly after the last unit. + /// + public static bool TrySplitLengthPrefixed(ReadOnlySpan data, int lengthSize, out List units) + { + if (lengthSize is not (1 or 2 or 4)) throw new ArgumentOutOfRangeException(nameof(lengthSize)); + units = []; + var pos = 0; + while (pos < data.Length) + { + if (data.Length - pos < lengthSize) return false; + var length = lengthSize switch + { + 1 => data[pos], + 2 => BinaryPrimitives.ReadUInt16BigEndian(data[pos..]), + _ => (long)BinaryPrimitives.ReadUInt32BigEndian(data[pos..]), + }; + pos += lengthSize; + if (length == 0 || length > data.Length - pos) return false; + units.Add(new NalUnit(pos, (int)length)); + pos += (int)length; + } + return units.Count > 0; + } + + /// + /// Splits one access unit given either with 4-byte length prefixes or as Annex-B. The length-prefixed reading + /// wins only when it covers the buffer exactly with valid NAL headers, which an Annex-B stream practically never does. + /// + public static List SplitAccessUnit(ReadOnlySpan data, out bool wasAnnexB) + { + if (TrySplitLengthPrefixed(data, 4, out var units) && HeadersValid(data, units)) + { + wasAnnexB = false; + return units; + } + wasAnnexB = true; + return Split(data); + } + + private static bool HeadersValid(ReadOnlySpan data, List units) + { + foreach (var u in units) + { + if ((data[u.Offset] & 0x80) != 0) return false; // forbidden_zero_bit + } + return true; + } + + /// Removes emulation_prevention_three_byte (00 00 03 → 00 00) to obtain the RBSP. + public static byte[] RemoveEmulationPrevention(ReadOnlySpan nal) + { + var output = new byte[nal.Length]; + var n = 0; + var zeros = 0; + foreach (var b in nal) + { + if (zeros >= 2 && b == 3) + { + zeros = 0; + continue; + } + output[n++] = b; + zeros = b == 0 ? zeros + 1 : 0; + } + return n == output.Length ? output : output.AsSpan(0, n).ToArray(); + } + + /// Inserts emulation prevention bytes so the payload contains no start-code prefix. + public static byte[] AddEmulationPrevention(ReadOnlySpan rbsp) + { + var output = new List(rbsp.Length + rbsp.Length / 64 + 2); + var zeros = 0; + foreach (var b in rbsp) + { + if (zeros >= 2 && b <= 3) + { + output.Add(3); + zeros = 0; + } + output.Add(b); + zeros = b == 0 ? zeros + 1 : 0; + } + // A payload ending in 0x00 (cabac_zero_word) gets a final 0x03 (H.264 7.4.1). + if (rbsp.Length > 0 && rbsp[^1] == 0) output.Add(3); + return [.. output]; + } + + public static H264NalUnitType H264Type(byte header) => (H264NalUnitType)(header & 0x1F); + + public static HevcNalUnitType HevcType(byte header) => (HevcNalUnitType)((header >> 1) & 0x3F); + + /// Converts an Annex-B stream to 4-byte big-endian length prefixes. + public static byte[] ToLengthPrefixed(ReadOnlySpan annexB) + { + var units = Split(annexB); + var total = 0; + foreach (var u in units) total += 4 + u.Length; + var output = new byte[total]; + var pos = 0; + foreach (var u in units) + { + BinaryPrimitives.WriteInt32BigEndian(output.AsSpan(pos), u.Length); + annexB.Slice(u.Offset, u.Length).CopyTo(output.AsSpan(pos + 4)); + pos += 4 + u.Length; + } + return output; + } + + /// Concatenates NAL units with 4-byte start codes. + public static byte[] ToAnnexB(IEnumerable nalUnits) + { + using var ms = new MemoryStream(); + foreach (var nal in nalUnits) + { + ms.Write([0, 0, 0, 1]); + ms.Write(nal); + } + return ms.ToArray(); + } +} diff --git a/src/Titano.Core/Video/Bitstream/Av1ObuParser.cs b/src/Titano.Core/Video/Bitstream/Av1ObuParser.cs new file mode 100644 index 00000000..ad5a2c8f --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/Av1ObuParser.cs @@ -0,0 +1,321 @@ +namespace Titano.Core.Video.Bitstream; + +/// AV1 obu_type values (AV1 specification 6.2.2). +public enum Av1ObuType : byte +{ + SequenceHeader = 1, + TemporalDelimiter = 2, + FrameHeader = 3, + TileGroup = 4, + Metadata = 5, + Frame = 6, + RedundantFrameHeader = 7, + TileList = 8, + Padding = 15, +} + +/// One OBU inside a buffer: header (with extension and size field) followed by the payload. +public readonly record struct Av1Obu(Av1ObuType Type, int Offset, int HeaderLength, int PayloadLength, bool HasSizeField, bool HasExtension, byte TemporalId, byte SpatialId) +{ + public int TotalLength => HeaderLength + PayloadLength; + + public ReadOnlySpan Payload(ReadOnlySpan buffer) => buffer.Slice(Offset + HeaderLength, PayloadLength); +} + +/// Sequence header fields needed by av1C, level checks and diagnostics. +public sealed record Av1SequenceHeader +{ + public required int SeqProfile { get; init; } + public required bool StillPicture { get; init; } + public required bool ReducedStillPictureHeader { get; init; } + public required int SeqLevelIdx { get; init; } + public required bool SeqTier { get; init; } + public required bool HighBitDepth { get; init; } + public required bool TwelveBit { get; init; } + public required int BitDepth { get; init; } + public required bool MonoChrome { get; init; } + public required bool ChromaSubsamplingX { get; init; } + public required bool ChromaSubsamplingY { get; init; } + public required int ChromaSamplePosition { get; init; } + public required int MaxFrameWidth { get; init; } + public required int MaxFrameHeight { get; init; } + public required int ColorPrimaries { get; init; } + public required int TransferCharacteristics { get; init; } + public required int MatrixCoefficients { get; init; } + public required bool FullRange { get; init; } + + /// initial_display_delay_minus_1 + 1 of operating point 0, when signalled. + public int? InitialDisplayDelay { get; init; } +} + +/// AV1 low-overhead bitstream (OBU) parsing. Never throws on malformed input. +public static class Av1ObuParser +{ + /// Reads the OBU at ; one without obu_size extends to the end of the buffer. + public static bool TryReadObu(ReadOnlySpan data, int offset, out Av1Obu obu) + { + obu = default; + if (offset < 0 || offset >= data.Length) return false; + var header = data[offset]; + if ((header & 0x80) != 0) return false; // obu_forbidden_bit + var type = (Av1ObuType)((header >> 3) & 0x0F); + var hasExtension = (header & 0x04) != 0; + var hasSize = (header & 0x02) != 0; + var pos = offset + 1; + byte temporalId = 0, spatialId = 0; + if (hasExtension) + { + if (pos >= data.Length) return false; + temporalId = (byte)(data[pos] >> 5); + spatialId = (byte)((data[pos] >> 3) & 3); + pos++; + } + long payload; + if (hasSize) + { + if (!TryReadLeb128(data[pos..], out var size, out var sizeLength)) return false; + pos += sizeLength; + payload = (long)Math.Min(size, int.MaxValue); + } + else + { + payload = data.Length - pos; + } + if (payload > data.Length - pos) return false; + obu = new Av1Obu(type, offset, pos - offset, (int)payload, hasSize, hasExtension, temporalId, spatialId); + return true; + } + + /// Splits a buffer into OBUs, stopping at the first malformed one. + public static List Split(ReadOnlySpan data) + { + var list = new List(); + var pos = 0; + while (pos < data.Length && TryReadObu(data, pos, out var obu)) + { + list.Add(obu); + pos += obu.TotalLength; + } + return list; + } + + /// Splits a low-overhead stream into temporal units, each starting at a temporal delimiter OBU. + public static List<(int Offset, int Length)> SplitTemporalUnits(ReadOnlySpan stream) + { + var units = new List<(int Offset, int Length)>(); + var start = -1; + var end = 0; + foreach (var obu in Split(stream)) + { + if (obu.Type == Av1ObuType.TemporalDelimiter) + { + if (start >= 0) units.Add((start, obu.Offset - start)); + start = obu.Offset; + } + else if (start < 0) + { + start = obu.Offset; // stream without a leading delimiter + } + end = obu.Offset + obu.TotalLength; + } + if (start >= 0 && end > start) units.Add((start, end - start)); + return units; + } + + public static bool TryReadLeb128(ReadOnlySpan data, out ulong value, out int length) + { + value = 0; + for (length = 0; length < 8 && length < data.Length; length++) + { + var b = data[length]; + value |= (ulong)(b & 0x7F) << (7 * length); + if ((b & 0x80) == 0) + { + length++; + return value <= uint.MaxValue; + } + } + return false; + } + + public static int Leb128Size(ulong value) + { + var n = 1; + while ((value >>= 7) != 0) n++; + return n; + } + + public static int WriteLeb128(Span destination, ulong value) + { + var n = 0; + do + { + var b = (byte)(value & 0x7F); + value >>= 7; + destination[n++] = value != 0 ? (byte)(b | 0x80) : b; + } + while (value != 0); + return n; + } + + /// Parses a sequence_header_obu() payload (AV1 5.5). + public static bool TryParseSequenceHeader(ReadOnlySpan payload, out Av1SequenceHeader header) + { + header = null!; + var r = new BitReader(payload); + var profile = (int)r.ReadBits(3); + if (profile > 2) return false; + var still = r.ReadFlag(); + var reduced = r.ReadFlag(); + int levelIdx; + var tier = false; + int? initialDelay = null; + if (reduced) + { + levelIdx = (int)r.ReadBits(5); + } + else + { + var decoderModelInfo = false; + var bufferDelayLength = 0; + if (r.ReadFlag()) + { + r.ReadBits(32); // num_units_in_display_tick + r.ReadBits(32); // time_scale + if (r.ReadFlag()) r.ReadUvlc(); // equal_picture_interval, num_ticks_per_picture_minus_1 + decoderModelInfo = r.ReadFlag(); + if (decoderModelInfo) + { + bufferDelayLength = (int)r.ReadBits(5) + 1; + r.ReadBits(32); // num_units_in_decoding_tick + r.ReadBits(5); // buffer_removal_time_length_minus_1 + r.ReadBits(5); // frame_presentation_time_length_minus_1 + } + } + var initialDisplayDelayPresent = r.ReadFlag(); + var operatingPoints = (int)r.ReadBits(5) + 1; + levelIdx = 0; + for (var i = 0; i < operatingPoints && !r.IsOverrun; i++) + { + r.ReadBits(12); // operating_point_idc + var level = (int)r.ReadBits(5); + var opTier = level > 7 && r.ReadFlag(); + if (decoderModelInfo && r.ReadFlag()) + { + r.Skip(bufferDelayLength * 2L + 1); // decoder/encoder buffer delay, low_delay_mode_flag + } + int? delay = null; + if (initialDisplayDelayPresent && r.ReadFlag()) delay = (int)r.ReadBits(4) + 1; + if (i == 0) + { + levelIdx = level; + tier = opTier; + initialDelay = delay; + } + } + } + + var widthBits = (int)r.ReadBits(4) + 1; + var heightBits = (int)r.ReadBits(4) + 1; + var maxWidth = (int)r.ReadBits(widthBits) + 1; + var maxHeight = (int)r.ReadBits(heightBits) + 1; + if (!reduced && r.ReadFlag()) + { + r.ReadBits(4); // delta_frame_id_length_minus_2 + r.ReadBits(3); // additional_frame_id_length_minus_1 + } + r.ReadBits(3); // use_128x128_superblock, enable_filter_intra, enable_intra_edge_filter + if (!reduced) + { + r.ReadBits(4); // interintra, masked compound, warped motion, dual filter + var orderHint = r.ReadFlag(); + if (orderHint) r.ReadBits(2); // enable_jnt_comp, enable_ref_frame_mvs + var forceScreenContent = r.ReadFlag() ? 2 : (int)r.ReadBits(1); + if (forceScreenContent > 0 && !r.ReadFlag()) r.ReadBits(1); // seq_force_integer_mv + if (orderHint) r.ReadBits(3); // order_hint_bits_minus_1 + } + r.ReadBits(3); // enable_superres, enable_cdef, enable_restoration + + // color_config() + var highBitDepth = r.ReadFlag(); + var twelveBit = false; + var bitDepth = 8; + if (profile == 2 && highBitDepth) + { + twelveBit = r.ReadFlag(); + bitDepth = twelveBit ? 12 : 10; + } + else if (highBitDepth) + { + bitDepth = 10; + } + var mono = profile != 1 && r.ReadFlag(); + int primaries = 2, transfer = 2, matrix = 2; + if (r.ReadFlag()) + { + primaries = (int)r.ReadBits(8); + transfer = (int)r.ReadBits(8); + matrix = (int)r.ReadBits(8); + } + bool fullRange, subX, subY; + var samplePosition = 0; + if (mono) + { + fullRange = r.ReadFlag(); + subX = subY = true; + } + else if (primaries == 1 && transfer == 13 && matrix == 0) + { + fullRange = true; + subX = subY = false; + } + else + { + fullRange = r.ReadFlag(); + if (profile == 0) + { + subX = subY = true; + } + else if (profile == 1) + { + subX = subY = false; + } + else if (bitDepth == 12) + { + subX = r.ReadFlag(); + subY = subX && r.ReadFlag(); + } + else + { + subX = true; + subY = false; + } + if (subX && subY) samplePosition = (int)r.ReadBits(2); + } + if (r.IsOverrun) return false; + + header = new Av1SequenceHeader + { + SeqProfile = profile, + StillPicture = still, + ReducedStillPictureHeader = reduced, + SeqLevelIdx = levelIdx, + SeqTier = tier, + HighBitDepth = highBitDepth, + TwelveBit = twelveBit, + BitDepth = bitDepth, + MonoChrome = mono, + ChromaSubsamplingX = subX, + ChromaSubsamplingY = subY, + ChromaSamplePosition = samplePosition, + MaxFrameWidth = maxWidth, + MaxFrameHeight = maxHeight, + ColorPrimaries = primaries, + TransferCharacteristics = transfer, + MatrixCoefficients = matrix, + FullRange = fullRange, + InitialDisplayDelay = initialDelay, + }; + return true; + } +} diff --git a/src/Titano.Core/Video/Bitstream/BitReader.cs b/src/Titano.Core/Video/Bitstream/BitReader.cs new file mode 100644 index 00000000..db70c16a --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/BitReader.cs @@ -0,0 +1,113 @@ +namespace Titano.Core.Video.Bitstream; + +/// +/// MSB-first bit reader over an RBSP (emulation prevention already removed). Reading past the end yields zero +/// bits and sets , so parsers finish a pass over truncated input and reject it afterwards +/// instead of throwing. +/// +public ref struct BitReader +{ + private readonly ReadOnlySpan _data; + private long _position; + + public BitReader(ReadOnlySpan data) + { + _data = data; + _position = 0; + IsOverrun = false; + } + + /// Bit offset from the start of the data. + public readonly long Position => _position; + + public readonly long BitsRemaining => Math.Max(0, (long)_data.Length * 8 - _position); + + public readonly bool IsByteAligned => (_position & 7) == 0; + + /// True once a read went past the end or an Exp-Golomb code exceeded 32 bits. + public bool IsOverrun { get; private set; } + + public uint ReadBit() + { + var index = _position >> 3; + if (index >= _data.Length) + { + IsOverrun = true; + _position++; + return 0; + } + var bit = (uint)(_data[(int)index] >> (7 - (int)(_position & 7))) & 1; + _position++; + return bit; + } + + public bool ReadFlag() => ReadBit() != 0; + + /// Reads 0–32 bits, most significant first. + public uint ReadBits(int count) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)count, 32u, nameof(count)); + uint value = 0; + // Whole bytes when aligned keep long fields (32-bit timing values) cheap. + while (count >= 8 && IsByteAligned && (_position >> 3) < _data.Length) + { + value = (value << 8) | _data[(int)(_position >> 3)]; + _position += 8; + count -= 8; + } + for (var i = 0; i < count; i++) value = (value << 1) | ReadBit(); + return value; + } + + /// Reads 0–64 bits, most significant first. + public ulong ReadBits64(int count) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)count, 64u, nameof(count)); + if (count <= 32) return ReadBits(count); + var high = (ulong)ReadBits(count - 32); + return (high << 32) | ReadBits(32); + } + + public void Skip(long bits) + { + _position += bits; + if (_position > (long)_data.Length * 8) IsOverrun = true; + } + + public void AlignToByte() => _position = (_position + 7) & ~7L; + + /// Unsigned Exp-Golomb ue(v). + public uint ReadUe() + { + var zeros = 0; + while (ReadBit() == 0) + { + if (++zeros > 31 || IsOverrun) + { + IsOverrun = true; + return 0; + } + } + return zeros == 0 ? 0 : (uint)((1UL << zeros) - 1 + ReadBits(zeros)); + } + + /// Signed Exp-Golomb se(v). + public int ReadSe() + { + var k = ReadUe(); + return (k & 1) != 0 ? (int)((k + 1) / 2) : -(int)(k / 2); + } + + /// AV1 uvlc(): returns for 32 or more leading zeros. + public uint ReadUvlc() + { + var zeros = 0; + while (ReadBit() == 0) + { + if (IsOverrun) return 0; + zeros++; + } + if (zeros >= 32) return uint.MaxValue; + return ReadBits(zeros) + (uint)((1UL << zeros) - 1); + } +} diff --git a/src/Titano.Core/Video/Bitstream/BitWriter.cs b/src/Titano.Core/Video/Bitstream/BitWriter.cs new file mode 100644 index 00000000..258a8731 --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/BitWriter.cs @@ -0,0 +1,80 @@ +using System.Numerics; + +namespace Titano.Core.Video.Bitstream; + +/// MSB-first bit writer with Exp-Golomb and AV1 leb128 helpers (used to synthesise parameter sets). +public sealed class BitWriter +{ + private byte[] _buffer = new byte[64]; + private long _bitLength; + + public long BitLength => _bitLength; + + public bool IsByteAligned => (_bitLength & 7) == 0; + + public void WriteBit(bool bit) => WriteBits(bit ? 1UL : 0UL, 1); + + /// Writes the low bits (0–64) of , most significant first. + public void WriteBits(ulong value, int count) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)count, 64u, nameof(count)); + EnsureCapacity(_bitLength + count); + for (var i = count - 1; i >= 0; i--) + { + if (((value >> i) & 1) != 0) _buffer[_bitLength >> 3] |= (byte)(0x80 >> (int)(_bitLength & 7)); + _bitLength++; + } + } + + /// Unsigned Exp-Golomb ue(v); values up to 2³² − 2 are readable by . + public void WriteUe(uint value) + { + var v = (ulong)value + 1; + var bits = 64 - BitOperations.LeadingZeroCount(v); + WriteBits(0, bits - 1); + WriteBits(v, bits); + } + + /// Signed Exp-Golomb se(v). + public void WriteSe(int value) => WriteUe(value > 0 ? (uint)(2L * value - 1) : (uint)(-2L * value)); + + /// rbsp_trailing_bits(): a stop bit followed by zero bits up to the byte boundary. + public void WriteTrailingBits() + { + WriteBit(true); + AlignWithZeros(); + } + + public void AlignWithZeros() + { + var pad = (int)((8 - (_bitLength & 7)) & 7); + WriteBits(0, pad); + } + + public void WriteBytes(ReadOnlySpan bytes) + { + foreach (var b in bytes) WriteBits(b, 8); + } + + /// AV1 leb128() (byte aligned). + public void WriteLeb128(ulong value) + { + do + { + var b = (byte)(value & 0x7F); + value >>= 7; + WriteBits(value != 0 ? b | 0x80u : b, 8); + } + while (value != 0); + } + + /// The written bytes; a partial last byte is zero padded. + public byte[] ToArray() => _buffer.AsSpan(0, (int)((_bitLength + 7) >> 3)).ToArray(); + + private void EnsureCapacity(long bits) + { + var bytes = (bits + 7) >> 3; + if (bytes <= _buffer.Length) return; + Array.Resize(ref _buffer, (int)Math.Max(bytes, _buffer.Length * 2L)); + } +} diff --git a/src/Titano.Core/Video/Bitstream/H264SpsParser.cs b/src/Titano.Core/Video/Bitstream/H264SpsParser.cs new file mode 100644 index 00000000..87924f4d --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/H264SpsParser.cs @@ -0,0 +1,230 @@ +namespace Titano.Core.Video.Bitstream; + +/// Fields of an H.264 sequence parameter set needed for containers and diagnostics. +public sealed record H264Sps +{ + public required int ProfileIdc { get; init; } + + /// constraint_set0..5 flags plus the two reserved bits, as the byte stored in avcC. + public required byte ConstraintFlags { get; init; } + + public required int LevelIdc { get; init; } + public required int SpsId { get; init; } + public required int ChromaFormatIdc { get; init; } + public required int BitDepthLuma { get; init; } + public required int BitDepthChroma { get; init; } + + /// Displayed width after frame cropping. + public required int Width { get; init; } + + /// Displayed height after frame cropping. + public required int Height { get; init; } + + public required int CodedWidth { get; init; } + public required int CodedHeight { get; init; } + public required bool FrameMbsOnly { get; init; } + public required int PicOrderCntType { get; init; } + public required int MaxNumRefFrames { get; init; } + public bool HasVui { get; init; } + public int SarWidth { get; init; } = 1; + public int SarHeight { get; init; } = 1; + public bool? FullRange { get; init; } + public int? ColourPrimaries { get; init; } + public int? TransferCharacteristics { get; init; } + public int? MatrixCoefficients { get; init; } + + /// VUI num_units_in_tick (0 when timing info is absent). + public uint NumUnitsInTick { get; init; } + + /// VUI time_scale (0 when timing info is absent). + public uint TimeScale { get; init; } + + public bool FixedFrameRate { get; init; } + + /// Frame rate from VUI timing (time_scale / 2·num_units_in_tick), or null. + public double? FrameRate => NumUnitsInTick > 0 && TimeScale > 0 ? TimeScale / (2.0 * NumUnitsInTick) : null; +} + +/// Parses H.264 SPS NAL units (ITU-T H.264 7.3.2.1.1). Never throws on malformed input. +public static class H264SpsParser +{ + /// Parses an SPS NAL unit (header byte included, emulation prevention present). + public static bool TryParse(ReadOnlySpan nal, out H264Sps sps) + { + sps = null!; + if (nal.Length < 4 || AnnexBParser.H264Type(nal[0]) != H264NalUnitType.Sps) return false; + var rbsp = AnnexBParser.RemoveEmulationPrevention(nal[1..]); + var r = new BitReader(rbsp); + + var profile = (int)r.ReadBits(8); + var constraints = (byte)r.ReadBits(8); + var level = (int)r.ReadBits(8); + var spsId = r.ReadUe(); + if (spsId > 31) return false; + + int chroma = 1, depthLuma = 8, depthChroma = 8; + var separateColourPlane = false; + if (profile is 100 or 110 or 122 or 244 or 44 or 83 or 86 or 118 or 128 or 138 or 139 or 134 or 135) + { + chroma = (int)r.ReadUe(); + if (chroma > 3) return false; + if (chroma == 3) separateColourPlane = r.ReadFlag(); + depthLuma = 8 + (int)r.ReadUe(); + depthChroma = 8 + (int)r.ReadUe(); + if (depthLuma > 14 || depthChroma > 14) return false; + r.ReadFlag(); // qpprime_y_zero_transform_bypass_flag + if (r.ReadFlag()) + { + var lists = chroma != 3 ? 8 : 12; + for (var i = 0; i < lists && !r.IsOverrun; i++) + { + if (r.ReadFlag()) SkipScalingList(ref r, i < 6 ? 16 : 64); + } + } + } + + r.ReadUe(); // log2_max_frame_num_minus4 + var pocType = (int)r.ReadUe(); + if (pocType == 0) + { + r.ReadUe(); // log2_max_pic_order_cnt_lsb_minus4 + } + else if (pocType == 1) + { + r.ReadFlag(); // delta_pic_order_always_zero_flag + r.ReadSe(); // offset_for_non_ref_pic + r.ReadSe(); // offset_for_top_to_bottom_field + var cycle = r.ReadUe(); + if (cycle > 255) return false; + for (var i = 0; i < cycle; i++) r.ReadSe(); + } + else if (pocType != 2) + { + return false; + } + + var maxRefFrames = (int)r.ReadUe(); + r.ReadFlag(); // gaps_in_frame_num_value_allowed_flag + var widthMbs = r.ReadUe() + 1L; + var heightMapUnits = r.ReadUe() + 1L; + var frameMbsOnly = r.ReadFlag(); + if (!frameMbsOnly) r.ReadFlag(); // mb_adaptive_frame_field_flag + r.ReadFlag(); // direct_8x8_inference_flag + long cropLeft = 0, cropRight = 0, cropTop = 0, cropBottom = 0; + if (r.ReadFlag()) + { + cropLeft = r.ReadUe(); + cropRight = r.ReadUe(); + cropTop = r.ReadUe(); + cropBottom = r.ReadUe(); + } + + var codedWidth = widthMbs * 16; + var codedHeight = (2 - (frameMbsOnly ? 1 : 0)) * heightMapUnits * 16; + var chromaArrayType = separateColourPlane ? 0 : chroma; + var cropUnitX = chromaArrayType == 0 ? 1 : (chromaArrayType == 3 ? 1 : 2); + var cropUnitY = (chromaArrayType == 0 ? 1 : (chromaArrayType == 1 ? 2 : 1)) * (frameMbsOnly ? 1 : 2); + var width = codedWidth - cropUnitX * (cropLeft + cropRight); + var height = codedHeight - cropUnitY * (cropTop + cropBottom); + if (r.IsOverrun || width <= 0 || height <= 0 || codedWidth > 65536 || codedHeight > 65536) return false; + + var result = new H264Sps + { + ProfileIdc = profile, + ConstraintFlags = constraints, + LevelIdc = level, + SpsId = (int)spsId, + ChromaFormatIdc = chroma, + BitDepthLuma = depthLuma, + BitDepthChroma = depthChroma, + Width = (int)width, + Height = (int)height, + CodedWidth = (int)codedWidth, + CodedHeight = (int)codedHeight, + FrameMbsOnly = frameMbsOnly, + PicOrderCntType = pocType, + MaxNumRefFrames = maxRefFrames, + }; + + if (r.ReadFlag()) result = ParseVui(ref r, result); + // VUI is optional detail: a truncated VUI still yields the core fields. + sps = result; + return true; + } + + private static H264Sps ParseVui(ref BitReader r, H264Sps sps) + { + int sarW = 1, sarH = 1; + if (r.ReadFlag()) + { + var idc = (int)r.ReadBits(8); + if (idc == 255) + { + sarW = (int)r.ReadBits(16); + sarH = (int)r.ReadBits(16); + } + else if (idc > 0 && idc < SarTable.Length / 2) + { + sarW = SarTable[idc * 2]; + sarH = SarTable[idc * 2 + 1]; + } + } + if (r.ReadFlag()) r.ReadFlag(); // overscan_info_present_flag, overscan_appropriate_flag + bool? fullRange = null; + int? primaries = null, transfer = null, matrix = null; + if (r.ReadFlag()) + { + r.ReadBits(3); // video_format + fullRange = r.ReadFlag(); + if (r.ReadFlag()) + { + primaries = (int)r.ReadBits(8); + transfer = (int)r.ReadBits(8); + matrix = (int)r.ReadBits(8); + } + } + if (r.ReadFlag()) + { + r.ReadUe(); // chroma_sample_loc_type_top_field + r.ReadUe(); // chroma_sample_loc_type_bottom_field + } + uint units = 0, scale = 0; + var fixedRate = false; + if (r.ReadFlag()) + { + units = r.ReadBits(32); + scale = r.ReadBits(32); + fixedRate = r.ReadFlag(); + } + if (r.IsOverrun) return sps with { HasVui = true }; + return sps with + { + HasVui = true, + SarWidth = sarW == 0 ? 1 : sarW, + SarHeight = sarH == 0 ? 1 : sarH, + FullRange = fullRange, + ColourPrimaries = primaries, + TransferCharacteristics = transfer, + MatrixCoefficients = matrix, + NumUnitsInTick = units, + TimeScale = scale, + FixedFrameRate = fixedRate, + }; + } + + private static void SkipScalingList(ref BitReader r, int size) + { + int last = 8, next = 8; + for (var j = 0; j < size && !r.IsOverrun; j++) + { + if (next != 0) next = (last + r.ReadSe() + 256) % 256; + last = next == 0 ? last : next; + } + } + + // Table E-1 sample aspect ratios for aspect_ratio_idc 1..16 (index 0 unused). + private static ReadOnlySpan SarTable => + [ + 0, 0, 1, 1, 12, 11, 10, 11, 16, 11, 40, 33, 24, 11, 20, 11, 32, 11, 80, 33, 18, 11, 15, 11, 64, 33, 160, 99, 4, 3, 3, 2, 2, 1, + ]; +} diff --git a/src/Titano.Core/Video/Bitstream/HevcSpsParser.cs b/src/Titano.Core/Video/Bitstream/HevcSpsParser.cs new file mode 100644 index 00000000..5305a521 --- /dev/null +++ b/src/Titano.Core/Video/Bitstream/HevcSpsParser.cs @@ -0,0 +1,120 @@ +namespace Titano.Core.Video.Bitstream; + +/// general_profile_tier_level fields of an HEVC SPS (ITU-T H.265 7.3.3), as stored in hvcC. +public sealed record HevcProfileTierLevel( + int ProfileSpace, + bool HighTier, + int ProfileIdc, + uint ProfileCompatibilityFlags, + ulong ConstraintIndicatorFlags, + int LevelIdc); + +/// Fields of an HEVC sequence parameter set needed for containers and diagnostics. +public sealed record HevcSps +{ + public required int VpsId { get; init; } + public required int MaxSubLayers { get; init; } + public required bool TemporalIdNesting { get; init; } + public required HevcProfileTierLevel ProfileTierLevel { get; init; } + public required int SpsId { get; init; } + public required int ChromaFormatIdc { get; init; } + public required int BitDepthLuma { get; init; } + public required int BitDepthChroma { get; init; } + public required int CodedWidth { get; init; } + public required int CodedHeight { get; init; } + + /// Width after the conformance window. + public required int Width { get; init; } + + /// Height after the conformance window. + public required int Height { get; init; } +} + +/// Parses HEVC SPS NAL units up to the bit depths. Never throws on malformed input. +public static class HevcSpsParser +{ + /// Parses an SPS NAL unit (2-byte header included, emulation prevention present). + public static bool TryParse(ReadOnlySpan nal, out HevcSps sps) + { + sps = null!; + if (nal.Length < 6 || AnnexBParser.HevcType(nal[0]) != HevcNalUnitType.Sps) return false; + var rbsp = AnnexBParser.RemoveEmulationPrevention(nal[2..]); + var r = new BitReader(rbsp); + + var vpsId = (int)r.ReadBits(4); + var maxSubLayersMinus1 = (int)r.ReadBits(3); + if (maxSubLayersMinus1 > 6) return false; + var nesting = r.ReadFlag(); + var ptl = ReadProfileTierLevel(ref r, maxSubLayersMinus1); + var spsId = r.ReadUe(); + if (spsId > 15) return false; + var chroma = (int)r.ReadUe(); + if (chroma > 3) return false; + if (chroma == 3) r.ReadFlag(); // separate_colour_plane_flag + var codedWidth = (long)r.ReadUe(); + var codedHeight = (long)r.ReadUe(); + long left = 0, right = 0, top = 0, bottom = 0; + if (r.ReadFlag()) + { + left = r.ReadUe(); + right = r.ReadUe(); + top = r.ReadUe(); + bottom = r.ReadUe(); + } + var depthLuma = 8 + (int)r.ReadUe(); + var depthChroma = 8 + (int)r.ReadUe(); + + var subWidth = chroma is 1 or 2 ? 2 : 1; + var subHeight = chroma == 1 ? 2 : 1; + var width = codedWidth - subWidth * (left + right); + var height = codedHeight - subHeight * (top + bottom); + if (r.IsOverrun || depthLuma > 16 || depthChroma > 16 || width <= 0 || height <= 0 || codedWidth > 65536 || codedHeight > 65536) + return false; + + sps = new HevcSps + { + VpsId = vpsId, + MaxSubLayers = maxSubLayersMinus1 + 1, + TemporalIdNesting = nesting, + ProfileTierLevel = ptl, + SpsId = (int)spsId, + ChromaFormatIdc = chroma, + BitDepthLuma = depthLuma, + BitDepthChroma = depthChroma, + CodedWidth = (int)codedWidth, + CodedHeight = (int)codedHeight, + Width = (int)width, + Height = (int)height, + }; + return true; + } + + /// profile_tier_level(1, maxNumSubLayersMinus1); sub-layer fields are skipped. + internal static HevcProfileTierLevel ReadProfileTierLevel(ref BitReader r, int maxSubLayersMinus1) + { + var space = (int)r.ReadBits(2); + var tier = r.ReadFlag(); + var profile = (int)r.ReadBits(5); + var compatibility = r.ReadBits(32); + var constraints = r.ReadBits64(48); + var level = (int)r.ReadBits(8); + + Span profilePresent = stackalloc bool[8]; + Span levelPresent = stackalloc bool[8]; + for (var i = 0; i < maxSubLayersMinus1; i++) + { + profilePresent[i] = r.ReadFlag(); + levelPresent[i] = r.ReadFlag(); + } + if (maxSubLayersMinus1 > 0) + { + for (var i = maxSubLayersMinus1; i < 8; i++) r.ReadBits(2); // reserved_zero_2bits + } + for (var i = 0; i < maxSubLayersMinus1; i++) + { + if (profilePresent[i]) r.Skip(88); + if (levelPresent[i]) r.Skip(8); + } + return new HevcProfileTierLevel(space, tier, profile, compatibility, constraints, level); + } +} diff --git a/tests/Titano.Core.Tests/Video/BitstreamTests.cs b/tests/Titano.Core.Tests/Video/BitstreamTests.cs new file mode 100644 index 00000000..f184c3c2 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/BitstreamTests.cs @@ -0,0 +1,229 @@ +using Titano.Core.Video.Bitstream; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class BitstreamTests +{ + [Test] + public void ExpGolombRoundTrip() + { + uint[] unsigned = [0, 1, 2, 3, 7, 8, 254, 255, 256, 65535, 1_000_000, uint.MaxValue - 1]; + int[] signed = [0, 1, -1, 2, -2, 100, -100, int.MaxValue, -int.MaxValue]; + var w = new BitWriter(); + foreach (var v in unsigned) w.WriteUe(v); + foreach (var v in signed) w.WriteSe(v); + w.WriteBits(0b101, 3); + var r = new BitReader(w.ToArray()); + foreach (var v in unsigned) Assert.Equal(v, r.ReadUe()); + foreach (var v in signed) Assert.Equal(v, r.ReadSe()); + Assert.Equal(0b101u, r.ReadBits(3)); + Assert.False(r.IsOverrun); + } + + [Test] + public void ReadingPastTheEndSetsOverrunWithoutThrowing() + { + var r = new BitReader([0xFF]); + Assert.Equal(0xFFu, r.ReadBits(8)); + Assert.Equal(0u, r.ReadBits(16)); + Assert.True(r.IsOverrun); + var zeros = new BitReader(new byte[8]); + Assert.Equal(0u, zeros.ReadUe()); + Assert.True(zeros.IsOverrun); + } + + [Test] + public void Leb128RoundTrip() + { + Span buffer = stackalloc byte[8]; + foreach (var v in new ulong[] { 0, 1, 127, 128, 16383, 16384, uint.MaxValue }) + { + var n = Av1ObuParser.WriteLeb128(buffer, v); + Assert.Equal(Av1ObuParser.Leb128Size(v), n); + Assert.True(Av1ObuParser.TryReadLeb128(buffer[..n], out var back, out var length)); + Assert.Equal(v, back); + Assert.Equal(n, length); + } + } + + [Test] + public void SplitsThreeAndFourByteStartCodes() + { + byte[] stream = [0xAA, 0, 0, 0, 1, 0x67, 1, 2, 0, 0, 1, 0x68, 3, 0, 0, 0, 0, 1, 0x65, 4, 5, 6, 0, 0]; + var units = AnnexBParser.Split(stream); + Assert.Count(3, units); + Assert.BytesEqual([0x67, 1, 2], units[0].Slice(stream)); + Assert.BytesEqual([0x68, 3], units[1].Slice(stream)); + Assert.BytesEqual([0x65, 4, 5, 6], units[2].Slice(stream)); + Assert.Equal(H264NalUnitType.Sps, AnnexBParser.H264Type(stream[units[0].Offset])); + Assert.Equal(H264NalUnitType.IdrSlice, AnnexBParser.H264Type(stream[units[2].Offset])); + } + + [Test] + public void ConvertsAnnexBToLengthPrefixedAndDetectsBoth() + { + var annexB = AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps(), SyntheticStreams.H264Slice(true, 300, 1)]); + var prefixed = AnnexBParser.ToLengthPrefixed(annexB); + var fromAnnexB = AnnexBParser.SplitAccessUnit(annexB, out var wasAnnexB); + var fromPrefixed = AnnexBParser.SplitAccessUnit(prefixed, out var wasAnnexB2); + Assert.True(wasAnnexB); + Assert.False(wasAnnexB2); + Assert.Equal(3, fromAnnexB.Count); + Assert.Equal(3, fromPrefixed.Count); + for (var i = 0; i < 3; i++) + Assert.BytesEqual(fromAnnexB[i].Slice(annexB), fromPrefixed[i].Slice(prefixed)); + } + + [Test] + public void LengthPrefixedSplitRejectsInconsistentLengths() + { + Assert.False(AnnexBParser.TrySplitLengthPrefixed([0, 0, 0, 9, 1, 2], 4, out _)); + Assert.False(AnnexBParser.TrySplitLengthPrefixed([0, 0, 0, 0], 4, out _)); + Assert.True(AnnexBParser.TrySplitLengthPrefixed([0, 2, 0x41, 9, 0, 1, 0x41], 2, out var units)); + Assert.Count(2, units); + } + + [Test] + public void EmulationPreventionRoundTrip() + { + var rng = new Random(7); + for (var trial = 0; trial < 200; trial++) + { + var data = new byte[rng.Next(1, 200)]; + for (var i = 0; i < data.Length; i++) data[i] = rng.Next(4) == 0 ? (byte)rng.Next(4) : (byte)0; + var escaped = AnnexBParser.AddEmulationPrevention(data); + for (var i = 2; i < escaped.Length; i++) + Assert.False(escaped[i - 2] == 0 && escaped[i - 1] == 0 && escaped[i] <= 2, "start code prefix survived escaping"); + var back = AnnexBParser.RemoveEmulationPrevention(escaped); + // After a lone trailing 0x00 the appended 0x03 is not preceded by two zeros, so it stays. + if (back.Length == data.Length + 1) back = back[..^1]; + Assert.BytesEqual(data, back); + } + Assert.BytesEqual([0, 0, 3, 1, 0, 0, 3, 0], AnnexBParser.AddEmulationPrevention([0, 0, 1, 0, 0, 0]).AsSpan(0, 8)); + } + + [Test] + public void ParsesH264HighProfileSps() + { + var nal = SyntheticStreams.H264Sps(1920, 1080, 100, 41); + Assert.True(H264SpsParser.TryParse(nal, out var sps)); + Assert.Equal(100, sps.ProfileIdc); + Assert.Equal(41, sps.LevelIdc); + Assert.Equal(1, sps.ChromaFormatIdc); + Assert.Equal(8, sps.BitDepthLuma); + Assert.Equal(1920, sps.Width); + Assert.Equal(1080, sps.Height); + Assert.Equal(1088, sps.CodedHeight); + Assert.Equal(1, sps.ColourPrimaries); + Assert.Equal(false, sps.FullRange); + Assert.Approximately(29.97, sps.FrameRate!.Value, 0.01); + } + + [Theory] + [Case(1280, 720, 77, 31)] + [Case(3840, 2160, 100, 51)] + [Case(642, 482, 66, 30)] + public void ParsesH264SizesWithCropping(int width, int height, int profile, int level) + { + Assert.True(H264SpsParser.TryParse(SyntheticStreams.H264Sps(width, height, profile, level), out var sps)); + Assert.Equal(width, sps.Width); + Assert.Equal(height, sps.Height); + Assert.Equal(profile, sps.ProfileIdc); + } + + [Test] + public void ParsesHevcMain10Sps() + { + Assert.True(HevcSpsParser.TryParse(SyntheticStreams.HevcSps(1920, 1080, 10, 153), out var sps)); + Assert.Equal(1920, sps.Width); + Assert.Equal(1080, sps.Height); + Assert.Equal(1080, sps.CodedHeight); + Assert.Equal(10, sps.BitDepthLuma); + Assert.Equal(10, sps.BitDepthChroma); + Assert.Equal(1, sps.ChromaFormatIdc); + Assert.Equal(2, sps.ProfileTierLevel.ProfileIdc); + Assert.Equal(153, sps.ProfileTierLevel.LevelIdc); + Assert.Equal(0x2000_0000u, sps.ProfileTierLevel.ProfileCompatibilityFlags); + Assert.Equal(0x9000_0000_0000UL, sps.ProfileTierLevel.ConstraintIndicatorFlags); + Assert.False(sps.ProfileTierLevel.HighTier); + Assert.True(sps.TemporalIdNesting); + } + + [Test] + public void AppliesHevcConformanceWindow() + { + Assert.True(HevcSpsParser.TryParse(SyntheticStreams.HevcSps(1916, 1076, 8, 120), out var sps)); + Assert.Equal(1920, sps.CodedWidth); + Assert.Equal(1080, sps.CodedHeight); + Assert.Equal(1916, sps.Width); + Assert.Equal(1076, sps.Height); + Assert.Equal(1, sps.ProfileTierLevel.ProfileIdc); + } + + [Test] + public void ParsesAv1SequenceHeader() + { + var obuBytes = SyntheticStreams.Av1SequenceHeaderObu(3840, 2160, 12, tenBit: true); + Assert.True(Av1ObuParser.TryReadObu(obuBytes, 0, out var obu)); + Assert.Equal(Av1ObuType.SequenceHeader, obu.Type); + Assert.True(obu.HasSizeField); + Assert.Equal(obuBytes.Length, obu.TotalLength); + Assert.True(Av1ObuParser.TryParseSequenceHeader(obu.Payload(obuBytes), out var header)); + Assert.Equal(3840, header.MaxFrameWidth); + Assert.Equal(2160, header.MaxFrameHeight); + Assert.Equal(12, header.SeqLevelIdx); + Assert.Equal(10, header.BitDepth); + Assert.True(header.ChromaSubsamplingX && header.ChromaSubsamplingY); + Assert.Equal(1, header.ColorPrimaries); + Assert.False(header.FullRange); + } + + [Test] + public void ReadsObuWithoutSizeFieldAndSplitsTemporalUnits() + { + byte[] lastWithoutSize = [(byte)Av1ObuType.Frame << 3, 9, 8, 7]; + Assert.True(Av1ObuParser.TryReadObu(lastWithoutSize, 0, out var obu)); + Assert.False(obu.HasSizeField); + Assert.Equal(3, obu.PayloadLength); + + var stream = SyntheticStreams.Concat( + SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1SequenceHeaderObu(), SyntheticStreams.Av1Frame(50, 1), + SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1Frame(40, 2), + SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1Frame(30, 3)); + var units = Av1ObuParser.SplitTemporalUnits(stream); + Assert.Count(3, units); + Assert.Equal(0, units[0].Offset); + Assert.Equal(stream.Length, units[2].Offset + units[2].Length); + Assert.Equal(units[0].Length, units[1].Offset); + } + + [Test] + public void ParsersSurviveTruncationAndGarbage() + { + byte[][] inputs = [SyntheticStreams.H264Sps(), SyntheticStreams.HevcSps(), SyntheticStreams.Av1SequenceHeaderObu()]; + var rng = new Random(3); + foreach (var input in inputs) + { + for (var length = 0; length < input.Length; length++) + { + var slice = input.AsSpan(0, length); + H264SpsParser.TryParse(slice, out _); + HevcSpsParser.TryParse(slice, out _); + Av1ObuParser.Split(slice); + if (length > 2) Av1ObuParser.TryParseSequenceHeader(slice[2..], out _); + } + for (var trial = 0; trial < 300; trial++) + { + var corrupt = (byte[])input.Clone(); + corrupt[rng.Next(corrupt.Length)] ^= (byte)(1 << rng.Next(8)); + H264SpsParser.TryParse(corrupt, out _); + HevcSpsParser.TryParse(corrupt, out _); + Av1ObuParser.SplitTemporalUnits(corrupt); + Av1ObuParser.TryParseSequenceHeader(corrupt, out _); + AnnexBParser.SplitAccessUnit(corrupt, out _); + } + } + Assert.False(H264SpsParser.TryParse(SyntheticStreams.H264Sps().AsSpan(0, 5), out _)); + } +} diff --git a/tests/Titano.Core.Tests/Video/SyntheticStreams.cs b/tests/Titano.Core.Tests/Video/SyntheticStreams.cs new file mode 100644 index 00000000..ef8b8177 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/SyntheticStreams.cs @@ -0,0 +1,323 @@ +using Titano.Core.Video.Bitstream; + +namespace Titano.Core.Tests.Video; + +/// Builds syntactically valid H.264/HEVC parameter sets, AV1 sequence headers and slice stubs. +internal static class SyntheticStreams +{ + /// H.264 SPS NAL (header included) for 4:2:0 8-bit with cropping to the requested size and VUI timing. + public static byte[] H264Sps(int width = 1920, int height = 1080, int profileIdc = 100, int levelIdc = 41, uint timeScale = 60000, uint unitsInTick = 1001) + { + var w = new BitWriter(); + w.WriteBits((ulong)profileIdc, 8); + w.WriteBits(0, 8); // constraint flags + w.WriteBits((ulong)levelIdc, 8); + w.WriteUe(0); // seq_parameter_set_id + if (profileIdc == 100) + { + w.WriteUe(1); // chroma_format_idc + w.WriteUe(0); // bit_depth_luma_minus8 + w.WriteUe(0); // bit_depth_chroma_minus8 + w.WriteBit(false); // qpprime_y_zero_transform_bypass_flag + w.WriteBit(false); // seq_scaling_matrix_present_flag + } + w.WriteUe(0); // log2_max_frame_num_minus4 + w.WriteUe(0); // pic_order_cnt_type + w.WriteUe(2); // log2_max_pic_order_cnt_lsb_minus4 + w.WriteUe(4); // max_num_ref_frames + w.WriteBit(false); // gaps_in_frame_num_value_allowed_flag + var mbW = (width + 15) / 16; + var mbH = (height + 15) / 16; + w.WriteUe((uint)mbW - 1); + w.WriteUe((uint)mbH - 1); + w.WriteBit(true); // frame_mbs_only_flag + w.WriteBit(true); // direct_8x8_inference_flag + var cropRight = (mbW * 16 - width) / 2; + var cropBottom = (mbH * 16 - height) / 2; + var crop = cropRight > 0 || cropBottom > 0; + w.WriteBit(crop); + if (crop) + { + w.WriteUe(0); + w.WriteUe((uint)cropRight); + w.WriteUe(0); + w.WriteUe((uint)cropBottom); + } + w.WriteBit(true); // vui_parameters_present_flag + w.WriteBit(true); // aspect_ratio_info_present_flag + w.WriteBits(1, 8); // aspect_ratio_idc 1:1 + w.WriteBit(false); // overscan_info_present_flag + w.WriteBit(true); // video_signal_type_present_flag + w.WriteBits(5, 3); // video_format + w.WriteBit(false); // video_full_range_flag + w.WriteBit(true); // colour_description_present_flag + w.WriteBits(1, 8); + w.WriteBits(1, 8); + w.WriteBits(1, 8); + w.WriteBit(false); // chroma_loc_info_present_flag + w.WriteBit(true); // timing_info_present_flag + w.WriteBits(unitsInTick, 32); + w.WriteBits(timeScale, 32); + w.WriteBit(true); // fixed_frame_rate_flag + w.WriteBit(false); // nal_hrd_parameters_present_flag + w.WriteBit(false); // vcl_hrd_parameters_present_flag + w.WriteBit(false); // pic_struct_present_flag + w.WriteBit(false); // bitstream_restriction_flag + w.WriteTrailingBits(); + return Nal([0x67], w.ToArray()); + } + + public static byte[] H264Pps() + { + var w = new BitWriter(); + w.WriteUe(0); // pic_parameter_set_id + w.WriteUe(0); // seq_parameter_set_id + w.WriteBit(true); // entropy_coding_mode_flag + w.WriteBit(false); // bottom_field_pic_order_in_frame_present_flag + w.WriteUe(0); // num_slice_groups_minus1 + w.WriteUe(0); // num_ref_idx_l0_default_active_minus1 + w.WriteUe(0); // num_ref_idx_l1_default_active_minus1 + w.WriteBit(false); // weighted_pred_flag + w.WriteBits(0, 2); // weighted_bipred_idc + w.WriteSe(0); // pic_init_qp_minus26 + w.WriteSe(0); // pic_init_qs_minus26 + w.WriteSe(0); // chroma_qp_index_offset + w.WriteBit(true); // deblocking_filter_control_present_flag + w.WriteBit(false); // constrained_intra_pred_flag + w.WriteBit(false); // redundant_pic_cnt_present_flag + w.WriteBit(true); // transform_8x8_mode_flag + w.WriteBit(false); // pic_scaling_matrix_present_flag + w.WriteSe(0); // second_chroma_qp_index_offset + w.WriteTrailingBits(); + return Nal([0x68], w.ToArray()); + } + + /// A slice NAL with a plausible header and pseudo-random payload. + public static byte[] H264Slice(bool idr, int payloadBytes, int seed) + { + var w = new BitWriter(); + w.WriteUe(0); // first_mb_in_slice + w.WriteUe(idr ? 7u : 5u); // slice_type I / P + w.WriteUe(0); // pic_parameter_set_id + w.WriteBytes(Random(payloadBytes, seed)); + w.WriteTrailingBits(); + return Nal([idr ? (byte)0x65 : (byte)0x41], w.ToArray()); + } + + public static byte[] H264AccessUnitDelimiter() => [0x09, 0xF0]; + + public static byte[] HevcVps() + { + var w = new BitWriter(); + w.WriteBits(0, 4); // vps_video_parameter_set_id + w.WriteBit(true); // vps_base_layer_internal_flag + w.WriteBit(true); // vps_base_layer_available_flag + w.WriteBits(0, 6); // vps_max_layers_minus1 + w.WriteBits(0, 3); // vps_max_sub_layers_minus1 + w.WriteBit(true); // vps_temporal_id_nesting_flag + w.WriteBits(0xFFFF, 16); + WriteHevcProfileTierLevel(w, 2, 153); + w.WriteBit(true); // vps_sub_layer_ordering_info_present_flag + w.WriteUe(4); + w.WriteUe(0); + w.WriteUe(0); + w.WriteBits(0, 6); // vps_max_layer_id + w.WriteUe(0); // vps_num_layer_sets_minus1 + w.WriteBit(false); // vps_timing_info_present_flag + w.WriteBit(false); // vps_extension_flag + w.WriteTrailingBits(); + return Nal([0x40, 0x01], w.ToArray()); + } + + /// HEVC SPS for 4:2:0 with the given bit depth, coded in 8×8 units with a conformance window. + public static byte[] HevcSps(int width = 1920, int height = 1080, int bitDepth = 10, int levelIdc = 153) + { + var w = new BitWriter(); + w.WriteBits(0, 4); // sps_video_parameter_set_id + w.WriteBits(0, 3); // sps_max_sub_layers_minus1 + w.WriteBit(true); // sps_temporal_id_nesting_flag + WriteHevcProfileTierLevel(w, bitDepth == 10 ? 2 : 1, levelIdc); + w.WriteUe(0); // sps_seq_parameter_set_id + w.WriteUe(1); // chroma_format_idc + var codedW = (width + 7) / 8 * 8; + var codedH = (height + 7) / 8 * 8; + w.WriteUe((uint)codedW); + w.WriteUe((uint)codedH); + var window = codedW != width || codedH != height; + w.WriteBit(window); + if (window) + { + w.WriteUe(0); + w.WriteUe((uint)(codedW - width) / 2); + w.WriteUe(0); + w.WriteUe((uint)(codedH - height) / 2); + } + w.WriteUe((uint)bitDepth - 8); + w.WriteUe((uint)bitDepth - 8); + w.WriteUe(4); // log2_max_pic_order_cnt_lsb_minus4 + w.WriteBit(true); // sps_sub_layer_ordering_info_present_flag + w.WriteUe(4); + w.WriteUe(0); + w.WriteUe(0); + w.WriteUe(0); // log2_min_luma_coding_block_size_minus3 + w.WriteUe(3); // log2_diff_max_min_luma_coding_block_size + w.WriteUe(0); // log2_min_luma_transform_block_size_minus2 + w.WriteUe(3); // log2_diff_max_min_luma_transform_block_size + w.WriteUe(1); // max_transform_hierarchy_depth_inter + w.WriteUe(1); // max_transform_hierarchy_depth_intra + w.WriteBit(false); // scaling_list_enabled_flag + w.WriteBit(true); // amp_enabled_flag + w.WriteBit(true); // sample_adaptive_offset_enabled_flag + w.WriteBit(false); // pcm_enabled_flag + w.WriteUe(0); // num_short_term_ref_pic_sets + w.WriteBit(false); // long_term_ref_pics_present_flag + w.WriteBit(true); // sps_temporal_mvp_enabled_flag + w.WriteBit(true); // strong_intra_smoothing_enabled_flag + w.WriteBit(false); // vui_parameters_present_flag + w.WriteBit(false); // sps_extension_present_flag + w.WriteTrailingBits(); + return Nal([0x42, 0x01], w.ToArray()); + } + + public static byte[] HevcPps() + { + var w = new BitWriter(); + w.WriteUe(0); // pps_pic_parameter_set_id + w.WriteUe(0); // pps_seq_parameter_set_id + w.WriteBit(false); // dependent_slice_segments_enabled_flag + w.WriteBit(false); // output_flag_present_flag + w.WriteBits(0, 3); // num_extra_slice_header_bits + w.WriteBit(false); // sign_data_hiding_enabled_flag + w.WriteBit(true); // cabac_init_present_flag + w.WriteUe(0); + w.WriteUe(0); + w.WriteSe(0); // init_qp_minus26 + w.WriteBit(false); // constrained_intra_pred_flag + w.WriteBit(false); // transform_skip_enabled_flag + w.WriteBit(false); // cu_qp_delta_enabled_flag + w.WriteSe(0); + w.WriteSe(0); + w.WriteBit(false); // pps_slice_chroma_qp_offsets_present_flag + w.WriteBit(false); // weighted_pred_flag + w.WriteBit(false); // weighted_bipred_flag + w.WriteBit(false); // transquant_bypass_enabled_flag + w.WriteBit(false); // tiles_enabled_flag + w.WriteBit(false); // entropy_coding_sync_enabled_flag + w.WriteBit(true); // pps_loop_filter_across_slices_enabled_flag + w.WriteBit(false); // deblocking_filter_control_present_flag + w.WriteBit(false); // pps_scaling_list_data_present_flag + w.WriteBit(false); // lists_modification_present_flag + w.WriteUe(0); // log2_parallel_merge_level_minus2 + w.WriteBit(false); // slice_segment_header_extension_present_flag + w.WriteBit(false); // pps_extension_present_flag + w.WriteTrailingBits(); + return Nal([0x44, 0x01], w.ToArray()); + } + + public static byte[] HevcSlice(bool idr, int payloadBytes, int seed) + { + var type = idr ? HevcNalUnitType.IdrWRadl : HevcNalUnitType.TrailR; + var w = new BitWriter(); + w.WriteBit(true); // first_slice_segment_in_pic_flag + w.WriteBytes(Random(payloadBytes, seed)); + w.WriteTrailingBits(); + return Nal([(byte)((byte)type << 1), 0x01], w.ToArray()); + } + + /// AV1 sequence header OBU (with size field) for profile 0 4:2:0. + public static byte[] Av1SequenceHeaderObu(int width = 1920, int height = 1080, int levelIdx = 8, bool tenBit = false) + { + var w = new BitWriter(); + w.WriteBits(0, 3); // seq_profile + w.WriteBit(false); // still_picture + w.WriteBit(false); // reduced_still_picture_header + w.WriteBit(false); // timing_info_present_flag + w.WriteBit(false); // initial_display_delay_present_flag + w.WriteBits(0, 5); // operating_points_cnt_minus_1 + w.WriteBits(0, 12); // operating_point_idc[0] + w.WriteBits((ulong)levelIdx, 5); + if (levelIdx > 7) w.WriteBit(false); // seq_tier[0] + const int bits = 16; + w.WriteBits(bits - 1, 4); + w.WriteBits(bits - 1, 4); + w.WriteBits((ulong)width - 1, bits); + w.WriteBits((ulong)height - 1, bits); + w.WriteBit(false); // frame_id_numbers_present_flag + w.WriteBit(false); // use_128x128_superblock + w.WriteBit(true); // enable_filter_intra + w.WriteBit(true); // enable_intra_edge_filter + w.WriteBits(0, 4); // interintra, masked, warped, dual filter + w.WriteBit(true); // enable_order_hint + w.WriteBits(0, 2); // enable_jnt_comp, enable_ref_frame_mvs + w.WriteBit(true); // seq_choose_screen_content_tools + w.WriteBit(true); // seq_choose_integer_mv + w.WriteBits(6, 3); // order_hint_bits_minus_1 + w.WriteBits(0, 3); // superres, cdef, restoration + w.WriteBit(tenBit); // high_bitdepth + w.WriteBit(false); // mono_chrome + w.WriteBit(true); // color_description_present_flag + w.WriteBits(1, 8); + w.WriteBits(1, 8); + w.WriteBits(1, 8); + w.WriteBit(false); // color_range + w.WriteBits(0, 2); // chroma_sample_position + w.WriteBit(false); // separate_uv_delta_q + w.WriteBit(false); // film_grain_params_present + w.WriteTrailingBits(); + return Obu(Av1ObuType.SequenceHeader, w.ToArray()); + } + + public static byte[] Av1TemporalDelimiter() => Obu(Av1ObuType.TemporalDelimiter, []); + + public static byte[] Av1Frame(int payloadBytes, int seed) => Obu(Av1ObuType.Frame, Random(payloadBytes, seed)); + + /// An OBU with obu_has_size_field set. + public static byte[] Obu(Av1ObuType type, ReadOnlySpan payload) + { + var w = new BitWriter(); + w.WriteBits((ulong)((byte)type << 3 | 0x02), 8); + w.WriteLeb128((ulong)payload.Length); + w.WriteBytes(payload); + return w.ToArray(); + } + + public static byte[] Concat(params byte[][] parts) + { + var total = 0; + foreach (var p in parts) total += p.Length; + var result = new byte[total]; + var pos = 0; + foreach (var p in parts) + { + p.CopyTo(result, pos); + pos += p.Length; + } + return result; + } + + public static byte[] Random(int length, int seed) + { + var bytes = new byte[length]; + new Random(seed).NextBytes(bytes); + return bytes; + } + + private static void WriteHevcProfileTierLevel(BitWriter w, int profileIdc, int levelIdc) + { + w.WriteBits(0, 2); // general_profile_space + w.WriteBit(false); // general_tier_flag + w.WriteBits((ulong)profileIdc, 5); + w.WriteBits(1UL << (31 - profileIdc), 32); // general_profile_compatibility_flag[profileIdc] + w.WriteBits(0x9000_0000_0000UL, 48); // progressive_source + frame_only_constraint + w.WriteBits((ulong)levelIdc, 8); + } + + private static byte[] Nal(ReadOnlySpan header, byte[] rbsp) + { + var escaped = AnnexBParser.AddEmulationPrevention(rbsp); + var nal = new byte[header.Length + escaped.Length]; + header.CopyTo(nal); + escaped.CopyTo(nal, header.Length); + return nal; + } +} From 25c71ac97c26f9a9fbe3fdf2ab201ebf3ebbd7e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:29:29 +0000 Subject: [PATCH 006/188] =?UTF-8?q?feat(motion):=20add=20luminance=20pyram?= =?UTF-8?q?id,=20motion=20field=20and=20dense=20pyramidal=20Lucas=E2=80=93?= =?UTF-8?q?Kanade=20flow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GrayPyramid builds Burt–Adelson binomial pyramids on pooled planes. MotionField stores grid vectors with bilinear sampling, forward–backward errors, magnitude histogram and statistics. OpticalFlowEngine solves a Lucas–Kanade window at every pixel of each level with a first-order correction for neighbouring flows (stable for any iteration count), binomial pre-smoothing, median filtering between levels, Draft/Balanced/ Best presets and forward–backward consistency. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/GrayPyramid.cs | 144 ++++++++ src/Titano.Core/Motion/MotionField.cs | 154 ++++++++ src/Titano.Core/Motion/OpticalFlowEngine.cs | 332 ++++++++++++++++++ src/Titano.Core/Motion/PlaneOps.cs | 222 ++++++++++++ .../Motion/OpticalFlowTests.cs | 155 ++++++++ 5 files changed, 1007 insertions(+) create mode 100644 src/Titano.Core/Motion/GrayPyramid.cs create mode 100644 src/Titano.Core/Motion/MotionField.cs create mode 100644 src/Titano.Core/Motion/OpticalFlowEngine.cs create mode 100644 src/Titano.Core/Motion/PlaneOps.cs create mode 100644 tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs diff --git a/src/Titano.Core/Motion/GrayPyramid.cs b/src/Titano.Core/Motion/GrayPyramid.cs new file mode 100644 index 00000000..f8abb9b3 --- /dev/null +++ b/src/Titano.Core/Motion/GrayPyramid.cs @@ -0,0 +1,144 @@ +using System.Buffers; +using System.Numerics; +using Titano.Core.Imaging; + +namespace Titano.Core.Motion; + +/// +/// Gaussian pyramid of a single-channel plane (Burt & Adelson 1983): each level is the previous one +/// filtered with the 5-tap binomial [1 4 6 4 1]/16 (replicated edges) and decimated by 2, keeping even +/// samples, so level-ℓ pixel k sits at full-resolution coordinate k·2^ℓ. Planes are pooled and reused +/// by every . +/// +public sealed class GrayPyramid : IDisposable +{ + private readonly float[][] _levels; + private readonly int[] _widths; + private readonly int[] _heights; + private float[]? _scratch; + + public GrayPyramid(int width, int height, int levels) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(levels); + Width = width; + Height = height; + Levels = levels; + _levels = new float[levels][]; + _widths = new int[levels]; + _heights = new int[levels]; + for (var l = 0; l < levels; l++) + { + _widths[l] = l == 0 ? width : (_widths[l - 1] + 1) / 2; + _heights[l] = l == 0 ? height : (_heights[l - 1] + 1) / 2; + _levels[l] = ArrayPool.Shared.Rent(_widths[l] * _heights[l]); + } + _scratch = ArrayPool.Shared.Rent(int.Max(1, _widths[int.Min(1, levels - 1)] * height)); + } + + public int Width { get; } + + public int Height { get; } + + public int Levels { get; } + + /// Levels needed until the smaller side would drop below , capped. + public static int LevelsFor(int width, int height, int minimumSize = 16, int maximumLevels = 8) + { + var levels = 1; + while (levels < maximumLevels && (int.Min(width, height) + 1) / 2 >= minimumSize) + { + width = (width + 1) / 2; + height = (height + 1) / 2; + levels++; + } + return levels; + } + + public int LevelWidth(int level) => _widths[level]; + + public int LevelHeight(int level) => _heights[level]; + + /// Row-major samples of one level. + public ReadOnlySpan Level(int level) => LevelArray(level).AsSpan(0, _widths[level] * _heights[level]); + + internal float[] LevelArray(int level) + { + ObjectDisposedException.ThrowIf(_scratch is null, this); + return _levels[level]; + } + + /// Builds the pyramid from a plane of × samples. + public void Build(ReadOnlySpan plane) + { + if (plane.Length < Width * Height) throw new ArgumentException("Plane is smaller than the pyramid base.", nameof(plane)); + plane[..(Width * Height)].CopyTo(LevelArray(0)); + BuildUpperLevels(); + } + + /// Builds the pyramid from the perceptual (sRGB-encoded) luminance of an image. + public void Build(ImageBuffer image) + { + if (image.Width != Width || image.Height != Height) throw new ArgumentException("Image size differs from the pyramid.", nameof(image)); + PlaneOps.PerceptualLuminance(image, LevelArray(0).AsSpan(0, Width * Height)); + BuildUpperLevels(); + } + + public void Dispose() + { + var scratch = Interlocked.Exchange(ref _scratch, null); + if (scratch is null) return; + ArrayPool.Shared.Return(scratch); + foreach (var level in _levels) ArrayPool.Shared.Return(level); + } + + private void BuildUpperLevels() + { + for (var l = 1; l < Levels; l++) Downsample(_levels[l - 1], _widths[l - 1], _heights[l - 1], _levels[l], _widths[l], _heights[l], _scratch!); + } + + private static void Downsample(float[] source, int width, int height, float[] destination, int halfWidth, int halfHeight, float[] scratch) + { + // Horizontal: filter and keep even columns (scratch is halfWidth × height). + PlaneOps.ForRows(height, width, y => + { + var row = source.AsSpan(y * width, width); + var output = scratch.AsSpan(y * halfWidth, halfWidth); + var last = width - 1; + for (var k = 0; k < halfWidth; k++) + { + var x = 2 * k; + output[k] = (row[int.Max(x - 2, 0)] + row[int.Min(x + 2, last)] + + 4 * (row[int.Max(x - 1, 0)] + row[int.Min(x + 1, last)]) + + 6 * row[int.Min(x, last)]) * (1f / 16); + } + }); + + // Vertical: five rows combined per output row, vectorised across columns. + PlaneOps.ForRows(halfHeight, halfWidth, k => + { + var y = 2 * k; + var last = height - 1; + var r0 = scratch.AsSpan(int.Max(y - 2, 0) * halfWidth, halfWidth); + var r1 = scratch.AsSpan(int.Max(y - 1, 0) * halfWidth, halfWidth); + var r2 = scratch.AsSpan(int.Min(y, last) * halfWidth, halfWidth); + var r3 = scratch.AsSpan(int.Min(y + 1, last) * halfWidth, halfWidth); + var r4 = scratch.AsSpan(int.Min(y + 2, last) * halfWidth, halfWidth); + var output = destination.AsSpan(k * halfWidth, halfWidth); + var i = 0; + if (Vector.IsHardwareAccelerated) + { + var vc = Vector.Count; + for (; i <= halfWidth - vc; i += vc) + { + var sum = new Vector(r0[i..]) + new Vector(r4[i..]) + + 4 * (new Vector(r1[i..]) + new Vector(r3[i..])) + + 6 * new Vector(r2[i..]); + (sum * (1f / 16)).CopyTo(output[i..]); + } + } + for (; i < halfWidth; i++) output[i] = (r0[i] + r4[i] + 4 * (r1[i] + r3[i]) + 6 * r2[i]) * (1f / 16); + }); + } +} diff --git a/src/Titano.Core/Motion/MotionField.cs b/src/Titano.Core/Motion/MotionField.cs new file mode 100644 index 00000000..bde6163f --- /dev/null +++ b/src/Titano.Core/Motion/MotionField.cs @@ -0,0 +1,154 @@ +using System.Buffers; + +namespace Titano.Core.Motion; + +/// Summary of a motion field's vector magnitudes (pixels per frame). +public readonly record struct MotionStatistics( + double MeanMagnitude, + double MedianMagnitude, + double P95Magnitude, + double MaxMagnitude, + double MeanU, + double MeanV, + double ReliableFraction); + +/// +/// Dense motion vectors (full-resolution pixels per frame) on a regular grid: node (i, j) describes the +/// pixel at (i·Step, j·Step). A vector (u, v) at p means the content at p in the first frame is found at +/// p + (u, v) in the second. holds the forward–backward consistency error in pixels +/// (NaN when not checked). Storage is pooled; dispose the field when done. +/// +public sealed class MotionField : IDisposable +{ + private float[]? _u; + private float[]? _v; + private float[]? _error; + + public MotionField(int imageWidth, int imageHeight, int step) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageHeight); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(step); + ImageWidth = imageWidth; + ImageHeight = imageHeight; + Step = step; + Columns = (imageWidth - 1) / step + 1; + Rows = (imageHeight - 1) / step + 1; + var n = Columns * Rows; + _u = ArrayPool.Shared.Rent(n); + _v = ArrayPool.Shared.Rent(n); + _error = ArrayPool.Shared.Rent(n); + U.Clear(); + V.Clear(); + Error.Fill(float.NaN); + } + + public int ImageWidth { get; } + + public int ImageHeight { get; } + + /// Grid spacing in full-resolution pixels. + public int Step { get; } + + public int Columns { get; } + + public int Rows { get; } + + public int Count => Columns * Rows; + + /// Horizontal components, row-major over the grid. + public Span U => Storage(_u); + + /// Vertical components, row-major over the grid. + public Span V => Storage(_v); + + /// Forward–backward error |w(p) + w'(p + w(p))| in pixels; NaN when unchecked. + public Span Error => Storage(_error); + + /// True when has been filled by a forward–backward check. + public bool HasConsistency { get; internal set; } + + /// Bilinearly interpolated vector at a full-resolution pixel-centre position (clamped to the grid). + public (float U, float V) Sample(double x, double y) + { + var gx = (float)(x / Step); + var gy = (float)(y / Step); + return (PlaneOps.Bilinear(U, Columns, Rows, gx, gy), PlaneOps.Bilinear(V, Columns, Rows, gx, gy)); + } + + /// Bilinearly interpolated forward–backward error (NaN when unchecked). + public float SampleError(double x, double y) => + HasConsistency ? PlaneOps.Bilinear(Error, Columns, Rows, (float)(x / Step), (float)(y / Step)) : float.NaN; + + /// Counts of vector magnitudes in equal bins over [0, max]; larger values land in the last bin. + public int[] MagnitudeHistogram(int bins, double maxMagnitude) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bins); + if (!(maxMagnitude > 0)) throw new ArgumentOutOfRangeException(nameof(maxMagnitude)); + var histogram = new int[bins]; + var u = U; + var v = V; + var scale = bins / maxMagnitude; + for (var i = 0; i < u.Length; i++) + { + var m = double.Sqrt((double)u[i] * u[i] + (double)v[i] * v[i]); + histogram[int.Min(bins - 1, (int)(m * scale))]++; + } + return histogram; + } + + /// Magnitude statistics; vectors with a forward–backward error above px count as unreliable. + public MotionStatistics Statistics(double reliableError = 1.0) + { + var n = Count; + var magnitudes = ArrayPool.Shared.Rent(n); + try + { + var u = U; + var v = V; + var error = Error; + double sum = 0, su = 0, sv = 0, max = 0; + var reliable = 0; + for (var i = 0; i < n; i++) + { + var m = float.Sqrt(u[i] * u[i] + v[i] * v[i]); + magnitudes[i] = m; + sum += m; + su += u[i]; + sv += v[i]; + max = double.Max(max, m); + if (!HasConsistency || error[i] <= reliableError) reliable++; + } + var span = magnitudes.AsSpan(0, n); + var median = PlaneOps.Median(span); + var p95 = PlaneOps.Select(span, int.Min(n - 1, (int)double.Ceiling(0.95 * n) - 1)); + return new MotionStatistics(sum / n, median, p95, max, su / n, sv / n, reliable / (double)n); + } + finally + { + ArrayPool.Shared.Return(magnitudes); + } + } + + /// Sets every vector to (u, v). + public void Fill(float u, float v) + { + U.Fill(u); + V.Fill(v); + } + + public void Dispose() + { + Return(ref _u); + Return(ref _v); + Return(ref _error); + } + + private Span Storage(float[]? array) => (array ?? throw new ObjectDisposedException(nameof(MotionField))).AsSpan(0, Count); + + private static void Return(ref float[]? array) + { + var a = Interlocked.Exchange(ref array, null); + if (a is not null) ArrayPool.Shared.Return(a); + } +} diff --git a/src/Titano.Core/Motion/OpticalFlowEngine.cs b/src/Titano.Core/Motion/OpticalFlowEngine.cs new file mode 100644 index 00000000..d3e1070c --- /dev/null +++ b/src/Titano.Core/Motion/OpticalFlowEngine.cs @@ -0,0 +1,332 @@ +using System.Buffers; +using Titano.Core.Imaging; + +namespace Titano.Core.Motion; + +/// Speed/quality trade-off of . +public enum FlowQuality +{ + /// Vectors every 4 px, few iterations: previews and analysis histograms. + Draft, + + /// Vectors every 2 px: motion blur and analysis. + Balanced, + + /// Per-pixel vectors, more iterations and a 5×5 median: frame interpolation. + Best, +} + +/// Parameters of the dense pyramidal Lucas–Kanade solver. +public sealed record OpticalFlowOptions +{ + /// Upper bound on pyramid levels (the coarsest level keeps ≥ 16 px on its short side). + public int MaxLevels { get; init; } = 5; + + /// Finest level solved; the output grid step is 2^FinestLevel pixels. + public int FinestLevel { get; init; } = 1; + + /// Warp–solve iterations per level. + public int Iterations { get; init; } = 4; + + /// Lucas–Kanade integration window radius (box of (2r+1)² samples) at every level. + public int WindowRadius { get; init; } = 3; + + /// Median filter radius applied to the field after each level (0 = off). + public int MedianRadius { get; init; } = 1; + + /// Tikhonov term added to the structure tensor diagonal (perceptual luminance² per px²). + public float Regularization { get; init; } = 1e-5f; + + public static OpticalFlowOptions For(FlowQuality quality) => quality switch + { + FlowQuality.Draft => new OpticalFlowOptions { MaxLevels = 4, FinestLevel = 2, Iterations = 3 }, + FlowQuality.Balanced => new OpticalFlowOptions(), + FlowQuality.Best => new OpticalFlowOptions { MaxLevels = 6, FinestLevel = 0, Iterations = 5, WindowRadius = 4, MedianRadius = 2 }, + _ => throw new ArgumentOutOfRangeException(nameof(quality)), + }; +} + +/// +/// Dense optical flow by pyramidal Lucas–Kanade (Lucas & Kanade 1981; Bouguet 2000) solved for a window +/// around every pixel of each level: both frames get a σ = 1 binomial blur, box-window structure tensors of +/// the first frame's gradients are inverted once per level (inverse-compositional form), and each iteration +/// warps the second frame by the current flow (bilinear) and re-solves every window with a first-order +/// correction for its neighbours' flows; the field is median filtered between levels (Sun, Roth & Black +/// 2010). Chosen over Farnebäck polynomial expansion because every step is a separable box filter or a +/// per-pixel 2×2 solve that vectorises and parallelises cleanly, with equal sub-pixel accuracy on smooth +/// motion. Forward–backward consistency (Sundaram et al. 2010) marks occlusions. One engine holds reusable +/// workspaces, so it must not be shared between threads. +/// +public sealed class OpticalFlowEngine : IDisposable +{ + private const float MaxUpdate = 2f; + + private GrayPyramid? _first; + private GrayPyramid? _second; + private float[][] _work = []; + private int _capacity; + + public OpticalFlowEngine(OpticalFlowOptions? options = null) => Options = options ?? new OpticalFlowOptions(); + + public OpticalFlowEngine(FlowQuality quality) : this(OpticalFlowOptions.For(quality)) + { + } + + public OpticalFlowOptions Options { get; } + + /// Flow from to (perceptual luminance of both). + public MotionField Compute(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default) + { + BuildPyramids(from, to); + return Compute(_first!, _second!, cancellationToken); + } + + /// Flow between two prebuilt pyramids (lets callers reuse each frame's pyramid for two pairs). + public MotionField Compute(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default) + { + if (from.Width != to.Width || from.Height != to.Height || from.Levels != to.Levels) + throw new ArgumentException("Pyramids differ in size or depth.", nameof(to)); + var coarsest = int.Min(from.Levels, Options.MaxLevels) - 1; + var finest = int.Clamp(Options.FinestLevel, 0, coarsest); + EnsureWorkspace(from.LevelWidth(finest) * from.LevelHeight(finest)); + + float[] u = _work[0], v = _work[1]; + for (var level = coarsest; level >= finest; level--) + { + cancellationToken.ThrowIfCancellationRequested(); + var w = from.LevelWidth(level); + var h = from.LevelHeight(level); + if (level == coarsest) + { + Array.Clear(u, 0, w * h); + Array.Clear(v, 0, w * h); + } + else + { + var (nu, nv) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]); + Upsample(u, nu, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h); + Upsample(v, nv, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h); + (u, v) = (nu, nv); + } + SolveLevel(from.LevelArray(level), to.LevelArray(level), w, h, u, v, cancellationToken); + } + + var step = 1 << finest; + var field = new MotionField(from.Width, from.Height, step); + var n = field.Count; + var fu = field.U; + var fv = field.V; + for (var i = 0; i < n; i++) + { + fu[i] = u[i] * step; + fv[i] = v[i] * step; + } + return field; + } + + /// Forward and backward flow with their forward–backward consistency errors filled in. + public (MotionField Forward, MotionField Backward) ComputeBidirectional(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default) + { + BuildPyramids(from, to); + return ComputeBidirectional(_first!, _second!, cancellationToken); + } + + /// + public (MotionField Forward, MotionField Backward) ComputeBidirectional(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default) + { + var forward = Compute(from, to, cancellationToken); + try + { + var backward = Compute(to, from, cancellationToken); + CheckConsistency(forward, backward); + return (forward, backward); + } + catch + { + forward.Dispose(); + throw; + } + } + + /// + /// Fills both fields' with |w(p) + w'(p + w(p))|; vectors leaving the + /// frame get +∞ (unverifiable, treated as occluded). + /// + public static void CheckConsistency(MotionField forward, MotionField backward) + { + if (forward.ImageWidth != backward.ImageWidth || forward.ImageHeight != backward.ImageHeight) + throw new ArgumentException("Fields describe different image sizes.", nameof(backward)); + Fill(forward, backward); + Fill(backward, forward); + forward.HasConsistency = backward.HasConsistency = true; + + static void Fill(MotionField field, MotionField other) + { + var u = field.U; + var v = field.V; + var error = field.Error; + var maxX = field.ImageWidth - 0.5; + var maxY = field.ImageHeight - 0.5; + for (var j = 0; j < field.Rows; j++) + { + for (var i = 0; i < field.Columns; i++) + { + var k = j * field.Columns + i; + var x = i * field.Step + (double)u[k]; + var y = j * field.Step + (double)v[k]; + if (x < -0.5 || y < -0.5 || x > maxX || y > maxY) + { + error[k] = float.PositiveInfinity; + continue; + } + var (bu, bv) = other.Sample(x, y); + error[k] = float.Hypot(u[k] + bu, v[k] + bv); + } + } + } + } + + public void Dispose() + { + _first?.Dispose(); + _second?.Dispose(); + _first = _second = null; + foreach (var a in _work) ArrayPool.Shared.Return(a); + _work = []; + _capacity = 0; + } + + private void BuildPyramids(ImageBuffer from, ImageBuffer to) + { + if (from.Width != to.Width || from.Height != to.Height) throw new ArgumentException("Frames differ in size.", nameof(to)); + if (_first is null || _first.Width != from.Width || _first.Height != from.Height) + { + _first?.Dispose(); + _second?.Dispose(); + var levels = GrayPyramid.LevelsFor(from.Width, from.Height, 16, Options.MaxLevels); + _first = new GrayPyramid(from.Width, from.Height, levels); + _second = new GrayPyramid(from.Width, from.Height, levels); + } + _first.Build(from); + _second!.Build(to); + } + + private void EnsureWorkspace(int length) + { + if (length <= _capacity) return; + foreach (var a in _work) ArrayPool.Shared.Return(a); + // u, v, u', v', Ix, Iy, H11, H12, H22, Bx, By, scratch, smoothed first, smoothed second. + _work = new float[14][]; + for (var i = 0; i < _work.Length; i++) _work[i] = ArrayPool.Shared.Rent(length); + _capacity = length; + } + + private void SolveLevel(float[] i0, float[] i1, int w, int h, float[] u, float[] v, CancellationToken cancellationToken) + { + var (spareU, spareV) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]); + float[] ix = _work[4], iy = _work[5], h11 = _work[6], h12 = _work[7], h22 = _work[8], bx = _work[9], by = _work[10], scratch = _work[11]; + var radius = Options.WindowRadius; + var lambda = Options.Regularization; + + // Central differences under-estimate high-frequency derivatives relative to how the bilinearly warped + // frame responds to a flow change (ratio 1/cos πf), which over-shoots the Gauss–Newton step beyond 2× + // above f ≈ 1/3 cycles/px and makes the iteration diverge. A σ = 1 blur of both frames removes that + // band; being the same translation-invariant filter on both, it does not bias the solution. + PlaneOps.Binomial5(i0, _work[12], scratch, w, h); + PlaneOps.Binomial5(i1, _work[13], scratch, w, h); + i0 = _work[12]; + i1 = _work[13]; + + // Gradients of the first frame and their structure-tensor products. + PlaneOps.ForRows(h, w, y => + { + var row = y * w; + var up = int.Max(y - 1, 0) * w; + var down = int.Min(y + 1, h - 1) * w; + for (var x = 0; x < w; x++) + { + var gx = 0.5f * (i0[row + int.Min(x + 1, w - 1)] - i0[row + int.Max(x - 1, 0)]); + var gy = 0.5f * (i0[down + x] - i0[up + x]); + ix[row + x] = gx; + iy[row + x] = gy; + h11[row + x] = gx * gx; + h12[row + x] = gx * gy; + h22[row + x] = gy * gy; + } + }); + PlaneOps.BoxFilter(h11, h11, scratch, w, h, radius); + PlaneOps.BoxFilter(h12, h12, scratch, w, h, radius); + PlaneOps.BoxFilter(h22, h22, scratch, w, h, radius); + PlaneOps.ForRows(h, w, y => + { + for (int x = 0, k = y * w; x < w; x++, k++) + { + var a = h11[k] + lambda; + var b = h12[k]; + var c = h22[k] + lambda; + var r = 1f / (a * c - b * b); + h11[k] = c * r; + h12[k] = -b * r; + h22[k] = a * r; + } + }); + + for (var iteration = 0; iteration < Options.Iterations; iteration++) + { + cancellationToken.ThrowIfCancellationRequested(); + // Each window solves for one flow v: min Σ_y (I1w(y) + g(y)·(v − u(y)) − I0(y))², i.e. the classic + // Lucas–Kanade window with a first-order correction for the neighbours' own flows. Unlike the + // per-pixel update u −= G⁻¹·box(g·It), this does not feed the current error back through + // ill-conditioned (aperture) windows, so it cannot diverge. Samples warped outside the frame + // vote for their current flow (It = 0). + PlaneOps.ForRows(h, w, y => + { + var span = i1.AsSpan(0, w * h); + for (int x = 0, k = y * w; x < w; x++, k++) + { + var px = x + u[k]; + var py = y + v[k]; + var it = px >= 0 && py >= 0 && px <= w - 1 && py <= h - 1 + ? PlaneOps.Bilinear(span, w, h, px, py) - i0[k] + : 0f; + var r = ix[k] * u[k] + iy[k] * v[k] - it; + bx[k] = ix[k] * r; + by[k] = iy[k] * r; + } + }); + PlaneOps.BoxFilter(bx, bx, scratch, w, h, radius); + PlaneOps.BoxFilter(by, by, scratch, w, h, radius); + PlaneOps.ForRows(h, w, y => + { + for (int x = 0, k = y * w; x < w; x++, k++) + { + // (G + λI)⁻¹ (box(q) + λu): the regulariser keeps textureless windows at their current flow. + var qx = bx[k] + lambda * u[k]; + var qy = by[k] + lambda * v[k]; + var nu = h11[k] * qx + h12[k] * qy; + var nv = h12[k] * qx + h22[k] * qy; + u[k] += float.Clamp(nu - u[k], -MaxUpdate, MaxUpdate); + v[k] += float.Clamp(nv - v[k], -MaxUpdate, MaxUpdate); + } + }); + } + + if (Options.MedianRadius > 0) + { + PlaneOps.MedianFilter(u, spareU, w, h, Options.MedianRadius); + PlaneOps.MedianFilter(v, spareV, w, h, Options.MedianRadius); + Array.Copy(spareU, u, w * h); + Array.Copy(spareV, v, w * h); + } + } + + /// Doubles the resolution and the magnitude of a level's flow (level-ℓ pixel k ↔ level-(ℓ−1) pixel 2k). + private static void Upsample(float[] coarse, float[] fine, int cw, int ch, int w, int h) + { + PlaneOps.ForRows(h, w, y => + { + var span = coarse.AsSpan(0, cw * ch); + for (var x = 0; x < w; x++) fine[y * w + x] = 2 * PlaneOps.Bilinear(span, cw, ch, 0.5f * x, 0.5f * y); + }); + } +} diff --git a/src/Titano.Core/Motion/PlaneOps.cs b/src/Titano.Core/Motion/PlaneOps.cs new file mode 100644 index 00000000..b93b65ef --- /dev/null +++ b/src/Titano.Core/Motion/PlaneOps.cs @@ -0,0 +1,222 @@ +using System.Numerics; +using System.Runtime.CompilerServices; +using Titano.Core.Imaging; + +namespace Titano.Core.Motion; + +/// Row-parallel kernels on single-channel float planes shared by the motion modules. +internal static class PlaneOps +{ + /// Below this many pixels per pass the Parallel.For overhead outweighs the work. + public const int ParallelThreshold = 1 << 15; + + /// Runs for every row, in parallel when the plane is large. + public static void ForRows(int height, int width, Action body) + { + if ((long)height * width < ParallelThreshold) + { + for (var y = 0; y < height; y++) body(y); + } + else + { + Parallel.For(0, height, body); + } + } + + /// + /// Perceptually uniform luminance (sRGB-encoded Rec.709 Y, 0..1). Motion estimation works on it so that + /// shadows carry texture weight comparable to highlights, unlike linear light. + /// + public static void PerceptualLuminance(ImageBuffer image, Span destination) + { + ColorSpace.Luminance(image, destination); + for (var i = 0; i < destination.Length; i++) destination[i] = ColorSpace.EncodeFast(destination[i]); + } + + /// Bilinear sample with edge clamping at pixel-centre coordinates. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Bilinear(ReadOnlySpan plane, int width, int height, float x, float y) + { + x = float.Clamp(x, 0, width - 1); + y = float.Clamp(y, 0, height - 1); + var x0 = int.Min((int)x, width - 2 < 0 ? 0 : width - 2); + var y0 = int.Min((int)y, height - 2 < 0 ? 0 : height - 2); + var fx = x - x0; + var fy = y - y0; + var x1 = int.Min(x0 + 1, width - 1); + var y1 = int.Min(y0 + 1, height - 1); + var r0 = y0 * width; + var r1 = y1 * width; + var top = plane[r0 + x0] + (plane[r0 + x1] - plane[r0 + x0]) * fx; + var bottom = plane[r1 + x0] + (plane[r1 + x1] - plane[r1 + x0]) * fx; + return top + (bottom - top) * fy; + } + + /// + /// Mean over a (2r+1)² box with replicated edges, by running sums: horizontal pass per row, then a + /// vertical pass that keeps Vector<float> column sums for blocks of columns. + /// + public static void BoxFilter(float[] source, float[] destination, float[] scratch, int width, int height, int radius) + { + var inv = 1f / (2 * radius + 1); + ForRows(height, width, y => + { + var row = source.AsSpan(y * width, width); + var output = scratch.AsSpan(y * width, width); + float sum = 0; + for (var k = -radius; k <= radius; k++) sum += row[int.Clamp(k, 0, width - 1)]; + for (var x = 0; x < width; x++) + { + output[x] = sum * inv; + sum += row[int.Min(x + radius + 1, width - 1)] - row[int.Max(x - radius, 0)]; + } + }); + + const int Block = 256; + var blocks = (width + Block - 1) / Block; + void Columns(int b) + { + var x0 = b * Block; + var n = int.Min(Block, width - x0); + Span acc = stackalloc float[Block]; + acc = acc[..n]; + acc.Clear(); + for (var k = -radius; k <= radius; k++) Add(acc, scratch.AsSpan(int.Clamp(k, 0, height - 1) * width + x0, n), 1f); + for (var y = 0; y < height; y++) + { + Scale(acc, destination.AsSpan(y * width + x0, n), inv); + Add(acc, scratch.AsSpan(int.Min(y + radius + 1, height - 1) * width + x0, n), 1f); + Add(acc, scratch.AsSpan(int.Max(y - radius, 0) * width + x0, n), -1f); + } + } + if ((long)width * height < ParallelThreshold || blocks == 1) + { + for (var b = 0; b < blocks; b++) Columns(b); + } + else + { + Parallel.For(0, blocks, Columns); + } + } + + /// Separable 5-tap binomial [1 4 6 4 1]/16 blur (σ = 1 px) with replicated edges; may run in place. + public static void Binomial5(float[] source, float[] destination, float[] scratch, int width, int height) + { + ForRows(height, width, y => + { + var row = source.AsSpan(y * width, width); + var output = scratch.AsSpan(y * width, width); + var last = width - 1; + for (var x = 0; x < width; x++) + { + output[x] = (row[int.Max(x - 2, 0)] + row[int.Min(x + 2, last)] + + 4 * (row[int.Max(x - 1, 0)] + row[int.Min(x + 1, last)]) + 6 * row[x]) * (1f / 16); + } + }); + ForRows(height, width, y => + { + var last = height - 1; + var r0 = scratch.AsSpan(int.Max(y - 2, 0) * width, width); + var r1 = scratch.AsSpan(int.Max(y - 1, 0) * width, width); + var r2 = scratch.AsSpan(y * width, width); + var r3 = scratch.AsSpan(int.Min(y + 1, last) * width, width); + var r4 = scratch.AsSpan(int.Min(y + 2, last) * width, width); + var output = destination.AsSpan(y * width, width); + var i = 0; + if (Vector.IsHardwareAccelerated) + { + for (; i <= width - Vector.Count; i += Vector.Count) + { + var sum = new Vector(r0[i..]) + new Vector(r4[i..]) + + 4 * (new Vector(r1[i..]) + new Vector(r3[i..])) + + 6 * new Vector(r2[i..]); + (sum * (1f / 16)).CopyTo(output[i..]); + } + } + for (; i < width; i++) output[i] = (r0[i] + r4[i] + 4 * (r1[i] + r3[i]) + 6 * r2[i]) * (1f / 16); + }); + } + + /// Median over a (2r+1)² window with replicated edges. + public static void MedianFilter(float[] source, float[] destination, int width, int height, int radius) + { + ForRows(height, width, y => + { + var size = 2 * radius + 1; + Span window = stackalloc float[size * size]; + for (var x = 0; x < width; x++) + { + var n = 0; + for (var dy = -radius; dy <= radius; dy++) + { + var row = int.Clamp(y + dy, 0, height - 1) * width; + for (var dx = -radius; dx <= radius; dx++) window[n++] = source[row + int.Clamp(x + dx, 0, width - 1)]; + } + destination[y * width + x] = Select(window, n / 2); + } + }); + } + + /// Exact median (mean of the two middle values for even counts); reorders . + public static float Median(Span values) + { + var n = values.Length; + var upper = Select(values, n / 2); + if ((n & 1) != 0) return upper; + // After selection everything left of n/2 is ≤ upper: the lower middle is their maximum. + var lower = values[0]; + for (var i = 1; i < n / 2; i++) lower = float.Max(lower, values[i]); + return 0.5f * (lower + upper); + } + + /// k-th smallest value by Wirth/Hoare selection (in place, O(n) expected). + public static float Select(Span values, int k) + { + int left = 0, right = values.Length - 1; + while (left < right) + { + var pivot = values[k]; + int i = left, j = right; + do + { + while (values[i] < pivot) i++; + while (pivot < values[j]) j--; + if (i <= j) + { + (values[i], values[j]) = (values[j], values[i]); + i++; + j--; + } + } + while (i <= j); + if (j < k) left = i; + if (k < i) right = j; + } + return values[k]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Add(Span acc, ReadOnlySpan row, float sign) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + var s = new Vector(sign); + for (; i <= acc.Length - Vector.Count; i += Vector.Count) + (new Vector(acc[i..]) + new Vector(row[i..]) * s).CopyTo(acc[i..]); + } + for (; i < acc.Length; i++) acc[i] += row[i] * sign; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Scale(ReadOnlySpan acc, Span output, float factor) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + for (; i <= acc.Length - Vector.Count; i += Vector.Count) + (new Vector(acc[i..]) * factor).CopyTo(output[i..]); + } + for (; i < acc.Length; i++) output[i] = acc[i] * factor; + } +} diff --git a/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs b/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs new file mode 100644 index 00000000..e9a0518d --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs @@ -0,0 +1,155 @@ +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class OpticalFlowTests +{ + private const int Base = 256; + private const int Frame = 192; + private const int Margin = 16; + + private readonly TestContext _context; + + public OpticalFlowTests(TestContext context) => _context = context; + + [Theory] + [Case(FlowQuality.Draft)] + [Case(FlowQuality.Balanced)] + [Case(FlowQuality.Best)] + public void TranslationEndPointErrorBelowAThirdOfAPixel(FlowQuality quality) + { + const double dx = 2.3, dy = -1.7; + var texture = SyntheticImages.Natural(Base, seed: 11); + using var a = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 32, 32, Frame, Frame), Frame, Frame); + using var b = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Shift(texture, Base, dx, dy), Base, 32, 32, Frame, Frame), Frame, Frame); + using var engine = new OpticalFlowEngine(quality); + using var field = engine.Compute(a, b); + var epe = MeanEndPointError(field, (_, _) => (dx, dy)); + _context.Log($"{quality}: step {field.Step}, mean EPE {epe:F4} px"); + Assert.Less(epe, 0.3); + } + + [Test] + public void RotationEndPointErrorBelowOnePixel() + { + var angle = 3.0 * double.Pi / 180; + var texture = SyntheticImages.Natural(Base, seed: 5); + using var baseImage = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 0, 0, Base, Base), Base, Base); + using var rotated = new ImageBuffer(Base, Base); + const double c = (Base - 1) / 2.0; + // rotated(x) = base(R⁻¹(x − c) + c): content turns by +angle about the centre. + GeometryStage.Warp(baseImage, rotated, Affine2D.About(Affine2D.Rotation(-angle), c, c)); + using var a = Crop(baseImage, 32); + using var b = Crop(rotated, 32); + using var engine = new OpticalFlowEngine(FlowQuality.Best); + using var field = engine.Compute(a, b); + var truth = Affine2D.About(Affine2D.Rotation(angle), c - 32, c - 32); + var epe = MeanEndPointError(field, (x, y) => + { + var (tx, ty) = truth.Apply(x, y); + return (tx - x, ty - y); + }); + _context.Log($"rotation 3°: mean EPE {epe:F4} px"); + Assert.Less(epe, 1.0); + } + + [Test] + public void ForwardBackwardErrorIsSmallForConsistentMotion() + { + var texture = SyntheticImages.Natural(Base, seed: 2); + using var a = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 32, 32, Frame, Frame), Frame, Frame); + using var b = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Shift(texture, Base, -1.5, 0.75), Base, 32, 32, Frame, Frame), Frame, Frame); + using var engine = new OpticalFlowEngine(FlowQuality.Balanced); + var (forward, backward) = engine.ComputeBidirectional(a, b); + using (forward) + using (backward) + { + Assert.True(forward.HasConsistency); + var stats = forward.Statistics(reliableError: 0.5); + _context.Log($"reliable {stats.ReliableFraction:P1}, mean |w| {stats.MeanMagnitude:F3}"); + Assert.Greater(stats.ReliableFraction, 0.85); + Assert.Approximately(1.677, stats.MedianMagnitude, 0.1); + Assert.Less(forward.SampleError(96, 96), 0.2); + var (bu, bv) = backward.Sample(96, 96); + Assert.Within(1.5, -0.75, bu, bv, 0.2); + } + } + + [Test] + public void FieldSamplingHistogramAndStatistics() + { + using var field = new MotionField(9, 5, 4); + Assert.Equal(3, field.Columns); + Assert.Equal(2, field.Rows); + for (var j = 0; j < field.Rows; j++) + for (var i = 0; i < field.Columns; i++) + { + field.U[j * field.Columns + i] = i; + field.V[j * field.Columns + i] = 2 * j; + } + var (u, v) = field.Sample(6, 2); + Assert.Approximately(1.5, u, 1e-6); + Assert.Approximately(1, v, 1e-6); + Assert.True(float.IsNaN(field.SampleError(0, 0))); + + field.Fill(3, 4); + var histogram = field.MagnitudeHistogram(10, 10); + Assert.Equal(6, histogram[5]); + Assert.Equal(6, field.MagnitudeHistogram(4, 2)[3]); + var stats = field.Statistics(); + Assert.Approximately(5, stats.MeanMagnitude, 1e-6); + Assert.Approximately(5, stats.P95Magnitude, 1e-6); + Assert.Approximately(3, stats.MeanU, 1e-6); + Assert.Equal(1.0, stats.ReliableFraction); + } + + [Test] + public void PyramidLevelsHalveAndPreserveMean() + { + var texture = SyntheticImages.Crop(SyntheticImages.Noise(Base, 1.5, seed: 8), Base, 0, 0, 101, 75); + using var pyramid = new GrayPyramid(101, 75, GrayPyramid.LevelsFor(101, 75)); + Assert.Equal(3, pyramid.Levels); + pyramid.Build(texture); + Assert.Equal(51, pyramid.LevelWidth(1)); + Assert.Equal(38, pyramid.LevelHeight(1)); + Assert.Equal(26, pyramid.LevelWidth(2)); + var mean0 = pyramid.Level(0).ToArray().Average(); + var mean2 = pyramid.Level(2).ToArray().Average(); + Assert.Approximately(mean0, mean2, 0.02); + + var flat = new float[64 * 64]; + flat.AsSpan().Fill(0.25f); + using var constant = new GrayPyramid(64, 64, 3); + constant.Build(flat); + Assert.True(constant.Level(2).ToArray().All(x => x == 0.25f)); + } + + private static double MeanEndPointError(MotionField field, Func truth) + { + double sum = 0; + var n = 0; + for (var j = 0; j < field.Rows; j++) + { + for (var i = 0; i < field.Columns; i++) + { + double x = i * field.Step, y = j * field.Step; + if (x < Margin || y < Margin || x >= Frame - Margin || y >= Frame - Margin) continue; + var (tu, tv) = truth(x, y); + var k = j * field.Columns + i; + sum += double.Hypot(field.U[k] - tu, field.V[k] - tv); + n++; + } + } + return sum / n; + } + + private static ImageBuffer Crop(ImageBuffer source, int offset) + { + var crop = new ImageBuffer(Frame, Frame); + GeometryStage.Warp(source, crop, Affine2D.Translation(offset, offset)); + return crop; + } +} From e3d3e3c72904d375209a94628b9ce48de63ad5e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:30:30 +0000 Subject: [PATCH 007/188] feat(motion): add gather-filter motion blur with shutter-angle composition ShutterAngle computes the real angle from exposure and interval and the blur fraction sqrt(target^2 - real^2)/360 (zero once the real angle reaches the target). MotionBlurRenderer averages bilinear taps along each pixel's motion vector with a tap count adaptive to the length. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/MotionBlurRenderer.cs | 143 ++++++++++++++++++ .../Motion/MotionBlurTests.cs | 105 +++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 src/Titano.Core/Motion/MotionBlurRenderer.cs create mode 100644 tests/Titano.Core.Tests/Motion/MotionBlurTests.cs diff --git a/src/Titano.Core/Motion/MotionBlurRenderer.cs b/src/Titano.Core/Motion/MotionBlurRenderer.cs new file mode 100644 index 00000000..af4f9bf2 --- /dev/null +++ b/src/Titano.Core/Motion/MotionBlurRenderer.cs @@ -0,0 +1,143 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Motion; + +/// Shutter-angle arithmetic for synthetic motion blur. +public static class ShutterAngle +{ + /// Shutter angle actually used by the camera, 360° × exposure / interval. + public static double FromExposure(double exposureSeconds, double intervalSeconds) + { + ArgumentOutOfRangeException.ThrowIfNegative(exposureSeconds); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(intervalSeconds); + return 360.0 * exposureSeconds / intervalSeconds; + } + + /// + /// Fraction of the frame-to-frame motion to smear so that the real exposure composed with the synthetic + /// blur behaves like the target shutter: √(target² − real²) / 360, and 0 when the real angle already + /// reaches the target (the blur would only be added on top of blur that is already there). + /// + public static double BlurFraction(double targetDegrees, double realDegrees) + { + ArgumentOutOfRangeException.ThrowIfNegative(targetDegrees); + ArgumentOutOfRangeException.ThrowIfNegative(realDegrees); + if (realDegrees >= targetDegrees) return 0; + return double.Sqrt(targetDegrees * targetDegrees - realDegrees * realDegrees) / 360.0; + } +} + +/// Tuning for . +public sealed record MotionBlurOptions +{ + /// Samples per pixel of blur length (≥ 1 keeps the bilinear taps overlapping). + public double TapsPerPixel { get; init; } = 1.0; + + /// Upper bound on samples per pixel. + public int MaxTaps { get; init; } = 64; +} + +/// +/// Motion blur by a gather filter: every output pixel averages bilinear samples of the source along a +/// segment centred on it, oriented by its motion vector and as long as the vector times the blur fraction +/// (a box shutter: uniform weights, tap count adaptive to the length). Equal weights and bilinear taps +/// preserve energy; zero vectors copy the pixel. Rows run in parallel. +/// +public sealed class MotionBlurRenderer +{ + private const double MinimumLength = 1e-3; + + public MotionBlurRenderer(MotionBlurOptions? options = null) + { + Options = options ?? new MotionBlurOptions(); + ArgumentOutOfRangeException.ThrowIfLessThan(Options.TapsPerPixel, 0.25); + ArgumentOutOfRangeException.ThrowIfLessThan(Options.MaxTaps, 2); + } + + public MotionBlurOptions Options { get; } + + /// + /// Renders blurred along (frame-to-frame vectors) + /// scaled by (see ). + /// + public void Render(ImageBuffer source, MotionField motion, double blurFraction, ImageBuffer destination, CancellationToken cancellationToken = default) + { + if (destination.Width != source.Width || destination.Height != source.Height || destination.Channels != source.Channels) + throw new ArgumentException("Destination must match the source.", nameof(destination)); + if (motion.ImageWidth != source.Width || motion.ImageHeight != source.Height) + throw new ArgumentException("Motion field describes a different image size.", nameof(motion)); + ArgumentOutOfRangeException.ThrowIfNegative(blurFraction); + if (blurFraction == 0) + { + source.CopyTo(destination); + return; + } + + var w = source.Width; + var h = source.Height; + var channels = source.Channels; + var plane = source.PlaneLength; + var src = source.Storage; + var dst = destination.Storage; + var tapsPerPixel = Options.TapsPerPixel; + var maxTaps = Options.MaxTaps; + + void Row(int y) + { + Span sum = stackalloc float[4]; + for (var x = 0; x < w; x++) + { + var o = y * w + x; + var (mu, mv) = motion.Sample(x, y); + var du = mu * blurFraction; + var dv = mv * blurFraction; + var length = double.Sqrt(du * du + dv * dv); + if (length < MinimumLength) + { + for (var c = 0; c < channels; c++) dst[c * plane + o] = src[c * plane + o]; + continue; + } + + var taps = int.Clamp((int)double.Ceiling(length * tapsPerPixel) + 1, 2, maxTaps); + sum.Clear(); + for (var k = 0; k < taps; k++) + { + var t = k / (double)(taps - 1) - 0.5; + var sx = double.Clamp(x + t * du, 0, w - 1); + var sy = double.Clamp(y + t * dv, 0, h - 1); + var x0 = int.Min((int)sx, int.Max(w - 2, 0)); + var y0 = int.Min((int)sy, int.Max(h - 2, 0)); + var x1 = int.Min(x0 + 1, w - 1); + var y1 = int.Min(y0 + 1, h - 1); + var fx = (float)(sx - x0); + var fy = (float)(sy - y0); + var w00 = (1 - fx) * (1 - fy); + var w10 = fx * (1 - fy); + var w01 = (1 - fx) * fy; + var w11 = fx * fy; + int i00 = y0 * w + x0, i10 = y0 * w + x1, i01 = y1 * w + x0, i11 = y1 * w + x1; + for (var c = 0; c < channels; c++) + { + var p = c * plane; + sum[c] += w00 * src[p + i00] + w10 * src[p + i10] + w01 * src[p + i01] + w11 * src[p + i11]; + } + } + var inv = 1f / taps; + for (var c = 0; c < channels; c++) dst[c * plane + o] = sum[c] * inv; + } + } + + if ((long)w * h < PlaneOps.ParallelThreshold) + { + for (var y = 0; y < h; y++) + { + cancellationToken.ThrowIfCancellationRequested(); + Row(y); + } + } + else + { + Parallel.For(0, h, new ParallelOptions { CancellationToken = cancellationToken }, Row); + } + } +} diff --git a/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs new file mode 100644 index 00000000..96c94d7e --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs @@ -0,0 +1,105 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class MotionBlurTests +{ + private const int Size = 128; + + [Theory] + [Case(180.0, 90.0, 0.4330127018922193)] + [Case(180.0, 0.0, 0.5)] + [Case(360.0, 0.0, 1.0)] + [Case(180.0, 180.0, 0.0)] + [Case(180.0, 270.0, 0.0)] + [Case(90.0, 54.0, 0.2)] + public void BlurFractionComposesShutterAngles(double target, double real, double expected) => + Assert.Approximately(expected, ShutterAngle.BlurFraction(target, real), 1e-12); + + [Test] + public void RealShutterAngleFromExposure() + { + Assert.Approximately(180, ShutterAngle.FromExposure(1, 2), 1e-12); + Assert.Approximately(3.6, ShutterAngle.FromExposure(1 / 250.0, 0.4), 1e-12); + } + + [Test] + public void ZeroVectorsLeaveTheImageIdentical() + { + using var source = Texture(); + using var motion = new MotionField(Size, Size, 2); + using var output = new ImageBuffer(Size, Size); + new MotionBlurRenderer().Render(source, motion, 0.5, output); + Assert.True(source.Data.SequenceEqual(output.Data)); + } + + [Test] + public void PointBlursIntoASegmentWithItsEnergy() + { + using var source = new ImageBuffer(Size, Size, 1); + source[0, 64, 64] = 1f; + using var motion = new MotionField(Size, Size, 4); + motion.Fill(20, 0); + using var output = new ImageBuffer(Size, Size, 1); + new MotionBlurRenderer().Render(source, motion, 0.5, output); + + double total = 0; + var columns = new HashSet(); + for (var y = 0; y < Size; y++) + { + for (var x = 0; x < Size; x++) + { + var value = output[0, x, y]; + total += value; + if (value <= 1e-6f) continue; + Assert.Equal(64, y); + columns.Add(x); + } + } + Assert.Approximately(1, total, 1e-4); + Assert.InRange(columns.Min(), 58, 60); + Assert.InRange(columns.Max(), 68, 70); + } + + [Test] + public void EnergyIsPreservedOnTexture() + { + using var source = Texture(); + using var motion = new MotionField(Size, Size, 2); + for (var j = 0; j < motion.Rows; j++) + for (var i = 0; i < motion.Columns; i++) + { + // A smooth swirl: magnitude up to ~6 px. + var k = j * motion.Columns + i; + motion.U[k] = (float)(6 * double.Sin(j * 0.1)); + motion.V[k] = (float)(4 * double.Cos(i * 0.08)); + } + using var output = new ImageBuffer(Size, Size); + new MotionBlurRenderer().Render(source, motion, 1.0, output); + for (var c = 0; c < 3; c++) + { + var before = Mean(source.Plane(c), 16); + var after = Mean(output.Plane(c), 16); + Assert.Approximately(before, after, 2e-3 * before); + } + Assert.False(source.Data.SequenceEqual(output.Data)); + } + + private static double Mean(ReadOnlySpan plane, int margin) + { + double sum = 0; + var n = 0; + for (var y = margin; y < Size - margin; y++) + for (var x = margin; x < Size - margin; x++) + { + sum += plane[y * Size + x]; + n++; + } + return sum / n; + } + + private static ImageBuffer Texture() => + SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Natural(Size, seed: 31), Size, 0, 0, Size, Size), Size, Size); +} From e2b0f8eb5cdb26873b53c43c8bfca9dc24df8773 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH 008/188] feat(math): add robust statistics helpers Linear-time selection, median, MAD, trimmed mean, type-7 and weighted percentiles, histogram helpers, Tukey resistant line + IRLS biweight fit and sample autocorrelation. Namespace Titano.Core.Mathematics: a Titano.Core.Math namespace would shadow System.Math in every Titano.Core file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/Statistics.cs | 417 ++++++++++++++++++ .../Titano.Core.Tests/Math/StatisticsTests.cs | 127 ++++++ 2 files changed, 544 insertions(+) create mode 100644 src/Titano.Core/Math/Statistics.cs create mode 100644 tests/Titano.Core.Tests/Math/StatisticsTests.cs diff --git a/src/Titano.Core/Math/Statistics.cs b/src/Titano.Core/Math/Statistics.cs new file mode 100644 index 00000000..587aefa6 --- /dev/null +++ b/src/Titano.Core/Math/Statistics.cs @@ -0,0 +1,417 @@ +using System.Buffers; +using System.Numerics; + +namespace Titano.Core.Mathematics; + +/// A robustly fitted straight line y = Intercept + Slope·x. +/// Robust residual standard deviation (1.4826 × MAD of the final residuals). +public readonly record struct RobustLine(double Slope, double Intercept, double Scale) +{ + public double Evaluate(double x) => Intercept + Slope * x; +} + +/// +/// Order statistics and robust estimators. Every function ignores NaN inputs and returns NaN when no +/// valid value remains. Selection is linear-time (quickselect with an introsort fallback). +/// +public static class Statistics +{ + /// Scales a median absolute deviation to the standard deviation of a normal distribution (1/Φ⁻¹(3/4)). + public const double MadToSigma = 1.482602218505602; + + /// + /// Rearranges so that values[k] is the k-th smallest, everything before it is + /// ≤ and everything after is ≥ (Hoare quickselect, median-of-three pivot; falls back to sorting the + /// remaining range after too many unbalanced rounds, so the worst case is O(n log n)). NaN-free input. + /// + public static double Select(Span values, int k) + { + if ((uint)k >= (uint)values.Length) throw new ArgumentOutOfRangeException(nameof(k)); + int lo = 0, hi = values.Length - 1; + var budget = 2 * BitOperations.Log2((uint)values.Length) + 4; + while (hi > lo) + { + if (hi - lo < 16 || --budget < 0) + { + values.Slice(lo, hi - lo + 1).Sort(); + return values[k]; + } + var mid = lo + ((hi - lo) >> 1); + if (values[mid] < values[lo]) (values[mid], values[lo]) = (values[lo], values[mid]); + if (values[hi] < values[lo]) (values[hi], values[lo]) = (values[lo], values[hi]); + if (values[hi] < values[mid]) (values[hi], values[mid]) = (values[mid], values[hi]); + var pivot = values[mid]; + int i = lo, j = hi; + while (i <= j) + { + while (values[i] < pivot) i++; + while (values[j] > pivot) j--; + if (i <= j) + { + (values[i], values[j]) = (values[j], values[i]); + i++; + j--; + } + } + if (k <= j) hi = j; + else if (k >= i) lo = i; + else return values[k]; + } + return values[k]; + } + + public static double Mean(ReadOnlySpan values) + { + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += v; + n++; + } + return n == 0 ? double.NaN : sum / n; + } + + /// Root mean square of the valid values. + public static double Rms(ReadOnlySpan values) + { + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += v * v; + n++; + } + return n == 0 ? double.NaN : Math.Sqrt(sum / n); + } + + /// Sample standard deviation (n − 1 denominator) of the valid values. + public static double StandardDeviation(ReadOnlySpan values) + { + var mean = Mean(values); + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += (v - mean) * (v - mean); + n++; + } + return n < 2 ? double.NaN : Math.Sqrt(sum / (n - 1)); + } + + public static double Median(ReadOnlySpan values) + { + var buffer = RentValid(values, out var n); + try + { + return n == 0 ? double.NaN : MedianInPlace(buffer.AsSpan(0, n)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Median of NaN-free , reordering them. + public static double MedianInPlace(Span values) + { + var n = values.Length; + if (n == 0) return double.NaN; + var upper = Select(values, n / 2); + if ((n & 1) == 1) return upper; + var lower = double.NegativeInfinity; + foreach (var v in values[..(n / 2)]) lower = Math.Max(lower, v); + return 0.5 * (lower + upper); + } + + /// Raw median absolute deviation about (the median when omitted). + /// Multiply by for a normal-consistent scale. + public static double MedianAbsoluteDeviation(ReadOnlySpan values, double? center = null) + { + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var c = center ?? MedianInPlace(span); + for (var i = 0; i < n; i++) span[i] = Math.Abs(span[i] - c); + return MedianInPlace(span); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Mean after discarding the lowest and highest + /// of the valid values (counts rounded down), in linear time. + public static double TrimmedMean(ReadOnlySpan values, double lowFraction, double highFraction) + { + if (!(lowFraction >= 0 && highFraction >= 0 && lowFraction + highFraction < 1)) + throw new ArgumentOutOfRangeException(nameof(lowFraction), "Fractions must be ≥ 0 and sum below 1."); + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var low = (int)(n * lowFraction); + var keep = n - low - (int)(n * highFraction); + if (keep <= 0) return MedianInPlace(span); + if (low > 0) Select(span, low); + var rest = span[low..]; + if (keep < rest.Length) Select(rest, keep - 1); + double sum = 0; + foreach (var v in rest[..keep]) sum += v; + return sum / keep; + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Percentile ∈ [0, 1] with linear interpolation between order statistics + /// (Hyndman–Fan type 7, the spreadsheet/NumPy default). + public static double Percentile(ReadOnlySpan values, double p) + { + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var h = (n - 1) * p; + var lo = (int)Math.Floor(h); + var a = Select(span, lo); + if (lo + 1 >= n || h == lo) return a; + var b = double.PositiveInfinity; + foreach (var v in span[(lo + 1)..]) b = Math.Min(b, v); + return a + (h - lo) * (b - a); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Weighted percentile: each value occupies a share of the cumulative weight and is placed at the centre + /// of its share; results interpolate linearly between centres and clamp outside them. Values with NaN or + /// non-positive weight are ignored. Equal weights reproduce the Hazen (type 5) percentile. + /// + public static double WeightedPercentile(ReadOnlySpan values, ReadOnlySpan weights, double p) + { + if (values.Length != weights.Length) throw new ArgumentException("Lengths differ.", nameof(weights)); + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + var keys = new List(values.Length); + var w = new List(values.Length); + for (var i = 0; i < values.Length; i++) + { + if (double.IsNaN(values[i]) || !(weights[i] > 0) || double.IsInfinity(weights[i])) continue; + keys.Add(values[i]); + w.Add(weights[i]); + } + var n = keys.Count; + if (n == 0) return double.NaN; + var k = keys.ToArray(); + var ww = w.ToArray(); + Array.Sort(k, ww); + double total = 0; + foreach (var x in ww) total += x; + var target = p * total; + double cumulative = 0; + var previousCentre = 0.0; + for (var i = 0; i < n; i++) + { + var centre = cumulative + 0.5 * ww[i]; + if (target <= centre) + { + if (i == 0) return k[0]; + var t = (target - previousCentre) / (centre - previousCentre); + return k[i - 1] + t * (k[i] - k[i - 1]); + } + previousCentre = centre; + cumulative += ww[i]; + } + return k[n - 1]; + } + + /// Accumulates (optionally weighted) into equal-width bins over + /// [, ); values outside are clamped into the end bins. + public static void AccumulateHistogram(ReadOnlySpan values, double min, double max, Span bins, ReadOnlySpan weights = default) + { + if (!(max > min)) throw new ArgumentOutOfRangeException(nameof(max)); + if (bins.IsEmpty) throw new ArgumentException("No bins.", nameof(bins)); + if (!weights.IsEmpty && weights.Length != values.Length) throw new ArgumentException("Lengths differ.", nameof(weights)); + var scale = bins.Length / (max - min); + var last = bins.Length - 1; + for (var i = 0; i < values.Length; i++) + { + var v = values[i]; + if (double.IsNaN(v)) continue; + var b = (v - min) * scale; + var index = b <= 0 ? 0 : b >= last ? last : (int)b; + bins[index] += weights.IsEmpty ? 1 : weights[i]; + } + } + + /// Percentile of a histogram over [, ), interpolating + /// linearly inside the bin that contains the target mass. + public static double HistogramPercentile(ReadOnlySpan bins, double min, double max, double p) + { + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + double total = 0; + foreach (var b in bins) total += b; + if (!(total > 0)) return double.NaN; + var width = (max - min) / bins.Length; + var target = p * total; + double cumulative = 0; + for (var i = 0; i < bins.Length; i++) + { + if (bins[i] <= 0) continue; + if (cumulative + bins[i] >= target) + return min + width * (i + (target - cumulative) / bins[i]); + cumulative += bins[i]; + } + return max; + } + + /// Symmetric chi-square distance ½·Σ (aᵢ − bᵢ)² / (aᵢ + bᵢ) between two histograms normalised to unit mass + /// (0 = identical, 1 = disjoint). + public static double ChiSquareDistance(ReadOnlySpan a, ReadOnlySpan b) + { + if (a.Length != b.Length) throw new ArgumentException("Lengths differ.", nameof(b)); + double sa = 0, sb = 0; + for (var i = 0; i < a.Length; i++) + { + sa += a[i]; + sb += b[i]; + } + if (!(sa > 0) || !(sb > 0)) return sa > 0 || sb > 0 ? 1 : 0; + double d = 0; + for (var i = 0; i < a.Length; i++) + { + var x = a[i] / sa; + var y = b[i] / sb; + var s = x + y; + if (s > 0) d += (x - y) * (x - y) / s; + } + return 0.5 * d; + } + + /// + /// Robust straight-line fit: Tukey's resistant line (medians of the outer thirds) as the start, then + /// iteratively reweighted least squares with Tukey biweights on residuals scaled by 6·MAD. + /// Pairs with a NaN coordinate are ignored. + /// + public static RobustLine RobustLinearFit(ReadOnlySpan x, ReadOnlySpan y, int iterations = 10) + { + if (x.Length != y.Length) throw new ArgumentException("Lengths differ.", nameof(y)); + var px = new List(x.Length); + var py = new List(x.Length); + for (var i = 0; i < x.Length; i++) + { + if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) continue; + px.Add(x[i]); + py.Add(y[i]); + } + var n = px.Count; + if (n == 0) return new RobustLine(0, double.NaN, double.NaN); + var xs = px.ToArray(); + var ys = py.ToArray(); + Array.Sort(xs, ys); + if (n < 3 || xs[^1] == xs[0]) + { + var c = Median(ys); + return new RobustLine(0, c, MadToSigma * MedianAbsoluteDeviation(ys, c)); + } + + var third = Math.Max(1, n / 3); + var xl = Median(xs.AsSpan(0, third)); + var xr = Median(xs.AsSpan(n - third)); + var slope = xr > xl ? (Median(ys.AsSpan(n - third)) - Median(ys.AsSpan(0, third))) / (xr - xl) : 0; + var residual = new double[n]; + for (var i = 0; i < n; i++) residual[i] = ys[i] - slope * xs[i]; + var intercept = Median(residual); + + var scaleFloor = 1e-12 * (1 + Math.Abs(Median(ys))); + for (var iteration = 0; iteration < iterations; iteration++) + { + for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i]; + var mad = MedianAbsoluteDeviation(residual, 0); + if (!(mad > scaleFloor)) break; + var c = 6 * mad; + double sw = 0, swx = 0, swy = 0, swxx = 0, swxy = 0; + for (var i = 0; i < n; i++) + { + var u = residual[i] / c; + if (Math.Abs(u) >= 1) continue; + var w = (1 - u * u) * (1 - u * u); + sw += w; + swx += w * xs[i]; + swy += w * ys[i]; + swxx += w * xs[i] * xs[i]; + swxy += w * xs[i] * ys[i]; + } + if (!(sw > 0)) break; + var mx = swx / sw; + var sxx = swxx - sw * mx * mx; + if (!(sxx > 1e-300)) break; + var newSlope = (swxy - swx * swy / sw) / sxx; + var newIntercept = swy / sw - newSlope * mx; + var converged = Math.Abs(newSlope - slope) <= 1e-12 * (1 + Math.Abs(slope)) + && Math.Abs(newIntercept - intercept) <= 1e-12 * (1 + Math.Abs(intercept)); + slope = newSlope; + intercept = newIntercept; + if (converged) break; + } + for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i]; + return new RobustLine(slope, intercept, MadToSigma * MedianAbsoluteDeviation(residual, 0)); + } + + /// + /// Sample autocorrelation r(k) for k = 0 … result.Length − 1 (biased estimator normalised by the lag-0 + /// sum, so |r| ≤ 1). Pairs containing NaN are skipped. A constant series yields r(0) = 1 and 0 elsewhere. + /// + public static void Autocorrelation(ReadOnlySpan values, Span result) + { + result.Clear(); + if (result.IsEmpty) return; + var mean = Mean(values); + if (double.IsNaN(mean)) return; + double denominator = 0; + foreach (var v in values) + { + if (!double.IsNaN(v)) denominator += (v - mean) * (v - mean); + } + result[0] = 1; + if (!(denominator > 0)) return; + var maxLag = Math.Min(result.Length - 1, values.Length - 1); + for (var k = 1; k <= maxLag; k++) + { + double sum = 0; + for (var i = 0; i + k < values.Length; i++) + { + var a = values[i]; + var b = values[i + k]; + if (double.IsNaN(a) || double.IsNaN(b)) continue; + sum += (a - mean) * (b - mean); + } + result[k] = sum / denominator; + } + } + + private static double[] RentValid(ReadOnlySpan values, out int count) + { + var buffer = ArrayPool.Shared.Rent(Math.Max(1, values.Length)); + count = 0; + foreach (var v in values) + { + if (!double.IsNaN(v)) buffer[count++] = v; + } + return buffer; + } +} diff --git a/tests/Titano.Core.Tests/Math/StatisticsTests.cs b/tests/Titano.Core.Tests/Math/StatisticsTests.cs new file mode 100644 index 00000000..0161826b --- /dev/null +++ b/tests/Titano.Core.Tests/Math/StatisticsTests.cs @@ -0,0 +1,127 @@ +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +public sealed class StatisticsTests +{ + [Test] + public void SelectMatchesSortedOrderOnRandomInput() + { + var random = new Random(7); + for (var trial = 0; trial < 200; trial++) + { + var n = 1 + random.Next(300); + // Few distinct values exercise the equal-to-pivot path. + var values = Enumerable.Range(0, n).Select(_ => (double)random.Next(trial % 2 == 0 ? 5 : 1000)).ToArray(); + var sorted = values.OrderBy(v => v).ToArray(); + var k = random.Next(n); + var work = (double[])values.Clone(); + Assert.Equal(sorted[k], Statistics.Select(work, k)); + for (var i = 0; i < k; i++) Assert.True(work[i] <= work[k]); + for (var i = k + 1; i < n; i++) Assert.True(work[i] >= work[k]); + } + } + + [Test] + public void MedianHandlesOddEvenAndNaN() + { + Assert.Equal(3.0, Statistics.Median([5, 1, 3, double.NaN, 4, 2])); + Assert.Equal(2.5, Statistics.Median([4, 1, 3, 2])); + Assert.True(double.IsNaN(Statistics.Median([double.NaN]))); + Assert.True(double.IsNaN(Statistics.Median([]))); + } + + [Test] + public void MadAndTrimmedMean() + { + double[] values = [1, 2, 3, 4, 100]; + Assert.Equal(1.0, Statistics.MedianAbsoluteDeviation(values)); + Assert.Equal(3.0, Statistics.MedianAbsoluteDeviation(values, 0)); + // 20 % trimmed each side of 1..10 keeps 3..8. + var oneToTen = Enumerable.Range(1, 10).Select(i => (double)i).ToArray(); + Assert.Approximately(5.5, Statistics.TrimmedMean(oneToTen, 0.2, 0.2), 1e-12); + Assert.Approximately(2.5, Statistics.TrimmedMean([1, 2, 3, 4, 1000], 0, 0.2), 1e-12); + Assert.Throws(() => Statistics.TrimmedMean(values, 0.6, 0.4)); + } + + [Theory] + [Case(0.0, 1.0)] + [Case(0.25, 1.75)] + [Case(0.5, 2.5)] + [Case(1.0, 4.0)] + public void PercentileIsTypeSeven(double p, double expected) => + Assert.Approximately(expected, Statistics.Percentile([4, 2, 1, 3], p), 1e-12); + + [Test] + public void WeightedPercentileWithEqualWeightsIsHazen() + { + double[] v = [10, 20, 30, 40]; + double[] w = [1, 1, 1, 1]; + Assert.Approximately(25, Statistics.WeightedPercentile(v, w, 0.5), 1e-12); + Assert.Approximately(10, Statistics.WeightedPercentile(v, w, 0.1), 1e-12); + Assert.Approximately(40, Statistics.WeightedPercentile(v, w, 0.95), 1e-12); + // A heavy weight drags the median towards its value: centres 0.5, 1.5, 2.5, 8 of 13 → 30 + 10·4/5.5. + Assert.Approximately(30 + 40 / 5.5, Statistics.WeightedPercentile(v, [1, 1, 1, 10], 0.5), 1e-12); + Assert.Approximately(40, Statistics.WeightedPercentile(v, [1, 1, 1, 10], 0.7), 1e-12); + } + + [Test] + public void HistogramPercentileAndDistance() + { + var bins = new double[10]; + var values = Enumerable.Range(0, 1000).Select(i => i / 100.0).ToArray(); + Statistics.AccumulateHistogram(values, 0, 10, bins); + Assert.True(bins.All(b => b == 100)); + Assert.Approximately(5.0, Statistics.HistogramPercentile(bins, 0, 10, 0.5), 1e-12); + Assert.Approximately(0.0, Statistics.ChiSquareDistance(bins, bins), 1e-15); + Assert.Approximately(1.0, Statistics.ChiSquareDistance([1, 0], [0, 3]), 1e-15); + } + + [Test] + public void RobustLineIgnoresTwentyPercentOutliers() + { + var random = new Random(3); + var n = 200; + var x = new double[n]; + var y = new double[n]; + for (var i = 0; i < n; i++) + { + x[i] = i * 0.5; + y[i] = 2.0 + 0.75 * x[i] + 0.05 * (random.NextDouble() - 0.5); + if (i % 5 == 0) y[i] += 20 + 10 * random.NextDouble(); + } + var fit = Statistics.RobustLinearFit(x, y); + Assert.Approximately(0.75, fit.Slope, 0.002); + Assert.Approximately(2.0, fit.Intercept, 0.05); + Assert.Less(fit.Scale, 0.05); + } + + [Test] + public void AutocorrelationPeaksAtThePeriod() + { + var series = Enumerable.Range(0, 240).Select(i => Math.Sin(2 * Math.PI * i / 12)).ToArray(); + var r = new double[40]; + Statistics.Autocorrelation(series, r); + Assert.Equal(1.0, r[0]); + Assert.Less(r[6], -0.9); + Assert.Greater(r[12], 0.9); + Assert.True(r[12] > r[11] && r[12] > r[13]); + + Statistics.Autocorrelation([2, 2, 2, double.NaN, 2], r); + Assert.Equal(1.0, r[0]); + Assert.True(r.Skip(1).All(v => v == 0)); + } + + [Test] + public void RandomInputsAreDeterministicAndFinite() + { + var random = new Random(11); + var values = Enumerable.Range(0, 501).Select(_ => random.NextDouble() < 0.1 ? double.NaN : random.NextDouble() * 10 - 5).ToArray(); + double Run() => Statistics.Median(values) + Statistics.MedianAbsoluteDeviation(values) + Statistics.TrimmedMean(values, 0.02, 0.02) + + Statistics.Percentile(values, 0.9) + Statistics.Mean(values) + Statistics.StandardDeviation(values); + var first = Run(); + Assert.True(double.IsFinite(first)); + Assert.Equal(first, Run()); + } +} From 4f1902d2871ac466719ed138a9d2d8be5e59dc40 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH 009/188] feat(math): add monotone, natural, Catmull-Rom and Bezier splines Fritsch-Carlson monotone cubic Hermite (evaluate, derivative, inverse), natural cubic spline, Catmull-Rom with uniform/centripetal/chordal knots (Barry-Goldman pyramid) and cubic Bezier curves plus CSS-style easing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/CatmullRom.cs | 92 +++++++++ src/Titano.Core/Math/CubicBezier.cs | 95 +++++++++ src/Titano.Core/Math/MonotoneSpline.cs | 177 +++++++++++++++++ src/Titano.Core/Math/NaturalCubicSpline.cs | 88 +++++++++ src/Titano.Core/Math/Point2.cs | 19 ++ tests/Titano.Core.Tests/Math/SplineTests.cs | 202 ++++++++++++++++++++ 6 files changed, 673 insertions(+) create mode 100644 src/Titano.Core/Math/CatmullRom.cs create mode 100644 src/Titano.Core/Math/CubicBezier.cs create mode 100644 src/Titano.Core/Math/MonotoneSpline.cs create mode 100644 src/Titano.Core/Math/NaturalCubicSpline.cs create mode 100644 src/Titano.Core/Math/Point2.cs create mode 100644 tests/Titano.Core.Tests/Math/SplineTests.cs diff --git a/src/Titano.Core/Math/CatmullRom.cs b/src/Titano.Core/Math/CatmullRom.cs new file mode 100644 index 00000000..d0d4bd51 --- /dev/null +++ b/src/Titano.Core/Math/CatmullRom.cs @@ -0,0 +1,92 @@ +namespace Titano.Core.Mathematics; + +/// Knot spacing of a Catmull–Rom spline: |Pᵢ₊₁ − Pᵢ|^α with α = 0, ½ or 1. +public enum CatmullRomParameterization +{ + /// α = 0: the classic spline; can cusp or self-intersect on uneven spacing. + Uniform, + + /// α = ½: no cusps or self-intersections within a segment (Yuksel, Schaefer & Keyser 2011). + Centripetal, + + /// α = 1: follows the chord lengths; smoothest on evenly sampled paths. + Chordal, +} + +/// +/// Catmull–Rom interpolating splines evaluated with the Barry–Goldman pyramid, so non-uniform (centripetal, +/// chordal) knots are exact. The parameter t ∈ [0, n − 1] selects segment ⌊t⌋; end segments use reflected +/// phantom points (P₋₁ = 2P₀ − P₁). +/// +public static class CatmullRom +{ + /// Scalar spline through (values treated as 1-D points for the knot spacing). + public static double Evaluate(ReadOnlySpan values, double t, CatmullRomParameterization kind = CatmullRomParameterization.Uniform) + { + if (values.IsEmpty) throw new ArgumentException("No control values.", nameof(values)); + if (values.Length == 1) return values[0]; + var (i, u) = Segment(values.Length, t); + var p1 = values[i]; + var p2 = values[i + 1]; + var p0 = i > 0 ? values[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < values.Length ? values[i + 2] : 2 * p2 - p1; + return Pyramid(new Point2(p0, 0), new Point2(p1, 0), new Point2(p2, 0), new Point2(p3, 0), u, Alpha(kind)).X; + } + + /// Planar spline through . + public static Point2 Evaluate(ReadOnlySpan points, double t, CatmullRomParameterization kind = CatmullRomParameterization.Centripetal) + { + if (points.IsEmpty) throw new ArgumentException("No control points.", nameof(points)); + if (points.Length == 1) return points[0]; + var (i, u) = Segment(points.Length, t); + var p1 = points[i]; + var p2 = points[i + 1]; + var p0 = i > 0 ? points[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < points.Length ? points[i + 2] : 2 * p2 - p1; + return Pyramid(p0, p1, p2, p3, u, Alpha(kind)); + } + + private static double Alpha(CatmullRomParameterization kind) => kind switch + { + CatmullRomParameterization.Uniform => 0, + CatmullRomParameterization.Centripetal => 0.5, + CatmullRomParameterization.Chordal => 1, + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + + private static (int Index, double Local) Segment(int count, double t) + { + if (double.IsNaN(t)) throw new ArgumentOutOfRangeException(nameof(t)); + t = Math.Clamp(t, 0, count - 1); + var i = Math.Min((int)t, count - 2); + return (i, t - i); + } + + /// Barry–Goldman recursive evaluation of the segment P1→P2 at local parameter u ∈ [0, 1]. + private static Point2 Pyramid(Point2 p0, Point2 p1, Point2 p2, Point2 p3, double u, double alpha) + { + if (u <= 0) return p1; + if (u >= 1) return p2; + var d1 = Knot(p0, p1, alpha); + var d2 = Knot(p1, p2, alpha); + var d3 = Knot(p2, p3, alpha); + double t0 = 0, t1 = d1, t2 = t1 + d2, t3 = t2 + d3; + var t = t1 + u * d2; + var a1 = Mix(p0, p1, t0, t1, t); + var a2 = Mix(p1, p2, t1, t2, t); + var a3 = Mix(p2, p3, t2, t3, t); + var b1 = Mix(a1, a2, t0, t2, t); + var b2 = Mix(a2, a3, t1, t3, t); + return Mix(b1, b2, t1, t2, t); + } + + private static Point2 Mix(Point2 a, Point2 b, double ta, double tb, double t) => ((tb - t) * a + (t - ta) * b) * (1 / (tb - ta)); + + /// Knot interval; coincident points fall back to a unit interval so the pyramid stays finite. + private static double Knot(Point2 a, Point2 b, double alpha) + { + if (alpha == 0) return 1; + var d = Math.Pow(Point2.Distance(a, b), alpha); + return d > 1e-12 ? d : 1; + } +} diff --git a/src/Titano.Core/Math/CubicBezier.cs b/src/Titano.Core/Math/CubicBezier.cs new file mode 100644 index 00000000..a210b02f --- /dev/null +++ b/src/Titano.Core/Math/CubicBezier.cs @@ -0,0 +1,95 @@ +namespace Titano.Core.Mathematics; + +/// Planar cubic Bézier curve in Bernstein form; t ∈ [0, 1]. +public readonly record struct CubicBezier(Point2 P0, Point2 P1, Point2 P2, Point2 P3) +{ + public Point2 Evaluate(double t) + { + var s = 1 - t; + return s * s * s * P0 + 3 * s * s * t * P1 + 3 * s * t * t * P2 + t * t * t * P3; + } + + public Point2 Derivative(double t) + { + var s = 1 - t; + return 3 * s * s * (P1 - P0) + 6 * s * t * (P2 - P1) + 3 * t * t * (P3 - P2); + } +} + +/// +/// CSS-style timing function cubic-bezier(x1, y1, x2, y2) with end points (0, 0) and (1, 1). x(t) is +/// monotone because x1, x2 ∈ [0, 1]; it is inverted with Newton's method guarded by bisection. +/// +public readonly record struct CubicBezierEasing +{ + public CubicBezierEasing(double x1, double y1, double x2, double y2) + { + if (!(x1 >= 0 && x1 <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "x1 must lie in [0, 1]."); + if (!(x2 >= 0 && x2 <= 1)) throw new ArgumentOutOfRangeException(nameof(x2), "x2 must lie in [0, 1]."); + if (!double.IsFinite(y1)) throw new ArgumentOutOfRangeException(nameof(y1)); + if (!double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y2)); + X1 = x1; + Y1 = y1; + X2 = x2; + Y2 = y2; + } + + public double X1 { get; } + public double Y1 { get; } + public double X2 { get; } + public double Y2 { get; } + + public static CubicBezierEasing Linear { get; } = new(0, 0, 1, 1); + public static CubicBezierEasing Ease { get; } = new(0.25, 0.1, 0.25, 1); + public static CubicBezierEasing EaseIn { get; } = new(0.42, 0, 1, 1); + public static CubicBezierEasing EaseOut { get; } = new(0, 0, 0.58, 1); + public static CubicBezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1); + + /// Eased progress for input progress (clamped to [0, 1]). + public double Evaluate(double x) => Component(Y1, Y2, SolveT(x)); + + /// Curve parameter t with x(t) = . + public double SolveT(double x) + { + if (!(x > 0)) return 0; + if (x >= 1) return 1; + var t = x; + for (var i = 0; i < 8; i++) + { + var error = Component(X1, X2, t) - x; + if (Math.Abs(error) < 1e-12) return t; + var slope = ComponentDerivative(X1, X2, t); + if (Math.Abs(slope) < 1e-9) break; + t -= error / slope; + if (t is < 0 or > 1) break; + } + double lo = 0, hi = 1; + t = x; + for (var i = 0; i < 64; i++) + { + var value = Component(X1, X2, t); + if (Math.Abs(value - x) < 1e-12) break; + if (value < x) lo = t; + else hi = t; + t = 0.5 * (lo + hi); + } + return t; + } + + /// One coordinate of the curve with P0 = 0 and P3 = 1: ((a·t + b)·t + c)·t. + private static double Component(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return ((a * t + b) * t + c) * t; + } + + private static double ComponentDerivative(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return (3 * a * t + 2 * b) * t + c; + } +} diff --git a/src/Titano.Core/Math/MonotoneSpline.cs b/src/Titano.Core/Math/MonotoneSpline.cs new file mode 100644 index 00000000..718e4918 --- /dev/null +++ b/src/Titano.Core/Math/MonotoneSpline.cs @@ -0,0 +1,177 @@ +namespace Titano.Core.Mathematics; + +/// +/// Monotone piecewise cubic Hermite interpolant (Fritsch & Carlson 1980): three-point tangents limited to the +/// circle α² + β² ≤ 9 so the curve never overshoots monotone data. Outside the knot range the value is clamped +/// to the end values (derivative 0), which keeps time remaps monotone. +/// +public sealed class MonotoneSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public MonotoneSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + _m = new double[_x.Length]; + var n = _x.Length; + if (n == 1) return; + + var delta = new double[n - 1]; + var increasing = true; + var decreasing = true; + for (var k = 0; k < n - 1; k++) + { + delta[k] = (_y[k + 1] - _y[k]) / (_x[k + 1] - _x[k]); + increasing &= delta[k] >= 0; + decreasing &= delta[k] <= 0; + } + IsMonotone = increasing || decreasing; + + _m[0] = delta[0]; + _m[n - 1] = delta[n - 2]; + for (var k = 1; k < n - 1; k++) + { + if (delta[k - 1] * delta[k] <= 0) + { + _m[k] = 0; + continue; + } + // Three-point derivative for non-uniform spacing (exact for quadratics). + var h0 = _x[k] - _x[k - 1]; + var h1 = _x[k + 1] - _x[k]; + _m[k] = (h1 * delta[k - 1] + h0 * delta[k]) / (h0 + h1); + } + + for (var k = 0; k < n - 1; k++) + { + if (delta[k] == 0) + { + _m[k] = 0; + _m[k + 1] = 0; + continue; + } + var alpha = _m[k] / delta[k]; + var beta = _m[k + 1] / delta[k]; + if (alpha < 0) _m[k] = alpha = 0; + if (beta < 0) _m[k + 1] = beta = 0; + var s = alpha * alpha + beta * beta; + if (s > 9) + { + var tau = 3 / Math.Sqrt(s); + _m[k] = tau * alpha * delta[k]; + _m[k + 1] = tau * beta * delta[k]; + } + } + } + + public int Count => _x.Length; + + public double MinX => _x[0]; + + public double MaxX => _x[^1]; + + /// True when the knot values are entirely non-decreasing or non-increasing (required by ). + public bool IsMonotone { get; } = true; + + public double Evaluate(double x) + { + if (!(x > _x[0])) return _y[0]; + if (x >= _x[^1]) return _y[^1]; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + var t3 = t2 * t; + // Increment form: rounding scales with the interval's rise, so flat intervals stay exactly flat. + return _y[k] + (_y[k + 1] - _y[k]) * (3 * t2 - 2 * t3) + h * ((t3 - 2 * t2 + t) * _m[k] + (t3 - t2) * _m[k + 1]); + } + + public double Derivative(double x) + { + if (!(x > _x[0]) || x >= _x[^1]) return 0; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + return ((6 * t2 - 6 * t) * _y[k] + + (3 * t2 - 4 * t + 1) * h * _m[k] + + (-6 * t2 + 6 * t) * _y[k + 1] + + (3 * t2 - 2 * t) * h * _m[k + 1]) / h; + } + + /// + /// The x at which the spline reaches (values outside the range clamp to the end knots; + /// on a flat stretch the first x is returned). Safeguarded Newton iteration inside the bracketing interval. + /// + /// The knot values are not monotone. + public double Inverse(double y) + { + if (!IsMonotone) throw new InvalidOperationException("Inverse requires monotone knot values."); + var n = _x.Length; + var sign = _y[^1] >= _y[0] ? 1.0 : -1.0; + var target = sign * y; + if (n == 1 || !(target > sign * _y[0])) return _x[0]; + if (target >= sign * _y[^1]) return FirstAtEnd(); + + int lo = 0, hi = n - 1; + while (hi - lo > 1) + { + var mid = (lo + hi) >> 1; + if (sign * _y[mid] < target) lo = mid; + else hi = mid; + } + if (sign * _y[hi] == target) + { + while (hi > 0 && _y[hi - 1] == _y[hi]) hi--; + return _x[hi]; + } + + double a = _x[lo], b = _x[hi]; + var x = a + (b - a) * (target - sign * _y[lo]) / (sign * (_y[hi] - _y[lo])); + for (var i = 0; i < 100 && b - a > 1e-14 * (1 + Math.Abs(a)); i++) + { + var f = sign * Evaluate(x) - target; + if (f == 0) return x; + if (f < 0) a = x; + else b = x; + var d = sign * Derivative(x); + var next = d > 0 ? x - f / d : double.NaN; + x = next > a && next < b ? next : 0.5 * (a + b); + } + return x; + } + + private double FirstAtEnd() + { + var i = _x.Length - 1; + while (i > 0 && _y[i - 1] == _y[i]) i--; + return _x[i]; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} + +internal static class SplineInput +{ + public static void Validate(ReadOnlySpan x, ReadOnlySpan y, int minimum) + { + if (x.Length != y.Length) throw new ArgumentException("x and y lengths differ.", nameof(y)); + if (x.Length < minimum) throw new ArgumentException($"At least {minimum} knot(s) required.", nameof(x)); + for (var i = 0; i < x.Length; i++) + { + if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) throw new ArgumentException("Knots must be finite.", nameof(x)); + if (i > 0 && !(x[i] > x[i - 1])) throw new ArgumentException("x must be strictly increasing.", nameof(x)); + } + } +} diff --git a/src/Titano.Core/Math/NaturalCubicSpline.cs b/src/Titano.Core/Math/NaturalCubicSpline.cs new file mode 100644 index 00000000..363f572f --- /dev/null +++ b/src/Titano.Core/Math/NaturalCubicSpline.cs @@ -0,0 +1,88 @@ +namespace Titano.Core.Mathematics; + +/// +/// Interpolating cubic spline with natural end conditions (zero second derivative), second derivatives solved +/// with the Thomas tridiagonal algorithm. C² inside the knot range; extrapolates linearly with the end slopes. +/// +public sealed class NaturalCubicSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public NaturalCubicSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + var n = _x.Length; + _m = new double[n]; + if (n < 3) return; + + // Interior equations: h[i-1]·M[i-1] + 2(h[i-1]+h[i])·M[i] + h[i]·M[i+1] = 6(δ[i] − δ[i-1]). + var c = new double[n]; + var d = new double[n]; + for (var i = 1; i < n - 1; i++) + { + var h0 = _x[i] - _x[i - 1]; + var h1 = _x[i + 1] - _x[i]; + var rhs = 6 * ((_y[i + 1] - _y[i]) / h1 - (_y[i] - _y[i - 1]) / h0); + var diag = 2 * (h0 + h1) - h0 * c[i - 1]; + c[i] = h1 / diag; + d[i] = (rhs - h0 * d[i - 1]) / diag; + } + for (var i = n - 2; i >= 1; i--) _m[i] = d[i] - c[i] * _m[i + 1]; + } + + public int Count => _x.Length; + + public double Evaluate(double x) + { + var n = _x.Length; + if (n == 1) return _y[0]; + if (x < _x[0]) return _y[0] + Slope(0, atEnd: false) * (x - _x[0]); + if (x > _x[^1]) return _y[^1] + Slope(n - 2, atEnd: true) * (x - _x[^1]); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return a * _y[k] + b * _y[k + 1] + ((a * a * a - a) * _m[k] + (b * b * b - b) * _m[k + 1]) * h * h / 6; + } + + public double Derivative(double x) + { + var n = _x.Length; + if (n == 1) return 0; + if (x < _x[0]) return Slope(0, atEnd: false); + if (x > _x[^1]) return Slope(n - 2, atEnd: true); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return (_y[k + 1] - _y[k]) / h - (3 * a * a - 1) / 6 * h * _m[k] + (3 * b * b - 1) / 6 * h * _m[k + 1]; + } + + public double SecondDerivative(double x) + { + if (_x.Length == 1 || x <= _x[0] || x >= _x[^1]) return 0; + var k = Interval(x); + var a = (_x[k + 1] - x) / (_x[k + 1] - _x[k]); + return a * _m[k] + (1 - a) * _m[k + 1]; + } + + private double Slope(int k, bool atEnd) + { + var h = _x[k + 1] - _x[k]; + var secant = (_y[k + 1] - _y[k]) / h; + return atEnd ? secant + h * (_m[k] + 2 * _m[k + 1]) / 6 : secant - h * (2 * _m[k] + _m[k + 1]) / 6; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} diff --git a/src/Titano.Core/Math/Point2.cs b/src/Titano.Core/Math/Point2.cs new file mode 100644 index 00000000..848095ae --- /dev/null +++ b/src/Titano.Core/Math/Point2.cs @@ -0,0 +1,19 @@ +namespace Titano.Core.Mathematics; + +/// A point or vector in the plane, double precision. +public readonly record struct Point2(double X, double Y) +{ + public static Point2 operator +(Point2 a, Point2 b) => new(a.X + b.X, a.Y + b.Y); + + public static Point2 operator -(Point2 a, Point2 b) => new(a.X - b.X, a.Y - b.Y); + + public static Point2 operator *(Point2 a, double s) => new(a.X * s, a.Y * s); + + public static Point2 operator *(double s, Point2 a) => new(a.X * s, a.Y * s); + + public double Length => Math.Sqrt(X * X + Y * Y); + + public static double Distance(Point2 a, Point2 b) => (a - b).Length; + + public static Point2 Lerp(Point2 a, Point2 b, double t) => new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); +} diff --git a/tests/Titano.Core.Tests/Math/SplineTests.cs b/tests/Titano.Core.Tests/Math/SplineTests.cs new file mode 100644 index 00000000..669ae785 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SplineTests.cs @@ -0,0 +1,202 @@ +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +public sealed class SplineTests +{ + // Monotone data with a plateau and a sharp rise: the classic overshoot trap for C² splines. + private static readonly double[] StepX = [0, 1, 2, 3, 4, 5, 6]; + private static readonly double[] StepY = [0, 0, 0, 1, 1, 1, 1]; + + [Test] + public void MonotoneSplineInterpolatesKnots() + { + var spline = new MonotoneSpline(StepX, StepY); + for (var i = 0; i < StepX.Length; i++) Assert.Equal(StepY[i], spline.Evaluate(StepX[i])); + Assert.Equal(0.0, spline.Evaluate(-5)); + Assert.Equal(1.0, spline.Evaluate(50)); + } + + [Test] + public void MonotoneSplineNeverOvershootsWhileNaturalSplineDoes() + { + var monotone = new MonotoneSpline(StepX, StepY); + var natural = new NaturalCubicSpline(StepX, StepY); + var samples = Enumerable.Range(0, 601).Select(i => monotone.Evaluate(i / 100.0)).ToList(); + Assert.Monotonic(samples); + Assert.InRange(samples.Min(), 0, 0); + Assert.InRange(samples.Max(), 1, 1); + var naturalMax = Enumerable.Range(0, 601).Max(i => natural.Evaluate(i / 100.0)); + Assert.Greater(naturalMax, 1.01); + } + + [Test] + public void MonotoneSplineOnRandomMonotoneDataIsMonotoneAndBounded() + { + var random = new Random(5); + for (var trial = 0; trial < 50; trial++) + { + var n = 2 + random.Next(20); + var x = new double[n]; + var y = new double[n]; + for (var i = 1; i < n; i++) + { + x[i] = x[i - 1] + 0.01 + random.NextDouble() * 3; + y[i] = y[i - 1] + (random.NextDouble() < 0.3 ? 0 : random.NextDouble() * random.NextDouble() * 10); + } + var spline = new MonotoneSpline(x, y); + Assert.True(spline.IsMonotone); + var values = Enumerable.Range(0, 400).Select(i => spline.Evaluate(x[^1] * i / 399.0)).ToList(); + Assert.True(values.All(double.IsFinite)); + Assert.Monotonic(values, message: $"trial {trial}"); + for (var k = 0; k < n - 1; k++) + { + var mid = spline.Evaluate(0.5 * (x[k] + x[k + 1])); + Assert.InRange(mid, y[k], y[k + 1], $"interval {k} of trial {trial}"); + } + } + } + + [Test] + public void MonotoneSplineDerivativeMatchesFiniteDifference() + { + double[] x = [0, 0.5, 2, 3, 5]; + double[] y = [1, 1.5, 2.2, 4, 4.5]; + var spline = new MonotoneSpline(x, y); + foreach (var at in new[] { 0.2, 0.9, 2.5, 4.1 }) + { + const double h = 1e-6; + var numeric = (spline.Evaluate(at + h) - spline.Evaluate(at - h)) / (2 * h); + Assert.Approximately(numeric, spline.Derivative(at), 1e-6); + } + } + + [Test] + public void MonotoneSplineInverseRoundTrips() + { + double[] x = [0, 1, 2.5, 4, 6]; + double[] y = [10, 8, 8, 3, -1]; + var spline = new MonotoneSpline(x, y); + for (var i = 0; i <= 120; i++) + { + var at = i * 0.05; + var value = spline.Evaluate(at); + var back = spline.Inverse(value); + Assert.Approximately(value, spline.Evaluate(back), 1e-10); + } + Assert.Equal(1.0, spline.Inverse(8)); + Assert.Equal(0.0, spline.Inverse(99)); + Assert.Equal(6.0, spline.Inverse(-99)); + Assert.Throws(() => new MonotoneSpline([0, 1, 2], [0, 1, 0]).Inverse(0.5)); + } + + [Test] + public void SplinesRejectInvalidKnots() + { + Assert.Throws(() => new MonotoneSpline([0, 0], [1, 2])); + Assert.Throws(() => new NaturalCubicSpline([0, 1], [1, double.NaN])); + Assert.Throws(() => new MonotoneSpline([], [])); + } + + [Test] + public void NaturalSplineReproducesLinesAndHasFreeEnds() + { + double[] x = [0, 1, 3, 4, 7]; + var line = new NaturalCubicSpline(x, x.Select(v => 2 - 0.5 * v).ToArray()); + foreach (var at in new[] { -2.0, 0.3, 2.2, 6.9, 9 }) Assert.Approximately(2 - 0.5 * at, line.Evaluate(at), 1e-12); + + var sine = new NaturalCubicSpline(Enumerable.Range(0, 21).Select(i => i * Math.PI / 10).ToArray(), + Enumerable.Range(0, 21).Select(i => Math.Sin(i * Math.PI / 10)).ToArray()); + Assert.Approximately(0, sine.SecondDerivative(1e-9), 1e-6); + for (var i = 0; i < 100; i++) + { + var at = 0.3 + i * 0.055; + Assert.Approximately(Math.Sin(at), sine.Evaluate(at), 2e-4); + Assert.Approximately(Math.Cos(at), sine.Derivative(at), 5e-3); + } + } + + [Test] + public void CatmullRomPassesThroughControlPoints() + { + Point2[] points = [new(0, 0), new(1, 2), new(3, 3), new(4, 1), new(6, 0)]; + foreach (var kind in Enum.GetValues()) + { + for (var i = 0; i < points.Length; i++) + { + var p = CatmullRom.Evaluate(points, i, kind); + Assert.Within(points[i].X, points[i].Y, p.X, p.Y, 1e-12); + } + } + } + + [Test] + public void UniformScalarCatmullRomMatchesClosedForm() + { + double[] v = [1, 4, 2, 5, 3]; + for (var i = 0; i <= 40; i++) + { + var t = 1 + i * 0.025; + var u = t - 1; + double p0 = v[0], p1 = v[1], p2 = v[2], p3 = v[3]; + var expected = 0.5 * (2 * p1 + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u * u * u); + Assert.Approximately(expected, CatmullRom.Evaluate(v, t), 1e-12); + } + } + + [Test] + public void CentripetalCatmullRomDoesNotBacktrackOnUnevenSpacing() + { + // Collinear points with a very short middle segment: the uniform spline overshoots past 10.1 and + // turns back; the centripetal one stays monotone along the line. + Point2[] points = [new(0, 0), new(10, 0), new(10.1, 0), new(20, 0)]; + double MaxX(CatmullRomParameterization kind) => Enumerable.Range(0, 101).Max(i => CatmullRom.Evaluate(points, 1 + i / 100.0, kind).X); + Assert.Greater(MaxX(CatmullRomParameterization.Uniform), 10.15); + var centripetal = Enumerable.Range(0, 101).Select(i => CatmullRom.Evaluate(points, 1 + i / 100.0, CatmullRomParameterization.Centripetal).X).ToList(); + Assert.Monotonic(centripetal); + Assert.LessOrEqual(centripetal.Max(), 10.1 + 1e-12); + } + + [Test] + public void BezierEndpointsAndDerivative() + { + var curve = new CubicBezier(new(0, 0), new(1, 2), new(3, 2), new(4, 0)); + Assert.Equal(new Point2(0, 0), curve.Evaluate(0)); + Assert.Equal(new Point2(4, 0), curve.Evaluate(1)); + var d0 = curve.Derivative(0); + Assert.Within(3, 6, d0.X, d0.Y, 1e-12); + var mid = curve.Evaluate(0.5); + Assert.Within(2, 1.5, mid.X, mid.Y, 1e-12); + } + + [Theory] + [Case("ease", 0.5, 0.802403387585)] + [Case("ease-in", 0.5, 0.315356812573)] + [Case("ease-out", 0.25, 0.378138130825)] + [Case("ease-in-out", 0.5, 0.5)] + [Case("linear", 0.37, 0.37)] + public void CssEasingMatchesReference(string name, double x, double expected) + { + var easing = name switch + { + "ease" => CubicBezierEasing.Ease, + "ease-in" => CubicBezierEasing.EaseIn, + "ease-out" => CubicBezierEasing.EaseOut, + "ease-in-out" => CubicBezierEasing.EaseInOut, + _ => CubicBezierEasing.Linear, + }; + Assert.Approximately(expected, easing.Evaluate(x), 1e-9); + } + + [Test] + public void EasingIsMonotoneAndClamped() + { + var easing = new CubicBezierEasing(0.9, -0.2, 0.1, 1.2); + Assert.Equal(0.0, easing.Evaluate(-1)); + Assert.Equal(1.0, easing.Evaluate(2)); + var ts = Enumerable.Range(0, 201).Select(i => easing.SolveT(i / 200.0)).ToList(); + Assert.Monotonic(ts); + Assert.Throws(() => new CubicBezierEasing(1.5, 0, 0.5, 1)); + } +} From 72ffd8ec47d9282f936e7b2624f55f943dac5b0d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH 010/188] feat(math): add robust LOWESS local regression Cleveland 1979: tricube-weighted local linear/quadratic fits over the k nearest valid samples (asymmetric at edges), Tukey biweight robustness on residuals scaled by 6 MAD, per-point surviving weight fraction, missing-sample interpolation, index or time positions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/LocalRegression.cs | 207 ++++++++++++++++++ .../Math/LocalRegressionTests.cs | 118 ++++++++++ 2 files changed, 325 insertions(+) create mode 100644 src/Titano.Core/Math/LocalRegression.cs create mode 100644 tests/Titano.Core.Tests/Math/LocalRegressionTests.cs diff --git a/src/Titano.Core/Math/LocalRegression.cs b/src/Titano.Core/Math/LocalRegression.cs new file mode 100644 index 00000000..6f2386a6 --- /dev/null +++ b/src/Titano.Core/Math/LocalRegression.cs @@ -0,0 +1,207 @@ +namespace Titano.Core.Mathematics; + +/// Output of ; every array has one entry per input sample. +public sealed class LocalRegressionResult +{ + internal LocalRegressionResult(double[] fitted, double[] robustWeights, double[] survivingFraction, int validCount) + { + Fitted = fitted; + RobustWeights = robustWeights; + SurvivingFraction = survivingFraction; + ValidCount = validCount; + } + + /// Smoothed value at every position, including missing samples (interpolated from their neighbours). + /// NaN only when there is no valid sample at all. + public double[] Fitted { get; } + + /// Tukey biweight each sample carried in the final fit (1 = full inlier, 0 = rejected or missing). + public double[] RobustWeights { get; } + + /// + /// Σ wᵢⱼ·ρⱼ / Σ wᵢⱼ over the window of each position: the share of its distance (tricube × prior) weight + /// that survived robustness. Near 1 for clean windows, lower where samples were rejected. + /// + public double[] SurvivingFraction { get; } + + public int ValidCount { get; } +} + +/// +/// Robust locally weighted regression, LOWESS (Cleveland 1979). Each position is fitted by weighted least squares +/// of degree 1 or 2 over its window nearest valid samples (asymmetric at the edges, so the count stays +/// constant), with tricube distance weights. Robustness iterations reweight samples with Tukey's biweight of the +/// residuals scaled by 6·MAD. Cost O(n·window) per iteration. +/// +public static class LocalRegression +{ + /// Samples; NaN/±∞ mark missing values. + /// Number of nearest valid samples in each local fit (clamped to the valid count). + /// Local polynomial degree, 1 (linear) or 2 (quadratic). + /// Tukey reweighting passes after the initial fit (Cleveland uses 2–3). + /// Non-decreasing positions (e.g. capture seconds); indices when empty. + /// Optional non-negative sample weights; zero marks a sample as missing. + public static LocalRegressionResult Smooth( + ReadOnlySpan y, + int window, + int degree = 1, + int robustIterations = 2, + ReadOnlySpan x = default, + ReadOnlySpan priorWeights = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(window, 1); + if (degree is not (1 or 2)) throw new ArgumentOutOfRangeException(nameof(degree), "Degree must be 1 or 2."); + ArgumentOutOfRangeException.ThrowIfNegative(robustIterations); + var n = y.Length; + if (!x.IsEmpty && x.Length != n) throw new ArgumentException("x and y lengths differ.", nameof(x)); + if (!priorWeights.IsEmpty && priorWeights.Length != n) throw new ArgumentException("Weight and y lengths differ.", nameof(priorWeights)); + + var pos = new double[n]; + for (var i = 0; i < n; i++) + { + pos[i] = x.IsEmpty ? i : x[i]; + if (!double.IsFinite(pos[i])) throw new ArgumentException("Positions must be finite.", nameof(x)); + if (i > 0 && pos[i] < pos[i - 1]) throw new ArgumentException("Positions must be non-decreasing.", nameof(x)); + } + + var valid = new List(n); + for (var i = 0; i < n; i++) + { + var w = priorWeights.IsEmpty ? 1 : priorWeights[i]; + if (double.IsFinite(y[i]) && w > 0 && double.IsFinite(w)) valid.Add(i); + } + var m = valid.Count; + var fitted = new double[n]; + var robust = new double[n]; + var surviving = new double[n]; + if (m == 0) + { + Array.Fill(fitted, double.NaN); + return new LocalRegressionResult(fitted, robust, surviving, 0); + } + + var vx = new double[m]; + var vy = new double[m]; + var prior = new double[m]; + for (var j = 0; j < m; j++) + { + var i = valid[j]; + vx[j] = pos[i]; + vy[j] = y[i]; + prior[j] = priorWeights.IsEmpty ? 1 : priorWeights[i]; + } + + var q = Math.Min(window, m); + var p = Math.Min(degree, q - 1); + var windows = BuildWindows(pos, vx, q); + var rho = new double[m]; + Array.Fill(rho, 1.0); + var residual = new double[m]; + var scaleFloor = 1e-12 * (1 + Math.Abs(Statistics.Median(vy))); + + for (var iteration = 0; ; iteration++) + { + FitAll(pos, windows, q, vx, vy, prior, rho, p, fitted, surviving); + if (iteration == robustIterations) break; + for (var j = 0; j < m; j++) residual[j] = vy[j] - fitted[valid[j]]; + var mad = Statistics.MedianAbsoluteDeviation(residual, 0); + if (!(mad > scaleFloor)) break; + var c = 6 * mad; + for (var j = 0; j < m; j++) + { + var u = residual[j] / c; + rho[j] = Math.Abs(u) < 1 ? (1 - u * u) * (1 - u * u) : 0; + } + } + + for (var j = 0; j < m; j++) robust[valid[j]] = rho[j]; + return new LocalRegressionResult(fitted, robust, surviving, m); + } + + /// Start of the contiguous block of valid samples nearest to each position + /// (sliding k-nearest-neighbour window; total O(n + m)). + private static int[] BuildWindows(double[] pos, double[] vx, int q) + { + var starts = new int[pos.Length]; + var s = 0; + for (var i = 0; i < pos.Length; i++) + { + var xi = pos[i]; + while (s + q < vx.Length && xi - vx[s] > vx[s + q] - xi) s++; + starts[i] = s; + } + return starts; + } + + private static void FitAll(double[] pos, int[] starts, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, double[] fitted, double[] surviving) + { + for (var i = 0; i < pos.Length; i++) + fitted[i] = FitAt(pos[i], starts[i], q, vx, vy, prior, rho, degree, out surviving[i]); + } + + private static double FitAt(double xi, int start, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, out double surviving) + { + var end = start + q - 1; + var dMax = Math.Max(xi - vx[start], vx[end] - xi); + // One mean sample spacing beyond the farthest neighbour, so every sample in the window keeps a positive weight. + var h = dMax + (q > 1 ? (vx[end] - vx[start]) / (q - 1) : 0); + if (!(h > 0)) h = 1; + + double s0 = 0, s1 = 0, s2 = 0, s3 = 0, s4 = 0, t0 = 0, t1 = 0, t2 = 0; + double distanceSum = 0, survivingSum = 0; + double r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, rt0 = 0, rt1 = 0, rt2 = 0; + for (var j = start; j <= end; j++) + { + var u = (vx[j] - xi) / h; + var a = 1 - Math.Abs(u * u * u); + var wd = a <= 0 ? 0 : a * a * a * prior[j]; + distanceSum += wd; + var w = wd * rho[j]; + survivingSum += w; + var uu = u * u; + s0 += w; + s1 += w * u; + s2 += w * uu; + t0 += w * vy[j]; + t1 += w * u * vy[j]; + r0 += wd; + r1 += wd * u; + r2 += wd * uu; + rt0 += wd * vy[j]; + rt1 += wd * u * vy[j]; + if (degree == 2) + { + s3 += w * uu * u; + s4 += w * uu * uu; + t2 += w * uu * vy[j]; + r3 += wd * uu * u; + r4 += wd * uu * uu; + rt2 += wd * uu * vy[j]; + } + } + surviving = distanceSum > 0 ? survivingSum / distanceSum : 0; + // A window whose every sample was rejected falls back to plain distance weights. + return s0 > 1e-12 * distanceSum + ? Solve(degree, s0, s1, s2, s3, s4, t0, t1, t2) + : Solve(degree, r0, r1, r2, r3, r4, rt0, rt1, rt2); + } + + /// Intercept of the weighted polynomial fit in centred coordinates, degrading to a lower degree when + /// the normal equations are ill-conditioned (e.g. all weight on one sample). + private static double Solve(int degree, double s0, double s1, double s2, double s3, double s4, double t0, double t1, double t2) + { + if (!(s0 > 0)) return double.NaN; + if (degree == 2) + { + var c00 = s2 * s4 - s3 * s3; + var c01 = s1 * s4 - s2 * s3; + var c02 = s1 * s3 - s2 * s2; + var det = s0 * c00 - s1 * c01 + s2 * c02; + if (det > 1e-10 * s0 * s2 * s4) + return (t0 * c00 - s1 * (t1 * s4 - s3 * t2) + s2 * (t1 * s3 - s2 * t2)) / det; + } + var det1 = s0 * s2 - s1 * s1; + if (det1 > 1e-10 * s0 * s2) return (s2 * t0 - s1 * t1) / det1; + return t0 / s0; + } +} diff --git a/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs new file mode 100644 index 00000000..66b7d158 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs @@ -0,0 +1,118 @@ +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +public sealed class LocalRegressionTests +{ + [Theory] + [Case(1)] + [Case(2)] + public void ReproducesPolynomialsOfItsDegreeIncludingEdges(int degree) + { + var y = Enumerable.Range(0, 60).Select(i => degree == 1 ? 3 - 0.2 * i : 1 + 0.1 * i - 0.004 * i * i).ToArray(); + var result = LocalRegression.Smooth(y, window: 11, degree: degree, robustIterations: 2); + for (var i = 0; i < y.Length; i++) Assert.Approximately(y[i], result.Fitted[i], 1e-9); + Assert.True(result.SurvivingFraction.All(f => Math.Abs(f - 1) < 1e-12)); + } + + [Test] + public void TimeSpaceWindowsHandleUnevenSpacing() + { + var random = new Random(4); + var x = new double[80]; + for (var i = 1; i < x.Length; i++) x[i] = x[i - 1] + 1 + 9 * random.NextDouble(); + var y = x.Select(v => 5 + 0.01 * v).ToArray(); + var result = LocalRegression.Smooth(y, window: 9, x: x); + for (var i = 0; i < y.Length; i++) Assert.Approximately(y[i], result.Fitted[i], 1e-9); + } + + [Test] + public void TwentyPercentOutliersBarelyMoveTheRobustFit() + { + var random = new Random(21); + var n = 300; + var clean = Enumerable.Range(0, n).Select(i => Math.Sin(i / 40.0) + 0.02 * (random.NextDouble() - 0.5)).ToArray(); + var truth = Enumerable.Range(0, n).Select(i => Math.Sin(i / 40.0)).ToArray(); + var contaminated = (double[])clean.Clone(); + var outliers = new HashSet(); + while (outliers.Count < n / 5) outliers.Add(random.Next(n)); + foreach (var i in outliers) contaminated[i] += (random.NextDouble() < 0.5 ? -1 : 1) * (1 + 2 * random.NextDouble()); + + var reference = LocalRegression.Smooth(clean, window: 31, robustIterations: 3); + var robust = LocalRegression.Smooth(contaminated, window: 31, robustIterations: 3); + var plain = LocalRegression.Smooth(contaminated, window: 31, robustIterations: 0); + + var robustShift = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - reference.Fitted[i])); + var plainShift = Enumerable.Range(0, n).Max(i => Math.Abs(plain.Fitted[i] - reference.Fitted[i])); + var robustError = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - truth[i])); + Assert.Less(robustShift, 0.03, "robust fit moved by the outliers"); + Assert.Less(robustError, 0.04); + Assert.Greater(plainShift, 10 * robustShift); + + // Outliers are rejected; their windows report the lost weight. + Assert.True(outliers.All(i => robust.RobustWeights[i] < 0.05)); + var inlierWeight = Enumerable.Range(0, n).Where(i => !outliers.Contains(i)).Average(i => robust.RobustWeights[i]); + Assert.Greater(inlierWeight, 0.8); + Assert.InRange(robust.SurvivingFraction.Average(), 0.6, 0.9); + } + + [Test] + public void MissingSamplesAreInterpolatedAndReportedAsRejected() + { + var y = Enumerable.Range(0, 40).Select(i => 0.5 * i).ToArray(); + y[0] = double.NaN; + y[10] = double.NaN; + y[11] = double.PositiveInfinity; + y[39] = double.NaN; + var result = LocalRegression.Smooth(y, window: 7); + Assert.Equal(36, result.ValidCount); + foreach (var i in new[] { 0, 10, 11, 39 }) + { + Assert.Approximately(0.5 * i, result.Fitted[i], 1e-9); + Assert.Equal(0.0, result.RobustWeights[i]); + } + } + + [Test] + public void PriorWeightsExcludeSamples() + { + var y = Enumerable.Range(0, 30).Select(i => (double)i).ToArray(); + y[15] = 1000; + var weights = Enumerable.Repeat(1.0, 30).ToArray(); + weights[15] = 0; + var result = LocalRegression.Smooth(y, window: 5, robustIterations: 0, priorWeights: weights); + Assert.Approximately(15, result.Fitted[15], 1e-9); + } + + [Test] + public void DegenerateInputs() + { + Assert.True(double.IsNaN(LocalRegression.Smooth([double.NaN, double.NaN], 3).Fitted[1])); + Assert.Equal(4.0, LocalRegression.Smooth([4.0], 5).Fitted[0]); + var two = LocalRegression.Smooth([1.0, 3.0, double.NaN], 5); + Assert.Approximately(5, two.Fitted[2], 1e-12); + Assert.Throws(() => LocalRegression.Smooth([1.0], 0)); + Assert.Throws(() => LocalRegression.Smooth([1.0, 2.0], 3, x: [1.0, 0.0])); + } + + [Test] + public void RandomInputsGiveFiniteDeterministicOutputs() + { + var random = new Random(99); + for (var trial = 0; trial < 20; trial++) + { + var n = 1 + random.Next(400); + var y = Enumerable.Range(0, n).Select(_ => random.NextDouble() < 0.15 ? double.NaN : 100 * (random.NextDouble() - 0.5)).ToArray(); + if (y.All(double.IsNaN)) y[0] = 1; + var window = 1 + random.Next(60); + var degree = 1 + random.Next(2); + var a = LocalRegression.Smooth(y, window, degree, robustIterations: 3); + var b = LocalRegression.Smooth(y, window, degree, robustIterations: 3); + Assert.True(a.Fitted.All(double.IsFinite), $"trial {trial}"); + Assert.True(a.SurvivingFraction.All(f => f is >= 0 and <= 1 + 1e-12)); + Assert.SequenceEqual(a.Fitted, b.Fitted); + Assert.SequenceEqual(a.RobustWeights, b.RobustWeights); + } + } +} From 8c2692073cb3a924bf310b78a6a7c6b3a31f920b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH 011/188] feat(math): add NOAA solar position and day phases Meeus/NOAA equations for elevation (with refraction) and azimuth, iteratively refined sunrise, sunset and civil/nautical/astronomical twilight per local solar day, and DayPhase classification. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/SolarPosition.cs | 219 ++++++++++++++++++ .../Math/SolarPositionTests.cs | 104 +++++++++ 2 files changed, 323 insertions(+) create mode 100644 src/Titano.Core/Math/SolarPosition.cs create mode 100644 tests/Titano.Core.Tests/Math/SolarPositionTests.cs diff --git a/src/Titano.Core/Math/SolarPosition.cs b/src/Titano.Core/Math/SolarPosition.cs new file mode 100644 index 00000000..bfa7eb16 --- /dev/null +++ b/src/Titano.Core/Math/SolarPosition.cs @@ -0,0 +1,219 @@ +namespace Titano.Core.Mathematics; + +/// Light condition by solar elevation (geometric centre of the disc). +public enum DayPhase +{ + /// Sun below −18°. + Night, + + /// −18° to −12°. + AstronomicalTwilight, + + /// −12° to −6°. + NauticalTwilight, + + /// −6° to sunrise/sunset (−0.833°). + CivilTwilight, + + /// Sun up but below 6°. + GoldenHour, + + /// Sun at or above 6°. + Day, +} + +/// Sun position for an instant and place. +/// Apparent elevation in degrees, corrected for standard atmospheric refraction. +/// Degrees clockwise from true north. +/// Elevation without refraction, in degrees (used for twilight limits). +/// Solar declination in degrees. +/// Apparent minus mean solar time, in minutes. +public readonly record struct SolarCoordinates(double Elevation, double Azimuth, double GeometricElevation, double Declination, double EquationOfTimeMinutes) +{ + public DayPhase Phase => SolarPosition.Classify(GeometricElevation); +} + +/// Sun events of one local solar day, all in UTC; null when the event does not occur (polar day/night). +public sealed record SolarDay( + DateOnly Date, + DateTime SolarNoon, + DateTime? Sunrise, + DateTime? Sunset, + DateTime? CivilDawn, + DateTime? CivilDusk, + DateTime? NauticalDawn, + DateTime? NauticalDusk, + DateTime? AstronomicalDawn, + DateTime? AstronomicalDusk); + +/// +/// Solar position and rise/set times with the NOAA Solar Calculator equations (after Meeus, "Astronomical +/// Algorithms"). Event times are refined iteratively at the event instant; accuracy is about one minute for +/// latitudes within ±72°. Longitudes are east-positive, latitudes north-positive, times UTC. +/// +public static class SolarPosition +{ + /// Geometric elevation of the disc centre at apparent sunrise/sunset (34′ refraction + 16′ semi-diameter). + public const double SunriseElevation = -0.833; + + public const double CivilTwilightElevation = -6; + public const double NauticalTwilightElevation = -12; + public const double AstronomicalTwilightElevation = -18; + public const double GoldenHourElevation = 6; + + private const double Deg = Math.PI / 180; + private static readonly DateTime J2000 = new(2000, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + /// Sun position at (a value of unspecified kind is taken as UTC). + public static SolarCoordinates Compute(DateTime utc, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + var sun = Ephemeris(utc); + var minutes = utc.TimeOfDay.TotalMinutes; + var trueSolarTime = Mod(minutes + sun.EquationOfTime + 4 * longitude, 1440); + var hourAngle = trueSolarTime / 4 - 180; + + var phi = latitude * Deg; + var delta = sun.Declination * Deg; + var cosZenith = Math.Clamp(Math.Sin(phi) * Math.Sin(delta) + Math.Cos(phi) * Math.Cos(delta) * Math.Cos(hourAngle * Deg), -1, 1); + var zenith = Math.Acos(cosZenith); + var geometric = 90 - zenith / Deg; + + double azimuth; + var denominator = Math.Cos(phi) * Math.Sin(zenith); + if (Math.Abs(denominator) < 1e-12) + { + azimuth = latitude > 0 ? 180 : 0; + } + else + { + var a = Math.Acos(Math.Clamp((Math.Sin(phi) * cosZenith - Math.Sin(delta)) / denominator, -1, 1)) / Deg; + azimuth = hourAngle > 0 ? Mod(a + 180, 360) : Mod(540 - a, 360); + } + return new SolarCoordinates(geometric + Refraction(geometric), azimuth, geometric, sun.Declination, sun.EquationOfTime); + } + + /// Day phase from the geometric elevation in degrees. + public static DayPhase Classify(double geometricElevation) => geometricElevation switch + { + < AstronomicalTwilightElevation => DayPhase.Night, + < NauticalTwilightElevation => DayPhase.AstronomicalTwilight, + < CivilTwilightElevation => DayPhase.NauticalTwilight, + < SunriseElevation => DayPhase.CivilTwilight, + < GoldenHourElevation => DayPhase.GoldenHour, + _ => DayPhase.Day, + }; + + public static DayPhase Phase(DateTime utc, double latitude, double longitude) => Compute(utc, latitude, longitude).Phase; + + /// All rise/set and twilight events of the local solar day (the day whose solar + /// noon falls on that calendar date at the given longitude). + public static SolarDay Events(DateOnly date, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + return new SolarDay( + date, + SolarNoon(date, longitude), + EventTime(date, latitude, longitude, SunriseElevation, rising: true), + EventTime(date, latitude, longitude, SunriseElevation, rising: false), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: true), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: false), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: false), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: false)); + } + + /// UTC solar noon (upper transit) of the local solar day. + public static DateTime SolarNoon(DateOnly date, double longitude) + { + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 3; i++) + minutes = 720 - 4 * longitude - Ephemeris(midnight.AddMinutes(minutes)).EquationOfTime; + return midnight.AddMinutes(minutes); + } + + /// + /// UTC time at which the sun's geometric centre crosses degrees on the given + /// local solar day, rising (morning) or setting (evening); null when it stays above or below all day. + /// + public static DateTime? EventTime(DateOnly date, double latitude, double longitude, double elevation, bool rising) + { + ValidateLocation(latitude, longitude); + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 4; i++) + { + var sun = Ephemeris(midnight.AddMinutes(minutes)); + var hourAngle = HourAngle(latitude, sun.Declination, elevation); + if (double.IsNaN(hourAngle)) return null; + var noon = 720 - 4 * longitude - sun.EquationOfTime; + minutes = noon + (rising ? -4 : 4) * hourAngle; + } + return midnight.AddMinutes(minutes); + } + + private static double HourAngle(double latitude, double declination, double elevation) + { + var phi = latitude * Deg; + var delta = declination * Deg; + var cosH = (Math.Cos((90 - elevation) * Deg) - Math.Sin(phi) * Math.Sin(delta)) / (Math.Cos(phi) * Math.Cos(delta)); + return cosH is < -1 or > 1 || double.IsNaN(cosH) ? double.NaN : Math.Acos(cosH) / Deg; + } + + /// NOAA approximation of standard atmospheric refraction, in degrees, for a geometric elevation. + private static double Refraction(double elevation) + { + if (elevation > 85) return 0; + var t = Math.Tan(elevation * Deg); + var arcSeconds = elevation switch + { + > 5 => 58.1 / t - 0.07 / (t * t * t) + 0.000086 / Math.Pow(t, 5), + > -0.575 => 1735 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + elevation * 0.711))), + _ => -20.772 / t, + }; + return arcSeconds / 3600; + } + + private readonly record struct Sun(double Declination, double EquationOfTime); + + private static Sun Ephemeris(DateTime utc) + { + var julianDay = 2451545.0 + (DateTime.SpecifyKind(utc, DateTimeKind.Utc) - J2000).TotalDays; + var t = (julianDay - 2451545.0) / 36525.0; + var meanLongitude = Mod(280.46646 + t * (36000.76983 + t * 0.0003032), 360); + var meanAnomaly = 357.52911 + t * (35999.05029 - 0.0001537 * t); + var eccentricity = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); + var m = meanAnomaly * Deg; + var center = Math.Sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t)) + + Math.Sin(2 * m) * (0.019993 - 0.000101 * t) + + Math.Sin(3 * m) * 0.000289; + var trueLongitude = meanLongitude + center; + var omega = (125.04 - 1934.136 * t) * Deg; + var apparentLongitude = trueLongitude - 0.00569 - 0.00478 * Math.Sin(omega); + var meanObliquity = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60; + var obliquity = (meanObliquity + 0.00256 * Math.Cos(omega)) * Deg; + var declination = Math.Asin(Math.Sin(obliquity) * Math.Sin(apparentLongitude * Deg)) / Deg; + + var y = Math.Tan(obliquity / 2); + y *= y; + var l0 = meanLongitude * Deg; + var e = eccentricity; + var equationOfTime = 4 / Deg * (y * Math.Sin(2 * l0) - 2 * e * Math.Sin(m) + 4 * e * y * Math.Sin(m) * Math.Cos(2 * l0) + - 0.5 * y * y * Math.Sin(4 * l0) - 1.25 * e * e * Math.Sin(2 * m)); + return new Sun(declination, equationOfTime); + } + + private static double Mod(double value, double modulus) + { + var r = value % modulus; + return r < 0 ? r + modulus : r; + } + + private static void ValidateLocation(double latitude, double longitude) + { + if (!(latitude >= -90 && latitude <= 90)) throw new ArgumentOutOfRangeException(nameof(latitude)); + if (!(longitude >= -180 && longitude <= 180)) throw new ArgumentOutOfRangeException(nameof(longitude)); + } +} diff --git a/tests/Titano.Core.Tests/Math/SolarPositionTests.cs b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs new file mode 100644 index 00000000..a81f514b --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +/// +/// Reference values are NOAA Solar Calculator results (spreadsheet equations as implemented by the +/// astral package, cross-checked against PyEphem/VSOP87 to within 35 s), UTC, for the local solar day. +/// +public sealed class SolarPositionTests +{ + private const double OneMinute = 60; + + [Theory] + [Case("Greenwich summer", 51.4769, -0.0005, "2024-06-21", "03:43:13", "20:20:36", "02:54:34", "21:09:14", "01:40:14", "22:23:33", null, null)] + [Case("Greenwich winter", 51.4769, -0.0005, "2024-12-21", "08:03:42", "15:52:56", "07:22:37", "16:34:01", "06:39:40", "17:16:58", "05:58:57", "17:57:41")] + [Case("New York equinox", 40.7128, -74.0060, "2024-03-20", "10:58:42", "23:08:28", "10:30:54", "23:36:20", "09:59:06", "+00:08:13", "09:26:36", "+00:40:50")] + [Case("Sydney winter", -33.8688, 151.2093, "2024-06-21", "-21:00:18", "06:53:41", "-20:32:02", "07:21:57", "-20:00:56", "07:53:03", "-19:30:30", "08:23:28")] + [Case("Quito equinox", -0.1807, -78.4678, "2024-09-22", "11:03:17", "23:09:26", "10:42:14", "23:30:29", "10:18:21", "23:54:22", "09:54:23", "+00:18:19")] + [Case("Tromso March", 69.6492, 18.9553, "2024-03-01", "06:08:32", "15:46:01", "05:06:36", "16:48:12", "03:57:47", "17:57:27", "02:44:21", "19:11:43")] + // The sun grazes −6° here, so tiny ephemeris differences move the crossing by minutes: astral's single-pass + // NOAA value is 77 s early, while the iterated NOAA solution and PyEphem agree on 08:31:31 / 12:53:21. + [Case("Tromso polar night", 69.6492, 18.9553, "2024-12-21", null, null, "08:31:31", "12:53:21", "06:46:35", "14:38:21", "05:28:22", "15:56:34")] + [Case("Tromso midnight sun", 69.6492, 18.9553, "2024-06-21", null, null, null, null, null, null, null, null)] + [Case("Golden NREL SPA site", 39.742476, -105.1786, "2003-10-17", "13:12:57", "+00:18:36", "12:45:10", "+00:46:21", "12:13:59", "+01:17:30", "11:42:47", "+01:48:39")] + public void EventsMatchNoaaWithinOneMinute(string place, double latitude, double longitude, string date, + string? sunrise, string? sunset, string? civilDawn, string? civilDusk, string? nauticalDawn, string? nauticalDusk, string? astroDawn, string? astroDusk) + { + var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture); + var events = SolarPosition.Events(day, latitude, longitude); + Check(place + " sunrise", day, sunrise, events.Sunrise); + Check(place + " sunset", day, sunset, events.Sunset); + Check(place + " civil dawn", day, civilDawn, events.CivilDawn); + Check(place + " civil dusk", day, civilDusk, events.CivilDusk); + Check(place + " nautical dawn", day, nauticalDawn, events.NauticalDawn); + Check(place + " nautical dusk", day, nauticalDusk, events.NauticalDusk); + Check(place + " astronomical dawn", day, astroDawn, events.AstronomicalDawn); + Check(place + " astronomical dusk", day, astroDusk, events.AstronomicalDusk); + } + + [Theory] + [Case(51.4769, -0.0005, "2024-06-21", "12:01:49")] + [Case(-33.8688, 151.2093, "2024-06-21", "01:56:58")] + [Case(39.742476, -105.1786, "2003-10-17", "18:46:14")] + public void SolarNoonMatchesNoaa(double latitude, double longitude, string date, string noon) + { + _ = latitude; + var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture); + Check("noon", day, noon, SolarPosition.SolarNoon(day, longitude)); + } + + [Theory] + [Case(39.742476, -105.1786, "2003-10-17T19:30:30", 39.8914, 39.8721, 194.3426)] + [Case(51.4769, -0.0005, "2024-06-21T12:00:00", 61.9665, 61.9579, 179.0598)] + [Case(-33.8688, 151.2093, "2024-01-15T06:30:00", 30.7712, 30.7442, 263.8208)] + [Case(35.6762, 139.6503, "2024-09-01T21:00:00", 8.4899, 8.3861, 86.3181)] + [Case(64.1466, -21.9426, "2024-12-01T15:00:00", 1.9248, 1.6140, 203.7679)] + public void PositionMatchesNoaa(double latitude, double longitude, string utc, double elevation, double geometric, double azimuth) + { + var time = DateTime.SpecifyKind(DateTime.ParseExact(utc, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture), DateTimeKind.Utc); + var sun = SolarPosition.Compute(time, latitude, longitude); + Assert.Approximately(geometric, sun.GeometricElevation, 0.01); + Assert.Approximately(elevation, sun.Elevation, 0.01); + Assert.Approximately(azimuth, sun.Azimuth, 0.01); + } + + [Theory] + [Case(10.0, DayPhase.Day)] + [Case(3.0, DayPhase.GoldenHour)] + [Case(-0.5, DayPhase.GoldenHour)] + [Case(-3.0, DayPhase.CivilTwilight)] + [Case(-8.0, DayPhase.NauticalTwilight)] + [Case(-15.0, DayPhase.AstronomicalTwilight)] + [Case(-30.0, DayPhase.Night)] + public void ClassifiesElevation(double elevation, DayPhase expected) => Assert.Equal(expected, SolarPosition.Classify(elevation)); + + [Test] + public void PhaseFollowsTheEvents() + { + var day = new DateOnly(2024, 12, 21); + var events = SolarPosition.Events(day, 51.4769, -0.0005); + Assert.Equal(DayPhase.Day, SolarPosition.Phase(events.SolarNoon, 51.4769, -0.0005)); + Assert.Equal(DayPhase.GoldenHour, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(-5), 51.4769, -0.0005)); + Assert.Equal(DayPhase.CivilTwilight, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(5), 51.4769, -0.0005)); + Assert.Equal(DayPhase.Night, SolarPosition.Phase(events.AstronomicalDusk!.Value.AddMinutes(5), 51.4769, -0.0005)); + Assert.Throws(() => SolarPosition.Compute(DateTime.UtcNow, 91, 0)); + } + + /// Expected "HH:mm:ss" on ; a leading '-' or '+' means the previous or next UTC day. + private static void Check(string label, DateOnly day, string? expected, DateTime? actual) + { + if (expected is null) + { + Assert.Null(actual); + return; + } + var offsetDays = expected[0] switch { '-' => -1, '+' => 1, _ => 0 }; + var clock = TimeOnly.ParseExact(expected.TrimStart('+', '-'), "HH:mm:ss", CultureInfo.InvariantCulture); + var reference = day.AddDays(offsetDays).ToDateTime(clock, DateTimeKind.Utc); + var value = Assert.NotNull(actual, label); + Assert.Approximately(0, (value - reference).TotalSeconds, OneMinute, label); + } +} From cce38c3927e73c0172938cf5e42f35453e3385f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH 012/188] feat(math): add Matrix3, Bradford adaptation and chromaticity Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/Chromaticity.cs | 39 +++++++ src/Titano.Core/Math/Matrix3.cs | 105 +++++++++++++++++++ tests/Titano.Core.Tests/Math/Matrix3Tests.cs | 70 +++++++++++++ 3 files changed, 214 insertions(+) create mode 100644 src/Titano.Core/Math/Chromaticity.cs create mode 100644 src/Titano.Core/Math/Matrix3.cs create mode 100644 tests/Titano.Core.Tests/Math/Matrix3Tests.cs diff --git a/src/Titano.Core/Math/Chromaticity.cs b/src/Titano.Core/Math/Chromaticity.cs new file mode 100644 index 00000000..49e123bd --- /dev/null +++ b/src/Titano.Core/Math/Chromaticity.cs @@ -0,0 +1,39 @@ +namespace Titano.Core.Mathematics; + +/// CIE 1931 chromaticity coordinates (lower-case x, y in the literature). +public readonly record struct Chromaticity(double X, double Y) +{ + /// CIE standard illuminant D65 (2° observer). + public static Chromaticity D65 { get; } = new(0.3127, 0.3290); + + /// CIE standard illuminant D50 (2° observer), the ICC/DNG profile connection white. + public static Chromaticity D50 { get; } = new(0.3457, 0.3585); + + /// Tristimulus values with luminance : X = x·Y/y, Z = (1 − x − y)·Y/y. + public Vector3D ToXyz(double luminance = 1) + { + if (!(Y > 0)) throw new InvalidOperationException("Chromaticity y must be positive."); + return new Vector3D(X * luminance / Y, luminance, (1 - X - Y) * luminance / Y); + } + + /// Chromaticity of tristimulus values; NaN coordinates when X + Y + Z is not positive. + public static Chromaticity FromXyz(Vector3D xyz) + { + var sum = xyz.X + xyz.Y + xyz.Z; + return sum > 0 ? new Chromaticity(xyz.X / sum, xyz.Y / sum) : new Chromaticity(double.NaN, double.NaN); + } + + /// CIE 1960 UCS coordinates u = 4x/(−2x + 12y + 3), v = 6y/(−2x + 12y + 3). + public (double U, double V) ToUv1960() + { + var d = -2 * X + 12 * Y + 3; + return (4 * X / d, 6 * Y / d); + } + + /// Chromaticity from CIE 1960 UCS coordinates. + public static Chromaticity FromUv1960(double u, double v) + { + var d = 2 * u - 8 * v + 4; + return new Chromaticity(3 * u / d, 2 * v / d); + } +} diff --git a/src/Titano.Core/Math/Matrix3.cs b/src/Titano.Core/Math/Matrix3.cs new file mode 100644 index 00000000..73b877cb --- /dev/null +++ b/src/Titano.Core/Math/Matrix3.cs @@ -0,0 +1,105 @@ +namespace Titano.Core.Mathematics; + +/// A 3-vector in double precision (colour triplets, homogeneous 2-D points). +public readonly record struct Vector3D(double X, double Y, double Z) +{ + public static Vector3D operator +(Vector3D a, Vector3D b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z); + + public static Vector3D operator -(Vector3D a, Vector3D b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z); + + public static Vector3D operator *(Vector3D a, double s) => new(a.X * s, a.Y * s, a.Z * s); + + public static double Dot(Vector3D a, Vector3D b) => a.X * b.X + a.Y * b.Y + a.Z * b.Z; +} + +/// Row-major 3×3 matrix in double precision for colour-space and planar projective work. +public readonly record struct Matrix3( + double M11, double M12, double M13, + double M21, double M22, double M23, + double M31, double M32, double M33) +{ + public static Matrix3 Identity { get; } = new(1, 0, 0, 0, 1, 0, 0, 0, 1); + + /// Bradford cone-response matrix (Lam 1985), XYZ → sharpened LMS. + public static Matrix3 Bradford { get; } = new( + 0.8951, 0.2664, -0.1614, + -0.7502, 1.7135, 0.0367, + 0.0389, -0.0685, 1.0296); + + /// Linear Rec.709/sRGB (D65) → CIE XYZ, derived from the primaries. + public static Matrix3 Rec709ToXyz { get; } = RgbToXyz(new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), Chromaticity.D65); + + /// CIE XYZ → linear Rec.709/sRGB (D65). + public static Matrix3 XyzToRec709 { get; } = Rec709ToXyz.Inverse(); + + public static Matrix3 Diagonal(double a, double b, double c) => new(a, 0, 0, 0, b, 0, 0, 0, c); + + /// Matrix whose columns are , , . + public static Matrix3 FromColumns(Vector3D c1, Vector3D c2, Vector3D c3) => new(c1.X, c2.X, c3.X, c1.Y, c2.Y, c3.Y, c1.Z, c2.Z, c3.Z); + + public static Matrix3 operator *(Matrix3 a, Matrix3 b) => new( + a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31, a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32, a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33, + a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31, a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32, a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33, + a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31, a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32, a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33); + + public static Vector3D operator *(Matrix3 m, Vector3D v) => new( + m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z, + m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z, + m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z); + + public static Matrix3 operator *(Matrix3 m, double s) => new( + m.M11 * s, m.M12 * s, m.M13 * s, m.M21 * s, m.M22 * s, m.M23 * s, m.M31 * s, m.M32 * s, m.M33 * s); + + public double Determinant => + M11 * (M22 * M33 - M23 * M32) - M12 * (M21 * M33 - M23 * M31) + M13 * (M21 * M32 - M22 * M31); + + public Matrix3 Transpose() => new(M11, M21, M31, M12, M22, M32, M13, M23, M33); + + /// Inverse by the adjugate; false when the matrix is singular relative to its scale. + public bool TryInvert(out Matrix3 inverse) + { + var det = Determinant; + var scale = MaxAbs(); + if (!(Math.Abs(det) > 1e-14 * scale * scale * scale) || !double.IsFinite(det)) + { + inverse = default; + return false; + } + var r = 1 / det; + inverse = new Matrix3( + (M22 * M33 - M23 * M32) * r, (M13 * M32 - M12 * M33) * r, (M12 * M23 - M13 * M22) * r, + (M23 * M31 - M21 * M33) * r, (M11 * M33 - M13 * M31) * r, (M13 * M21 - M11 * M23) * r, + (M21 * M32 - M22 * M31) * r, (M12 * M31 - M11 * M32) * r, (M11 * M22 - M12 * M21) * r); + return true; + } + + /// The matrix is singular. + public Matrix3 Inverse() => TryInvert(out var inverse) ? inverse : throw new InvalidOperationException("Matrix is singular."); + + /// + /// Bradford chromatic adaptation (von Kries scaling in the Bradford cone space) mapping colours seen under + /// to ; both whites as XYZ. + /// + public static Matrix3 BradfordAdaptation(Vector3D sourceWhite, Vector3D destinationWhite) + { + var s = Bradford * sourceWhite; + var d = Bradford * destinationWhite; + if (!(s.X > 0 && s.Y > 0 && s.Z > 0)) throw new ArgumentOutOfRangeException(nameof(sourceWhite), "White point must have positive cone responses."); + return Bradford.Inverse() * Diagonal(d.X / s.X, d.Y / s.Y, d.Z / s.Z) * Bradford; + } + + /// RGB → XYZ matrix of an additive colour space from its primaries and white point (white maps to Y = 1). + public static Matrix3 RgbToXyz(Chromaticity red, Chromaticity green, Chromaticity blue, Chromaticity white) + { + var primaries = FromColumns(red.ToXyz(), green.ToXyz(), blue.ToXyz()); + var s = primaries.Inverse() * white.ToXyz(); + return primaries * Diagonal(s.X, s.Y, s.Z); + } + + private double MaxAbs() + { + var m = Math.Max(Math.Max(Math.Abs(M11), Math.Abs(M12)), Math.Abs(M13)); + m = Math.Max(m, Math.Max(Math.Max(Math.Abs(M21), Math.Abs(M22)), Math.Abs(M23))); + return Math.Max(m, Math.Max(Math.Max(Math.Abs(M31), Math.Abs(M32)), Math.Abs(M33))); + } +} diff --git a/tests/Titano.Core.Tests/Math/Matrix3Tests.cs b/tests/Titano.Core.Tests/Math/Matrix3Tests.cs new file mode 100644 index 00000000..23128b2f --- /dev/null +++ b/tests/Titano.Core.Tests/Math/Matrix3Tests.cs @@ -0,0 +1,70 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +public sealed class Matrix3Tests +{ + [Test] + public void InverseAndTranspose() + { + var m = new Matrix3(2, -1, 0.5, 0.3, 4, 1, -2, 0.7, 3); + AssertClose(Matrix3.Identity, m * m.Inverse(), 1e-12); + AssertClose(Matrix3.Identity, m.Inverse() * m, 1e-12); + Assert.Equal(m, m.Transpose().Transpose()); + Assert.Equal(m.M12, m.Transpose().M21); + Assert.Approximately(m.Determinant, m.Transpose().Determinant, 1e-12); + Assert.False(new Matrix3(1, 2, 3, 2, 4, 6, 0, 1, 1).TryInvert(out _)); + Assert.Throws(() => new Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0).Inverse()); + } + + [Test] + public void BradfordD65ToD50MatchesLindbloom() + { + // Lindbloom's published matrix uses these tristimulus whites. + var d65 = new Vector3D(0.95047, 1.0, 1.08883); + var d50 = new Vector3D(0.96422, 1.0, 0.82521); + var expected = new Matrix3( + 1.0478112, 0.0228866, -0.0501270, + 0.0295424, 0.9904844, -0.0170491, + -0.0092345, 0.0150436, 0.7521316); + var adaptation = Matrix3.BradfordAdaptation(d65, d50); + AssertClose(expected, adaptation, 1e-6); + var mapped = adaptation * d65; + Assert.Approximately(d50.X, mapped.X, 1e-12); + Assert.Approximately(d50.Z, mapped.Z, 1e-12); + } + + [Test] + public void Rec709MatrixMatchesLumaWeightsAndWhite() + { + var m = Matrix3.Rec709ToXyz; + Assert.Approximately(ColorSpace.LumaR, m.M21, 1e-4); + Assert.Approximately(ColorSpace.LumaG, m.M22, 1e-4); + Assert.Approximately(ColorSpace.LumaB, m.M23, 1e-4); + var white = Chromaticity.FromXyz(m * new Vector3D(1, 1, 1)); + Assert.Within(0.3127, 0.3290, white.X, white.Y, 1e-12); + AssertClose(Matrix3.Identity, Matrix3.XyzToRec709 * m, 1e-12); + } + + [Test] + public void ChromaticityRoundTrips() + { + var xyz = Chromaticity.D50.ToXyz(0.4); + var back = Chromaticity.FromXyz(xyz); + Assert.Within(0.3457, 0.3585, back.X, back.Y, 1e-14); + Assert.Approximately(0.4, xyz.Y, 1e-15); + var (u, v) = Chromaticity.D65.ToUv1960(); + var again = Chromaticity.FromUv1960(u, v); + Assert.Within(0.3127, 0.3290, again.X, again.Y, 1e-14); + Assert.True(double.IsNaN(Chromaticity.FromXyz(new Vector3D(0, 0, 0)).X)); + } + + private static void AssertClose(Matrix3 expected, Matrix3 actual, double tolerance) + { + double[] e = [expected.M11, expected.M12, expected.M13, expected.M21, expected.M22, expected.M23, expected.M31, expected.M32, expected.M33]; + double[] a = [actual.M11, actual.M12, actual.M13, actual.M21, actual.M22, actual.M23, actual.M31, actual.M32, actual.M33]; + for (var i = 0; i < 9; i++) Assert.Approximately(e[i], a[i], tolerance, $"element {i}"); + } +} From 648f5ca7b0b95e9cfc37a5222694f94fe1efdd64 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:33:30 +0000 Subject: [PATCH 013/188] feat(video): add streaming MP4 muxer, decoder configuration records and MP4 inspector Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/Mp4/BoxWriter.cs | 106 +++ .../Video/Mp4/DecoderConfiguration.cs | 251 +++++++ src/Titano.Core/Video/Mp4/Mp4Muxer.cs | 662 +++++++++++++++++ src/Titano.Core/Video/Mp4Inspector.cs | 683 ++++++++++++++++++ .../Titano.Core.Tests/Video/Mp4MuxerTests.cs | 240 ++++++ tests/Titano.Core.Tests/Video/SparseStream.cs | 76 ++ 6 files changed, 2018 insertions(+) create mode 100644 src/Titano.Core/Video/Mp4/BoxWriter.cs create mode 100644 src/Titano.Core/Video/Mp4/DecoderConfiguration.cs create mode 100644 src/Titano.Core/Video/Mp4/Mp4Muxer.cs create mode 100644 src/Titano.Core/Video/Mp4Inspector.cs create mode 100644 tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs create mode 100644 tests/Titano.Core.Tests/Video/SparseStream.cs diff --git a/src/Titano.Core/Video/Mp4/BoxWriter.cs b/src/Titano.Core/Video/Mp4/BoxWriter.cs new file mode 100644 index 00000000..80542462 --- /dev/null +++ b/src/Titano.Core/Video/Mp4/BoxWriter.cs @@ -0,0 +1,106 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Video.Mp4; + +/// +/// Big-endian ISO-BMFF box builder over a growable in-memory buffer. Boxes nest with +/// /; sizes (32-bit) are patched when a box closes. +/// +public sealed class BoxWriter +{ + private readonly Stack _open = new(); + private byte[] _buffer; + private int _length; + + public BoxWriter(int capacity = 4096) => _buffer = new byte[Math.Max(capacity, 64)]; + + public int Length => _length; + + public ReadOnlySpan WrittenSpan => _buffer.AsSpan(0, _length); + + public void BeginBox(string type) + { + _open.Push(_length); + WriteUInt32(0); + WriteFourCc(type); + } + + public void BeginFullBox(string type, byte version, uint flags) + { + BeginBox(type); + WriteUInt32((uint)version << 24 | (flags & 0xFFFFFF)); + } + + public void EndBox() + { + var start = _open.Pop(); + BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(start), (uint)(_length - start)); + } + + public void WriteByte(int value) => Grow(1)[0] = (byte)value; + + public void WriteUInt16(int value) => BinaryPrimitives.WriteUInt16BigEndian(Grow(2), (ushort)value); + + public void WriteInt16(short value) => BinaryPrimitives.WriteInt16BigEndian(Grow(2), value); + + public void WriteUInt24(uint value) + { + var span = Grow(3); + span[0] = (byte)(value >> 16); + span[1] = (byte)(value >> 8); + span[2] = (byte)value; + } + + public void WriteUInt32(uint value) => BinaryPrimitives.WriteUInt32BigEndian(Grow(4), value); + + public void WriteInt32(int value) => BinaryPrimitives.WriteInt32BigEndian(Grow(4), value); + + public void WriteUInt48(ulong value) + { + WriteUInt16((int)(value >> 32)); + WriteUInt32((uint)value); + } + + public void WriteUInt64(ulong value) => BinaryPrimitives.WriteUInt64BigEndian(Grow(8), value); + + public void WriteInt64(long value) => BinaryPrimitives.WriteInt64BigEndian(Grow(8), value); + + public void WriteFourCc(string fourCc) + { + if (fourCc.Length != 4) throw new ArgumentException("A four-character code is required", nameof(fourCc)); + var span = Grow(4); + for (var i = 0; i < 4; i++) span[i] = (byte)fourCc[i]; + } + + public void WriteBytes(ReadOnlySpan bytes) => bytes.CopyTo(Grow(bytes.Length)); + + public void WriteZeros(int count) => Grow(count).Clear(); + + /// The identity transformation matrix of mvhd/tkhd. + public void WriteUnityMatrix() + { + WriteUInt32(0x00010000); + WriteUInt32(0); + WriteUInt32(0); + WriteUInt32(0); + WriteUInt32(0x00010000); + WriteUInt32(0); + WriteUInt32(0); + WriteUInt32(0); + WriteUInt32(0x40000000); + } + + public byte[] ToArray() + { + if (_open.Count != 0) throw new InvalidOperationException("Unclosed box"); + return WrittenSpan.ToArray(); + } + + private Span Grow(int count) + { + if (_length + count > _buffer.Length) Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + count)); + var span = _buffer.AsSpan(_length, count); + _length += count; + return span; + } +} diff --git a/src/Titano.Core/Video/Mp4/DecoderConfiguration.cs b/src/Titano.Core/Video/Mp4/DecoderConfiguration.cs new file mode 100644 index 00000000..a9df9b77 --- /dev/null +++ b/src/Titano.Core/Video/Mp4/DecoderConfiguration.cs @@ -0,0 +1,251 @@ +using System.Buffers.Binary; +using System.Globalization; +using Titano.Core.Video.Bitstream; + +namespace Titano.Core.Video.Mp4; + +/// +/// A decoder configuration record (avcC, hvcC or av1C payload) with the stream properties it declares. +/// +public sealed record DecoderConfiguration( + VideoCodec Codec, + string BoxType, + byte[] Payload, + int Width, + int Height, + int BitDepth, + string CodecString) +{ + /// Builds avcC (ISO/IEC 14496-15 5.3.3) from SPS and PPS NAL units; the first SPS describes the stream. + public static DecoderConfiguration ForAvc(IReadOnlyList sps, IReadOnlyList pps) + { + if (sps.Count is 0 or > 31 || pps.Count is 0 or > 255) throw new ArgumentException("avcC needs 1–31 SPS and 1–255 PPS"); + if (!H264SpsParser.TryParse(sps[0], out var info)) throw new ArgumentException("Unparseable H.264 SPS", nameof(sps)); + var w = new BoxWriter(256); + w.WriteByte(1); + w.WriteByte(info.ProfileIdc); + w.WriteByte(info.ConstraintFlags); + w.WriteByte(info.LevelIdc); + w.WriteByte(0xFF); // reserved + lengthSizeMinusOne = 3 + w.WriteByte(0xE0 | sps.Count); + foreach (var s in sps) + { + w.WriteUInt16(s.Length); + w.WriteBytes(s); + } + w.WriteByte(pps.Count); + foreach (var p in pps) + { + w.WriteUInt16(p.Length); + w.WriteBytes(p); + } + if (info.ProfileIdc is 100 or 110 or 122 or 144) + { + w.WriteByte(0xFC | info.ChromaFormatIdc); + w.WriteByte(0xF8 | (info.BitDepthLuma - 8)); + w.WriteByte(0xF8 | (info.BitDepthChroma - 8)); + w.WriteByte(0); // numOfSequenceParameterSetExt + } + return new DecoderConfiguration(VideoCodec.H264, "avcC", w.ToArray(), info.Width, info.Height, info.BitDepthLuma, AvcCodecString(info)); + } + + /// Builds hvcC (ISO/IEC 14496-15 8.3.3) with complete VPS/SPS/PPS arrays; the first SPS describes the stream. + public static DecoderConfiguration ForHevc(IReadOnlyList vps, IReadOnlyList sps, IReadOnlyList pps) + { + if (vps.Count == 0 || sps.Count == 0 || pps.Count == 0) throw new ArgumentException("hvcC needs VPS, SPS and PPS"); + if (!HevcSpsParser.TryParse(sps[0], out var info)) throw new ArgumentException("Unparseable HEVC SPS", nameof(sps)); + var ptl = info.ProfileTierLevel; + var w = new BoxWriter(256); + w.WriteByte(1); + w.WriteByte(ptl.ProfileSpace << 6 | (ptl.HighTier ? 0x20 : 0) | ptl.ProfileIdc); + w.WriteUInt32(ptl.ProfileCompatibilityFlags); + w.WriteUInt48(ptl.ConstraintIndicatorFlags); + w.WriteByte(ptl.LevelIdc); + w.WriteUInt16(0xF000); // min_spatial_segmentation_idc = 0 + w.WriteByte(0xFC); // parallelismType = 0 (unknown) + w.WriteByte(0xFC | info.ChromaFormatIdc); + w.WriteByte(0xF8 | (info.BitDepthLuma - 8)); + w.WriteByte(0xF8 | (info.BitDepthChroma - 8)); + w.WriteUInt16(0); // avgFrameRate unspecified + w.WriteByte((info.MaxSubLayers & 7) << 3 | (info.TemporalIdNesting ? 4 : 0) | 3); + w.WriteByte(3); + WriteArray(w, HevcNalUnitType.Vps, vps); + WriteArray(w, HevcNalUnitType.Sps, sps); + WriteArray(w, HevcNalUnitType.Pps, pps); + return new DecoderConfiguration(VideoCodec.Hevc, "hvcC", w.ToArray(), info.Width, info.Height, info.BitDepthLuma, HevcCodecString(ptl)); + + static void WriteArray(BoxWriter w, HevcNalUnitType type, IReadOnlyList nals) + { + w.WriteByte(0x80 | (int)type); // array_completeness = 1: no parameter sets in-band (hvc1) + w.WriteUInt16(nals.Count); + foreach (var nal in nals) + { + w.WriteUInt16(nal.Length); + w.WriteBytes(nal); + } + } + } + + /// Builds av1C (AV1-ISOBMFF 2.3) around a sequence header OBU written with obu_size. + public static DecoderConfiguration ForAv1(byte[] sequenceHeaderObu) + { + if (!Av1ObuParser.TryReadObu(sequenceHeaderObu, 0, out var obu) || obu.Type != Av1ObuType.SequenceHeader || !obu.HasSizeField + || !Av1ObuParser.TryParseSequenceHeader(obu.Payload(sequenceHeaderObu), out var seq)) + throw new ArgumentException("A sized sequence header OBU is required", nameof(sequenceHeaderObu)); + var w = new BoxWriter(64); + w.WriteByte(0x81); // marker + version 1 + w.WriteByte(seq.SeqProfile << 5 | seq.SeqLevelIdx); + w.WriteByte((seq.SeqTier ? 0x80 : 0) | (seq.HighBitDepth ? 0x40 : 0) | (seq.TwelveBit ? 0x20 : 0) | (seq.MonoChrome ? 0x10 : 0) + | (seq.ChromaSubsamplingX ? 0x08 : 0) | (seq.ChromaSubsamplingY ? 0x04 : 0) | seq.ChromaSamplePosition); + w.WriteByte(seq.InitialDisplayDelay is { } delay ? 0x10 | ((delay - 1) & 0x0F) : 0); + w.WriteBytes(sequenceHeaderObu.AsSpan(0, obu.TotalLength)); + return new DecoderConfiguration(VideoCodec.Av1, "av1C", w.ToArray(), seq.MaxFrameWidth, seq.MaxFrameHeight, seq.BitDepth, Av1CodecString(seq)); + } + + /// Parses an avcC/hvcC/av1C payload back; explains a failure. + public static bool TryParse(string boxType, ReadOnlySpan payload, out DecoderConfiguration? configuration, out string? error) + { + configuration = null; + error = null; + try + { + configuration = boxType switch + { + "avcC" => ParseAvc(payload, out error), + "hvcC" => ParseHevc(payload, out error), + "av1C" => ParseAv1(payload, out error), + _ => null, + }; + } + catch (ArgumentException ex) + { + error = ex.Message; + configuration = null; + } + error ??= configuration is null ? $"unsupported configuration box '{boxType}'" : null; + return configuration is not null; + } + + private static DecoderConfiguration? ParseAvc(ReadOnlySpan p, out string? error) + { + error = null; + if (p.Length < 7 || p[0] != 1) + { + error = "avcC header invalid"; + return null; + } + if ((p[4] & 3) != 3) error = "avcC lengthSizeMinusOne is not 3"; + var pos = 5; + var sps = ReadNalList(p, ref pos, p[5] & 0x1F, 1); + var pps = pos < p.Length ? ReadNalList(p, ref pos, p[pos], 1) : null; + if (sps is null || pps is null || sps.Count == 0 || pps.Count == 0) + { + error = "avcC parameter set lists truncated or empty"; + return null; + } + var config = ForAvc(sps, pps); + if (config.Payload[1] != p[1] || config.Payload[3] != p[3]) error = "avcC profile/level differ from its SPS"; + return config; + } + + private static DecoderConfiguration? ParseHevc(ReadOnlySpan p, out string? error) + { + error = null; + if (p.Length < 23 || p[0] != 1) + { + error = "hvcC header invalid"; + return null; + } + if ((p[21] & 3) != 3) error = "hvcC lengthSizeMinusOne is not 3"; + var arrays = p[22]; + var pos = 23; + List vps = [], sps = [], pps = []; + for (var a = 0; a < arrays; a++) + { + if (pos + 3 > p.Length) + { + error = "hvcC arrays truncated"; + return null; + } + var type = (HevcNalUnitType)(p[pos] & 0x3F); + var count = BinaryPrimitives.ReadUInt16BigEndian(p[(pos + 1)..]); + pos += 3; + var list = ReadNalList(p, ref pos, count, 0); + if (list is null) + { + error = "hvcC NAL units truncated"; + return null; + } + (type switch { HevcNalUnitType.Vps => vps, HevcNalUnitType.Sps => sps, HevcNalUnitType.Pps => pps, _ => [] }).AddRange(list); + } + if (vps.Count == 0 || sps.Count == 0 || pps.Count == 0) + { + error = "hvcC lacks a VPS, SPS or PPS array"; + return null; + } + var config = ForHevc(vps, sps, pps); + if (!config.Payload.AsSpan(1, 12).SequenceEqual(p.Slice(1, 12))) error = "hvcC profile/tier/level differ from its SPS"; + return config; + } + + private static DecoderConfiguration? ParseAv1(ReadOnlySpan p, out string? error) + { + error = null; + if (p.Length < 4 || p[0] != 0x81) + { + error = "av1C marker/version invalid"; + return null; + } + var obus = p[4..]; + foreach (var obu in Av1ObuParser.Split(obus)) + { + if (obu.Type != Av1ObuType.SequenceHeader) continue; + var config = ForAv1(obus.Slice(obu.Offset, obu.TotalLength).ToArray()); + if (config.Payload[1] != p[1] || config.Payload[2] != p[2]) error = "av1C fields differ from its sequence header"; + return config; + } + error = "av1C has no sequence header OBU"; + return null; + } + + private static List? ReadNalList(ReadOnlySpan p, ref int pos, int count, int countBytes) + { + pos += countBytes; + var list = new List(count); + for (var i = 0; i < count; i++) + { + if (pos + 2 > p.Length) return null; + var length = BinaryPrimitives.ReadUInt16BigEndian(p[pos..]); + pos += 2; + if (length == 0 || pos + length > p.Length) return null; + list.Add(p.Slice(pos, length).ToArray()); + pos += length; + } + return list; + } + + private static string AvcCodecString(H264Sps sps) => + string.Create(CultureInfo.InvariantCulture, $"avc1.{sps.ProfileIdc:x2}{sps.ConstraintFlags:x2}{sps.LevelIdc:x2}"); + + private static string HevcCodecString(HevcProfileTierLevel ptl) + { + var space = ptl.ProfileSpace == 0 ? string.Empty : ((char)('A' + ptl.ProfileSpace - 1)).ToString(); + var compatibility = ReverseBits(ptl.ProfileCompatibilityFlags); + var s = string.Create(CultureInfo.InvariantCulture, + $"hvc1.{space}{ptl.ProfileIdc}.{compatibility:X}.{(ptl.HighTier ? 'H' : 'L')}{ptl.LevelIdc}"); + var last = 5; + while (last >= 0 && ((ptl.ConstraintIndicatorFlags >> (8 * (5 - last))) & 0xFF) == 0) last--; + for (var i = 0; i <= last; i++) s += "." + ((ptl.ConstraintIndicatorFlags >> (8 * (5 - i))) & 0xFF).ToString("X", CultureInfo.InvariantCulture); + return s; + } + + private static string Av1CodecString(Av1SequenceHeader seq) => + string.Create(CultureInfo.InvariantCulture, $"av01.{seq.SeqProfile}.{seq.SeqLevelIdx:D2}{(seq.SeqTier ? 'H' : 'M')}.{seq.BitDepth:D2}"); + + private static uint ReverseBits(uint v) + { + uint r = 0; + for (var i = 0; i < 32; i++, v >>= 1) r = (r << 1) | (v & 1); + return r; + } +} diff --git a/src/Titano.Core/Video/Mp4/Mp4Muxer.cs b/src/Titano.Core/Video/Mp4/Mp4Muxer.cs new file mode 100644 index 00000000..2e1f3e74 --- /dev/null +++ b/src/Titano.Core/Video/Mp4/Mp4Muxer.cs @@ -0,0 +1,662 @@ +using System.Buffers.Binary; +using Titano.Core.Diagnostics; +using Titano.Core.Video.Bitstream; + +namespace Titano.Core.Video.Mp4; + +/// Parameters of the single video track written by . +public sealed record VideoTrackConfig +{ + /// , or . + public required VideoCodec Codec { get; init; } + + /// Display width (tkhd); the sample entry uses the size declared by the bitstream. + public required int Width { get; init; } + + public required int Height { get; init; } + + /// Moves moov in front of mdat when completing (progressive playback); the stream must be readable. + public bool FastStart { get; init; } + + /// Signalled in colr; Titano encodes limited (video) range. + public bool FullRange { get; init; } + + public DateTime CreationTime { get; init; } = DateTime.UtcNow; +} + +/// +/// Streaming MP4 writer for one video track: ftyp, then samples straight into mdat, then moov at the end +/// (optionally moved to the front). Timescale 90 kHz; parameter sets are taken from the bitstream. +/// The output stream is not disposed. +/// +public sealed class Mp4Muxer +{ + /// Media and movie timescale (ticks per second). + public const int TimeScale = 90_000; + + private const long ChunkTicks = TimeScale; + private const long ChunkBytes = 4 << 20; + private const string LogCategory = "Mp4Muxer"; + + private readonly Stream _stream; + private readonly VideoTrackConfig _config; + private readonly long _mdatHeader; + private readonly List _sizes = []; + private readonly List _durations = []; + private readonly List _compositionOffsets = []; + private readonly List _syncSamples = []; + private readonly List _chunkOffsets = []; + private readonly List _chunkSampleCounts = []; + private readonly SortedDictionary _vps = []; + private readonly SortedDictionary _sps = []; + private readonly SortedDictionary _pps = []; + private byte[]? _av1SequenceHeader; + private long _position; + private long _chunkTicks; + private long _chunkBytes; + private long _totalTicks; + private long _totalBytes; + private bool _warnedInBandChange; + private bool _completed; + + public Mp4Muxer(Stream output, VideoTrackConfig config) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(config); + if (config.Codec is not (VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1)) + throw new ArgumentException($"MP4 muxing supports H.264, HEVC and AV1, not {config.Codec}", nameof(config)); + if (config.Width is <= 0 or > ushort.MaxValue || config.Height is <= 0 or > ushort.MaxValue) + throw new ArgumentOutOfRangeException(nameof(config), "Frame size out of range"); + if (!output.CanSeek || !output.CanWrite) throw new ArgumentException("The output stream must be writable and seekable", nameof(output)); + if (config.FastStart && !output.CanRead) throw new ArgumentException("FastStart needs a readable stream", nameof(output)); + + _stream = output; + _config = config; + var ftyp = new BoxWriter(64); + ftyp.BeginBox("ftyp"); + ftyp.WriteFourCc("isom"); + ftyp.WriteUInt32(0x200); + ftyp.WriteFourCc("isom"); + ftyp.WriteFourCc("iso6"); + ftyp.WriteFourCc("mp41"); + if (config.Codec == VideoCodec.Av1) ftyp.WriteFourCc("av01"); + ftyp.EndBox(); + _stream.Write(ftyp.WrittenSpan); + _mdatHeader = _stream.Position; + // 16 bytes: 'free' + 32-bit 'mdat' header, or one 64-bit 'mdat' header when the payload exceeds 4 GiB. + _stream.Write(stackalloc byte[16]); + _position = _mdatHeader + 16; + } + + public int SampleCount => _sizes.Count; + + /// Sum of the sample durations written so far, in 90 kHz ticks. + public long Duration90k => _totalTicks; + + /// + /// Records parameter sets (H.264/HEVC NAL units, Annex-B or length-prefixed) or an AV1 sequence header OBU + /// delivered outside the samples, e.g. an encoder's MF_MT_MPEG_SEQUENCE_HEADER. + /// + public void AddParameterSets(ReadOnlySpan data) + { + if (_config.Codec == VideoCodec.Av1) + { + foreach (var obu in Av1ObuParser.Split(data)) + { + if (obu.Type == Av1ObuType.SequenceHeader) _av1SequenceHeader ??= SizedObu(data, obu); + } + return; + } + foreach (var unit in AnnexBParser.SplitAccessUnit(data, out _)) RecordNal(unit.Slice(data)); + } + + /// + /// Appends one access unit (H.264/HEVC: Annex-B or 4-byte length-prefixed NAL units; AV1: a temporal unit of OBUs) + /// in decode order. is presentation minus decode time and may be negative. + /// + public void WriteSample(ReadOnlySpan data, long duration90k, bool isSync, long compositionOffset90k = 0) + { + if (_completed) throw new InvalidOperationException("The muxer is complete"); + if (duration90k <= 0 || duration90k > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(duration90k)); + if (Math.Abs(compositionOffset90k) > int.MaxValue / 2) throw new ArgumentOutOfRangeException(nameof(compositionOffset90k)); + + var start = _position; + if (_stream.Position != start) _stream.Position = start; + var size = _config.Codec == VideoCodec.Av1 ? WriteObus(data) : WriteNalUnits(data); + if (size == 0) throw new ArgumentException("The sample contains no picture data", nameof(data)); + if (_sizes.Count == 0 && !isSync) Log.Warning(LogCategory, "First sample is not a sync sample; players may not start decoding"); + + if (_chunkSampleCounts.Count == 0 || _chunkTicks >= ChunkTicks || _chunkBytes >= ChunkBytes) + { + _chunkOffsets.Add(start); + _chunkSampleCounts.Add(0); + _chunkTicks = 0; + _chunkBytes = 0; + } + _chunkSampleCounts[^1]++; + _chunkTicks += duration90k; + _chunkBytes += size; + _sizes.Add((uint)size); + _durations.Add((uint)duration90k); + _compositionOffsets.Add(compositionOffset90k); + if (isSync) _syncSamples.Add((uint)_sizes.Count); + _totalTicks += duration90k; + _totalBytes += size; + } + + /// Patches mdat, writes moov (and relocates it when is set) and flushes. + public void Complete() + { + if (_completed) throw new InvalidOperationException("The muxer is already complete"); + if (_sizes.Count == 0) throw new InvalidOperationException("No samples were written"); + var configuration = BuildDecoderConfiguration(); + if (configuration.Width != _config.Width || configuration.Height != _config.Height) + { + Log.Warning(LogCategory, $"Bitstream size {configuration.Width}×{configuration.Height} differs from the track size {_config.Width}×{_config.Height}"); + } + + WriteMdatHeader(); + var moov = BuildMoov(configuration, 0); + _stream.Position = _position; + _stream.Write(moov); + if (_config.FastStart) MoveMoovToFront(configuration, moov.Length); + else _position += moov.Length; + _stream.Flush(); + _completed = true; + } + + private long WriteNalUnits(ReadOnlySpan data) + { + Span length = stackalloc byte[4]; + long size = 0; + var picture = false; + foreach (var unit in AnnexBParser.SplitAccessUnit(data, out _)) + { + var nal = unit.Slice(data); + if (!RecordNal(nal)) continue; + BinaryPrimitives.WriteInt32BigEndian(length, nal.Length); + _stream.Write(length); + _stream.Write(nal); + size += 4 + nal.Length; + picture |= IsPicture(nal[0]); + } + _position += size; + return picture ? size : 0; + } + + private long WriteObus(ReadOnlySpan data) + { + var obus = Av1ObuParser.Split(data); + if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length) + throw new ArgumentException("Malformed AV1 temporal unit", nameof(data)); + Span header = stackalloc byte[2 + 8]; + long size = 0; + var picture = false; + foreach (var obu in obus) + { + if (obu.Type is Av1ObuType.TemporalDelimiter or Av1ObuType.Padding) continue; + if (obu.Type == Av1ObuType.SequenceHeader) _av1SequenceHeader ??= SizedObu(data, obu); + picture |= obu.Type is Av1ObuType.Frame or Av1ObuType.FrameHeader or Av1ObuType.TileGroup; + if (obu.HasSizeField) + { + _stream.Write(data.Slice(obu.Offset, obu.TotalLength)); + size += obu.TotalLength; + continue; + } + // Samples carry every OBU with obu_size (AV1-ISOBMFF 2.4). + var n = WriteSizedHeader(header, data, obu); + _stream.Write(header[..n]); + _stream.Write(obu.Payload(data)); + size += n + obu.PayloadLength; + } + _position += size; + return picture ? size : 0; + } + + private static int WriteSizedHeader(Span header, ReadOnlySpan data, Av1Obu obu) + { + header[0] = (byte)(data[obu.Offset] | 0x02); + var n = 1; + if (obu.HasExtension) header[n++] = data[obu.Offset + 1]; + return n + Av1ObuParser.WriteLeb128(header[n..], (ulong)obu.PayloadLength); + } + + private static byte[] SizedObu(ReadOnlySpan data, Av1Obu obu) + { + Span header = stackalloc byte[2 + 8]; + var n = WriteSizedHeader(header, data, obu); + var result = new byte[n + obu.PayloadLength]; + header[..n].CopyTo(result); + obu.Payload(data).CopyTo(result.AsSpan(n)); + return result; + } + + private bool IsPicture(byte header) => _config.Codec == VideoCodec.H264 + ? AnnexBParser.H264Type(header) is >= H264NalUnitType.NonIdrSlice and <= H264NalUnitType.IdrSlice + : (int)AnnexBParser.HevcType(header) < 32; + + /// Stores parameter sets for the sample entry; returns whether the NAL unit belongs in the sample. + private bool RecordNal(ReadOnlySpan nal) + { + if (nal.Length < 2) return true; + SortedDictionary table; + int id; + if (_config.Codec == VideoCodec.H264) + { + switch (AnnexBParser.H264Type(nal[0])) + { + case H264NalUnitType.AccessUnitDelimiter or H264NalUnitType.FillerData: + return false; + case H264NalUnitType.Sps when H264SpsParser.TryParse(nal, out var sps): + (table, id) = (_sps, sps.SpsId); + break; + case H264NalUnitType.Pps: + (table, id) = (_pps, FirstUe(nal[1..])); + break; + default: + return true; + } + } + else + { + switch (AnnexBParser.HevcType(nal[0])) + { + case HevcNalUnitType.AccessUnitDelimiter or HevcNalUnitType.FillerData: + return false; + case HevcNalUnitType.Vps when nal.Length > 2: + (table, id) = (_vps, nal[2] >> 4); + break; + case HevcNalUnitType.Sps when HevcSpsParser.TryParse(nal, out var sps): + (table, id) = (_sps, sps.SpsId); + break; + case HevcNalUnitType.Pps: + (table, id) = (_pps, FirstUe(nal[2..])); + break; + default: + return true; + } + } + if (id < 0) return true; + if (!table.TryGetValue(id, out var known)) + { + table[id] = nal.ToArray(); + return false; + } + if (nal.SequenceEqual(known)) return false; + // A redefinition keeps working in-band, but the sample entry describes only the first definition. + if (!_warnedInBandChange) + { + Log.Warning(LogCategory, "A parameter set changed mid-stream; keeping the new one in-band"); + _warnedInBandChange = true; + } + return true; + } + + private static int FirstUe(ReadOnlySpan payload) + { + var rbsp = AnnexBParser.RemoveEmulationPrevention(payload[..Math.Min(payload.Length, 8)]); + var r = new BitReader(rbsp); + var v = r.ReadUe(); + return r.IsOverrun || v > 255 ? -1 : (int)v; + } + + private DecoderConfiguration BuildDecoderConfiguration() => _config.Codec switch + { + VideoCodec.H264 when _sps.Count > 0 && _pps.Count > 0 => DecoderConfiguration.ForAvc([.. _sps.Values], [.. _pps.Values]), + VideoCodec.Hevc when _vps.Count > 0 && _sps.Count > 0 && _pps.Count > 0 => + DecoderConfiguration.ForHevc([.. _vps.Values], [.. _sps.Values], [.. _pps.Values]), + VideoCodec.Av1 when _av1SequenceHeader is not null => DecoderConfiguration.ForAv1(_av1SequenceHeader), + _ => throw new InvalidOperationException("The bitstream carried no parameter sets / sequence header"), + }; + + private void WriteMdatHeader() + { + Span header = stackalloc byte[16]; + var compact = _position - (_mdatHeader + 8); + if (compact <= uint.MaxValue) + { + BinaryPrimitives.WriteUInt32BigEndian(header, 8); + "free"u8.CopyTo(header[4..]); + BinaryPrimitives.WriteUInt32BigEndian(header[8..], (uint)compact); + "mdat"u8.CopyTo(header[12..]); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(header, 1); + "mdat"u8.CopyTo(header[4..]); + BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(_position - _mdatHeader)); + } + _stream.Position = _mdatHeader; + _stream.Write(header); + } + + private void MoveMoovToFront(DecoderConfiguration configuration, int moovAtEnd) + { + // Chunk offsets grow by the relocated moov size, which itself grows if they now need co64. + var delta = moovAtEnd; + byte[] moov; + while (true) + { + moov = BuildMoov(configuration, delta); + if (moov.Length == delta) break; + delta = moov.Length; + } + + var buffer = new byte[1 << 20]; + var remaining = _position - _mdatHeader; + while (remaining > 0) + { + var n = (int)Math.Min(buffer.Length, remaining); + var source = _mdatHeader + remaining - n; + _stream.Position = source; + _stream.ReadExactly(buffer, 0, n); + _stream.Position = source + delta; + _stream.Write(buffer, 0, n); + remaining -= n; + } + _stream.Position = _mdatHeader; + _stream.Write(moov); + _position += delta; + } + + private byte[] BuildMoov(DecoderConfiguration configuration, long chunkOffsetDelta) + { + var count = _sizes.Count; + long minOffset = 0; + foreach (var o in _compositionOffsets) minOffset = Math.Min(minOffset, o); + var shift = -minOffset; + + // Presentation span: earliest composition time to the latest composition end. + long decode = 0, minCts = long.MaxValue, maxEnd = 0; + var anyOffset = false; + for (var i = 0; i < count; i++) + { + var cts = decode + _compositionOffsets[i] + shift; + minCts = Math.Min(minCts, cts); + maxEnd = Math.Max(maxEnd, cts + _durations[i]); + anyOffset |= _compositionOffsets[i] + shift != 0; + decode += _durations[i]; + } + var edit = minCts > 0; + var presentation = edit ? Math.Max(1, maxEnd - minCts) : _totalTicks; + var wide = presentation > uint.MaxValue || _totalTicks > uint.MaxValue; + var created = (ulong)Math.Max(0, (_config.CreationTime.ToUniversalTime() - new DateTime(1904, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); + + var w = new BoxWriter(4096 + count * 16); + w.BeginBox("moov"); + + w.BeginFullBox("mvhd", wide ? (byte)1 : (byte)0, 0); + WriteTimes(w, wide, created, presentation); + w.WriteUInt32(0x00010000); // rate 1.0 + w.WriteUInt16(0x0100); // volume 1.0 + w.WriteZeros(10); + w.WriteUnityMatrix(); + w.WriteZeros(24); + w.WriteUInt32(2); // next_track_ID + w.EndBox(); + + w.BeginBox("trak"); + w.BeginFullBox("tkhd", wide ? (byte)1 : (byte)0, 3); // enabled | in movie + if (wide) + { + w.WriteUInt64(created); + w.WriteUInt64(created); + w.WriteUInt32(1); + w.WriteUInt32(0); + w.WriteUInt64((ulong)presentation); + } + else + { + w.WriteUInt32((uint)created); + w.WriteUInt32((uint)created); + w.WriteUInt32(1); + w.WriteUInt32(0); + w.WriteUInt32((uint)presentation); + } + w.WriteZeros(8); + w.WriteZeros(8); // layer, alternate_group, volume, reserved + w.WriteUnityMatrix(); + w.WriteUInt32((uint)_config.Width << 16); + w.WriteUInt32((uint)_config.Height << 16); + w.EndBox(); + + if (edit) + { + w.BeginBox("edts"); + w.BeginFullBox("elst", wide ? (byte)1 : (byte)0, 0); + w.WriteUInt32(1); + if (wide) + { + w.WriteUInt64((ulong)presentation); + w.WriteInt64(minCts); + } + else + { + w.WriteUInt32((uint)presentation); + w.WriteInt32((int)minCts); + } + w.WriteUInt32(0x00010000); // media_rate 1.0 + w.EndBox(); + w.EndBox(); + } + + w.BeginBox("mdia"); + w.BeginFullBox("mdhd", wide ? (byte)1 : (byte)0, 0); + WriteTimes(w, wide, created, _totalTicks); + w.WriteUInt16(0x55C4); // 'und' + w.WriteUInt16(0); + w.EndBox(); + + w.BeginFullBox("hdlr", 0, 0); + w.WriteUInt32(0); + w.WriteFourCc("vide"); + w.WriteZeros(12); + w.WriteBytes("VideoHandler\0"u8); + w.EndBox(); + + w.BeginBox("minf"); + w.BeginFullBox("vmhd", 0, 1); + w.WriteZeros(8); + w.EndBox(); + w.BeginBox("dinf"); + w.BeginFullBox("dref", 0, 0); + w.WriteUInt32(1); + w.BeginFullBox("url ", 0, 1); // media data in this file + w.EndBox(); + w.EndBox(); + w.EndBox(); + + w.BeginBox("stbl"); + WriteSampleDescription(w, configuration); + WriteTimeToSample(w); + if (anyOffset) WriteCompositionOffsets(w, shift); + if (_syncSamples.Count != count) + { + w.BeginFullBox("stss", 0, 0); + w.WriteUInt32((uint)_syncSamples.Count); + foreach (var s in _syncSamples) w.WriteUInt32(s); + w.EndBox(); + } + WriteSampleToChunk(w); + WriteSampleSizes(w); + WriteChunkOffsets(w, chunkOffsetDelta); + w.EndBox(); // stbl + w.EndBox(); // minf + w.EndBox(); // mdia + w.EndBox(); // trak + w.EndBox(); // moov + return w.ToArray(); + } + + private static void WriteTimes(BoxWriter w, bool wide, ulong created, long duration) + { + if (wide) + { + w.WriteUInt64(created); + w.WriteUInt64(created); + w.WriteUInt32(TimeScale); + w.WriteUInt64((ulong)duration); + } + else + { + w.WriteUInt32((uint)created); + w.WriteUInt32((uint)created); + w.WriteUInt32(TimeScale); + w.WriteUInt32((uint)duration); + } + } + + private void WriteSampleDescription(BoxWriter w, DecoderConfiguration configuration) + { + w.BeginFullBox("stsd", 0, 0); + w.WriteUInt32(1); + w.BeginBox(_config.Codec switch { VideoCodec.H264 => "avc1", VideoCodec.Hevc => "hvc1", _ => "av01" }); + w.WriteZeros(6); + w.WriteUInt16(1); // data_reference_index + w.WriteZeros(16); // pre_defined, reserved + w.WriteUInt16(configuration.Width); + w.WriteUInt16(configuration.Height); + w.WriteUInt32(0x00480000); // 72 dpi + w.WriteUInt32(0x00480000); + w.WriteUInt32(0); + w.WriteUInt16(1); // frame_count + Span compressor = stackalloc byte[32]; + compressor.Clear(); + compressor[0] = 6; + "Titano"u8.CopyTo(compressor[1..]); + w.WriteBytes(compressor); + w.WriteUInt16(0x0018); + w.WriteInt16(-1); + + w.BeginBox(configuration.BoxType); + w.WriteBytes(configuration.Payload); + w.EndBox(); + + w.BeginBox("colr"); + w.WriteFourCc("nclx"); + w.WriteUInt16(1); // BT.709 primaries + w.WriteUInt16(1); // BT.709 transfer + w.WriteUInt16(1); // BT.709 matrix + w.WriteByte(_config.FullRange ? 0x80 : 0); + w.EndBox(); + + w.BeginBox("pasp"); + w.WriteUInt32(1); + w.WriteUInt32(1); + w.EndBox(); + + w.BeginBox("btrt"); + uint maxSize = 0; + foreach (var s in _sizes) maxSize = Math.Max(maxSize, s); + var seconds = _totalTicks / (double)TimeScale; + w.WriteUInt32(maxSize); + w.WriteUInt32((uint)Math.Min(uint.MaxValue, PeakBitrate())); + w.WriteUInt32((uint)Math.Min(uint.MaxValue, _totalBytes * 8 / Math.Max(seconds, 1e-9))); + w.EndBox(); + + w.EndBox(); // sample entry + w.EndBox(); // stsd + } + + /// Largest number of bits in any one-second window of decode time. + private long PeakBitrate() + { + long peak = 0, window = 0, startTime = 0, time = 0; + var first = 0; + for (var i = 0; i < _sizes.Count; i++) + { + window += _sizes[i]; + while (time - startTime >= TimeScale) + { + window -= _sizes[first]; + startTime += _durations[first]; + first++; + } + peak = Math.Max(peak, window * 8); + time += _durations[i]; + } + return _totalTicks < TimeScale ? (long)(peak * (TimeScale / (double)_totalTicks)) : peak; + } + + private void WriteTimeToSample(BoxWriter w) + { + var runs = new List<(uint Count, uint Delta)>(); + foreach (var d in _durations) + { + if (runs.Count > 0 && runs[^1].Delta == d) runs[^1] = (runs[^1].Count + 1, d); + else runs.Add((1, d)); + } + w.BeginFullBox("stts", 0, 0); + w.WriteUInt32((uint)runs.Count); + foreach (var (count, delta) in runs) + { + w.WriteUInt32(count); + w.WriteUInt32(delta); + } + w.EndBox(); + } + + private void WriteCompositionOffsets(BoxWriter w, long shift) + { + var runs = new List<(uint Count, uint Offset)>(); + foreach (var o in _compositionOffsets) + { + var v = (uint)(o + shift); + if (runs.Count > 0 && runs[^1].Offset == v) runs[^1] = (runs[^1].Count + 1, v); + else runs.Add((1, v)); + } + w.BeginFullBox("ctts", 0, 0); + w.WriteUInt32((uint)runs.Count); + foreach (var (count, offset) in runs) + { + w.WriteUInt32(count); + w.WriteUInt32(offset); + } + w.EndBox(); + } + + private void WriteSampleToChunk(BoxWriter w) + { + var entries = new List<(uint FirstChunk, uint Samples)>(); + for (var i = 0; i < _chunkSampleCounts.Count; i++) + { + if (entries.Count == 0 || entries[^1].Samples != _chunkSampleCounts[i]) entries.Add(((uint)i + 1, _chunkSampleCounts[i])); + } + w.BeginFullBox("stsc", 0, 0); + w.WriteUInt32((uint)entries.Count); + foreach (var (firstChunk, samples) in entries) + { + w.WriteUInt32(firstChunk); + w.WriteUInt32(samples); + w.WriteUInt32(1); + } + w.EndBox(); + } + + private void WriteSampleSizes(BoxWriter w) + { + var constant = true; + foreach (var s in _sizes) constant &= s == _sizes[0]; + w.BeginFullBox("stsz", 0, 0); + w.WriteUInt32(constant ? _sizes[0] : 0); + w.WriteUInt32((uint)_sizes.Count); + if (!constant) + { + foreach (var s in _sizes) w.WriteUInt32(s); + } + w.EndBox(); + } + + private void WriteChunkOffsets(BoxWriter w, long delta) + { + var wide = _chunkOffsets.Count > 0 && _chunkOffsets[^1] + delta > uint.MaxValue; + w.BeginFullBox(wide ? "co64" : "stco", 0, 0); + w.WriteUInt32((uint)_chunkOffsets.Count); + foreach (var offset in _chunkOffsets) + { + if (wide) w.WriteUInt64((ulong)(offset + delta)); + else w.WriteUInt32((uint)(offset + delta)); + } + w.EndBox(); + } +} diff --git a/src/Titano.Core/Video/Mp4Inspector.cs b/src/Titano.Core/Video/Mp4Inspector.cs new file mode 100644 index 00000000..1edfa8c7 --- /dev/null +++ b/src/Titano.Core/Video/Mp4Inspector.cs @@ -0,0 +1,683 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Titano.Core.Video.Bitstream; +using Titano.Core.Video.Mp4; + +namespace Titano.Core.Video; + +/// One ISO-BMFF box of an inspected file. +public sealed record Mp4Box(string Type, long Offset, long Size, int HeaderSize, IReadOnlyList Children) +{ + /// Payload bytes (only kept for boxes inside moov). + internal ReadOnlyMemory Payload { get; init; } + + public Mp4Box? Child(string type) + { + foreach (var c in Children) + { + if (c.Type == type) return c; + } + return null; + } +} + +/// One sample of the inspected video track, in decode order. +public readonly record struct Mp4SampleInfo(long Offset, int Size, long DecodeTime, uint Duration, long CompositionOffset, bool IsSync); + +/// Result of : structure, stream properties and problems found. +public sealed class Mp4Report +{ + public List Errors { get; } = []; + public List Warnings { get; } = []; + public bool IsValid => Errors.Count == 0; + public IReadOnlyList Boxes { get; internal set; } = []; + + /// Sample entry four-character code ("avc1", "hvc1", "av01"…). + public string? SampleEntry { get; internal set; } + + public VideoCodec? Codec { get; internal set; } + + /// RFC 6381 codec string, e.g. "avc1.640029". + public string? CodecString { get; internal set; } + + /// Coded picture size from the sample entry. + public int Width { get; internal set; } + + public int Height { get; internal set; } + public int BitDepth { get; internal set; } + public int FrameCount { get; internal set; } + public int SyncSampleCount { get; internal set; } + public uint TimeScale { get; internal set; } + + /// Presentation duration in ticks (edit list applied). + public long DurationTicks { get; internal set; } + + public TimeSpan Duration => TimeScale == 0 ? TimeSpan.Zero : TimeSpan.FromSeconds(DurationTicks / (double)TimeScale); + public long MediaBytes { get; internal set; } + + /// Average bit rate in bits per second. + public double AverageBitrate { get; internal set; } + + /// moov precedes mdat (progressive download). + public bool FastStart { get; internal set; } + + public bool UsesCo64 { get; internal set; } + public bool UsesLargeMdat { get; internal set; } + public bool HasCompositionOffsets { get; internal set; } + public bool HasEditList { get; internal set; } + public IReadOnlyList Samples { get; internal set; } = []; + + public override string ToString() + { + var sb = new StringBuilder(); + var inv = CultureInfo.InvariantCulture; + sb.AppendLine(inv, $"{CodecString ?? SampleEntry ?? "unknown"} {Width}x{Height} {BitDepth}-bit, {FrameCount} frames ({SyncSampleCount} sync), {Duration.TotalSeconds:0.###} s, {AverageBitrate / 1000:0} kbit/s"); + sb.AppendLine(inv, $"fast start: {FastStart}, co64: {UsesCo64}, 64-bit mdat: {UsesLargeMdat}, composition offsets: {HasCompositionOffsets}, edit list: {HasEditList}"); + foreach (var e in Errors) sb.AppendLine("error: " + e); + foreach (var w in Warnings) sb.AppendLine("warning: " + w); + return sb.ToString(); + } +} + +/// +/// Parses an MP4 into a box tree and validates the first video track: required boxes, sample-table consistency, +/// chunk offsets inside mdat, sync start, durations, decoder configuration versus sample entry. Never throws on +/// malformed input. +/// +public static class Mp4Inspector +{ + private const int MaxDepth = 16; + private const int MaxBoxes = 100_000; + private const long MaxMoovBytes = 256L << 20; + private const int CheckedSamples = 4; + + public static Mp4Report Inspect(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.RandomAccess); + return Inspect(stream); + } + + public static Mp4Report Inspect(Stream stream) + { + var report = new Mp4Report(); + if (!stream.CanSeek || !stream.CanRead) + { + report.Errors.Add("stream is not readable and seekable"); + return report; + } + try + { + Run(stream, report); + } + catch (IOException ex) + { + report.Errors.Add("read failed: " + ex.Message); + } + return report; + } + + private static void Run(Stream stream, Mp4Report report) + { + var length = stream.Length; + var top = new List(); + var mdats = new List<(long Start, long End)>(); + Mp4Box? moov = null; + long pos = 0; + var budget = MaxBoxes; + Span header = stackalloc byte[16]; + while (pos + 8 <= length && budget-- > 0) + { + stream.Position = pos; + var want = (int)Math.Min(16, length - pos); + var read = stream.ReadAtLeast(header[..want], want, throwOnEndOfStream: false); + long size = BinaryPrimitives.ReadUInt32BigEndian(header); + var type = FourCc(header[4..8]); + var headerSize = 8; + if (size == 1) + { + if (read < 16) + { + report.Errors.Add($"box '{type}' at {pos} is truncated"); + break; + } + size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(header[8..]), long.MaxValue); + headerSize = 16; + if (type == "mdat") report.UsesLargeMdat = true; + } + else if (size == 0) + { + size = length - pos; + } + if (size < headerSize) + { + report.Errors.Add($"box '{type}' at {pos} has invalid size {size}"); + break; + } + if (size > length - pos) + { + report.Errors.Add($"box '{type}' at {pos} extends past the end of the file ({size} > {length - pos} bytes)"); + size = length - pos; + } + + var children = (IReadOnlyList)[]; + if (type == "moov") + { + if (moov is not null) + { + report.Errors.Add("more than one moov box"); + } + else if (size - headerSize > MaxMoovBytes) + { + report.Errors.Add($"moov is implausibly large ({size} bytes)"); + } + else + { + var data = new byte[size - headerSize]; + stream.Position = pos + headerSize; + stream.ReadExactly(data); + children = ParseBoxes(data, 0, data.Length, pos + headerSize, 1, report, ref budget); + } + } + var box = new Mp4Box(type, pos, size, headerSize, children); + if (type == "moov" && moov is null && children.Count > 0) moov = box; + if (type == "mdat") mdats.Add((pos + headerSize, pos + size)); + if (type == "moof") report.Warnings.Add("fragmented MP4 (moof) is not inspected"); + top.Add(box); + pos += size; + } + if (pos < length && budget > 0) report.Warnings.Add($"{length - pos} trailing bytes after the last box"); + report.Boxes = top; + + if (top.Count == 0 || top[0].Type != "ftyp") + { + if (top.Exists(b => b.Type == "ftyp")) report.Warnings.Add("ftyp is not the first box"); + else report.Errors.Add("ftyp box missing"); + } + if (mdats.Count == 0) report.Errors.Add("mdat box missing"); + if (moov is null) + { + report.Errors.Add("moov box missing or empty"); + return; + } + report.FastStart = mdats.Count > 0 && moov.Offset < mdats[0].Start; + InspectMovie(stream, moov, mdats, report); + } + + private static List ParseBoxes(byte[] data, int start, int end, long baseOffset, int depth, Mp4Report report, ref int budget) + { + var list = new List(); + var pos = start; + while (end - pos >= 8 && budget-- > 0) + { + long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos)); + var type = FourCc(data.AsSpan(pos + 4, 4)); + var headerSize = 8; + if (size == 1) + { + if (end - pos < 16) break; + size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(pos + 8)), long.MaxValue); + headerSize = 16; + } + else if (size == 0) + { + size = end - pos; + } + if (size < headerSize || size > end - pos) + { + report.Errors.Add($"box '{type}' at {baseOffset + pos} overruns its parent"); + return list; + } + var payloadStart = pos + headerSize; + var boxEnd = pos + (int)size; + var childStart = ChildrenStart(type, payloadStart); + var children = childStart >= 0 && childStart <= boxEnd && depth < MaxDepth + ? ParseBoxes(data, childStart, boxEnd, baseOffset, depth + 1, report, ref budget) + : []; + list.Add(new Mp4Box(type, baseOffset + pos, size, headerSize, children) + { + Payload = data.AsMemory(payloadStart, boxEnd - payloadStart), + }); + pos = boxEnd; + } + return list; + } + + private static int ChildrenStart(string type, int payload) => type switch + { + "moov" or "trak" or "edts" or "mdia" or "minf" or "dinf" or "stbl" or "mvex" => payload, + "stsd" or "dref" => payload + 8, + "avc1" or "avc3" or "hvc1" or "hev1" or "av01" => payload + 78, + _ => -1, + }; + + private static void InspectMovie(Stream stream, Mp4Box moov, List<(long Start, long End)> mdats, Mp4Report report) + { + var mvhd = moov.Child("mvhd"); + if (mvhd is null) report.Errors.Add("mvhd missing"); + var movieScale = mvhd is null ? 0u : ReadTimescale(mvhd.Payload.Span, out _); + + Mp4Box? trak = null; + foreach (var t in moov.Children) + { + if (t.Type == "trak" && Handler(t) == "vide") + { + trak = t; + break; + } + } + if (trak is null) + { + report.Errors.Add("no video track (trak with hdlr 'vide')"); + return; + } + if (trak.Child("tkhd") is null) report.Errors.Add("tkhd missing"); + var mdia = trak.Child("mdia"); + var mdhd = mdia?.Child("mdhd"); + var minf = mdia?.Child("minf"); + var stbl = minf?.Child("stbl"); + if (mdhd is null) report.Errors.Add("mdhd missing"); + if (minf?.Child("vmhd") is null) report.Errors.Add("vmhd missing"); + if (minf?.Child("dinf")?.Child("dref") is null) report.Errors.Add("dinf/dref missing"); + if (stbl is null) + { + report.Errors.Add("stbl missing"); + return; + } + long mdhdDuration = 0; + var mediaScale = mdhd is null ? 0u : ReadTimescale(mdhd.Payload.Span, out mdhdDuration); + if (mdhd is not null && mediaScale == 0) report.Errors.Add("mdhd timescale is zero"); + report.TimeScale = mediaScale; + + var config = InspectSampleDescription(stbl, report); + var durations = ReadTimeToSample(stbl, report); + var sizes = ReadSampleSizes(stbl, report); + var chunkOffsets = ReadChunkOffsets(stbl, report); + var samplesPerChunk = ReadSampleToChunk(stbl, chunkOffsets?.Length ?? 0, report); + if (durations is null || sizes is null || chunkOffsets is null || samplesPerChunk is null) return; + + long stscTotal = 0; + foreach (var n in samplesPerChunk) stscTotal += n; + if (durations.Length != sizes.Length) report.Errors.Add($"stts covers {durations.Length} samples, stsz has {sizes.Length}"); + if (stscTotal != sizes.Length) report.Errors.Add($"stsc/stco map {stscTotal} samples, stsz has {sizes.Length}"); + var count = sizes.Length; + report.FrameCount = count; + if (count == 0) + { + report.Errors.Add("track has no samples"); + return; + } + + var offsets = ReadCompositionOffsets(stbl, count, report); + var sync = ReadSyncSamples(stbl, count, report); + report.SyncSampleCount = sync?.Count ?? count; + if (sync is not null && (sync.Count == 0 || sync[0] != 1)) report.Errors.Add("first sample is not a sync sample"); + + var samples = new Mp4SampleInfo[count]; + var index = 0; + long decode = 0, bytes = 0; + var syncIndex = 0; + for (var c = 0; c < chunkOffsets.Length && index < count; c++) + { + var offset = chunkOffsets[c]; + var chunkStart = offset; + for (var s = 0; s < samplesPerChunk[c] && index < count; s++, index++) + { + var isSync = sync is null || (syncIndex < sync.Count && sync[syncIndex] == index + 1); + if (isSync && sync is not null) syncIndex++; + var duration = index < durations.Length ? durations[index] : 0u; + samples[index] = new Mp4SampleInfo(offset, (int)Math.Min(sizes[index], int.MaxValue), decode, duration, offsets?[index] ?? 0, isSync); + offset += sizes[index]; + decode += duration; + bytes += sizes[index]; + } + if (!InsideMdat(chunkStart, offset, mdats)) report.Errors.Add($"chunk {c + 1} [{chunkStart}, {offset}) lies outside mdat"); + } + report.Samples = samples; + report.MediaBytes = bytes; + + for (var i = 0; i < durations.Length; i++) + { + if (durations[i] != 0) continue; + if (i == durations.Length - 1) report.Warnings.Add("last sample has zero duration"); + else report.Errors.Add($"sample {i + 1} has zero duration"); + } + if (mdhd is not null && mdhdDuration != decode) report.Warnings.Add($"mdhd duration {mdhdDuration} differs from the sample durations sum {decode}"); + + report.DurationTicks = decode; + var elst = trak.Child("edts")?.Child("elst"); + if (elst is not null && ReadEditList(elst.Payload.Span, out var segment, out var mediaTime, report)) + { + report.HasEditList = true; + if (mediaTime < 0 || (mediaTime >= decode && decode > 0)) report.Errors.Add($"edit list media_time {mediaTime} outside the media"); + if (movieScale > 0) report.DurationTicks = (long)Math.Round(segment * (double)mediaScale / movieScale); + } + var seconds = mediaScale == 0 ? 0 : report.DurationTicks / (double)mediaScale; + report.AverageBitrate = seconds > 0 ? bytes * 8 / seconds : 0; + + if (config is not null) CheckSamplePayloads(stream, samples, config.Codec, report); + } + + private static DecoderConfiguration? InspectSampleDescription(Mp4Box stbl, Mp4Report report) + { + var stsd = stbl.Child("stsd"); + if (stsd is null || stsd.Children.Count == 0) + { + report.Errors.Add("stsd missing or empty"); + return null; + } + var entry = stsd.Children[0]; + report.SampleEntry = entry.Type; + var payload = entry.Payload.Span; + if (payload.Length < 78) + { + report.Errors.Add($"sample entry '{entry.Type}' truncated"); + return null; + } + report.Width = BinaryPrimitives.ReadUInt16BigEndian(payload[24..]); + report.Height = BinaryPrimitives.ReadUInt16BigEndian(payload[26..]); + var configBox = entry.Type switch + { + "avc1" or "avc3" => "avcC", + "hvc1" or "hev1" => "hvcC", + "av01" => "av1C", + _ => null, + }; + if (configBox is null) + { + report.Warnings.Add($"sample entry '{entry.Type}' is not validated"); + return null; + } + var box = entry.Child(configBox); + if (box is null) + { + report.Errors.Add($"{configBox} missing in '{entry.Type}'"); + return null; + } + if (!DecoderConfiguration.TryParse(configBox, box.Payload.Span, out var config, out var error) || config is null) + { + report.Errors.Add($"{configBox} unparseable: {error}"); + return null; + } + if (error is not null) report.Errors.Add(error); + report.Codec = config.Codec; + report.CodecString = config.CodecString; + report.BitDepth = config.BitDepth; + if (config.Width != report.Width || config.Height != report.Height) + report.Errors.Add($"{configBox} declares {config.Width}x{config.Height}, sample entry {report.Width}x{report.Height}"); + return config; + } + + /// Walks the NAL length prefixes / OBU sizes of the first samples and checks the first picture is a random access point. + private static void CheckSamplePayloads(Stream stream, Mp4SampleInfo[] samples, VideoCodec codec, Mp4Report report) + { + var length = stream.Length; + for (var i = 0; i < Math.Min(CheckedSamples, samples.Length); i++) + { + var s = samples[i]; + if (s.Size <= 0 || s.Offset + s.Size > length || s.Size > 64 << 20) continue; + var data = new byte[s.Size]; + stream.Position = s.Offset; + stream.ReadExactly(data); + if (codec == VideoCodec.Av1) + { + var obus = Av1ObuParser.Split(data); + if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length) + report.Errors.Add($"sample {i + 1}: OBU sizes do not cover the sample"); + continue; + } + if (!AnnexBParser.TrySplitLengthPrefixed(data, 4, out var units)) + { + report.Errors.Add($"sample {i + 1}: NAL length prefixes do not cover the sample"); + continue; + } + if (i != 0) continue; + var randomAccess = false; + foreach (var u in units) + { + var h = data[u.Offset]; + randomAccess |= codec == VideoCodec.H264 + ? AnnexBParser.H264Type(h) == H264NalUnitType.IdrSlice + : AnnexBParser.HevcType(h) is >= HevcNalUnitType.BlaWLp and <= HevcNalUnitType.Cra; + } + if (!randomAccess) report.Warnings.Add("first sample contains no IDR/IRAP picture"); + } + } + + private static uint[]? ReadTimeToSample(Mp4Box stbl, Mp4Report report) + { + var box = stbl.Child("stts"); + if (box is null) + { + report.Errors.Add("stts missing"); + return null; + } + var p = box.Payload.Span; + if (!Entries(p, 8, report, "stts", out var entries)) return null; + var list = new List(); + for (var i = 0; i < entries; i++) + { + var n = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 8)..]); + var delta = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 8)..]); + if (list.Count + (long)n > 50_000_000) + { + report.Errors.Add("stts sample count implausible"); + return null; + } + for (var k = 0; k < n; k++) list.Add(delta); + } + return [.. list]; + } + + private static long[]? ReadCompositionOffsets(Mp4Box stbl, int count, Mp4Report report) + { + var box = stbl.Child("ctts"); + if (box is null) return null; + var p = box.Payload.Span; + if (!Entries(p, 8, report, "ctts", out var entries)) return null; + var signed = p[0] == 1; + var result = new long[count]; + long covered = 0; + for (var i = 0; i < entries; i++) + { + var n = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 8)..]); + var raw = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 8)..]); + long offset = signed ? (int)raw : raw; + for (var k = covered; k < Math.Min(count, covered + n); k++) result[k] = offset; + covered += n; + } + report.HasCompositionOffsets = true; + if (covered != count) report.Errors.Add($"ctts covers {covered} of {count} samples"); + return result; + } + + private static List? ReadSyncSamples(Mp4Box stbl, int count, Mp4Report report) + { + var box = stbl.Child("stss"); + if (box is null) return null; + var p = box.Payload.Span; + if (!Entries(p, 4, report, "stss", out var entries)) return []; + var list = new List(entries); + for (var i = 0; i < entries; i++) + { + var s = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 4)..]); + if (s == 0 || s > count || (list.Count > 0 && s <= list[^1])) + { + report.Errors.Add($"stss entry {s} out of order or range"); + break; + } + list.Add(s); + } + return list; + } + + private static uint[]? ReadSampleSizes(Mp4Box stbl, Mp4Report report) + { + var box = stbl.Child("stsz") ?? stbl.Child("stz2"); + if (box is null) + { + report.Errors.Add("stsz missing"); + return null; + } + var p = box.Payload.Span; + if (p.Length < 12) + { + report.Errors.Add($"{box.Type} truncated"); + return null; + } + var count = BinaryPrimitives.ReadUInt32BigEndian(p[8..]); + if (count > 50_000_000) + { + report.Errors.Add($"{box.Type} sample count implausible"); + return null; + } + var sizes = new uint[count]; + if (box.Type == "stsz") + { + var constant = BinaryPrimitives.ReadUInt32BigEndian(p[4..]); + if (constant != 0) + { + Array.Fill(sizes, constant); + return sizes; + } + if (p.Length < 12 + count * 4L) + { + report.Errors.Add("stsz truncated"); + return null; + } + for (var i = 0; i < count; i++) sizes[i] = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 4)..]); + return sizes; + } + var field = p[7]; + if (field is not (4 or 8 or 16) || p.Length < 12 + (count * field + 7) / 8) + { + report.Errors.Add("stz2 invalid"); + return null; + } + for (var i = 0; i < count; i++) + { + sizes[i] = field switch + { + 16 => BinaryPrimitives.ReadUInt16BigEndian(p[(12 + i * 2)..]), + 8 => p[12 + i], + _ => (uint)((p[12 + i / 2] >> ((i & 1) == 0 ? 4 : 0)) & 0x0F), + }; + } + return sizes; + } + + private static long[]? ReadChunkOffsets(Mp4Box stbl, Mp4Report report) + { + var box = stbl.Child("stco") ?? stbl.Child("co64"); + if (box is null) + { + report.Errors.Add("stco/co64 missing"); + return null; + } + var wide = box.Type == "co64"; + report.UsesCo64 = wide; + var p = box.Payload.Span; + if (!Entries(p, wide ? 8 : 4, report, box.Type, out var entries)) return null; + var offsets = new long[entries]; + for (var i = 0; i < entries; i++) + { + offsets[i] = wide + ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[(8 + i * 8)..]), long.MaxValue) + : BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 4)..]); + } + return offsets; + } + + private static uint[]? ReadSampleToChunk(Mp4Box stbl, int chunks, Mp4Report report) + { + var box = stbl.Child("stsc"); + if (box is null) + { + report.Errors.Add("stsc missing"); + return null; + } + var p = box.Payload.Span; + if (!Entries(p, 12, report, "stsc", out var entries)) return null; + var perChunk = new uint[chunks]; + for (var i = 0; i < entries; i++) + { + var first = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 12)..]); + var samples = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 12)..]); + var next = i + 1 < entries ? BinaryPrimitives.ReadUInt32BigEndian(p[(8 + (i + 1) * 12)..]) : (uint)chunks + 1; + if (first == 0 || next <= first || (i == 0 && first != 1)) + { + report.Errors.Add("stsc first_chunk values invalid"); + return null; + } + if (BinaryPrimitives.ReadUInt32BigEndian(p[(16 + i * 12)..]) != 1) report.Errors.Add("stsc references a sample description other than 1"); + for (var c = first; c < next && c <= chunks; c++) perChunk[c - 1] = samples; + } + return perChunk; + } + + private static bool ReadEditList(ReadOnlySpan p, out long segment, out long mediaTime, Mp4Report report) + { + segment = mediaTime = 0; + var wide = p.Length > 0 && p[0] == 1; + if (!Entries(p, wide ? 20 : 12, report, "elst", out var entries) || entries == 0) return false; + if (entries > 1) report.Warnings.Add($"edit list has {entries} entries; only the first is evaluated"); + segment = wide ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[8..]), long.MaxValue) : BinaryPrimitives.ReadUInt32BigEndian(p[8..]); + mediaTime = wide ? BinaryPrimitives.ReadInt64BigEndian(p[16..]) : BinaryPrimitives.ReadInt32BigEndian(p[12..]); + return true; + } + + /// Reads entry_count of a full box and checks the table fits its payload. + private static bool Entries(ReadOnlySpan p, int entrySize, Mp4Report report, string type, out int entries) + { + entries = 0; + if (p.Length < 8) + { + report.Errors.Add($"{type} truncated"); + return false; + } + var n = BinaryPrimitives.ReadUInt32BigEndian(p[4..]); + if (n > (p.Length - 8) / entrySize) + { + report.Errors.Add($"{type} declares {n} entries but holds {(p.Length - 8) / entrySize}"); + return false; + } + entries = (int)n; + return true; + } + + private static uint ReadTimescale(ReadOnlySpan p, out long duration) + { + duration = 0; + if (p.Length < 20) return 0; + if (p[0] == 1) + { + if (p.Length < 32) return 0; + duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[24..]), long.MaxValue); + return BinaryPrimitives.ReadUInt32BigEndian(p[20..]); + } + duration = BinaryPrimitives.ReadUInt32BigEndian(p[16..]); + return BinaryPrimitives.ReadUInt32BigEndian(p[12..]); + } + + private static string? Handler(Mp4Box trak) + { + var hdlr = trak.Child("mdia")?.Child("hdlr"); + return hdlr is null || hdlr.Payload.Length < 12 ? null : FourCc(hdlr.Payload.Span[8..12]); + } + + private static bool InsideMdat(long start, long end, List<(long Start, long End)> mdats) + { + foreach (var (s, e) in mdats) + { + if (start >= s && end <= e) return true; + } + return false; + } + + private static string FourCc(ReadOnlySpan bytes) + { + Span chars = stackalloc char[4]; + for (var i = 0; i < 4; i++) chars[i] = bytes[i] is >= 0x20 and < 0x7F ? (char)bytes[i] : '?'; + return new string(chars); + } +} diff --git a/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs b/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs new file mode 100644 index 00000000..d505885b --- /dev/null +++ b/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs @@ -0,0 +1,240 @@ +using System.Buffers.Binary; +using Titano.Core.Video; +using Titano.Core.Video.Bitstream; +using Titano.Core.Video.Mp4; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class Mp4MuxerTests(TestContext context) +{ + private static long Duration(int i) => 3000 + i % 3 * 1500; + + [Test] + public void H264WithVariableDurationsInspectsClean() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }); + var expected = new List(); + long total = 0; + for (var i = 0; i < 30; i++) + { + var idr = i % 10 == 0; + var slice = SyntheticStreams.H264Slice(idr, 200 + i * 7, i); + List nals = [SyntheticStreams.H264AccessUnitDelimiter()]; + if (idr) nals.AddRange([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()]); + nals.Add(slice); + var annexB = AnnexBParser.ToAnnexB(nals); + // Alternate input formats: the muxer accepts both. + muxer.WriteSample(i % 2 == 0 ? annexB : AnnexBParser.ToLengthPrefixed(annexB), Duration(i), idr); + expected.Add(AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([slice]))); + total += Duration(i); + } + muxer.Complete(); + + var report = Mp4Inspector.Inspect(ms); + AssertClean(report); + Assert.Equal("avc1", report.SampleEntry); + Assert.Equal("avc1.640029", report.CodecString); + Assert.Equal(1920, report.Width); + Assert.Equal(1080, report.Height); + Assert.Equal(30, report.FrameCount); + Assert.Equal(3, report.SyncSampleCount); + Assert.Equal(90000u, report.TimeScale); + Assert.Equal(total, report.DurationTicks); + Assert.False(report.FastStart); + Assert.False(report.HasEditList); + for (var i = 0; i < 30; i++) + { + Assert.Equal(Duration(i), (long)report.Samples[i].Duration); + Assert.BytesEqual(expected[i], ReadSample(ms, report.Samples[i])); + } + } + + [Test] + public void HevcMain10InspectsClean() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.Hevc, Width = 3840, Height = 2160 }); + for (var i = 0; i < 12; i++) + { + var idr = i % 6 == 0; + List nals = idr ? [SyntheticStreams.HevcVps(), SyntheticStreams.HevcSps(3840, 2160), SyntheticStreams.HevcPps()] : []; + nals.Add(SyntheticStreams.HevcSlice(idr, 500, i)); + muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 1500, idr); + } + muxer.Complete(); + var report = Mp4Inspector.Inspect(ms); + AssertClean(report); + Assert.Equal("hvc1", report.SampleEntry); + Assert.Equal(VideoCodec.Hevc, report.Codec); + Assert.Equal("hvc1.2.4.L153.90", report.CodecString); + Assert.Equal(3840, report.Width); + Assert.Equal(2160, report.Height); + Assert.Equal(10, report.BitDepth); + Assert.Equal(12, report.FrameCount); + Assert.Equal(18000L, report.DurationTicks); + Assert.Approximately(0.2, report.Duration.TotalSeconds, 1e-9); + } + + [Test] + public void Av1InspectsCleanAndGetsSizeFields() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.Av1, Width = 1280, Height = 720 }); + for (var i = 0; i < 10; i++) + { + var key = i == 0; + var frame = SyntheticStreams.Random(300, i); + // Last OBU of the temporal unit without obu_size, as encoders may emit it. + byte[] lastWithoutSize = [(byte)Av1ObuType.Frame << 3, .. frame]; + var tu = key + ? SyntheticStreams.Concat(SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1SequenceHeaderObu(1280, 720, 5), lastWithoutSize) + : SyntheticStreams.Concat(SyntheticStreams.Av1TemporalDelimiter(), lastWithoutSize); + muxer.WriteSample(tu, 3003, key); + } + muxer.Complete(); + var report = Mp4Inspector.Inspect(ms); + AssertClean(report); + Assert.Equal("av01", report.SampleEntry); + Assert.Equal("av01.0.05M.08", report.CodecString); + Assert.Equal(1280, report.Width); + Assert.Equal(720, report.Height); + Assert.Equal(10, report.FrameCount); + Assert.Equal(1, report.SyncSampleCount); + var second = ReadSample(ms, report.Samples[1]); + Assert.True(Av1ObuParser.TryReadObu(second, 0, out var obu)); + Assert.True(obu.HasSizeField); + Assert.Equal(Av1ObuType.Frame, obu.Type); + Assert.Equal(second.Length, obu.TotalLength); + } + + [Test] + public void FastStartMovesMoovAndKeepsOffsetsValid() + { + var path = Path.Combine(context.CreateTempDirectory(), "fast.mp4"); + var expected = new List(); + using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite)) + { + var muxer = new Mp4Muxer(fs, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1280, Height = 720, FastStart = true }); + for (var i = 0; i < 90; i++) + { + var idr = i % 30 == 0; + var slice = SyntheticStreams.H264Slice(idr, 4000 + i, i); + List nals = idr ? [SyntheticStreams.H264Sps(1280, 720, 77, 31), SyntheticStreams.H264Pps(), slice] : [slice]; + muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, idr); + expected.Add(AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([slice]))); + } + muxer.Complete(); + } + var report = Mp4Inspector.Inspect(path); + AssertClean(report); + Assert.True(report.FastStart); + Assert.SequenceEqual(["ftyp", "moov", "free", "mdat"], report.Boxes.Select(b => b.Type)); + Assert.Equal(new FileInfo(path).Length, report.Boxes.Sum(b => b.Size)); + using var read = File.OpenRead(path); + for (var i = 0; i < expected.Count; i++) Assert.BytesEqual(expected[i], ReadSample(read, report.Samples[i])); + } + + [Test] + public void CompositionOffsetsProduceCttsAndEditList() + { + // Decode order I0 P3 B1 B2 P6 B4 B5 with unit durations of 3000 ticks; encoder gives PTS − DTS. + int[] pts = [0, 3, 1, 2, 6, 4, 5]; + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }); + for (var i = 0; i < pts.Length; i++) + { + List nals = i == 0 ? [SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()] : []; + nals.Add(SyntheticStreams.H264Slice(i == 0, 100, i)); + muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, i == 0, (pts[i] - i) * 3000L); + } + muxer.Complete(); + var report = Mp4Inspector.Inspect(ms); + AssertClean(report); + Assert.True(report.HasCompositionOffsets); + Assert.True(report.HasEditList); + Assert.Equal(7 * 3000L, report.DurationTicks); + // After the shift every composition time is non-negative and I0 presents first. + var cts = report.Samples.Select(s => s.DecodeTime + s.CompositionOffset).ToArray(); + Assert.Equal(cts.Min(), cts[0]); + Assert.True(report.Samples.All(s => s.CompositionOffset >= 0)); + } + + [Test] + public void LargeFilesUseCo64AndLargeMdat() + { + const int sampleSize = 1 << 20; + const int samples = 4200; // ≈ 4.4 GB of payload, dropped by the sparse stream + var slice = new byte[sampleSize]; + BinaryPrimitives.WriteInt32BigEndian(slice, sampleSize - 4); + slice[4] = 0x41; // non-IDR slice header + var first = SyntheticStreams.Concat( + AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()])), slice); + first[first.Length - sampleSize + 4] = 0x65; + + using var sparse = new SparseStream(); + var muxer = new Mp4Muxer(sparse, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }); + muxer.WriteSample(first, 3000, true); + for (var i = 1; i < samples; i++) muxer.WriteSample(slice, 3000, i % 60 == 0); + muxer.Complete(); + + var report = Mp4Inspector.Inspect(sparse); + AssertClean(report); + Assert.True(report.UsesCo64); + Assert.True(report.UsesLargeMdat); + Assert.Equal(samples, report.FrameCount); + Assert.Greater(report.Samples[^1].Offset, uint.MaxValue); + Assert.Equal((long)sampleSize * samples, report.MediaBytes); + } + + [Test] + public void CompleteWithoutParameterSetsThrows() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 64, Height = 64 }); + muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Slice(true, 10, 1)]), 3000, true); + Assert.Throws(muxer.Complete); + Assert.Throws(() => muxer.WriteSample([0, 0, 1, 0x65, 1], 0, true)); + } + + [Test] + public void InspectorSurvivesTruncationAndCorruption() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }); + for (var i = 0; i < 5; i++) + { + List nals = i == 0 ? [SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()] : []; + nals.Add(SyntheticStreams.H264Slice(i == 0, 50, i)); + muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, i == 0); + } + muxer.Complete(); + var valid = ms.ToArray(); + for (var cut = 0; cut < valid.Length; cut += 7) + { + var report = Mp4Inspector.Inspect(new MemoryStream(valid, 0, cut)); + Assert.False(report.IsValid, $"truncated at {cut} should not validate"); + } + var rng = new Random(11); + for (var trial = 0; trial < 500; trial++) + { + var corrupt = (byte[])valid.Clone(); + for (var k = 0; k < 3; k++) corrupt[rng.Next(corrupt.Length)] = (byte)rng.Next(256); + Mp4Inspector.Inspect(new MemoryStream(corrupt)).ToString(); + } + } + + private static void AssertClean(Mp4Report report) + { + if (!report.IsValid) Assert.Fail("Inspector errors: " + string.Join("; ", report.Errors)); + } + + private static byte[] ReadSample(Stream stream, Mp4SampleInfo sample) + { + var data = new byte[sample.Size]; + stream.Position = sample.Offset; + stream.ReadExactly(data); + return data; + } +} diff --git a/tests/Titano.Core.Tests/Video/SparseStream.cs b/tests/Titano.Core.Tests/Video/SparseStream.cs new file mode 100644 index 00000000..d470d960 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/SparseStream.cs @@ -0,0 +1,76 @@ +namespace Titano.Core.Tests.Video; + +/// +/// A seekable stream that keeps small writes (headers, length prefixes, moov) and drops large payload writes, +/// which read back as zeros. Lets tests produce multi-gigabyte container layouts without the bytes. +/// +internal sealed class SparseStream : Stream +{ + private const int PageSize = 1024; + private const int LargeWrite = 64 * 1024; + private readonly Dictionary _pages = []; + private long _length; + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => true; + public override long Length => _length; + + public override long Position + { + get => _position; + set => _position = value; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => _position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => _length + offset, + }; + + public override void SetLength(long value) => _length = value; + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = (int)Math.Clamp(_length - _position, 0, buffer.Length); + for (var i = 0; i < n;) + { + var at = _position + i; + var inPage = (int)(at % PageSize); + var chunk = Math.Min(n - i, PageSize - inPage); + if (_pages.TryGetValue(at / PageSize, out var page)) page.AsSpan(inPage, chunk).CopyTo(buffer.Slice(i, chunk)); + else buffer.Slice(i, chunk).Clear(); + i += chunk; + } + _position += n; + return n; + } + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + if (buffer.Length < LargeWrite) + { + for (var i = 0; i < buffer.Length;) + { + var at = _position + i; + var inPage = (int)(at % PageSize); + var chunk = Math.Min(buffer.Length - i, PageSize - inPage); + if (!_pages.TryGetValue(at / PageSize, out var page)) _pages[at / PageSize] = page = new byte[PageSize]; + buffer.Slice(i, chunk).CopyTo(page.AsSpan(inPage, chunk)); + i += chunk; + } + } + _position += buffer.Length; + _length = Math.Max(_length, _position); + } +} From acde397c520e88e271869d9dea0a532d773b8c93 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:34:56 +0000 Subject: [PATCH 014/188] feat(motion): add nine-patch stabiliser with texture gating and smoothed path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per frame, nine phase-correlation patches on a 3x3 grid are gated by noise-compensated gradient energy (Immerkær noise estimate) and peak sharpness, then fitted with a similarity by exhaustive two-point hypotheses and weighted least squares on the inliers. Solve smooths the camera path with Gaussian-weighted local linear regression, derives corrections, shake RMS, recommendation (> 0.3 px) and the crop needed to hide borders. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/PathSmoother.cs | 40 ++ src/Titano.Core/Motion/Stabilizer.cs | 409 ++++++++++++++++++ .../Motion/StabilizerTests.cs | 171 ++++++++ 3 files changed, 620 insertions(+) create mode 100644 src/Titano.Core/Motion/PathSmoother.cs create mode 100644 src/Titano.Core/Motion/Stabilizer.cs create mode 100644 tests/Titano.Core.Tests/Motion/StabilizerTests.cs diff --git a/src/Titano.Core/Motion/PathSmoother.cs b/src/Titano.Core/Motion/PathSmoother.cs new file mode 100644 index 00000000..7c54fcdb --- /dev/null +++ b/src/Titano.Core/Motion/PathSmoother.cs @@ -0,0 +1,40 @@ +namespace Titano.Core.Motion; + +/// Smoothing of per-frame series (camera paths). +internal static class PathSmoother +{ + /// + /// Gaussian-weighted local linear regression (degree-1 LOESS with a Gaussian kernel truncated at 3σ): + /// each sample is replaced by the value at its own position of a line fitted to its neighbourhood. + /// Linear trends (pans) pass unchanged and the ends are not pulled toward the interior, unlike a plain + /// Gaussian average. σ ≤ 0 returns a copy. + /// + public static double[] LocalLinear(ReadOnlySpan values, double sigma) + { + var n = values.Length; + var result = values.ToArray(); + if (!(sigma > 0) || n < 2) return result; + var radius = (int)double.Ceiling(3 * sigma); + Span kernel = radius <= 1024 ? stackalloc double[radius + 1] : new double[radius + 1]; + for (var d = 0; d <= radius; d++) kernel[d] = double.Exp(-0.5 * d * d / (sigma * sigma)); + for (var k = 0; k < n; k++) + { + double s0 = 0, s1 = 0, s2 = 0, t0 = 0, t1 = 0; + var lo = int.Max(0, k - radius); + var hi = int.Min(n - 1, k + radius); + for (var j = lo; j <= hi; j++) + { + var d = j - k; + var w = kernel[int.Abs(d)]; + s0 += w; + s1 += w * d; + s2 += w * d * d; + t0 += w * values[j]; + t1 += w * d * values[j]; + } + var det = s0 * s2 - s1 * s1; + result[k] = det > 1e-12 * s0 * s0 ? (s2 * t0 - s1 * t1) / det : t0 / s0; + } + return result; + } +} diff --git a/src/Titano.Core/Motion/Stabilizer.cs b/src/Titano.Core/Motion/Stabilizer.cs new file mode 100644 index 00000000..7bb44d60 --- /dev/null +++ b/src/Titano.Core/Motion/Stabilizer.cs @@ -0,0 +1,409 @@ +using System.Buffers; +using System.Numerics; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; + +namespace Titano.Core.Motion; + +/// Tuning for . +public sealed record StabilizerOptions +{ + /// Phase-correlation patch side (power of two recommended); 0 picks min(W, H)/3 rounded down to a power of two, 8..256. + public int PatchSize { get; init; } + + /// + /// Texture gate: minimum gradient energy of a patch (perceptual luminance² per px², measured after a + /// 3×3 binomial blur, with the expected contribution of the estimated noise removed). + /// + public double TextureThreshold { get; init; } = 1e-5; + + /// Minimum phase-correlation peak sharpness for a patch vector to be used. + public double MinimumConfidence { get; init; } = 0.3; + + /// Residual (px) under which a patch vector is an inlier of a similarity hypothesis. + public double InlierThreshold { get; init; } = 1.0; + + /// Largest plausible frame-to-frame rotation (radians) and |ln scale| of a hypothesis. + public double MaxRotation { get; init; } = 0.05; + + public double MaxScaleChange { get; init; } = 0.05; + + /// σ (frames) of the Gaussian-weighted local linear regression that smooths the camera path; 0 disables. + public double SmoothingSigma { get; init; } = 12; + + /// Shake (RMS px) above which stabilisation is recommended (brief §10.3). + public double RecommendThreshold { get; init; } = 0.3; +} + +/// Similarity between consecutive frames: maps previous-frame pixel coordinates to current-frame ones. +public readonly record struct FrameMotion(Affine2D Transform, int ValidPatches, int Inliers) +{ + /// False when no patch passed the texture and confidence gates (identity assumed). + public bool Estimated => ValidPatches > 0; +} + +/// Outcome of ; every transform uses pixel-centre coordinates. +public sealed record StabilizationResult( + IReadOnlyList Motions, + IReadOnlyList CameraPath, + IReadOnlyList SmoothedPath, + IReadOnlyList Corrections, + double ShakeRms, + double CropScale, + bool Recommended) +{ + /// Fraction of the frame area lost to the centred crop that hides every correction's borders, 1 − scale². + public double CropCost => 1 - CropScale * CropScale; +} + +/// +/// Video stabilisation. Per frame: Kuglin–Hines phase correlation of nine patches on a 3×3 grid against the +/// previous frame, texture gating (noise-compensated gradient energy, Immerkær 1996 noise estimate; a +/// textureless frame yields no vectors and therefore no motion), then a robust similarity fit (exhaustive +/// two-point hypotheses as deterministic RANSAC, plausibility limits, weighted least squares on the +/// inliers). accumulates the camera path, smooths its translation, rotation and log-scale +/// with Gaussian-weighted local linear regression (pans survive unchanged), and reports per-frame +/// corrections (smoothed ∘ raw⁻¹), shake RMS and the crop needed to hide borders. Memory holds two +/// luminance planes regardless of sequence length. +/// +public sealed class Stabilizer : IDisposable +{ + // Expected smoothed-gradient energy of unit-variance white noise: 2 · Σ([−1 −2 0 2 1]/8)² · Σ([1 2 1]/4)². + private const double NoiseGradientGain = 2 * (10.0 / 64) * (6.0 / 16); + + private readonly PhaseCorrelator _correlator; + private readonly (int X, int Y)[] _patches; + private readonly double[] _previousEnergy; + private readonly double[] _currentEnergy; + private readonly float[] _smooth; + private readonly Match[] _matches = new Match[9]; + private readonly List _motions = []; + private float[]? _previous; + private float[]? _current; + + public Stabilizer(int width, int height, StabilizerOptions? options = null) + { + ArgumentOutOfRangeException.ThrowIfLessThan(width, 16); + ArgumentOutOfRangeException.ThrowIfLessThan(height, 16); + Options = options ?? new StabilizerOptions(); + Width = width; + Height = height; + PatchSize = Options.PatchSize > 0 + ? int.Min(Options.PatchSize, int.Min(width, height)) + : int.Clamp(1 << BitOperations.Log2((uint)(int.Min(width, height) / 3)), 8, 256); + _correlator = new PhaseCorrelator(PatchSize, PatchSize); + _patches = new (int, int)[9]; + for (var j = 0; j < 3; j++) + { + for (var i = 0; i < 3; i++) + { + var x = (int)double.Round(width * (2 * i + 1) / 6.0 - PatchSize / 2.0); + var y = (int)double.Round(height * (2 * j + 1) / 6.0 - PatchSize / 2.0); + _patches[j * 3 + i] = (int.Clamp(x, 0, width - PatchSize), int.Clamp(y, 0, height - PatchSize)); + } + } + _previousEnergy = new double[9]; + _currentEnergy = new double[9]; + _smooth = new float[PatchSize * PatchSize]; + _previous = ArrayPool.Shared.Rent(width * height); + _current = ArrayPool.Shared.Rent(width * height); + } + + public int Width { get; } + + public int Height { get; } + + public int PatchSize { get; } + + public StabilizerOptions Options { get; } + + public int FrameCount => _motions.Count; + + /// Adds the next frame (its perceptual luminance is analysed) and returns its motion from the previous frame. + public FrameMotion AddFrame(ImageBuffer frame) + { + if (frame.Width != Width || frame.Height != Height) throw new ArgumentException("Frame size differs.", nameof(frame)); + PlaneOps.PerceptualLuminance(frame, CurrentPlane.AsSpan(0, Width * Height)); + return Analyse(); + } + + /// Adds the next frame as a perceptual (sRGB-encoded) luminance plane. + public FrameMotion AddFrame(ReadOnlySpan luminance) + { + if (luminance.Length < Width * Height) throw new ArgumentException("Plane is smaller than the frame.", nameof(luminance)); + luminance[..(Width * Height)].CopyTo(CurrentPlane); + return Analyse(); + } + + /// Smooths the accumulated camera path and derives corrections, shake and crop. + public StabilizationResult Solve() + { + var n = _motions.Count; + if (n == 0) throw new InvalidOperationException("No frames were added."); + double cx = (Width - 1) / 2.0, cy = (Height - 1) / 2.0; + + // Camera path C_k: frame-0 coordinates → frame-k coordinates, as (tx, ty, angle, ln scale) about the centre. + var path = new Affine2D[n]; + var parameters = new double[4][]; + for (var p = 0; p < 4; p++) parameters[p] = new double[n]; + var current = Affine2D.Identity; + for (var k = 0; k < n; k++) + { + current = _motions[k].Transform * current; + path[k] = current; + var (x, y) = current.Apply(cx, cy); + var angle = current.Angle; + if (k > 0) angle += double.Round((parameters[2][k - 1] - angle) / double.Tau) * double.Tau; + parameters[0][k] = x - cx; + parameters[1][k] = y - cy; + parameters[2][k] = angle; + parameters[3][k] = double.Log(current.Scale); + } + + var smoothed = new Affine2D[n]; + var corrections = new Affine2D[n]; + var series = new double[4][]; + for (var p = 0; p < 4; p++) series[p] = PathSmoother.LocalLinear(parameters[p], Options.SmoothingSigma); + for (var k = 0; k < n; k++) + { + smoothed[k] = Affine2D.Translation(cx + series[0][k], cy + series[1][k]) + * Affine2D.Similarity(double.Exp(series[3][k]), series[2][k], 0, 0) + * Affine2D.Translation(-cx, -cy); + var correction = smoothed[k] * path[k].Invert(); + corrections[k] = correction.IsIdentity(1e-12) ? Affine2D.Identity : correction; + } + + var shake = ShakeRms(corrections); + var crop = CropScale(corrections); + return new StabilizationResult(_motions.ToArray(), path, smoothed, corrections, shake, crop, shake > Options.RecommendThreshold); + } + + public void Dispose() + { + var previous = Interlocked.Exchange(ref _previous, null); + var current = Interlocked.Exchange(ref _current, null); + if (previous is not null) ArrayPool.Shared.Return(previous); + if (current is not null) ArrayPool.Shared.Return(current); + } + + private float[] CurrentPlane => _current ?? throw new ObjectDisposedException(nameof(Stabilizer)); + + private FrameMotion Analyse() + { + var current = CurrentPlane; + for (var i = 0; i < 9; i++) _currentEnergy[i] = TextureEnergy(current, _patches[i].X, _patches[i].Y); + + FrameMotion motion; + if (_motions.Count == 0) + { + motion = new FrameMotion(Affine2D.Identity, 0, 0); + } + else + { + var count = 0; + var half = (PatchSize - 1) / 2.0; + for (var i = 0; i < 9; i++) + { + if (double.Min(_previousEnergy[i], _currentEnergy[i]) < Options.TextureThreshold) continue; + var (x0, y0) = _patches[i]; + var r = _correlator.Correlate(_previous, current, Width, x0, y0); + if (r.Confidence < Options.MinimumConfidence) continue; + _matches[count++] = new Match(x0 + half, y0 + half, x0 + half + r.Dx, y0 + half + r.Dy, r.Confidence); + } + motion = FitSimilarity(_matches.AsSpan(0, count)); + } + + _motions.Add(motion); + (_previous, _current) = (_current, _previous); + _currentEnergy.CopyTo(_previousEnergy, 0); + return motion; + } + + /// Noise-compensated mean squared gradient of the blurred patch. + private double TextureEnergy(float[] plane, int x0, int y0) + { + var p = PatchSize; + var w = Width; + double laplacian = 0; + for (var y = 1; y < p - 1; y++) + { + var row = (y0 + y) * w + x0; + for (var x = 1; x < p - 1; x++) + { + var c = row + x; + float a = plane[c - w - 1], b = plane[c - w], d = plane[c - w + 1]; + float e = plane[c - 1], f = plane[c], g = plane[c + 1]; + float h = plane[c + w - 1], i = plane[c + w], j = plane[c + w + 1]; + _smooth[y * p + x] = (a + d + h + j + 2 * (b + e + g + i) + 4 * f) * (1f / 16); + laplacian += float.Abs(a + d + h + j - 2 * (b + e + g + i) + 4 * f); + } + } + var sigma = double.Sqrt(double.Pi / 2) * laplacian / (6.0 * (p - 2) * (p - 2)); + + double energy = 0; + var samples = 0; + for (var y = 2; y < p - 2; y++) + { + for (var x = 2; x < p - 2; x++) + { + var k = y * p + x; + var gx = 0.5 * (_smooth[k + 1] - _smooth[k - 1]); + var gy = 0.5 * (_smooth[k + p] - _smooth[k - p]); + energy += gx * gx + gy * gy; + samples++; + } + } + return samples == 0 ? 0 : energy / samples - NoiseGradientGain * sigma * sigma; + } + + private FrameMotion FitSimilarity(ReadOnlySpan matches) + { + var n = matches.Length; + if (n == 0) return new FrameMotion(Affine2D.Identity, 0, 0); + + Span inliers = stackalloc bool[n]; + Span best = stackalloc bool[n]; + var bestCount = 0; + var bestResidual = double.PositiveInfinity; + Span pair = stackalloc bool[n]; + for (var a = 0; a < n; a++) + { + for (var b = a + 1; b < n; b++) + { + pair.Clear(); + pair[a] = pair[b] = true; + var model = Similarity(matches, pair); + if (double.Abs(model.Angle) > Options.MaxRotation || double.Abs(double.Log(model.Scale)) > Options.MaxScaleChange) continue; + Consider(model, matches, inliers, best, ref bestCount, ref bestResidual); + } + } + + // Translation hypotheses, one per vector: covers a single valid patch and sets of implausible pairs. + if (bestCount < 2) + { + foreach (var m in matches) Consider(Affine2D.Translation(m.Qx - m.Px, m.Qy - m.Py), matches, inliers, best, ref bestCount, ref bestResidual); + return new FrameMotion(Translation(matches, best), n, bestCount); + } + return new FrameMotion(Similarity(matches, best), n, bestCount); + } + + /// Scores a hypothesis and keeps it when it has more inliers (ties: smaller summed residual). + private void Consider(Affine2D model, ReadOnlySpan matches, Span inliers, Span best, ref int bestCount, ref double bestResidual) + { + var count = 0; + double residual = 0; + for (var i = 0; i < matches.Length; i++) + { + var m = matches[i]; + var (x, y) = model.Apply(m.Px, m.Py); + var r = double.Hypot(x - m.Qx, y - m.Qy); + inliers[i] = r <= Options.InlierThreshold; + if (!inliers[i]) continue; + count++; + residual += r; + } + if (count < bestCount || (count == bestCount && residual >= bestResidual)) return; + bestCount = count; + bestResidual = residual; + inliers.CopyTo(best); + } + + /// Weighted least-squares similarity q ≈ [a −b; b a]·p + t over the selected correspondences. + private static Affine2D Similarity(ReadOnlySpan matches, ReadOnlySpan selected) + { + double sw = 0, mpx = 0, mpy = 0, mqx = 0, mqy = 0; + for (var i = 0; i < matches.Length; i++) + { + if (!selected[i]) continue; + var m = matches[i]; + sw += m.Weight; + mpx += m.Weight * m.Px; + mpy += m.Weight * m.Py; + mqx += m.Weight * m.Qx; + mqy += m.Weight * m.Qy; + } + mpx /= sw; + mpy /= sw; + mqx /= sw; + mqy /= sw; + double dot = 0, cross = 0, norm = 0; + for (var i = 0; i < matches.Length; i++) + { + if (!selected[i]) continue; + var m = matches[i]; + double ax = m.Px - mpx, ay = m.Py - mpy, bx = m.Qx - mqx, by = m.Qy - mqy; + dot += m.Weight * (ax * bx + ay * by); + cross += m.Weight * (ax * by - ay * bx); + norm += m.Weight * (ax * ax + ay * ay); + } + if (norm <= 1e-12) return Affine2D.Translation(mqx - mpx, mqy - mpy); + var a = dot / norm; + var b = cross / norm; + return new Affine2D(a, -b, b, a, mqx - (a * mpx - b * mpy), mqy - (b * mpx + a * mpy)); + } + + private static Affine2D Translation(ReadOnlySpan matches, ReadOnlySpan selected) + { + double sw = 0, tx = 0, ty = 0; + for (var i = 0; i < matches.Length; i++) + { + if (!selected[i]) continue; + var m = matches[i]; + sw += m.Weight; + tx += m.Weight * (m.Qx - m.Px); + ty += m.Weight * (m.Qy - m.Py); + } + return sw > 0 ? Affine2D.Translation(tx / sw, ty / sw) : Affine2D.Identity; + } + + /// RMS displacement of the patch-grid centres under the corrections. + private double ShakeRms(Affine2D[] corrections) + { + double sum = 0; + var half = (PatchSize - 1) / 2.0; + foreach (var k in corrections) + { + foreach (var (x0, y0) in _patches) + { + var (x, y) = k.Apply(x0 + half, y0 + half); + sum += (x - x0 - half) * (x - x0 - half) + (y - y0 - half) * (y - y0 - half); + } + } + return double.Sqrt(sum / (corrections.Length * _patches.Length)); + } + + /// + /// Largest scale f of a centred, frame-shaped output rectangle whose corners map inside the source under + /// every inverse correction (each corner gives linear bounds on f). + /// + private double CropScale(Affine2D[] corrections) + { + double cx = (Width - 1) / 2.0, cy = (Height - 1) / 2.0; + double hx = Width / 2.0, hy = Height / 2.0; + double minX = -0.5, minY = -0.5, maxX = Width - 0.5, maxY = Height - 0.5; + var scale = 1.0; + foreach (var correction in corrections) + { + var inverse = correction.Invert(); + var (ox, oy) = inverse.Apply(cx, cy); + if (ox < minX || ox > maxX || oy < minY || oy > maxY) return 0; + for (var corner = 0; corner < 4; corner++) + { + var (dx, dy) = inverse.ApplyVector((corner & 1) == 0 ? -hx : hx, (corner & 2) == 0 ? -hy : hy); + scale = Limit(scale, ox, dx, minX, maxX); + scale = Limit(scale, oy, dy, minY, maxY); + } + } + return double.Clamp(scale, 0, 1); + + static double Limit(double f, double origin, double direction, double min, double max) + { + if (direction > 0) return double.Min(f, (max - origin) / direction); + if (direction < 0) return double.Min(f, (min - origin) / direction); + return f; + } + } + + /// Patch centre in the previous frame (P) and where its content moved in the current one (Q). + private readonly record struct Match(double Px, double Py, double Qx, double Qy, double Weight); +} diff --git a/tests/Titano.Core.Tests/Motion/StabilizerTests.cs b/tests/Titano.Core.Tests/Motion/StabilizerTests.cs new file mode 100644 index 00000000..aedd1119 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/StabilizerTests.cs @@ -0,0 +1,171 @@ +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class StabilizerTests +{ + private const int Width = 256; + private const int Height = 192; + private const int Frames = 48; + + private readonly TestContext _context; + + public StabilizerTests(TestContext context) => _context = context; + + [Test] + public void TexturelessFramesReportNoShakeAndNoCorrection() + { + var random = new Random(17); + using var stabilizer = new Stabilizer(128, 128); + using var frame = new ImageBuffer(128, 128); + for (var k = 0; k < 20; k++) + { + var data = frame.Data; + for (var i = 0; i < data.Length; i++) data[i] = 0.3f + 0.004f * (float)Gaussian(random); + Assert.False(stabilizer.AddFrame(frame).Estimated); + } + var result = stabilizer.Solve(); + _context.Log($"textureless shake {result.ShakeRms:F4} px, crop scale {result.CropScale:F4}"); + Assert.LessOrEqual(result.ShakeRms, 0.1); + Assert.False(result.Recommended); + Assert.Equal(1.0, result.CropScale); + Assert.True(result.Corrections.All(c => c == Affine2D.Identity)); + } + + [Test] + public void JitterIsReducedByAtLeastEightyPercent() + { + var random = new Random(23); + var cameras = new Affine2D[Frames]; + for (var k = 0; k < Frames; k++) cameras[k] = Camera(2.0 * Gaussian(random), 2.0 * Gaussian(random), 0.3 * Gaussian(random), pan: 0, k); + var result = Stabilize(cameras, out var motionError); + var before = Jitter(cameras, null); + var after = Jitter(cameras, result.Corrections); + var reduction = 1 - after / before; + _context.Log($"frame-to-frame jitter {before:F3} → {after:F3} px ({reduction:P1}); motion error {motionError:F4} px; shake {result.ShakeRms:F3} px; crop cost {result.CropCost:P1}"); + Assert.GreaterOrEqual(reduction, 0.8); + Assert.Less(motionError, 0.1); + Assert.True(result.Recommended); + Assert.Greater(result.ShakeRms, 1.0); + Assert.InRange(result.CropCost, 0.01, 0.3); + } + + [Test] + public void IntentionalPanSurvivesStabilisation() + { + const double pan = 1.5; + var random = new Random(29); + var cameras = new Affine2D[Frames]; + for (var k = 0; k < Frames; k++) cameras[k] = Camera(1.5 * Gaussian(random), 1.5 * Gaussian(random), 0.2 * Gaussian(random), pan, k); + var result = Stabilize(cameras, out _); + + // The stabilised view still follows the pan: content drifts left by `pan` px per frame. + var (bx, by) = cameras[0].Apply(Width / 2.0, Height / 2.0); + (double X, double Y) Track(int k) + { + var (x, y) = cameras[k].Invert().Apply(bx, by); + return result.Corrections[k].Apply(x, y); + } + var (sx, sy) = Track(0); + var (ex, ey) = Track(Frames - 1); + var velocity = (ex - sx) / (Frames - 1); + _context.Log($"stabilised velocity {velocity:F3} px/frame (pan {-pan}), vertical drift {ey - sy:F3} px"); + Assert.Approximately(-pan, velocity, 0.1); + var reduction = 1 - Jitter(cameras, result.Corrections, removeMean: true) / Jitter(cameras, null, removeMean: true); + Assert.GreaterOrEqual(reduction, 0.8); + } + + [Test] + public void SmootherKeepsLinesAndEnds() + { + var line = Enumerable.Range(0, 30).Select(i => 3 + 0.5 * i).ToArray(); + var smoothed = PathSmoother.LocalLinear(line, 5); + for (var i = 0; i < line.Length; i++) Assert.Approximately(line[i], smoothed[i], 1e-9); + // Frame-rate jitter (alternating ±1) is removed in the interior and strongly attenuated at the ends. + var noisy = Enumerable.Range(0, 200).Select(i => i % 2 == 0 ? 1.0 : -1.0).ToArray(); + var flat = PathSmoother.LocalLinear(noisy, 8); + var interior = flat.Skip(24).SkipLast(24).Max(double.Abs); + var ends = flat.Max(double.Abs); + _context.Log($"interior {interior:E2}, ends {ends:E2}"); + Assert.Less(interior, 0.01); + Assert.Less(ends, 0.2); + } + + /// Frame pixel → base-texture coordinate: jitter translation and rotation about the frame centre, plus a pan. + private static Affine2D Camera(double tx, double ty, double degrees, double pan, int k) => + Affine2D.Translation(100 + pan * k, 150) + * Affine2D.About(Affine2D.Rotation(degrees * double.Pi / 180), (Width - 1) / 2.0, (Height - 1) / 2.0) + * Affine2D.Translation(tx, ty); + + private static StabilizationResult Stabilize(Affine2D[] cameras, out double motionError) + { + const int Base = 512; + using var texture = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Natural(Base, seed: 41), Base, 0, 0, Base, Base), Base, Base); + using var frame = new ImageBuffer(Width, Height); + using var stabilizer = new Stabilizer(Width, Height); + double error = 0; + var samples = 0; + for (var k = 0; k < cameras.Length; k++) + { + GeometryStage.Warp(texture, frame, cameras[k]); + var motion = stabilizer.AddFrame(frame); + if (k == 0) continue; + // True inter-frame map: previous frame → base → current frame. + var truth = cameras[k].Invert() * cameras[k - 1]; + foreach (var (x, y) in GridPoints()) + { + var (tx, ty) = truth.Apply(x, y); + var (mx, my) = motion.Transform.Apply(x, y); + error += double.Hypot(tx - mx, ty - my); + samples++; + } + } + motionError = error / samples; + return stabilizer.Solve(); + } + + /// RMS frame-to-frame displacement of fixed content points in the (corrected) frames. + private static double Jitter(Affine2D[] cameras, IReadOnlyList? corrections, bool removeMean = false) + { + var points = GridPoints().Select(p => cameras[0].Apply(p.X, p.Y)).ToArray(); + var steps = new List<(double X, double Y)>(); + for (var k = 1; k < cameras.Length; k++) + { + foreach (var (bx, by) in points) + { + var (x0, y0) = cameras[k - 1].Invert().Apply(bx, by); + var (x1, y1) = cameras[k].Invert().Apply(bx, by); + if (corrections is not null) + { + (x0, y0) = corrections[k - 1].Apply(x0, y0); + (x1, y1) = corrections[k].Apply(x1, y1); + } + steps.Add((x1 - x0, y1 - y0)); + } + } + double mx = 0, my = 0; + if (removeMean) + { + mx = steps.Average(s => s.X); + my = steps.Average(s => s.Y); + } + return double.Sqrt(steps.Average(s => (s.X - mx) * (s.X - mx) + (s.Y - my) * (s.Y - my))); + } + + private static IEnumerable<(double X, double Y)> GridPoints() + { + for (var j = 1; j <= 3; j++) + for (var i = 1; i <= 3; i++) + yield return (Width * i / 4.0, Height * j / 4.0); + } + + private static double Gaussian(Random random) + { + var u1 = 1.0 - random.NextDouble(); + var u2 = random.NextDouble(); + return double.Sqrt(-2 * double.Log(u1)) * double.Cos(2 * double.Pi * u2); + } +} From bc543f99b6c50d3320cf9760e31039b1c7d9728f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:35:00 +0000 Subject: [PATCH 015/188] feat(video): add H.264/HEVC/AV1 level tables with level selection and size capping Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/CodecLimits.cs | 214 ++++++++++++++++++ .../Video/CodecLimitsTests.cs | 70 ++++++ 2 files changed, 284 insertions(+) create mode 100644 src/Titano.Core/Video/CodecLimits.cs create mode 100644 tests/Titano.Core.Tests/Video/CodecLimitsTests.cs diff --git a/src/Titano.Core/Video/CodecLimits.cs b/src/Titano.Core/Video/CodecLimits.cs new file mode 100644 index 00000000..4c95e39c --- /dev/null +++ b/src/Titano.Core/Video/CodecLimits.cs @@ -0,0 +1,214 @@ +using System.Globalization; + +namespace Titano.Core.Video; + +/// A codec level such as H.264 4.1, HEVC 5.1 or AV1 5.0. +public readonly record struct CodecLevel(VideoCodec Codec, int Major, int Minor) +{ + public string Name => string.Create(CultureInfo.InvariantCulture, $"{Major}.{Minor}"); + + /// H.264 level_idc (10 × level), also the eAVEncH264VLevel value. + public int H264LevelIdc => Major * 10 + Minor; + + /// HEVC general_level_idc (30 × level), also the eAVEncH265VLevel value. + public int HevcLevelIdc => Major * 30 + Minor * 3; + + /// AV1 seq_level_idx. + public int Av1SeqLevelIdx => (Major - 2) * 4 + Minor; + + public override string ToString() => Name; +} + +/// Level constraints a configuration can break. +[Flags] +public enum LevelLimit +{ + None = 0, + PictureSize = 1, + Dimension = 2, + SampleRate = 4, + BitRate = 8, +} + +/// Outcome of . +/// Lowest level that fits, or null when even the highest level is exceeded. +/// Highest level defined for the codec. +/// Limits the highest level violates ( when a level fits). +/// Largest even width with the same aspect ratio that fits the highest level at this frame rate. +/// Height matching . +/// Bit-rate ceiling of the highest level for the profile, in bits per second. +public sealed record LevelCheck(CodecLevel? Level, CodecLevel HighestLevel, LevelLimit Exceeded, int SuggestedWidth, int SuggestedHeight, long MaxBitRate) +{ + public bool Fits => Level is not null; +} + +/// +/// Level tables for H.264 (Table A-1), HEVC (Tables A.8/A.9, Main/Main10, main tier) and AV1 (Annex A.3, main tier): +/// picks the lowest level for a size, frame rate and bit rate, and proposes a capped size when none fits. +/// +public static class CodecLimits +{ + // Major, Minor, max luma picture samples, max luma samples per second, max bit rate (kbit/s, before the profile factor), + // max width, max height (0 = derived from the picture size as sqrt(8 × size)). + private readonly record struct Limits(int Major, int Minor, long PictureSamples, long SampleRate, long BitRateKbps, int MaxWidth, int MaxHeight); + + // H.264 limits are in macroblocks: MaxFS × 256 samples, MaxMBPS × 256 samples/s. + private static readonly Limits[] H264 = + [ + new(1, 0, 99 * 256L, 1485 * 256L, 64, 0, 0), + new(1, 1, 396 * 256L, 3000 * 256L, 192, 0, 0), + new(1, 2, 396 * 256L, 6000 * 256L, 384, 0, 0), + new(1, 3, 396 * 256L, 11880 * 256L, 768, 0, 0), + new(2, 0, 396 * 256L, 11880 * 256L, 2000, 0, 0), + new(2, 1, 792 * 256L, 19800 * 256L, 4000, 0, 0), + new(2, 2, 1620 * 256L, 20250 * 256L, 4000, 0, 0), + new(3, 0, 1620 * 256L, 40500 * 256L, 10000, 0, 0), + new(3, 1, 3600 * 256L, 108000 * 256L, 14000, 0, 0), + new(3, 2, 5120 * 256L, 216000 * 256L, 20000, 0, 0), + new(4, 0, 8192 * 256L, 245760 * 256L, 20000, 0, 0), + new(4, 1, 8192 * 256L, 245760 * 256L, 50000, 0, 0), + new(4, 2, 8704 * 256L, 522240 * 256L, 50000, 0, 0), + new(5, 0, 22080 * 256L, 589824 * 256L, 135000, 0, 0), + new(5, 1, 36864 * 256L, 983040 * 256L, 240000, 0, 0), + new(5, 2, 36864 * 256L, 2073600 * 256L, 240000, 0, 0), + new(6, 0, 139264 * 256L, 4177920 * 256L, 240000, 0, 0), + new(6, 1, 139264 * 256L, 8355840 * 256L, 480000, 0, 0), + new(6, 2, 139264 * 256L, 16711680 * 256L, 800000, 0, 0), + ]; + + private static readonly Limits[] Hevc = + [ + new(1, 0, 36864, 552960, 128, 0, 0), + new(2, 0, 122880, 3686400, 1500, 0, 0), + new(2, 1, 245760, 7372800, 3000, 0, 0), + new(3, 0, 552960, 16588800, 6000, 0, 0), + new(3, 1, 983040, 33177600, 10000, 0, 0), + new(4, 0, 2228224, 66846720, 12000, 0, 0), + new(4, 1, 2228224, 133693440, 20000, 0, 0), + new(5, 0, 8912896, 267386880, 25000, 0, 0), + new(5, 1, 8912896, 534773760, 40000, 0, 0), + new(5, 2, 8912896, 1069547520, 60000, 0, 0), + new(6, 0, 35651584, 1069547520, 60000, 0, 0), + new(6, 1, 35651584, 2139095040, 120000, 0, 0), + new(6, 2, 35651584, 4278190080, 240000, 0, 0), + ]; + + // AV1: MaxPicSize, MaxDisplayRate, main-tier MaxBitrate, MaxHSize, MaxVSize. + private static readonly Limits[] Av1 = + [ + new(2, 0, 147456, 4423680, 1500, 2048, 1152), + new(2, 1, 278784, 8363520, 3000, 2816, 1584), + new(3, 0, 665856, 19975680, 6000, 4352, 2448), + new(3, 1, 1065024, 31950720, 10000, 5504, 3096), + new(4, 0, 2359296, 70778880, 12000, 6144, 3456), + new(4, 1, 2359296, 141557760, 20000, 6144, 3456), + new(5, 0, 8912896, 267386880, 30000, 8192, 4352), + new(5, 1, 8912896, 534773760, 40000, 8192, 4352), + new(5, 2, 8912896, 1069547520, 60000, 8192, 4352), + new(5, 3, 8912896, 1069547520, 60000, 8192, 4352), + new(6, 0, 35651584, 1069547520, 60000, 16384, 8704), + new(6, 1, 35651584, 2139095040, 100000, 16384, 8704), + new(6, 2, 35651584, 4278190080, 160000, 16384, 8704), + new(6, 3, 35651584, 4278190080, 160000, 16384, 8704), + ]; + + /// Levels defined for , lowest first. + public static IReadOnlyList Levels(VideoCodec codec) => [.. Table(codec).Select(l => new CodecLevel(codec, l.Major, l.Minor))]; + + /// Finds the lowest level for the configuration; ≤ 0 skips the bit-rate check. + public static LevelCheck Check(VideoCodec codec, int width, int height, double fps, long bitRate, CodecProfile profile = CodecProfile.Auto) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (!(fps > 0)) throw new ArgumentOutOfRangeException(nameof(fps)); + var table = Table(codec); + var factor = BitRateFactor(codec, profile); + foreach (var limits in table) + { + if (Violations(codec, limits, width, height, fps, bitRate, factor) == LevelLimit.None) + return new LevelCheck(new CodecLevel(codec, limits.Major, limits.Minor), Highest(codec), LevelLimit.None, width, height, MaxBitRate(table[^1], factor)); + } + var top = table[^1]; + var exceeded = Violations(codec, top, width, height, fps, bitRate, factor); + var (w, h) = Cap(codec, top, width, height, fps); + return new LevelCheck(null, Highest(codec), exceeded, w, h, MaxBitRate(top, factor)); + } + + /// Largest even size with the aspect ratio of × that fits the highest level. + public static (int Width, int Height) CapResolution(VideoCodec codec, int width, int height, double fps) + { + var check = Check(codec, width, height, fps, 0); + return (check.SuggestedWidth, check.SuggestedHeight); + } + + private static (int Width, int Height) Cap(VideoCodec codec, Limits top, int width, int height, double fps) + { + // Fitting is monotonic in the scale, so bisect on half the width (keeps sizes even). + int lo = 0, hi = width / 2; + while (lo < hi) + { + var mid = (lo + hi + 1) / 2; + var (w, h) = Scaled(width, height, mid * 2); + if ((Violations(codec, top, w, h, fps, 0, 1) & ~LevelLimit.BitRate) == LevelLimit.None) lo = mid; + else hi = mid - 1; + } + return lo == 0 ? (0, 0) : Scaled(width, height, lo * 2); + } + + private static (int Width, int Height) Scaled(int width, int height, int newWidth) + { + var h = (int)Math.Max(2, Math.Round(newWidth * (double)height / width / 2) * 2); + return (newWidth, h); + } + + private static LevelLimit Violations(VideoCodec codec, Limits l, int width, int height, double fps, long bitRate, double factor) + { + long w = width, h = height; + if (codec == VideoCodec.H264) + { + w = (width + 15) / 16 * 16; + h = (height + 15) / 16 * 16; + } + else if (codec == VideoCodec.Hevc) + { + w = (width + 7) / 8 * 8; // MinCbSizeY of 8 + h = (height + 7) / 8 * 8; + } + var size = w * h; + var result = LevelLimit.None; + if (size > l.PictureSamples) result |= LevelLimit.PictureSize; + if (l.MaxWidth > 0) + { + if (w > l.MaxWidth || h > l.MaxHeight) result |= LevelLimit.Dimension; + } + else + { + // H.264 A.3.1 / HEVC A.4.1: each side at most sqrt(8 × maximum picture size). + var side = Math.Sqrt(8.0 * l.PictureSamples); + if (w > side || h > side) result |= LevelLimit.Dimension; + } + if (size * fps > l.SampleRate * (1 + 1e-9)) result |= LevelLimit.SampleRate; + if (bitRate > 0 && bitRate > MaxBitRate(l, factor)) result |= LevelLimit.BitRate; + return result; + } + + private static long MaxBitRate(Limits l, double factor) => (long)(l.BitRateKbps * 1000 * factor); + + /// cpbBrVclFactor relative to 1000: H.264 High is 1250 (A.3.3.2); Baseline/Main, HEVC Main/Main10 and AV1 main are 1000. + private static double BitRateFactor(VideoCodec codec, CodecProfile profile) => + codec == VideoCodec.H264 && profile is CodecProfile.H264High or CodecProfile.Auto ? 1.25 : 1.0; + + private static CodecLevel Highest(VideoCodec codec) + { + var top = Table(codec)[^1]; + return new CodecLevel(codec, top.Major, top.Minor); + } + + private static Limits[] Table(VideoCodec codec) => codec switch + { + VideoCodec.H264 => H264, + VideoCodec.Hevc => Hevc, + VideoCodec.Av1 => Av1, + _ => throw new ArgumentException($"No level table for {codec}", nameof(codec)), + }; +} diff --git a/tests/Titano.Core.Tests/Video/CodecLimitsTests.cs b/tests/Titano.Core.Tests/Video/CodecLimitsTests.cs new file mode 100644 index 00000000..27cc9521 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/CodecLimitsTests.cs @@ -0,0 +1,70 @@ +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class CodecLimitsTests +{ + [Theory] + [Case(VideoCodec.H264, 1920, 1080, 30.0, 6_220_800L, "4.0", Name = "1080p30 H.264 (0.10 bpp)")] + [Case(VideoCodec.H264, 1920, 1080, 60.0, 12_441_600L, "4.2")] + [Case(VideoCodec.H264, 1280, 720, 30.0, 0L, "3.1")] + [Case(VideoCodec.H264, 3840, 2160, 30.0, 24_883_200L, "5.1")] + [Case(VideoCodec.H264, 1920, 1080, 30.0, 40_000_000L, "4.1", Name = "1080p30 H.264 at 40 Mbit/s")] + [Case(VideoCodec.Hevc, 3840, 2160, 60.0, 34_836_480L, "5.1", Name = "4K60 HEVC (0.07 bpp)")] + [Case(VideoCodec.Hevc, 7680, 4320, 30.0, 69_672_960L, "6.1", Name = "8K30 HEVC (0.07 bpp)")] + [Case(VideoCodec.Hevc, 7680, 4320, 30.0, 50_000_000L, "6.0")] + [Case(VideoCodec.Hevc, 1920, 1080, 30.0, 0L, "4.0")] + [Case(VideoCodec.Av1, 1920, 1080, 30.0, 0L, "4.0")] + [Case(VideoCodec.Av1, 3840, 2160, 60.0, 29_859_840L, "5.1")] + [Case(VideoCodec.Av1, 640, 360, 24.0, 0L, "2.1")] + public void ChoosesLowestFittingLevel(VideoCodec codec, int width, int height, double fps, long bitRate, string level) + { + var check = CodecLimits.Check(codec, width, height, fps, bitRate); + Assert.True(check.Fits); + Assert.Equal(level, check.Level!.Value.Name); + Assert.Equal(LevelLimit.None, check.Exceeded); + Assert.Equal(width, check.SuggestedWidth); + } + + [Test] + public void LevelIdentifiersMatchTheBitstreamCodes() + { + Assert.Equal(41, new CodecLevel(VideoCodec.H264, 4, 1).H264LevelIdc); + Assert.Equal(153, new CodecLevel(VideoCodec.Hevc, 5, 1).HevcLevelIdc); + Assert.Equal(186, new CodecLevel(VideoCodec.Hevc, 6, 2).HevcLevelIdc); + Assert.Equal(13, new CodecLevel(VideoCodec.Av1, 5, 1).Av1SeqLevelIdx); + Assert.Equal(19, CodecLimits.Levels(VideoCodec.H264).Count); + Assert.Equal("6.3", CodecLimits.Levels(VideoCodec.Av1)[^1].Name); + } + + [Theory] + [Case(VideoCodec.H264, 16384, 8640, 30.0)] + [Case(VideoCodec.Hevc, 15360, 8640, 60.0)] + [Case(VideoCodec.Av1, 20000, 10000, 30.0)] + public void OversizedConfigurationsGetACappedSuggestion(VideoCodec codec, int width, int height, double fps) + { + var check = CodecLimits.Check(codec, width, height, fps, 0); + Assert.False(check.Fits); + Assert.True((check.Exceeded & (LevelLimit.PictureSize | LevelLimit.SampleRate | LevelLimit.Dimension)) != 0); + Assert.True(check.SuggestedWidth % 2 == 0 && check.SuggestedHeight % 2 == 0); + Assert.Approximately(width / (double)height, check.SuggestedWidth / (double)check.SuggestedHeight, 0.01); + Assert.True(CodecLimits.Check(codec, check.SuggestedWidth, check.SuggestedHeight, fps, 0).Fits); + // The suggestion is tight: a slightly larger size no longer fits. + var w = check.SuggestedWidth + 64; + var h = (int)Math.Round(w * (double)height / width); + Assert.False(CodecLimits.Check(codec, w, h, fps, 0).Fits); + } + + [Test] + public void ExcessiveBitRateIsReportedWithoutResizing() + { + var check = CodecLimits.Check(VideoCodec.H264, 1920, 1080, 30, 2_000_000_000, CodecProfile.H264High); + Assert.False(check.Fits); + Assert.Equal(LevelLimit.BitRate, check.Exceeded); + Assert.Equal(1920, check.SuggestedWidth); + Assert.Equal(1080, check.SuggestedHeight); + Assert.Equal(1_000_000_000L, check.MaxBitRate); + Assert.Equal(800_000_000L, CodecLimits.Check(VideoCodec.H264, 64, 64, 30, 0, CodecProfile.H264Main).MaxBitRate); + } +} From c40b6a7cd31b26379c2e8d44b64f22af09c2ad79 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:34:52 +0000 Subject: [PATCH 016/188] feat: Phase 0 shells, design system, server skeleton, Docker and CI - Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set, styles for all standard controls, custom chrome window with snap layouts, rail, job bar, Auto/manual slider, chips, toasts. - Titano desktop shell with sections, Settings (language, theme), About and a --capture screenshot mode. - Titano Server skeleton: env/server.json configuration, self-signed TLS with fingerprint, /health, /server/info, i18n endpoint and the embedded admin panel; in-process server tests. - Docker image (multi-arch, PUID/PGID, health check), compose file, Unraid template; CI, release and nightly workflows; changelog tool. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .dockerignore | 10 + .github/workflows/ci.yml | 214 +++ .github/workflows/docker.yml | 37 + .github/workflows/release.yml | 206 +++ .gitignore | 3 + Directory.Build.props | 9 + branding/ui-icons/icons.py | 153 ++ branding/ui-icons/icons.svg | 417 +++++ deploy/docker/.env.example | 8 + deploy/docker/Dockerfile | 43 + deploy/docker/docker-compose.yml | 44 + deploy/docker/entrypoint.sh | 19 + deploy/unraid/titano.xml | 41 + docs/CHANGELOG.md | 13 +- docs/DECISIONS.md | 10 + docs/STATUS.md | 14 +- i18n/en/About.resx | 14 + i18n/en/Admin.resx | 37 + i18n/en/Archive.resx | 8 + i18n/en/Common.resx | 15 + i18n/en/Editor.resx | 8 + i18n/en/Errors.resx | 8 + i18n/en/Import.resx | 8 + i18n/en/Jobs.resx | 8 + i18n/en/Library.resx | 11 + i18n/en/Server.resx | 8 + i18n/en/Settings.resx | 25 + i18n/en/Shell.resx | 21 +- i18n/en/Tooltips.resx | 37 + i18n/it/About.it.resx | 14 + i18n/it/Admin.it.resx | 37 + i18n/it/Archive.it.resx | 8 + i18n/it/Common.it.resx | 15 + i18n/it/Editor.it.resx | 8 + i18n/it/Errors.it.resx | 8 + i18n/it/Import.it.resx | 8 + i18n/it/Jobs.it.resx | 8 + i18n/it/Library.it.resx | 11 + i18n/it/Server.it.resx | 8 + i18n/it/Settings.it.resx | 25 + i18n/it/Shell.it.resx | 19 +- i18n/it/Tooltips.it.resx | 37 + src/Titano.App/App.xaml | 10 +- src/Titano.App/App.xaml.cs | 90 ++ .../Infrastructure/AppEnvironment.cs | 35 + src/Titano.App/Infrastructure/AppSettings.cs | 51 + src/Titano.App/Infrastructure/Formatting.cs | 34 + src/Titano.App/Infrastructure/ProductLinks.cs | 14 + src/Titano.App/Infrastructure/ShellActions.cs | 20 + src/Titano.App/Sections/AboutView.xaml | 43 + src/Titano.App/Sections/AboutView.xaml.cs | 8 + src/Titano.App/Sections/ArchiveView.xaml | 9 + src/Titano.App/Sections/ArchiveView.xaml.cs | 8 + src/Titano.App/Sections/ImportView.xaml | 9 + src/Titano.App/Sections/ImportView.xaml.cs | 8 + src/Titano.App/Sections/JobsView.xaml | 9 + src/Titano.App/Sections/JobsView.xaml.cs | 8 + src/Titano.App/Sections/LibraryView.xaml | 15 + src/Titano.App/Sections/LibraryView.xaml.cs | 8 + src/Titano.App/Sections/Sections.cs | 164 ++ src/Titano.App/Sections/SequenceView.xaml | 11 + src/Titano.App/Sections/SequenceView.xaml.cs | 8 + src/Titano.App/Sections/ServerView.xaml | 9 + src/Titano.App/Sections/ServerView.xaml.cs | 8 + src/Titano.App/Sections/SettingsView.xaml | 88 ++ src/Titano.App/Sections/SettingsView.xaml.cs | 22 + src/Titano.App/Shell/MainWindow.xaml | 69 + src/Titano.App/Shell/MainWindow.xaml.cs | 63 + src/Titano.App/Shell/ScreenCapture.cs | 80 + src/Titano.App/Shell/SectionTemplates.xaml | 13 + src/Titano.App/Shell/SectionViewModel.cs | 59 + src/Titano.App/Shell/ShellViewModel.cs | 168 ++ src/Titano.Protocol/Dtos.cs | 33 + src/Titano.Server/Admin/web/admin.css | 100 ++ src/Titano.Server/Admin/web/api.js | 47 + src/Titano.Server/Admin/web/app.js | 102 ++ src/Titano.Server/Admin/web/favicon.svg | 17 + src/Titano.Server/Admin/web/i18n.js | 27 + src/Titano.Server/Admin/web/icons.js | 16 + src/Titano.Server/Admin/web/index.html | 16 +- src/Titano.Server/Admin/web/pages/about.js | 12 + .../Admin/web/pages/dashboard.js | 18 + src/Titano.Server/Api/SystemEndpoints.cs | 66 + .../Configuration/ServerOptions.cs | 130 ++ src/Titano.Server/Hosting/CertificateStore.cs | 79 + .../Hosting/EmbeddedStaticFiles.cs | 70 + .../Hosting/FileLoggerProvider.cs | 54 + src/Titano.Server/Hosting/HealthProbe.cs | 26 + src/Titano.Server/Hosting/ServerHost.cs | 98 ++ src/Titano.Server/Program.cs | 15 +- src/Titano.Tools/Commands/ChangelogCommand.cs | 90 ++ src/Titano.Tools/Commands/I18nCommand.cs | 2 + src/Titano.Tools/Program.cs | 1 + src/Titano.Ui/Controls/AutoSlider.cs | 142 ++ src/Titano.Ui/Controls/BrandMarkIcon.cs | 61 + src/Titano.Ui/Controls/Chip.cs | 29 + src/Titano.Ui/Controls/ControlState.cs | 28 + src/Titano.Ui/Controls/Converters.cs | 44 + src/Titano.Ui/Controls/EmptyState.cs | 17 + src/Titano.Ui/Controls/Field.cs | 32 + src/Titano.Ui/Controls/Icon.cs | 79 + src/Titano.Ui/Controls/IconData.cs | 30 + src/Titano.Ui/Controls/JobBar.cs | 34 + src/Titano.Ui/Controls/NavRail.cs | 43 + src/Titano.Ui/Controls/StatusGlyph.cs | 42 + src/Titano.Ui/Controls/TitanoWindow.cs | 138 ++ src/Titano.Ui/Controls/Toasts.cs | 79 + src/Titano.Ui/Icons/Icons.xaml | 107 ++ src/Titano.Ui/Interop/NativeMethods.cs | 45 + src/Titano.Ui/Localization/LocExtension.cs | 49 + src/Titano.Ui/Mvvm/ObservableObject.cs | 39 + src/Titano.Ui/Mvvm/RelayCommand.cs | 70 + src/Titano.Ui/Themes/Controls.xaml | 1391 +++++++++++++++++ src/Titano.Ui/Themes/Tokens.Dark.xaml | 70 + src/Titano.Ui/Themes/Tokens.Light.xaml | 70 + src/Titano.Ui/Themes/Typography.xaml | 85 + src/Titano.Ui/Theming/ThemeManager.cs | 112 ++ .../Hosting/SystemEndpointTests.cs | 126 ++ tests/Titano.Server.Tests/TestServer.cs | 61 + tests/Titano.Testing/Assert.cs | 8 +- tests/Titano.Testing/ConsoleReporter.cs | 7 + tests/Titano.Testing/TestRunner.cs | 7 +- 122 files changed, 6838 insertions(+), 22 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/docker.yml create mode 100644 .github/workflows/release.yml create mode 100644 branding/ui-icons/icons.py create mode 100644 branding/ui-icons/icons.svg create mode 100644 deploy/docker/.env.example create mode 100644 deploy/docker/Dockerfile create mode 100644 deploy/docker/docker-compose.yml create mode 100755 deploy/docker/entrypoint.sh create mode 100644 deploy/unraid/titano.xml create mode 100644 i18n/en/About.resx create mode 100644 i18n/en/Admin.resx create mode 100644 i18n/en/Archive.resx create mode 100644 i18n/en/Common.resx create mode 100644 i18n/en/Editor.resx create mode 100644 i18n/en/Errors.resx create mode 100644 i18n/en/Import.resx create mode 100644 i18n/en/Jobs.resx create mode 100644 i18n/en/Library.resx create mode 100644 i18n/en/Server.resx create mode 100644 i18n/en/Settings.resx create mode 100644 i18n/en/Tooltips.resx create mode 100644 i18n/it/About.it.resx create mode 100644 i18n/it/Admin.it.resx create mode 100644 i18n/it/Archive.it.resx create mode 100644 i18n/it/Common.it.resx create mode 100644 i18n/it/Editor.it.resx create mode 100644 i18n/it/Errors.it.resx create mode 100644 i18n/it/Import.it.resx create mode 100644 i18n/it/Jobs.it.resx create mode 100644 i18n/it/Library.it.resx create mode 100644 i18n/it/Server.it.resx create mode 100644 i18n/it/Settings.it.resx create mode 100644 i18n/it/Tooltips.it.resx create mode 100644 src/Titano.App/Infrastructure/AppEnvironment.cs create mode 100644 src/Titano.App/Infrastructure/AppSettings.cs create mode 100644 src/Titano.App/Infrastructure/Formatting.cs create mode 100644 src/Titano.App/Infrastructure/ProductLinks.cs create mode 100644 src/Titano.App/Infrastructure/ShellActions.cs create mode 100644 src/Titano.App/Sections/AboutView.xaml create mode 100644 src/Titano.App/Sections/AboutView.xaml.cs create mode 100644 src/Titano.App/Sections/ArchiveView.xaml create mode 100644 src/Titano.App/Sections/ArchiveView.xaml.cs create mode 100644 src/Titano.App/Sections/ImportView.xaml create mode 100644 src/Titano.App/Sections/ImportView.xaml.cs create mode 100644 src/Titano.App/Sections/JobsView.xaml create mode 100644 src/Titano.App/Sections/JobsView.xaml.cs create mode 100644 src/Titano.App/Sections/LibraryView.xaml create mode 100644 src/Titano.App/Sections/LibraryView.xaml.cs create mode 100644 src/Titano.App/Sections/Sections.cs create mode 100644 src/Titano.App/Sections/SequenceView.xaml create mode 100644 src/Titano.App/Sections/SequenceView.xaml.cs create mode 100644 src/Titano.App/Sections/ServerView.xaml create mode 100644 src/Titano.App/Sections/ServerView.xaml.cs create mode 100644 src/Titano.App/Sections/SettingsView.xaml create mode 100644 src/Titano.App/Sections/SettingsView.xaml.cs create mode 100644 src/Titano.App/Shell/MainWindow.xaml create mode 100644 src/Titano.App/Shell/MainWindow.xaml.cs create mode 100644 src/Titano.App/Shell/ScreenCapture.cs create mode 100644 src/Titano.App/Shell/SectionTemplates.xaml create mode 100644 src/Titano.App/Shell/SectionViewModel.cs create mode 100644 src/Titano.App/Shell/ShellViewModel.cs create mode 100644 src/Titano.Protocol/Dtos.cs create mode 100644 src/Titano.Server/Admin/web/admin.css create mode 100644 src/Titano.Server/Admin/web/api.js create mode 100644 src/Titano.Server/Admin/web/app.js create mode 100644 src/Titano.Server/Admin/web/favicon.svg create mode 100644 src/Titano.Server/Admin/web/i18n.js create mode 100644 src/Titano.Server/Admin/web/icons.js create mode 100644 src/Titano.Server/Admin/web/pages/about.js create mode 100644 src/Titano.Server/Admin/web/pages/dashboard.js create mode 100644 src/Titano.Server/Api/SystemEndpoints.cs create mode 100644 src/Titano.Server/Configuration/ServerOptions.cs create mode 100644 src/Titano.Server/Hosting/CertificateStore.cs create mode 100644 src/Titano.Server/Hosting/EmbeddedStaticFiles.cs create mode 100644 src/Titano.Server/Hosting/FileLoggerProvider.cs create mode 100644 src/Titano.Server/Hosting/HealthProbe.cs create mode 100644 src/Titano.Server/Hosting/ServerHost.cs create mode 100644 src/Titano.Tools/Commands/ChangelogCommand.cs create mode 100644 src/Titano.Ui/Controls/AutoSlider.cs create mode 100644 src/Titano.Ui/Controls/BrandMarkIcon.cs create mode 100644 src/Titano.Ui/Controls/Chip.cs create mode 100644 src/Titano.Ui/Controls/ControlState.cs create mode 100644 src/Titano.Ui/Controls/Converters.cs create mode 100644 src/Titano.Ui/Controls/EmptyState.cs create mode 100644 src/Titano.Ui/Controls/Field.cs create mode 100644 src/Titano.Ui/Controls/Icon.cs create mode 100644 src/Titano.Ui/Controls/IconData.cs create mode 100644 src/Titano.Ui/Controls/JobBar.cs create mode 100644 src/Titano.Ui/Controls/NavRail.cs create mode 100644 src/Titano.Ui/Controls/StatusGlyph.cs create mode 100644 src/Titano.Ui/Controls/TitanoWindow.cs create mode 100644 src/Titano.Ui/Controls/Toasts.cs create mode 100644 src/Titano.Ui/Icons/Icons.xaml create mode 100644 src/Titano.Ui/Interop/NativeMethods.cs create mode 100644 src/Titano.Ui/Localization/LocExtension.cs create mode 100644 src/Titano.Ui/Mvvm/ObservableObject.cs create mode 100644 src/Titano.Ui/Mvvm/RelayCommand.cs create mode 100644 src/Titano.Ui/Themes/Controls.xaml create mode 100644 src/Titano.Ui/Themes/Tokens.Dark.xaml create mode 100644 src/Titano.Ui/Themes/Tokens.Light.xaml create mode 100644 src/Titano.Ui/Themes/Typography.xaml create mode 100644 src/Titano.Ui/Theming/ThemeManager.cs create mode 100644 tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs create mode 100644 tests/Titano.Server.Tests/TestServer.cs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..767471fe --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +**/bin/ +**/obj/ +artifacts/ +out/ +publish/ +tests/ +docs/ +.git/ +.github/ +**/*.user diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..6088ed24 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,214 @@ +name: CI + +on: + push: + branches: ["**"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1" + TOOLS: src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll + +jobs: + build: + name: Build and test (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: .NET info + run: dotnet --info + + - name: Restore fixtures cache + uses: actions/cache@v4 + with: + path: tests/fixtures/external + key: fixtures-${{ hashFiles('tests/fixtures/manifest.json') }} + + - name: Build (warnings are errors) + run: dotnet build Titano.slnx -c Release + + - name: Zero-package guard + run: dotnet "$TOOLS" package-guard + + - name: Localization check + run: dotnet "$TOOLS" i18n check + + - name: XAML lint + run: dotnet "$TOOLS" xaml-lint + + - name: Format check + if: runner.os == 'Windows' + run: dotnet format whitespace Titano.slnx --verify-no-changes + + - name: Fetch CC0 fixtures + continue-on-error: true + run: | + if dotnet "$TOOLS" --help | grep -q '^ fixtures'; then dotnet "$TOOLS" fixtures; fi + + - name: Test · Core + run: dotnet run --project tests/Titano.Core.Tests -c Release --no-build -- --junit out/junit/core.xml + + - name: Test · Data (SQLite) + run: dotnet run --project tests/Titano.Data.Tests -c Release --no-build -- --junit out/junit/data.xml + + - name: Test · Server + run: dotnet run --project tests/Titano.Server.Tests -c Release --no-build -- --junit out/junit/server.xml + + - name: Test · Core.Windows + if: runner.os == 'Windows' + run: dotnet run --project tests/Titano.Core.Windows.Tests -c Release --no-build -- --junit out/junit/core-windows.xml + + - name: Test · App + if: runner.os == 'Windows' + run: dotnet run --project tests/Titano.App.Tests -c Release --no-build -- --junit out/junit/app.xml + + - name: Screenshots + if: runner.os == 'Windows' + run: | + src/Titano.App/bin/Release/net10.0-windows/Titano.exe --capture out/screenshots & + wait $! + ls -la out/screenshots + + - name: Publish desktop programs (win-x64, self-contained single file) + if: runner.os == 'Windows' + run: | + for p in Titano.App Titano.Uploader; do + dotnet publish "src/$p/$p.csproj" -c Release -r win-x64 --self-contained \ + -p:PublishSingleFile=true -p:PublishReadyToRun=true -p:IncludeNativeLibrariesForSelfExtract=true \ + -o "out/publish/$p" + done + dotnet publish src/Titano.Server/Titano.Server.csproj -c Release -r win-x64 --self-contained \ + -p:PublishSingleFile=true -o out/publish/Titano.Server + + - name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-results-${{ matrix.os }} + path: out/junit/ + if-no-files-found: ignore + + - name: Upload screenshots + if: runner.os == 'Windows' && always() + uses: actions/upload-artifact@v4 + with: + name: screenshots + path: out/screenshots/ + if-no-files-found: ignore + + - name: Upload Windows programs + if: runner.os == 'Windows' + uses: actions/upload-artifact@v4 + with: + name: titano-win-x64-${{ github.sha }} + path: out/publish/ + retention-days: 14 + + postgres: + name: PostgreSQL ${{ matrix.pg }} integration + strategy: + fail-fast: false + matrix: + pg: ["16", "17"] + runs-on: ubuntu-latest + services: + postgres: + image: postgres:${{ matrix.pg }} + env: + POSTGRES_USER: titano + POSTGRES_PASSWORD: titano-ci + POSTGRES_DB: titano_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U titano -d titano_test" + --health-interval 5s --health-timeout 5s --health-retries 20 + env: + TITANO_TEST_PG: Host=127.0.0.1;Port=5432;Database=titano_test;Username=titano;Password=titano-ci;SslMode=disable + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + - name: Test · Data (PostgreSQL) + run: dotnet run --project tests/Titano.Data.Tests -c Release -- --junit out/junit/data-pg${{ matrix.pg }}.xml + - name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-results-pg${{ matrix.pg }} + path: out/junit/ + if-no-files-found: ignore + + docker: + name: Docker image + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: titano + POSTGRES_PASSWORD: titano-ci + POSTGRES_DB: titano + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U titano -d titano" + --health-interval 5s --health-timeout 5s --health-retries 20 + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - name: Build image + uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64 + load: true + push: false + tags: titano-server:ci + build-args: TITANO_VERSION=0.0.0-ci + cache-from: type=gha + cache-to: type=gha,mode=max + - name: Smoke test (/health) + run: | + mkdir -p "$RUNNER_TEMP/archive" "$RUNNER_TEMP/data" + docker run -d --name titano --network host \ + -e TITANO_DB_HOST=127.0.0.1 -e TITANO_DB_USER=titano -e TITANO_DB_PASSWORD=titano-ci -e TITANO_DB_NAME=titano \ + -e TITANO_ADMIN_USER=admin -e TITANO_ADMIN_PASSWORD=ci-password-1234 \ + -e PUID="$(id -u)" -e PGID="$(id -g)" \ + -v "$RUNNER_TEMP/archive:/archive" -v "$RUNNER_TEMP/data:/data" titano-server:ci + for i in $(seq 1 60); do + if curl -fsS http://127.0.0.1:8080/health; then echo; break; fi + sleep 2 + done + curl -fsS http://127.0.0.1:8080/api/v1/server/info + curl -fsSk https://127.0.0.1:8443/health + test "$(docker inspect --format '{{.State.Running}}' titano)" = "true" + - name: Container logs + if: always() + run: docker logs titano || true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 00000000..3079bf87 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,37 @@ +name: Nightly image + +on: + schedule: + - cron: "17 2 * * *" + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + nightly: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Image name + id: image + run: echo "name=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/titano-server" >> "$GITHUB_OUTPUT" + - uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.image.outputs.name }}:nightly + build-args: TITANO_VERSION=0.0.0-nightly.${{ github.run_number }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..03ecd78e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,206 @@ +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: "Existing tag to (re)publish, e.g. v0.2.0" + required: true + +permissions: + contents: write + packages: write + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + # Public repository that receives releases (BRIEF §19.4). Override with the RELEASES_REPO variable. + RELEASES_REPO: ${{ vars.RELEASES_REPO || format('{0}/titano-releases', github.repository_owner) }} + +jobs: + version: + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.v.outputs.tag }} + version: ${{ steps.v.outputs.version }} + prerelease: ${{ steps.v.outputs.prerelease }} + steps: + - id: v + run: | + tag="${{ github.event.inputs.tag || github.ref_name }}" + version="${tag#v}" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + if [[ "$version" == *-* ]]; then echo "prerelease=true" >> "$GITHUB_OUTPUT"; else echo "prerelease=false" >> "$GITHUB_OUTPUT"; fi + + windows: + needs: version + runs-on: windows-latest + defaults: + run: + shell: bash + env: + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + fetch-depth: 0 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Build and test + run: | + dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" + for t in Core Data Server Core.Windows App; do + dotnet run --project "tests/Titano.$t.Tests" -c Release --no-build -- --junit "out/junit/$t.xml" + done + + - name: Publish self-contained programs + run: | + common="-c Release -r win-x64 --self-contained -p:TitanoVersion=$VERSION -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none" + dotnet publish src/Titano.App/Titano.App.csproj $common -p:PublishReadyToRun=true -o out/publish/app + dotnet publish src/Titano.Uploader/Titano.Uploader.csproj $common -p:PublishReadyToRun=true -o out/publish/uploader + dotnet publish src/Titano.Server/Titano.Server.csproj $common -o out/publish/server + dotnet publish src/Titano.Setup/Titano.Setup.csproj $common -p:PublishReadyToRun=true -o out/publish/setup + + - name: Sign binaries + if: env.SIGN_PFX != '' + env: + SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} + SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} + shell: pwsh + run: | + $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + Get-ChildItem out/publish -Recurse -Include *.exe | ForEach-Object { + & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + Remove-Item $pfx + + - name: Package installers and archives + run: | + mkdir -p out/release + tools=src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll + dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product Titano \ + --component "Titano=out/publish/app" --component "Uploader=out/publish/uploader" --component "Server=out/publish/server" \ + --version "$VERSION" --out "out/release/Titano-Setup-$VERSION.exe" + dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product "Titano Uploader" \ + --component "Uploader=out/publish/uploader" --version "$VERSION" --out "out/release/Titano-Uploader-Setup-$VERSION.exe" + (cd out/publish/server && 7z a -tzip "../../release/Titano-Server-win-x64-$VERSION.zip" . > /dev/null) + (cd out/publish/app && 7z a -tzip "../../release/Titano-win-x64-portable-$VERSION.zip" . > /dev/null) + + - name: Sign installers + if: env.SIGN_PFX != '' + env: + SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} + SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} + shell: pwsh + run: | + $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + Get-ChildItem out/release -Filter *.exe | ForEach-Object { & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName } + Remove-Item $pfx + + - name: Release notes + run: | + tag="${{ needs.version.outputs.tag }}" + previous="$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true)" + range="${previous:+$previous..}$tag" + git log --format='%h%x09%s' "$range" | dotnet src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll changelog --title "Titano ${{ needs.version.outputs.version }}" --out out/release-notes.md + + - uses: actions/upload-artifact@v4 + with: + name: release-windows + path: | + out/release/ + out/release-notes.md + + docker: + needs: version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Image name + id: image + run: echo "name=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/titano-server" >> "$GITHUB_OUTPUT" + - uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + build-args: TITANO_VERSION=${{ needs.version.outputs.version }} + tags: | + ${{ steps.image.outputs.name }}:${{ needs.version.outputs.version }} + ${{ needs.version.outputs.prerelease == 'false' && format('{0}:latest', steps.image.outputs.name) || '' }} + cache-from: type=gha + cache-to: type=gha,mode=max + + publish: + needs: [version, windows, docker] + runs-on: ubuntu-latest + env: + TAG: ${{ needs.version.outputs.tag }} + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + - uses: actions/download-artifact@v4 + with: + name: release-windows + path: out + - name: Checksums + run: | + cd out/release + sha256sum * > SHA256SUMS + cat SHA256SUMS + + - name: Create release in the public releases repository + if: env.RELEASES_TOKEN != '' + env: + RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} + GH_TOKEN: ${{ secrets.RELEASES_TOKEN }} + run: | + flags="" + if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi + gh release create "$TAG" out/release/* --repo "$RELEASES_REPO" --title "Titano $VERSION" --notes-file out/release-notes.md $flags + # Keep the Unraid template, icon and EULA in the public repository up to date. + git clone --depth 1 "https://x-access-token:${RELEASES_TOKEN}@github.com/${RELEASES_REPO}.git" public + mkdir -p public/unraid + cp deploy/unraid/titano.xml public/unraid/titano.xml + dotnet run --project src/Titano.Tools -c Release -- make-icon --out "$RUNNER_TEMP/icons" + cp "$RUNNER_TEMP/icons/titano-server-256.png" public/unraid/titano-server.png + if [ -f docs/legal/EULA.md ]; then cp docs/legal/EULA.md public/EULA.md; fi + cd public + git config user.name "titano-release" + git config user.email "titano-release@users.noreply.github.com" + git add -A + git diff --cached --quiet || git commit -m "chore: update Unraid template and assets for $TAG" + git push + + - name: Create release in this repository (no RELEASES_TOKEN configured) + if: env.RELEASES_TOKEN == '' + env: + RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + flags="" + if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi + gh release create "$TAG" out/release/* --repo "$GITHUB_REPOSITORY" --title "Titano $VERSION" --notes-file out/release-notes.md $flags diff --git a/.gitignore b/.gitignore index 1732a815..62b03a69 100644 --- a/.gitignore +++ b/.gitignore @@ -435,3 +435,6 @@ tests/fixtures/external/ /artifacts/ *.junit.xml TestResults/ + +# Local agent tooling +.claude/ diff --git a/Directory.Build.props b/Directory.Build.props index 5b59ad91..cda20b1f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,6 +6,7 @@ $([System.Text.RegularExpressions.Regex]::Match($(TitanoVersion), '^\d+\.\d+\.\d+').Value).0 $(AssemblyVersion) $(TitanoVersion) + false Titano Titano © Titano @@ -34,6 +35,14 @@ embedded + + + alby96/titano-releases + + + + + true diff --git a/branding/ui-icons/icons.py b/branding/ui-icons/icons.py new file mode 100644 index 00000000..51aa85d7 --- /dev/null +++ b/branding/ui-icons/icons.py @@ -0,0 +1,153 @@ +"""Titano UI icon set (DESIGN.md §5): 16-px grid, 1.5-px strokes, round caps/joins. +Each icon = stroke path data + optional fill path data. Generates the WPF resource dictionary +src/Titano.Ui/Icons/Icons.xaml and a preview sheet (icons.svg). Run: python3 branding/ui-icons/icons.py""" +import math, os + +def rr(x, y, w, h, r): + return (f"M{x+r} {y} H{x+w-r} A{r} {r} 0 0 1 {x+w} {y+r} V{y+h-r} A{r} {r} 0 0 1 {x+w-r} {y+h} " + f"H{x+r} A{r} {r} 0 0 1 {x} {y+h-r} V{y+r} A{r} {r} 0 0 1 {x+r} {y} Z") + +def circ(cx, cy, r): + return f"M{cx-r} {cy} A{r} {r} 0 1 0 {cx+r} {cy} A{r} {r} 0 1 0 {cx-r} {cy} Z" + +def arc(cx, cy, r, a0, a1): + """Arc clockwise from a0 to a1 degrees (0 = 12 o'clock).""" + p = lambda a: (cx + r * math.sin(math.radians(a)), cy - r * math.cos(math.radians(a))) + x0, y0 = p(a0); x1, y1 = p(a1) + large = 1 if (a1 - a0) % 360 > 180 else 0 + return f"M{x0:.2f} {y0:.2f} A{r} {r} 0 {large} 1 {x1:.2f} {y1:.2f}" + +I = {} +# Navigation +I["Library"] = (rr(1.5,1.5,5.5,5.5,1)+rr(9,1.5,5.5,5.5,1)+rr(1.5,9,5.5,5.5,1)+rr(9,9,5.5,5.5,1), None) +I["Import"] = ("M8 2V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5", None) +I["Sequence"] = ("M2 12.5 L11.5 3 L13 4.5 L3.5 14 H2 Z", None) +I["Archive"] = ("M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10", None) +I["Jobs"] = ("M3 8 H13 M3 4 H13 M3 12 H9", None) +I["Server"] = ("M4.5 12.5 A3 3 0 0 1 4.2 6.5 A4 4 0 0 1 11.9 5.5 A3.5 3.5 0 0 1 12.2 12.5 Z", None) +I["Settings"] = (circ(8,8,2.2)+" M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4", None) +I["About"] = (circ(8,8,6.5)+" M8 7 V11 M8 4.8 V5.2", None) +I["Menu"] = ("M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5", None) +I["Users"] = (circ(8,5,3)+" M2.5 14 A5.5 5.5 0 0 1 13.5 14", None) +I["User"] = I["Users"] +I["Logs"] = ("M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5", None) +# Toolbar / actions +I["Search"] = (circ(7,7,4.5)+" M10.4 10.4 L14 14", None) +I["Refresh"] = (arc(8,8,5.5,30,320)+" M13.2 2.6 L13.2 5.3 L10.5 5.3", None) +I["ViewGrid"] = I["Library"] +I["ViewList"] = ("M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6", None) +I["ViewTimeline"] = ("M2 13.5 H14 M3.5 11 V8 M6 11 V5 M8.5 11 V7 M11 11 V3.5 M13.5 11 V9", None) +I["ChevronDown"] = ("M4 6 L8 10 L12 6", None) +I["ChevronUp"] = ("M4 10 L8 6 L12 10", None) +I["ChevronRight"] = ("M6 4 L10 8 L6 12", None) +I["ChevronLeft"] = ("M10 4 L6 8 L10 12", None) +I["Close"] = ("M4 4 L12 12 M12 4 L4 12", None) +I["Check"] = ("M3 8.5 L6.5 12 L13 4.5", None) +I["Back"] = ("M13 8 H3 M7 4 L3 8 L7 12", None) +I["Forward"] = ("M3 8 H13 M9 4 L13 8 L9 12", None) +I["Plus"] = ("M8 3 V13 M3 8 H13", None) +I["Minus"] = ("M3 8 H13", None) +I["More"] = (None, circ(3.5,8,1.1)+circ(8,8,1.1)+circ(12.5,8,1.1)) +I["Play"] = (None, "M4.5 2.8 L13 8 L4.5 13.2 Z") +I["Pause"] = (None, rr(4,3,2.6,10,0.8)+rr(9.4,3,2.6,10,0.8)) +I["Stop"] = (None, rr(3.5,3.5,9,9,1.5)) +I["Folder"] = ("M1.5 4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H13.5 A1 1 0 0 1 14.5 5.5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z", None) +I["FolderOpen"] = ("M1.5 12.5 V4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H12.5 V6.5 M1.5 12.5 L3.5 7 H14.5 L12.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z", None) +I["Card"] = ("M4.5 1.5 H10 L12.5 4 V13.5 A1 1 0 0 1 11.5 14.5 H4.5 A1 1 0 0 1 3.5 13.5 V2.5 A1 1 0 0 1 4.5 1.5 Z M6 3.5 V5.5 M8 3.5 V5.5 M10 4.5 V5.5", None) +I["Drive"] = (rr(1.5,4.5,13,7,1.5)+" M4.5 8 H4.6 M7 8 H11.5", None) +I["Eject"] = ("M3 13 H13", "M8 2.8 L13 9.5 H3 Z") +I["Download"] = ("M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5", None) +I["Upload"] = ("M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5", None) +I["Sync"] = (arc(8,8,5.5,20,160)+" "+arc(8,8,5.5,200,340)+" M13.5 6.5 L13.2 9.4 L10.6 8.4 M2.5 9.5 L2.8 6.6 L5.4 7.6", None) +I["Compare"] = (rr(1.5,2.5,13,11,1.5)+" M8 1 V15", None) +I["Vectors"] = ("M2.5 12.5 L7 8 M7 8 H4.5 M7 8 V10.5 M9 7 L13.5 2.5 M13.5 2.5 H11 M13.5 2.5 V5", None) +I["Regions"] = ("M1.5 9.5 C4 8 6 10.5 8.5 9 C10.5 7.8 12.5 8.5 14.5 9.5 M1.5 13.5 H14.5 M1.5 2.5 H14.5", None) +I["CropMask"] = ("M4 1.5 V12 H14.5 M1.5 4 H12 V14.5", None) +I["Fullscreen"] = ("M2 6 V2 H6 M10 2 H14 V6 M14 10 V14 H10 M6 14 H2 V10", None) +I["ActualSize"] = (rr(1.5,2.5,13,11,1.5)+" M5 6 L6 5.5 V10.5 M9.5 6 L10.5 5.5 V10.5 M8 7 V7.1 M8 9.5 V9.6", None) +I["Reset"] = (arc(8,8.5,5,300,210)+" M3.2 3.2 V6.2 H6.2", None) +I["Warning"] = ("M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8", None) +I["ErrorCircle"] = (circ(8,8,6.5)+" M5.8 5.8 L10.2 10.2 M10.2 5.8 L5.8 10.2", None) +I["SuccessCircle"] = (circ(8,8,6.5)+" M5 8.3 L7.1 10.3 L11 6", None) +I["Lock"] = (rr(3,7,10,7.5,1.5)+" M5.5 7 V5 A2.5 2.5 0 0 1 10.5 5 V7", None) +I["Key"] = (circ(5,10.5,3)+" M7.2 8.3 L13.5 2 M11.5 4 L13 5.5 M9.8 5.7 L11 6.9", None) +I["Power"] = ("M8 1.8 V7.5 "+arc(8,8.8,5.5,40,320), None) +I["Moon"] = ("M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z", None) +I["Sun"] = (circ(8,8,3)+" M8 1 V2.5 M8 13.5 V15 M1 8 H2.5 M13.5 8 H15 M3 3 L4 4 M12 12 L13 13 M3 13 L4 12 M12 4 L13 3", None) +I["Star"] = ("M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z", None) +I["StarFilled"] = (None, "M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z") +I["Tag"] = ("M1.5 2.5 A1 1 0 0 1 2.5 1.5 H7.5 L14.5 8.5 L8.5 14.5 L1.5 7.5 Z M5 5 H5.1", None) +I["Delete"] = ("M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2", None) +I["Copy"] = (rr(5,5,9.5,9.5,1.5)+" M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5", None) +I["Link"] = ("M6.8 9.2 L9.2 6.8 M7.5 4.5 L9 3 A2.8 2.8 0 0 1 13 7 L11.5 8.5 M8.5 11.5 L7 13 A2.8 2.8 0 0 1 3 9 L4.5 7.5", None) +I["ExternalLink"] = ("M9.5 2 H14 V6.5 M14 2 L7.5 8.5 M12 9.5 V13 A1 1 0 0 1 11 14 H3 A1 1 0 0 1 2 13 V5 A1 1 0 0 1 3 4 H6.5", None) +I["Calendar"] = (rr(1.5,3,13,11.5,1.5)+" M1.5 6.5 H14.5 M5 1.5 V4 M11 1.5 V4", None) +I["Camera"] = ("M1.5 5 A1 1 0 0 1 2.5 4 H4.5 L6 2.5 H10 L11.5 4 H13.5 A1 1 0 0 1 14.5 5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z "+circ(8,8.5,2.8), None) +I["Chart"] = ("M2 2 V14 H14 M4.5 10.5 L7.5 7 L9.5 9 L13.5 4", None) +I["Filmstrip"] = (rr(1.5,2.5,13,11,1.5)+" M4.5 2.5 V13.5 M11.5 2.5 V13.5 M1.5 6 H4.5 M1.5 10 H4.5 M11.5 6 H14.5 M11.5 10 H14.5", None) +I["Layers"] = ("M8 1.8 L14.5 5.2 L8 8.6 L1.5 5.2 Z M1.5 8.2 L8 11.6 L14.5 8.2 M1.5 11 L8 14.4 L14.5 11", None) +I["Clock"] = (circ(8,8,6.5)+" M8 4.5 V8 L10.5 9.5", None) +I["Exposure"] = (circ(8,8,6.5)+" M3.4 12.6 L12.6 3.4 M4.5 6 H7 M5.75 4.75 V7.25 M9 10 H11.5", None) +I["Motion"] = ("M1.5 8 C3.5 3 5.5 3 7.5 8 C9.5 13 11.5 13 14.5 8", None) +I["Time"] = I["Clock"] +I["Stack"] = I["Layers"] +I["Export"] = ("M8 10 V1.8 M4.8 5 L8 1.8 L11.2 5 M5 7.5 H3 A1 1 0 0 0 2 8.5 V13.5 A1 1 0 0 0 3 14.5 H13 A1 1 0 0 0 14 13.5 V8.5 A1 1 0 0 0 13 7.5 H11", None) +I["Render"] = (rr(1.5,2.5,13,11,1.5), "M6.5 5.5 L10.8 8 L6.5 10.5 Z") +I["Analyse"] = ("M1.5 8.5 H4.5 L6.5 3.5 L9.5 12.5 L11.5 8.5 H14.5", None) +I["Optimise"] = ("M7 2 L8.2 5.8 L12 7 L8.2 8.2 L7 12 L5.8 8.2 L2 7 L5.8 5.8 Z M12.5 10.5 L13 12 L14.5 12.5 L13 13 L12.5 14.5 L12 13 L10.5 12.5 L12 12 Z", None) +I["Duplicate"] = I["Copy"] +I["Verify"] = ("M8 1.5 L13.5 3.5 V7.5 C13.5 11 11 13.3 8 14.5 C5 13.3 2.5 11 2.5 7.5 V3.5 Z M5.5 8 L7.3 9.8 L10.6 6.3", None) +I["Database"] = ("M2.5 3.8 C2.5 2.5 13.5 2.5 13.5 3.8 C13.5 5.1 2.5 5.1 2.5 3.8 Z M2.5 3.8 V12.2 C2.5 13.5 13.5 13.5 13.5 12.2 V3.8 M2.5 8 C2.5 9.3 13.5 9.3 13.5 8", None) +I["Gpu"] = (rr(3.5,3.5,9,9,1.5)+" "+rr(6,6,4,4,0.5)+" M6 1.5 V3.5 M10 1.5 V3.5 M6 12.5 V14.5 M10 12.5 V14.5 M1.5 6 H3.5 M1.5 10 H3.5 M12.5 6 H14.5 M12.5 10 H14.5", None) +I["Network"] = ("M2 6 A8.5 8.5 0 0 1 14 6 M4 8.5 A5.5 5.5 0 0 1 12 8.5 M6 11 A2.6 2.6 0 0 1 10 11", circ(8,13,1.1)) +I["Sort"] = ("M5 2.5 V13.5 M2.5 11 L5 13.5 L7.5 11 M11 13.5 V2.5 M8.5 5 L11 2.5 L13.5 5", None) +I["Filter"] = ("M1.5 2.5 H14.5 L9.5 8.5 V13.5 L6.5 12 V8.5 Z", None) +I["Info"] = I["About"] +I["Image"] = (rr(1.5,2.5,13,11,1.5)+" M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12", circ(10.8,5.6,1.2)) +I["Hero"] = (rr(1.5,2.5,13,11,1.5), "M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z") +I["Exclude"] = (circ(8,8,6.5)+" M3.4 12.6 L12.6 3.4", None) +I["Eye"] = ("M1.5 8 C3.5 4 12.5 4 14.5 8 C12.5 12 3.5 12 1.5 8 Z "+circ(8,8,2.2), None) +I["Wipe"] = I["Compare"] +I["Spline"] = ("M2 13 C5 13 5 3 8 8 C11 13 11 3 14 3", circ(2,13,1.2)+circ(14,3,1.2)) +I["Keyframe"] = ("M8 2 L13 8 L8 14 L3 8 Z", None) +I["Tray"] = ("M1.5 9.5 H5 L6.5 11.5 H9.5 L11 9.5 H14.5 M1.5 9.5 L3.5 3 H12.5 L14.5 9.5 V13.5 H1.5 Z", None) +I["Window"] = (rr(1.5,2.5,13,11,1.5)+" M1.5 5.5 H14.5", None) +I["Clipboard"] = (rr(2.5,2.5,11,12,1.5)+" "+rr(5.5,1.5,5,2.5,0.8), None) +I["Cancel"] = I["ErrorCircle"] +I["Retry"] = I["Refresh"] +I["Grip"] = (None, circ(6,4,1)+circ(10,4,1)+circ(6,8,1)+circ(10,8,1)+circ(6,12,1)+circ(10,12,1)) +I["Dot"] = (None, circ(8,8,3.5)) +I["Ring"] = (circ(8,8,3.5), None) +I["HalfDot"] = (circ(8,8,3.5), "M8 4.5 A3.5 3.5 0 0 1 8 11.5 Z") +I["Triangle"] = (None, "M8 3 L13.5 12.5 H2.5 Z") +I["TriangleRight"] = (None, "M5 3 L12 8 L5 13 Z") +I["Cross"] = ("M4.5 4.5 L11.5 11.5 M11.5 4.5 L4.5 11.5", None) + +out = os.path.join(os.path.dirname(__file__), "..", "..", "src", "Titano.Ui", "Icons", "Icons.xaml") +with open(out, "w") as f: + f.write('\n') + f.write(' \n') + for name, (stroke, fill) in sorted(I.items()): + attrs = '' + if stroke: attrs += f' Stroke="{stroke}"' + if fill: attrs += f' Fill="{fill}"' + f.write(f' \n') + f.write('\n') + +cols = 10 +names = sorted(I) +rows = (len(names) + cols - 1) // cols +svg = [f''] +for k, name in enumerate(names): + x, y = (k % cols) * 90 + 37, (k // cols) * 70 + 14 + stroke, fill = I[name] + svg.append(f'') + if fill: svg.append(f'') + if stroke: svg.append(f'') + svg.append('') + svg.append(f'{name}') +svg.append('') +open(os.path.join(os.path.dirname(__file__), "icons.svg"), "w").write("\n".join(svg)) +print(len(I), "icons") diff --git a/branding/ui-icons/icons.svg b/branding/ui-icons/icons.svg new file mode 100644 index 00000000..a63e85c2 --- /dev/null +++ b/branding/ui-icons/icons.svg @@ -0,0 +1,417 @@ + + + + +About + + + +ActualSize + + + +Analyse + + + +Archive + + + +Back + + + +Calendar + + + +Camera + + + +Cancel + + + +Card + + + +Chart + + + +Check + + + +ChevronDown + + + +ChevronLeft + + + +ChevronRight + + + +ChevronUp + + + +Clipboard + + + +Clock + + + +Close + + + +Compare + + + +Copy + + + +CropMask + + + +Cross + + + +Database + + + +Delete + + + +Dot + + + +Download + + + +Drive + + + +Duplicate + + + + +Eject + + + +ErrorCircle + + + +Exclude + + + +Export + + + +Exposure + + + +ExternalLink + + + +Eye + + + +Filmstrip + + + +Filter + + + +Folder + + + +FolderOpen + + + +Forward + + + +Fullscreen + + + +Gpu + + + +Grip + + + + +HalfDot + + + + +Hero + + + + +Image + + + +Import + + + +Info + + + +Jobs + + + +Key + + + +Keyframe + + + +Layers + + + +Library + + + +Link + + + +Lock + + + +Logs + + + +Menu + + + +Minus + + + +Moon + + + +More + + + +Motion + + + + +Network + + + +Optimise + + + +Pause + + + +Play + + + +Plus + + + +Power + + + +Refresh + + + +Regions + + + + +Render + + + +Reset + + + +Retry + + + +Ring + + + +Search + + + +Sequence + + + +Server + + + +Settings + + + +Sort + + + + +Spline + + + +Stack + + + +Star + + + +StarFilled + + + +Stop + + + +SuccessCircle + + + +Sun + + + +Sync + + + +Tag + + + +Time + + + +Tray + + + +Triangle + + + +TriangleRight + + + +Upload + + + +User + + + +Users + + + +Vectors + + + +Verify + + + +ViewGrid + + + +ViewList + + + +ViewTimeline + + + +Warning + + + +Window + + + +Wipe + \ No newline at end of file diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example new file mode 100644 index 00000000..f7e438eb --- /dev/null +++ b/deploy/docker/.env.example @@ -0,0 +1,8 @@ +TITANO_ADMIN_PASSWORD=change-me-at-first-login +TITANO_DB_PASSWORD=choose-a-long-random-password +TITANO_ARCHIVE=/mnt/user/Timelapse +TITANO_DATA=./data +TITANO_PGDATA=./pgdata +PUID=1000 +PGID=1000 +TZ=Europe/Rome diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 00000000..f3bd6889 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -0,0 +1,43 @@ +# syntax=docker/dockerfile:1 +# Titano Server — multi-stage, multi-arch (linux/amd64, linux/arm64). BRIEF §14.9. + +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG TARGETARCH +ARG TITANO_VERSION=0.0.0-dev +WORKDIR /src +COPY global.json Directory.Build.props Directory.Build.targets Titano.slnx ./ +COPY i18n/ i18n/ +COPY src/Titano.Core/ src/Titano.Core/ +COPY src/Titano.Data/ src/Titano.Data/ +COPY src/Titano.Protocol/ src/Titano.Protocol/ +COPY src/Titano.Server/ src/Titano.Server/ +RUN dotnet publish src/Titano.Server/Titano.Server.csproj \ + -c Release -a "$TARGETARCH" --no-self-contained \ + -p:TitanoVersion="$TITANO_VERSION" -o /out \ + && rm -f /out/*.pdb + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 +ARG TITANO_VERSION=0.0.0-dev +LABEL org.opencontainers.image.title="Titano Server" \ + org.opencontainers.image.description="Time-lapse archive, uploads, jobs and rendering server" \ + org.opencontainers.image.version="$TITANO_VERSION" \ + org.opencontainers.image.licenses="LicenseRef-Titano-EULA" +ENV TITANO_ARCHIVE_PATH=/archive \ + TITANO_DATA_PATH=/data \ + TITANO_HTTP_PORT=8080 \ + TITANO_HTTPS_PORT=8443 \ + TITANO_DB=postgres \ + PUID=1000 \ + PGID=1000 \ + DOTNET_gcServer=1 \ + DOTNET_GCHeapAffinitizeMask= \ + DOTNET_NOLOGO=1 +WORKDIR /app +COPY --from=build /out/ ./ +COPY deploy/docker/entrypoint.sh /usr/local/bin/titano-entrypoint +RUN chmod 0755 /usr/local/bin/titano-entrypoint && mkdir -p /archive /data +VOLUME ["/archive", "/data"] +EXPOSE 8080 8443 +HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \ + CMD ["dotnet", "/app/Titano.Server.dll", "--healthcheck"] +ENTRYPOINT ["/usr/local/bin/titano-entrypoint"] diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml new file mode 100644 index 00000000..9cc7dd66 --- /dev/null +++ b/deploy/docker/docker-compose.yml @@ -0,0 +1,44 @@ +# Titano Server with PostgreSQL 17. Start: docker compose up -d Admin panel: http://:8080/admin +name: titano + +services: + titano: + image: ghcr.io/alby96/titano-server:latest + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + ports: + - "8080:8080" + - "8443:8443" + environment: + TITANO_ADMIN_USER: admin + TITANO_ADMIN_PASSWORD: ${TITANO_ADMIN_PASSWORD:?set TITANO_ADMIN_PASSWORD in .env} + TITANO_DB: postgres + TITANO_DB_HOST: postgres + TITANO_DB_NAME: titano + TITANO_DB_USER: titano + TITANO_DB_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env} + TITANO_TLS_MODE: auto + TITANO_SERVER_NAME: Titano Server + PUID: ${PUID:-1000} + PGID: ${PGID:-1000} + TZ: ${TZ:-UTC} + volumes: + - ${TITANO_ARCHIVE:-./archive}:/archive + - ${TITANO_DATA:-./data}:/data + + postgres: + image: postgres:17 + restart: unless-stopped + environment: + POSTGRES_DB: titano + POSTGRES_USER: titano + POSTGRES_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env} + volumes: + - ${TITANO_PGDATA:-./pgdata}:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U titano -d titano"] + interval: 10s + timeout: 5s + retries: 10 diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh new file mode 100755 index 00000000..9ea31992 --- /dev/null +++ b/deploy/docker/entrypoint.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Runs Titano Server as PUID:PGID (Unraid/NAS convention). /data is owned by that user; /archive is left as +# mounted (it may hold terabytes) and only checked for write access. +set -eu + +PUID="${PUID:-1000}" +PGID="${PGID:-1000}" +umask 002 + +if [ "$(id -u)" = "0" ]; then + mkdir -p /data + chown -R "$PUID:$PGID" /data + if ! setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- test -w "${TITANO_ARCHIVE_PATH:-/archive}"; then + echo "warning: ${TITANO_ARCHIVE_PATH:-/archive} is not writable by $PUID:$PGID" >&2 + fi + exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Titano.Server.dll "$@" +fi + +exec dotnet /app/Titano.Server.dll "$@" diff --git a/deploy/unraid/titano.xml b/deploy/unraid/titano.xml new file mode 100644 index 00000000..08649b6a --- /dev/null +++ b/deploy/unraid/titano.xml @@ -0,0 +1,41 @@ + + + titano-server + ghcr.io/alby96/titano-server:latest + https://github.com/alby96/titano-releases + bridge + + sh + false + https://github.com/alby96/titano-releases/issues + https://github.com/alby96/titano-releases + Titano Server keeps a shared, verified archive of time-lapse photo sequences and renders them. Pair it with the official PostgreSQL 17 container. + MediaServer:Photos Tools: + http://[IP]:[PORT:8080]/admin + https://raw.githubusercontent.com/alby96/titano-releases/main/unraid/titano.xml + https://raw.githubusercontent.com/alby96/titano-releases/main/unraid/titano-server.png + --restart unless-stopped + + + + + + A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Titano. + 8080 + 8443 + /mnt/user/Timelapse + /mnt/user/appdata/titano + admin + + postgresql17 + 5432 + titano + titano + + prefer + auto + Titano Server + 99 + 100 + Europe/Rome + diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 88a030af..ab7f9c76 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,7 +6,12 @@ All notable changes. Format: Keep a Changelog; versions follow SemVer; commits f ### Added - Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin. -- `Titano.Testing`: in-house test framework and runner with JUnit XML output. -- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages) and `i18n check/export`. -- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon`. -- Core contracts: image buffers and decoder providers, video encoder providers, domain model, atomic file writes. +- `Titano.Testing`: in-house test framework and runner with JUnit XML output and GitHub annotations. +- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages), `en` + `it` catalogs, `i18n check/export`. +- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon` (program icons generated at build time). +- Core contracts: image buffers and decoder providers, video encoder providers, domain model, TIFF/IFD reader, sRGB helpers, atomic file writes, logging. +- `Titano.Ui` design system: DESIGN.md tokens (dark/light), 100+ stroke icons, styles for every standard control, custom chrome window with snap layouts, navigation rail, job bar, Auto/manual slider, chips, status glyphs, toasts, empty states. +- Titano desktop shell: rail, job bar, status strip, sections, Settings (language, theme) and About; `--capture` screenshot mode. +- Titano Server skeleton: configuration from environment/`server.json`, self-signed TLS with fingerprint, `/health`, `/api/v1/server/info`, `/api/v1/i18n/{culture}`, embedded admin panel (login, dashboard). +- Docker image (multi-arch, PUID/PGID, health check), compose file with PostgreSQL 17, Unraid template. +- CI (Windows + Linux build/test, PostgreSQL 16/17, Docker smoke test, screenshots, Windows program artifacts), release and nightly image workflows. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 4b79c26f..b1074064 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -14,3 +14,13 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | In-house CRC-32 (`Titano.Core.Hashing.Crc32`). | System.IO.Hashing | That assembly is a NuGet package, not part of the shared framework. | | 2026-10-02 | Windows projects target `net10.0-windows` (platform version 7.0) without a Windows SDK projection TFM; Windows 10 APIs are reached by P/Invoke/COM. | `net10.0-windows10.0.19041.0` | Avoids the CsWinRT projection; toasts use the in-window toast host plus tray balloon. | | 2026-10-02 | Test projects use an explicit `TestMain` entry point. | Top-level statements | Avoids the `Program` type clash with the server's top-level program. | +| 2026-10-02 | SQLite P/Invoke binding lives in `Titano.Data` with a library resolver (winsqlite3 on Windows, system libsqlite3 elsewhere for tests/dev); the Linux server still refuses SQLite at configuration time. | Binding in Core.Windows only | Lets repository tests run on Linux CI against both dialects. | +| 2026-10-02 | Client preferences needed before the database opens (language, theme, window placement) are stored in `settings.json` next to the database. | Settings table only | Language and theme must apply before the first window appears. | +| 2026-10-02 | Server Windows-service hosting will use an in-house advapi32 P/Invoke host. | Microsoft.Extensions.Hosting.WindowsServices | That assembly is a NuGet package, not part of the shared framework. | +| 2026-10-02 | Admin panel files are embedded resources served by an in-house middleware with ETags and SPA fallback. | ManifestEmbeddedFileProvider | Its manifest generator ships in a NuGet package. | +| 2026-10-02 | Container health check runs `Titano.Server --healthcheck` (in-process HTTP probe). | curl/wget in the image | Keeps the runtime image free of extra tools. | +| 2026-10-02 | Container drops privileges with `setpriv` to PUID:PGID; `/data` is chowned, `/archive` only checked for write access. | Recursive chown of the archive | The archive may hold terabytes on NAS shares. | +| 2026-10-02 | Release workflow publishes to `RELEASES_REPO` (default `/titano-releases`) when the `RELEASES_TOKEN` secret exists, otherwise to this repository. | Fail without the token | First releases work before the public repository is set up. | +| 2026-10-02 | Release notes are generated by `Titano.Tools changelog` from `git log` piped on stdin. | Tool spawning git | Keeps the tool free of external process calls. | +| 2026-10-02 | CI `dotnet format` gate checks whitespace formatting. | Full style/analyzer verification | Analyzer rules already fail the build (warnings as errors); style preferences stay suggestions. | +| 2026-10-02 | Test runner exits 0 for a project with no tests and 2 when a filter matches nothing. | Always 2 | Empty projects during bootstrap are not failures; mistyped filters are. | diff --git a/docs/STATUS.md b/docs/STATUS.md index 992f99a0..32885bdd 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,17 @@ # Status -Current phase: **Phase 0 — Bootstrap** (in progress). +Current phase: **Phase 0 — Bootstrap** complete on Linux; Windows verification runs in CI. +Engine workstreams for Phases 1–2 and 5–6 (metadata, codecs, data, video, analysis, motion, Windows interop) are in progress. + +## How to try it + +``` +dotnet build Titano.slnx -c Release +dotnet run --project src/Titano.Server # http://localhost:8080/admin (set TITANO_DATA_PATH/TITANO_ARCHIVE_PATH) +src/Titano.App/bin/Release/net10.0-windows/Titano.exe # Windows +docker compose -f deploy/docker/docker-compose.yml up -d # server + PostgreSQL 17 +``` + +## Next steps See docs/BRIEF.md §22 for the phase plan. diff --git a/i18n/en/About.resx b/i18n/en/About.resx new file mode 100644 index 00000000..a9d2a50d --- /dev/null +++ b/i18n/en/About.resx @@ -0,0 +1,14 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Data + Data folder + Releases + Runtime + System + Third-party code + None + diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx new file mode 100644 index 00000000..d63f15e8 --- /dev/null +++ b/i18n/en/Admin.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + TLS SHA-256 + Titano Server + API version + Archive + Server + The server did not answer; try again.long + Wrong user name or password.long + Password + Sign in + Sign in to administer this server + User + About + Version and certificate fingerprint + Archive + Archive path, templates, scan and verify + Dashboard + Storage, jobs and render nodes at a glance + Jobs + Queue, history and render nodes + Logs + Recent log lines and downloads + Settings + Server name, ports, TLS, limits and language + Users + Accounts, roles and quotas + Administrator + Editor + Uploader + Viewer + Sign out of the admin panel + diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx new file mode 100644 index 00000000..20ad648e --- /dev/null +++ b/i18n/en/Archive.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No archive yet + diff --git a/i18n/en/Common.resx b/i18n/en/Common.resx new file mode 100644 index 00000000..5b7c5adf --- /dev/null +++ b/i18n/en/Common.resx @@ -0,0 +1,15 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Auto + {0} d {1} h + {0} h {1} m + {0} min + {0} s + n/a + Open + Open logs + diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx new file mode 100644 index 00000000..2de00b56 --- /dev/null +++ b/i18n/en/Editor.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Pick a sequence in the Library + diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx new file mode 100644 index 00000000..702ea76f --- /dev/null +++ b/i18n/en/Errors.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Something went wrong. + diff --git a/i18n/en/Import.resx b/i18n/en/Import.resx new file mode 100644 index 00000000..1dd4adb7 --- /dev/null +++ b/i18n/en/Import.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Insert a card or pick a folder + diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx new file mode 100644 index 00000000..9be7175a --- /dev/null +++ b/i18n/en/Jobs.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No jobs yet + diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx new file mode 100644 index 00000000..7db63837 --- /dev/null +++ b/i18n/en/Library.resx @@ -0,0 +1,11 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No sequences yet + Connect to a server + Import a card + Open an archive + diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx new file mode 100644 index 00000000..b9ba718d --- /dev/null +++ b/i18n/en/Server.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Not connected to a server + diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx new file mode 100644 index 00000000..bd1f5673 --- /dev/null +++ b/i18n/en/Settings.resx @@ -0,0 +1,25 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Data folder + Check on start + Language + Theme + Dark + Light + System + Updates + Advanced + Analysis + Archive + Formats + General + Import + Licence + Rendering + Server + Updates + diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index dd4fb457..80a2fb84 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -4,7 +4,22 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Titano - {0:N0} photo - {0:N0} photos + Titanoinvariant + Ready · {0} jobs queued + About + Archive + Import + Jobs + Library + Sequence + Server + Settings + Connected to "{0}" + {0:N0} job + {0:N0} jobs + Not connected + {0:N0} photo + {0:N0} photos + {0:N0} sequence + {0:N0} sequences diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx new file mode 100644 index 00000000..b6393fa1 --- /dev/null +++ b/i18n/en/Tooltips.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Open the folder with database, settings and logs + Open the public releases page in the browser + Dismiss + Open the folder with the log files + Return to the advisor's value + Work with the archive of a Titano Server + Copy and verify photos from a memory card + Use an existing archive folder on this PC or the network + Version, diagnostics and links + Scan, verify and maintain the archive · Ctrl+4 + Import photos from a card or folder · Ctrl+2 + Queue and history of long operations · Ctrl+5 + Browse every sequence of the archive · Ctrl+1 + Edit and render the open sequence · Ctrl+3 + Connection, sync and render node · Ctrl+6 + Preferences of this PC · Ctrl+, + Look for a new release when Titano starts · no data is sent + Database, settings, logs and caches of this PC + Language of the interface · applies immediately + Open the data folder in Explorer + Dark interface (default) + Light interface + Follow the Windows app mode + Collapse navigation to icons + Show navigation names + Stop the current job · it can be resumed later + Close + Maximize + Minimize + Restore + diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx new file mode 100644 index 00000000..3f3261ff --- /dev/null +++ b/i18n/it/About.it.resx @@ -0,0 +1,14 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Dati + Cartella dati + Versioni + Runtime + Sistema + Codice di terzi + Nessuno + diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx new file mode 100644 index 00000000..4e1f7a66 --- /dev/null +++ b/i18n/it/Admin.it.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + TLS SHA-256 + Titano Server + Versione API + Archivio + Server + Il server non ha risposto; riprova. + Nome utente o password errati. + Password + Accedi + Accedi per amministrare questo server + Utente + Informazioni + Versione e impronta del certificato + Archivio + Percorso archivio, modelli, scansione e verifica + Panoramica + Spazio, attività e nodi di rendering in sintesi + Attività + Coda, cronologia e nodi di rendering + Log + Ultime righe di log e download + Impostazioni + Nome server, porte, TLS, limiti e lingua + Utenti + Account, ruoli e quote + Amministratore + Editor + Caricamento + Lettore + Esci dal pannello di amministrazione + diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx new file mode 100644 index 00000000..00b325d1 --- /dev/null +++ b/i18n/it/Archive.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessun archivio + diff --git a/i18n/it/Common.it.resx b/i18n/it/Common.it.resx new file mode 100644 index 00000000..24f3494c --- /dev/null +++ b/i18n/it/Common.it.resx @@ -0,0 +1,15 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Auto + {0} g {1} h + {0} h {1} m + {0} min + {0} s + n/d + Apri + Apri log + diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx new file mode 100644 index 00000000..a0b523f2 --- /dev/null +++ b/i18n/it/Editor.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Scegli una sequenza in Libreria + diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx new file mode 100644 index 00000000..cc83b7f7 --- /dev/null +++ b/i18n/it/Errors.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Si è verificato un problema. + diff --git a/i18n/it/Import.it.resx b/i18n/it/Import.it.resx new file mode 100644 index 00000000..1d75e138 --- /dev/null +++ b/i18n/it/Import.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Inserisci una scheda o una cartella + diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx new file mode 100644 index 00000000..2495adbd --- /dev/null +++ b/i18n/it/Jobs.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessuna attività + diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx new file mode 100644 index 00000000..11ad6451 --- /dev/null +++ b/i18n/it/Library.it.resx @@ -0,0 +1,11 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessuna sequenza + Connetti a un server + Importa una scheda + Apri un archivio + diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx new file mode 100644 index 00000000..d80ac2f7 --- /dev/null +++ b/i18n/it/Server.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Non connesso a un server + diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx new file mode 100644 index 00000000..bcfe6714 --- /dev/null +++ b/i18n/it/Settings.it.resx @@ -0,0 +1,25 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cartella dati + Controlla all'avvio + Lingua + Tema + Scuro + Chiaro + Sistema + Aggiornamenti + Avanzate + Analisi + Archivio + Formati + Generale + Importazione + Licenza + Rendering + Server + Aggiornamenti + diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 7d948680..471272fb 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -4,6 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - {0:N0} foto - {0:N0} foto + Pronto · {0} attività in coda + Informazioni + Archivio + Importa + Attività + Libreria + Sequenza + Server + Impostazioni + Connesso a «{0}» + {0:N0} attività + {0:N0} attività + Non connesso + {0:N0} foto + {0:N0} foto + {0:N0} sequenza + {0:N0} sequenze diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx new file mode 100644 index 00000000..6892a5f4 --- /dev/null +++ b/i18n/it/Tooltips.it.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Apri la cartella con database, impostazioni e log + Apri la pagina pubblica delle versioni nel browser + Chiudi + Apri la cartella dei file di log + Torna al valore consigliato + Lavora con l'archivio di un Titano Server + Copia e verifica le foto da una scheda di memoria + Usa una cartella archivio esistente su questo PC o in rete + Versione, diagnostica e collegamenti + Scansiona, verifica e gestisci l'archivio · Ctrl+4 + Importa foto da una scheda o una cartella · Ctrl+2 + Coda e cronologia delle operazioni lunghe · Ctrl+5 + Sfoglia tutte le sequenze dell'archivio · Ctrl+1 + Modifica e renderizza la sequenza aperta · Ctrl+3 + Connessione, sincronizzazione e nodo di rendering · Ctrl+6 + Preferenze di questo PC · Ctrl+, + Cerca una nuova versione all'avvio di Titano · nessun dato viene inviato + Database, impostazioni, log e cache di questo PC + Lingua dell'interfaccia · si applica subito + Apri la cartella dati in Esplora file + Interfaccia scura (predefinita) + Interfaccia chiara + Segui la modalità app di Windows + Riduci la navigazione alle icone + Mostra i nomi della navigazione + Ferma l'attività in corso · potrai riprenderla + Chiudi + Ingrandisci + Riduci a icona + Ripristina + diff --git a/src/Titano.App/App.xaml b/src/Titano.App/App.xaml index fa7e5103..c70dfc76 100644 --- a/src/Titano.App/App.xaml +++ b/src/Titano.App/App.xaml @@ -1,4 +1,12 @@ + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + ShutdownMode="OnMainWindowClose"> + + + + + + + diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 83019998..d3122b31 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -1,7 +1,97 @@ +using System.Globalization; using System.Windows; +using System.Windows.Threading; +using Titano.App.Infrastructure; +using Titano.App.Shell; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Ui.Mvvm; +using Titano.Ui.Theming; namespace Titano.App; public partial class App : Application { + private FileLogSink? _log; + + public AppEnvironment Environment { get; private set; } = null!; + public AppSettings Settings { get; private set; } = null!; + + public static new App Current => (App)Application.Current; + + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + Environment = AppEnvironment.Detect(); + _log = new FileLogSink(Environment.LogDirectory, "titano"); + Log.SetSink(_log); + Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}"); + + Settings = AppSettings.Load(Environment.SettingsPath); + ApplyLanguage(Settings.Language); + ThemeManager.Initialize(this, Settings.Theme); + + DispatcherUnhandledException += OnUnhandledException; + AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception); + TaskScheduler.UnobservedTaskException += (_, args) => + { + Log.Error("app", "Unobserved task exception", args.Exception); + args.SetObserved(); + }; + + var shell = new ShellViewModel(Settings); + AsyncRelayCommand.Failed += ex => shell.ReportError(ex); + var window = new MainWindow(shell); + MainWindow = window; + + var captureIndex = Array.IndexOf(e.Args, "--capture"); + if (captureIndex >= 0) + { + var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots"; + ScreenCapture.Run(window, shell, dir); + return; + } + window.Show(); + } + + /// Switches the UI language at run time (BRIEF §16) and remembers the choice. + public void ApplyLanguage(string? code) + { + var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code)); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + foreach (Window w in Windows) + w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + } + + public void SaveSettings() + { + try + { + Settings.Save(Environment.SettingsPath); + } + catch (System.IO.IOException ex) + { + Log.Warning("app", "Settings not saved", ex); + } + } + + protected override void OnExit(ExitEventArgs e) + { + SaveSettings(); + Log.Info("app", "Titano exiting"); + _log?.Dispose(); + base.OnExit(e); + } + + private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + Log.Error("app", "Unhandled UI exception", e.Exception); + if (MainWindow?.DataContext is ShellViewModel shell) + { + shell.ReportError(e.Exception); + e.Handled = true; + } + } } diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs new file mode 100644 index 00000000..5b0d9db2 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -0,0 +1,35 @@ +using System.IO; + +namespace Titano.App.Infrastructure; + +/// +/// Where the client keeps its data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the +/// executable when portable.txt exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders). +/// +public sealed class AppEnvironment +{ + private AppEnvironment(string dataDirectory, bool portable) + { + DataDirectory = dataDirectory; + IsPortable = portable; + Directory.CreateDirectory(DataDirectory); + Directory.CreateDirectory(LogDirectory); + Directory.CreateDirectory(CacheDirectory); + } + + public string DataDirectory { get; } + public bool IsPortable { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); + public string CacheDirectory => Path.Combine(DataDirectory, "cache"); + public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); + public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); + + public static AppEnvironment Detect() + { + var exeDir = AppContext.BaseDirectory; + if (File.Exists(Path.Combine(exeDir, "portable.txt"))) + return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true); + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return new AppEnvironment(Path.Combine(local, "Titano"), portable: false); + } +} diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs new file mode 100644 index 00000000..9022de83 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppSettings.cs @@ -0,0 +1,51 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.IO; +using Titano.Ui.Theming; + +namespace Titano.App.Infrastructure; + +/// Per-user preferences needed before the database opens (language, theme, window layout). +public sealed class AppSettings +{ + public string? Language { get; set; } + public AppTheme Theme { get; set; } = AppTheme.Dark; + public bool RailCollapsed { get; set; } + public bool CheckForUpdates { get; set; } = true; + public bool AnonymousUsageCounts { get; set; } + public string? LastArchivePath { get; set; } + public WindowPlacement? Window { get; set; } + + public sealed class WindowPlacement + { + public double Left { get; set; } + public double Top { get; set; } + public double Width { get; set; } + public double Height { get; set; } + public bool Maximized { get; set; } + } + + public static AppSettings Load(string path) + { + try + { + if (File.Exists(path)) + return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings(); + } + catch (JsonException) + { + // A corrupt settings file must never block startup; defaults apply. + } + catch (IOException) + { + } + return new AppSettings(); + } + + public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings)); +} + +[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)] +[JsonSerializable(typeof(AppSettings))] +internal sealed partial class AppSettingsJson : JsonSerializerContext; diff --git a/src/Titano.App/Infrastructure/Formatting.cs b/src/Titano.App/Infrastructure/Formatting.cs new file mode 100644 index 00000000..5a3c2ab8 --- /dev/null +++ b/src/Titano.App/Infrastructure/Formatting.cs @@ -0,0 +1,34 @@ +using Titano.Core.Localization; + +namespace Titano.App.Infrastructure; + +/// Culture-aware number, size and duration formatting for the UI. +public static class Formatting +{ + private static readonly string[] ByteUnits = ["B", "KB", "MB", "GB", "TB", "PB"]; + + /// 1,536 → "1.5 KB" (decimal units, as Explorer shows for drives). + public static string Bytes(long bytes) + { + double value = bytes; + var unit = 0; + while (value >= 1000 && unit < ByteUnits.Length - 1) + { + value /= 1000; + unit++; + } + var format = unit == 0 || value >= 100 ? "0" : "0.#"; + return value.ToString(format, Loc.Culture) + " " + ByteUnits[unit]; + } + + public static string Count(long n) => n.ToString("N0", Loc.Culture); + + /// Compact duration: "2 h 00 m", "5 min", "40 s". + public static string Duration(TimeSpan t) + { + if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours); + if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture)); + if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes)); + return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds)); + } +} diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs new file mode 100644 index 00000000..abdef10a --- /dev/null +++ b/src/Titano.App/Infrastructure/ProductLinks.cs @@ -0,0 +1,14 @@ +namespace Titano.App.Infrastructure; + +/// Public links (BRIEF §19.4). Overridable at build time via the TitanoReleasesRepo property. +public static class ProductLinks +{ + public static string ReleasesRepository { get; } = + typeof(ProductLinks).Assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyMetadataAttribute), false) + .OfType() + .FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases"; + + public static string Releases => $"https://github.com/{ReleasesRepository}/releases"; + + public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest"; +} diff --git a/src/Titano.App/Infrastructure/ShellActions.cs b/src/Titano.App/Infrastructure/ShellActions.cs new file mode 100644 index 00000000..ba546bb5 --- /dev/null +++ b/src/Titano.App/Infrastructure/ShellActions.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.IO; + +namespace Titano.App.Infrastructure; + +/// The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder. +public static class ShellActions +{ + public static void OpenUrl(string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return; + Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + } + + public static void OpenFolder(string path) + { + if (!Directory.Exists(path)) return; + Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" }); + } +} diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml new file mode 100644 index 00000000..adaa0d17 --- /dev/null +++ b/src/Titano.App/Sections/AboutView.xaml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `; + applyStrings(app); + const form = app.querySelector("form"); + const error = form.querySelector(".error"); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + error.textContent = ""; + const data = new FormData(form); + try { + await api.signIn(String(data.get("username")), String(data.get("password"))); + render(); + } catch (err) { + error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable"); + } + }); + form.querySelector("input").focus(); +} + +function renderShell(page) { + const nav = pages.map((p) => ` + ${icons[pageIcon[p]]}`).join(""); + const user = api.user(); + app.innerHTML = ` +
+ +
+

+
+
+
`; + applyStrings(app); + app.querySelector("#signout").addEventListener("click", async () => { + await api.signOut(); + render(); + }); + const content = app.querySelector("#content"); + import(`./pages/${page}.js`) + .then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") })) + .catch(() => { + content.innerHTML = `
`; + applyStrings(content); + }); +} + +export function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} + +start(); diff --git a/src/Titano.Server/Admin/web/favicon.svg b/src/Titano.Server/Admin/web/favicon.svg new file mode 100644 index 00000000..7cd565b2 --- /dev/null +++ b/src/Titano.Server/Admin/web/favicon.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Titano.Server/Admin/web/i18n.js b/src/Titano.Server/Admin/web/i18n.js new file mode 100644 index 00000000..3b50350c --- /dev/null +++ b/src/Titano.Server/Admin/web/i18n.js @@ -0,0 +1,27 @@ +// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps. +let strings = {}; + +export async function loadStrings(culture) { + try { + const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`); + strings = await res.json(); + } catch { + strings = {}; + } + document.documentElement.lang = strings.$culture || "en"; + document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr"; +} + +/** Localized string for key with {0}, {1}… placeholders filled from args. */ +export function t(key, ...args) { + const s = strings[key]; + if (s === undefined) return `⟦${key}⟧`; + return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? "")); +} + +/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */ +export function applyStrings(root) { + root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); }); + root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); }); + root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); }); +} diff --git a/src/Titano.Server/Admin/web/icons.js b/src/Titano.Server/Admin/web/icons.js new file mode 100644 index 00000000..1ea443a0 --- /dev/null +++ b/src/Titano.Server/Admin/web/icons.js @@ -0,0 +1,16 @@ +// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps). +export const icons = { + dashboard: ``, + users: ``, + archive: ``, + jobs: ``, + settings: ``, + logs: ``, + about: ``, + power: ``, + moon: ``, + refresh: ``, + close: ``, + plus: ``, + search: ``, +}; diff --git a/src/Titano.Server/Admin/web/index.html b/src/Titano.Server/Admin/web/index.html index 7c26771a..12113418 100644 --- a/src/Titano.Server/Admin/web/index.html +++ b/src/Titano.Server/Admin/web/index.html @@ -1 +1,15 @@ -Titano + + + + + + + Titano Server + + + + + +
+ + diff --git a/src/Titano.Server/Admin/web/pages/about.js b/src/Titano.Server/Admin/web/pages/about.js new file mode 100644 index 00000000..1228e1fe --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/about.js @@ -0,0 +1,12 @@ +import { applyStrings } from "../i18n.js"; +import { escapeHtml } from "../app.js"; + +export async function render(root, { info }) { + root.innerHTML = ` +
+

+

Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}

+

${escapeHtml(info?.tlsFingerprint ?? "–")}

+
`; + applyStrings(root); +} diff --git a/src/Titano.Server/Admin/web/pages/dashboard.js b/src/Titano.Server/Admin/web/pages/dashboard.js new file mode 100644 index 00000000..4a4ab432 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/dashboard.js @@ -0,0 +1,18 @@ +// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only. +import { applyStrings } from "../i18n.js"; + +export async function render(root, { api, t, info, meta }) { + const health = await api.get("/health").catch(() => null); + meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : ""; + root.innerHTML = ` +
+
+
${health?.status === "ok" ? `●` : `✕`}${health?.status ?? ""}
+
${info?.name ?? ""}
+
+
${health?.checks?.archive === "ok" ? `●` : `▲`}${health?.checks?.archive ?? ""}
+
+
${info?.apiVersion ?? "–"}
${(info?.capabilities ?? []).join(" · ")}
+
`; + applyStrings(root); +} diff --git a/src/Titano.Server/Api/SystemEndpoints.cs b/src/Titano.Server/Api/SystemEndpoints.cs new file mode 100644 index 00000000..a7da0fe4 --- /dev/null +++ b/src/Titano.Server/Api/SystemEndpoints.cs @@ -0,0 +1,66 @@ +using System.Globalization; +using System.Reflection; +using Titano.Core.Localization; +using Titano.Protocol; +using Titano.Server.Configuration; + +namespace Titano.Server.Api; + +/// /health, /api/v1/server/info and /api/v1/i18n/{culture}. +public static class SystemEndpoints +{ + private static readonly string[] AdminAreas = ["Common", "Admin"]; + + public static string Version { get; } = + typeof(SystemEndpoints).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + public static void Map(WebApplication app, ServerOptions options, ServerState state) + { + app.MapGet("/health", () => + { + var checks = new Dictionary(StringComparer.Ordinal) + { + ["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing", + ["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing", + }; + return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus); + }); + + var api = app.MapGroup("/api/v1"); + api.MapGet("/server/info", () => Results.Json(new ServerInfo( + options.ServerName, + Version, + ApiVersion.Current, + state.Capabilities, + state.TlsFingerprint, + ["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"], + new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo)); + + api.MapGet("/i18n/{culture}", (string culture) => + { + CultureInfo ci; + try + { + ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture)); + } + catch (CultureNotFoundException) + { + ci = CultureInfo.GetCultureInfo("en"); + } + var strings = new Dictionary(StringComparer.Ordinal); + foreach (var area in AdminAreas) + foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v; + strings["$culture"] = ci.Name; + strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false"; + return Results.Json(strings, ProtocolJson.Default.DictionaryStringString); + }); + } +} + +/// Process-wide facts computed at startup. +public sealed class ServerState +{ + public string? TlsFingerprint { get; set; } + public List Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"]; + public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; +} diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs new file mode 100644 index 00000000..d1bcbfa8 --- /dev/null +++ b/src/Titano.Server/Configuration/ServerOptions.cs @@ -0,0 +1,130 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Titano.Server.Configuration; + +public enum TlsMode +{ + /// Self-signed certificate generated at first start (stored under /data/tls). + Auto, + + /// Certificate and key from PEM files. + Pem, + + /// Plain HTTP behind a TLS-terminating reverse proxy. + Proxy, +} + +public enum DatabaseKind +{ + Postgres, + Sqlite, +} + +/// +/// Server configuration (BRIEF §14.9): environment variables override /data/server.json, which overrides defaults. +/// +public sealed class ServerOptions +{ + public string ServerName { get; set; } = "Titano Server"; + public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive"; + public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data"; + public string? AdminUser { get; set; } + public string? AdminPassword { get; set; } + public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres; + public string DbHost { get; set; } = "postgres"; + public int DbPort { get; set; } = 5432; + public string DbName { get; set; } = "titano"; + public string DbUser { get; set; } = "titano"; + public string? DbPassword { get; set; } + public string DbSslMode { get; set; } = "prefer"; + public int HttpPort { get; set; } = 8080; + public int HttpsPort { get; set; } = 8443; + public TlsMode TlsMode { get; set; } = TlsMode.Auto; + public string? TlsCert { get; set; } + public string? TlsKey { get; set; } + public string Language { get; set; } = "en"; + public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2); + public bool Discovery { get; set; } = true; + public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024; + public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024; + public int JobHistoryDays { get; set; } = 90; + public int TokenLifetimeDays { get; set; } = 30; + + [JsonIgnore] + public string LogPath => Path.Combine(DataPath, "logs"); + + [JsonIgnore] + public string TlsPath => Path.Combine(DataPath, "tls"); + + [JsonIgnore] + public string UploadsPath => Path.Combine(DataPath, "uploads"); + + /// Loads {DataPath}/server.json (if present) then applies TITANO_* environment variables. + public static ServerOptions Load(IReadOnlyDictionary? environment = null) + { + var env = environment ?? ReadEnvironment(); + string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null; + + var dataPath = Env("TITANO_DATA_PATH") ?? new ServerOptions().DataPath; + var options = new ServerOptions(); + var file = Path.Combine(dataPath, "server.json"); + if (File.Exists(file)) + { + try + { + options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options; + } + catch (JsonException ex) + { + throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex); + } + } + options.DataPath = dataPath; + + options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName; + options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath; + options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser; + options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword; + if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse(db, ignoreCase: true); + options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost; + if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture); + options.DbName = Env("TITANO_DB_NAME") ?? options.DbName; + options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser; + options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword; + options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode; + if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture); + if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture); + if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse(tls, ignoreCase: true); + options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert; + options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey; + options.Language = Env("TITANO_LANG") ?? options.Language; + if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture)); + if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery); + options.Validate(); + return options; + } + + private static Dictionary ReadEnvironment() + { + // Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins. + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value; + return result; + } + + public void Validate() + { + if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite) + throw new InvalidOperationException("TITANO_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9)."); + if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey))) + throw new InvalidOperationException("TITANO_TLS_MODE=pem requires TITANO_TLS_CERT and TITANO_TLS_KEY."); + // Port 0 asks the OS for a free port (used by the in-process test host). + if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535) + throw new InvalidOperationException("Ports must be between 0 and 65535."); + } +} + +[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(ServerOptions))] +internal sealed partial class ServerOptionsJson : JsonSerializerContext; diff --git a/src/Titano.Server/Hosting/CertificateStore.cs b/src/Titano.Server/Hosting/CertificateStore.cs new file mode 100644 index 00000000..bfcf9c24 --- /dev/null +++ b/src/Titano.Server/Hosting/CertificateStore.cs @@ -0,0 +1,79 @@ +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls +/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy). +/// +public static class CertificateStore +{ + public static X509Certificate2? Load(ServerOptions options, ILogger logger) + { + switch (options.TlsMode) + { + case TlsMode.Proxy: + return null; + case TlsMode.Pem: + { + var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey); + return Exportable(pem); + } + default: + { + Directory.CreateDirectory(options.TlsPath); + var path = Path.Combine(options.TlsPath, "server.pfx"); + if (File.Exists(path)) + { + var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable); + if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing; + logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter); + } + var created = CreateSelfSigned(options.ServerName); + File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12)); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created)); + return created; + } + } + } + + /// SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use. + public static string Fingerprint(X509Certificate2 certificate) => + string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + + public static X509Certificate2 CreateSelfSigned(string serverName) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256); + var san = new SubjectAlternativeNameBuilder(); + san.AddDnsName("localhost"); + try + { + var host = Dns.GetHostName(); + san.AddDnsName(host); + foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6)) + san.AddIpAddress(address); + } + catch (SocketException) + { + // Without name resolution the certificate still covers localhost. + } + san.AddIpAddress(IPAddress.Loopback); + request.CertificateExtensions.Add(san.Build()); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false)); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5)); + return Exportable(certificate); + } + + private static X509Certificate2 Exportable(X509Certificate2 certificate) => + X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable); + + private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray()); +} diff --git a/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs b/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs new file mode 100644 index 00000000..638aa087 --- /dev/null +++ b/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs @@ -0,0 +1,70 @@ +using System.Collections.Frozen; +using System.Reflection; +using System.Security.Cryptography; + +namespace Titano.Server.Hosting; + +/// +/// Serves the admin panel from embedded resources named admin/… (no build step, single-file friendly), +/// with strong ETags, conditional GET and SPA fallback to index.html. +/// +public sealed class EmbeddedStaticFiles +{ + private static readonly FrozenDictionary ContentTypes = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [".html"] = "text/html; charset=utf-8", + [".js"] = "text/javascript; charset=utf-8", + [".mjs"] = "text/javascript; charset=utf-8", + [".css"] = "text/css; charset=utf-8", + [".svg"] = "image/svg+xml", + [".png"] = "image/png", + [".json"] = "application/json; charset=utf-8", + [".ico"] = "image/x-icon", + [".woff2"] = "font/woff2", + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + private readonly FrozenDictionary _files; + + public EmbeddedStaticFiles(Assembly assembly, string prefix) + { + var files = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal))) + { + using var stream = assembly.GetManifestResourceStream(name)!; + using var ms = new MemoryStream(); + stream.CopyTo(ms); + var bytes = ms.ToArray(); + var path = name[prefix.Length..].Replace('\\', '/'); + var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\""; + var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream"; + files[path] = (bytes, etag, type); + } + _files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + } + + public int Count => _files.Count; + + public async Task TryServeAsync(HttpContext context, string relativePath) + { + var path = relativePath.TrimStart('/'); + if (path.Length == 0) path = "index.html"; + if (!_files.TryGetValue(path, out var file)) + { + // Client-side routes (no extension) fall back to the shell. + if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false; + } + var response = context.Response; + response.Headers.ETag = file.ETag; + response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600"; + response.Headers.XContentTypeOptions = "nosniff"; + if (context.Request.Headers.IfNoneMatch == file.ETag) + { + response.StatusCode = StatusCodes.Status304NotModified; + return true; + } + response.ContentType = file.ContentType; + response.ContentLength = file.Content.Length; + if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted); + return true; + } +} diff --git a/src/Titano.Server/Hosting/FileLoggerProvider.cs b/src/Titano.Server/Hosting/FileLoggerProvider.cs new file mode 100644 index 00000000..7052813b --- /dev/null +++ b/src/Titano.Server/Hosting/FileLoggerProvider.cs @@ -0,0 +1,54 @@ +using Titano.Core.Diagnostics; +using CoreLogLevel = Titano.Core.Diagnostics.LogLevel; +using MsLogLevel = Microsoft.Extensions.Logging.LogLevel; + +namespace Titano.Server.Hosting; + +/// In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs). +public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider +{ + public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName); + + public void Dispose() => sink.Dispose(); + + private sealed class FileLogger(FileLogSink sink, string category) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information; + + public void Log(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) return; + var level = logLevel switch + { + MsLogLevel.Trace => CoreLogLevel.Trace, + MsLogLevel.Debug => CoreLogLevel.Debug, + MsLogLevel.Information => CoreLogLevel.Info, + MsLogLevel.Warning => CoreLogLevel.Warning, + _ => CoreLogLevel.Error, + }; + sink.Write(level, category, formatter(state, exception), exception); + } + } +} + +/// Bridges engine logging (Titano.Core.Diagnostics.Log) into ASP.NET Core logging. +public sealed class LoggerSink(ILoggerFactory factory) : ILogSink +{ + public void Write(CoreLogLevel level, string category, string message, Exception? exception) + { + var logger = factory.CreateLogger("Titano." + category); + var ms = level switch + { + CoreLogLevel.Trace => MsLogLevel.Trace, + CoreLogLevel.Debug => MsLogLevel.Debug, + CoreLogLevel.Info => MsLogLevel.Information, + CoreLogLevel.Warning => MsLogLevel.Warning, + _ => MsLogLevel.Error, + }; +#pragma warning disable CA2254 // Engine messages are preformatted. + logger.Log(ms, exception, message); +#pragma warning restore CA2254 + } +} diff --git a/src/Titano.Server/Hosting/HealthProbe.cs b/src/Titano.Server/Hosting/HealthProbe.cs new file mode 100644 index 00000000..336afbaf --- /dev/null +++ b/src/Titano.Server/Hosting/HealthProbe.cs @@ -0,0 +1,26 @@ +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// Titano.Server --healthcheck: probes the local /health endpoint and exits 0/1, so the container +/// HEALTHCHECK needs no curl/wget in the image. +/// +public static class HealthProbe +{ + public static async Task RunAsync() + { + try + { + var port = ServerOptions.Load().HttpPort; + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; + using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false); + return response.IsSuccessStatusCode ? 0 : 1; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException) + { + await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false); + return 1; + } + } +} diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs new file mode 100644 index 00000000..592a15d7 --- /dev/null +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -0,0 +1,98 @@ +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Titano.Core.Diagnostics; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// Builds the Titano Server web application from (used by Program and tests). +public static class ServerHost +{ + public static WebApplication Build(ServerOptions options, string[] args) + { + Directory.CreateDirectory(options.DataPath); + Directory.CreateDirectory(options.LogPath); + + var builder = WebApplication.CreateSlimBuilder(args); + builder.Logging.ClearProviders(); + builder.Logging.AddSimpleConsole(c => c.SingleLine = true); + builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server"))); + builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning); + builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information); + + using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true)); + var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server")); + var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) }; + + builder.WebHost.ConfigureKestrel(k => + { + k.AddServerHeader = false; + k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024; + k.ListenAnyIP(options.HttpPort); + if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => + { + l.Protocols = HttpProtocols.Http1AndHttp2; + l.UseHttps(certificate); + }); + }); + builder.Services.AddSingleton(options); + builder.Services.AddSingleton(state); + builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); + if (options.TlsMode == TlsMode.Proxy) + { + builder.Services.Configure(f => + { + f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; + f.KnownIPNetworks.Clear(); + f.KnownProxies.Clear(); + }); + } + + var app = builder.Build(); + Log.SetSink(new LoggerSink(app.Services.GetRequiredService())); + var logger = app.Logger; + logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}", + SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode, + state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint); + + if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders(); + + app.Use(async (context, next) => + { + context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture); + context.Response.Headers.XContentTypeOptions = "nosniff"; + context.Response.Headers["Referrer-Policy"] = "no-referrer"; + try + { + await next(context); + } + catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException) + { + logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError); + } + }); + + var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/"); + app.MapGet("/", () => Results.Redirect("/admin/")); + app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) => + { + // Relative asset URLs need the trailing slash. + if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path)) + { + context.Response.Redirect("/admin/"); + return; + } + if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound; + }); + + SystemEndpoints.Map(app, options, state); + + app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404)); + app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping")); + return app; + } +} diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs index 14d0787d..9bfebd2c 100644 --- a/src/Titano.Server/Program.cs +++ b/src/Titano.Server/Program.cs @@ -1,4 +1,11 @@ -var builder = WebApplication.CreateBuilder(args); -var app = builder.Build(); -app.MapGet("/health", () => Results.Ok(new { status = "ok" })); -app.Run(); +using Titano.Server.Configuration; +using Titano.Server.Hosting; + +if (args.Contains("--healthcheck")) return await HealthProbe.RunAsync(); + +var app = ServerHost.Build(ServerOptions.Load(), args); +await app.RunAsync(); +return 0; + +/// Entry point type, visible to the in-process test host. +public partial class Program; diff --git a/src/Titano.Tools/Commands/ChangelogCommand.cs b/src/Titano.Tools/Commands/ChangelogCommand.cs new file mode 100644 index 00000000..6e9731bc --- /dev/null +++ b/src/Titano.Tools/Commands/ChangelogCommand.cs @@ -0,0 +1,90 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace Titano.Tools.Commands; + +/// +/// Builds release notes from Conventional Commits. Reads git log --format=%h%x09%s lines from stdin +/// (or --in file) and writes Markdown grouped by type. +/// +internal sealed partial class ChangelogCommand : ICommand +{ + private static readonly (string Type, string Heading)[] Sections = + [ + ("feat", "Added"), + ("fix", "Fixed"), + ("perf", "Performance"), + ("security", "Security"), + ("i18n", "Localization"), + ("docs", "Documentation"), + ]; + + public string Name => "changelog"; + public string Summary => "Release notes from Conventional Commits on stdin (--title, --out file)"; + + public async Task RunAsync(string[] args) + { + var a = new Args(args); + IReadOnlyList input = a.Get("in") is { } file ? await File.ReadAllLinesAsync(file) : ReadStdin(); + var markdown = Render(input, a.Get("title")); + if (a.Get("out") is { } outFile) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outFile))!); + await File.WriteAllTextAsync(outFile, markdown, new UTF8Encoding(false)); + } + else + { + Console.Write(markdown); + } + return 0; + } + + internal static string Render(IEnumerable lines, string? title) + { + var groups = new Dictionary>(StringComparer.Ordinal); + var breaking = new List(); + foreach (var line in lines) + { + var tab = line.IndexOf('\t'); + var hash = tab > 0 ? line[..tab] : string.Empty; + var subject = tab > 0 ? line[(tab + 1)..] : line; + var m = Conventional().Match(subject); + if (!m.Success) continue; + var type = m.Groups["type"].Value.ToLowerInvariant(); + var scope = m.Groups["scope"].Success ? $"**{m.Groups["scope"].Value}**: " : string.Empty; + var entry = $"- {scope}{m.Groups["desc"].Value.Trim()}{(hash.Length > 0 ? $" ({hash})" : string.Empty)}"; + if (m.Groups["bang"].Success) breaking.Add(entry); + if (!groups.TryGetValue(type, out var list)) groups[type] = list = []; + list.Add(entry); + } + + var sb = new StringBuilder(); + if (title is not null) sb.Append("# ").AppendLine(title).AppendLine(); + if (breaking.Count > 0) + { + sb.AppendLine("### Breaking changes"); + foreach (var e in breaking) sb.AppendLine(e); + sb.AppendLine(); + } + foreach (var (type, heading) in Sections) + { + if (!groups.TryGetValue(type, out var entries)) continue; + sb.Append("### ").AppendLine(heading); + foreach (var e in entries) sb.AppendLine(e); + sb.AppendLine(); + } + if (sb.Length == 0) sb.AppendLine("Maintenance release."); + return sb.ToString(); + } + + private static List ReadStdin() + { + var lines = new List(); + if (!Console.IsInputRedirected) return lines; + while (Console.In.ReadLine() is { } line) lines.Add(line); + return lines; + } + + [GeneratedRegex(@"^(?[a-zA-Z]+)(?:\((?[^)]+)\))?(?!)?:\s*(?.+)$")] + private static partial Regex Conventional(); +} diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs index 2c835d93..fa657663 100644 --- a/src/Titano.Tools/Commands/I18nCommand.cs +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -83,6 +83,8 @@ internal sealed partial class I18nCommand : ICommand foreach (var (file, key) in UsedKeys(root)) { if (en.ContainsKey(key)) continue; + // Prefix lookups such as L("Settings.Page." + page) are satisfied by any key under the prefix. + if (key.EndsWith('.') && en.Keys.Any(k => k.StartsWith(key, StringComparison.Ordinal))) continue; // Plural lookups reference the stem; any suffix satisfies them. if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue; errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}"); diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index 5d569615..d5575d16 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -7,6 +7,7 @@ var commands = new ICommand[] new I18nCommand(), new XamlLintCommand(), new PackageGuardCommand(), + new ChangelogCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") diff --git a/src/Titano.Ui/Controls/AutoSlider.cs b/src/Titano.Ui/Controls/AutoSlider.cs new file mode 100644 index 00000000..cc2a1bb1 --- /dev/null +++ b/src/Titano.Ui/Controls/AutoSlider.cs @@ -0,0 +1,142 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// +/// Advisor-aware slider (BRIEF §10.4, DESIGN §4): in Auto the track is accent with an "Auto · value" pill whose +/// tooltip carries the advisor's reason; touching the slider switches to manual (sun track, value shown, reset +/// button returns to Auto). When not applicable the value reads "n/a" with the reason in the tooltip. +/// +[TemplatePart(Name = PartSlider, Type = typeof(Slider))] +public class AutoSlider : Control +{ + public const string PartSlider = "PART_Slider"; + + public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(nameof(Header), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(double), typeof(AutoSlider), + new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged)); + public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0)); + public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0)); + public static readonly DependencyProperty SmallChangeProperty = DependencyProperty.Register(nameof(SmallChange), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.01)); + public static readonly DependencyProperty IsSnapToTickEnabledProperty = DependencyProperty.Register(nameof(IsSnapToTickEnabled), typeof(bool), typeof(AutoSlider), new PropertyMetadata(false)); + public static readonly DependencyProperty TickFrequencyProperty = DependencyProperty.Register(nameof(TickFrequency), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0)); + public static readonly DependencyProperty IsAutoProperty = DependencyProperty.Register(nameof(IsAuto), typeof(bool), typeof(AutoSlider), + new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + public static readonly DependencyProperty AutoValueProperty = DependencyProperty.Register(nameof(AutoValue), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0, OnAutoValueChanged)); + public static readonly DependencyProperty AutoReasonProperty = DependencyProperty.Register(nameof(AutoReason), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty IsApplicableProperty = DependencyProperty.Register(nameof(IsApplicable), typeof(bool), typeof(AutoSlider), new PropertyMetadata(true)); + public static readonly DependencyProperty NotApplicableReasonProperty = DependencyProperty.Register(nameof(NotApplicableReason), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty ValueFormatProperty = DependencyProperty.Register(nameof(ValueFormat), typeof(string), typeof(AutoSlider), new PropertyMetadata("0.##", OnFormatChanged)); + public static readonly DependencyProperty DisplayValueProperty = DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty)); + public static readonly DependencyProperty AutoTextProperty = DependencyProperty.Register(nameof(AutoText), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty)); + public static readonly DependencyProperty SliderToolTipProperty = DependencyProperty.Register(nameof(SliderToolTip), typeof(object), typeof(AutoSlider)); + + public static readonly RoutedCommand ResetCommand = new(nameof(ResetCommand), typeof(AutoSlider)); + + private Slider? _slider; + private bool _syncing; + + static AutoSlider() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoSlider), new FrameworkPropertyMetadata(typeof(AutoSlider))); + } + + public AutoSlider() + { + CommandBindings.Add(new CommandBinding(ResetCommand, (_, _) => ResetToAuto())); + UpdateTexts(); + } + + public string? Header { get => (string?)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); } + public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } + public double Minimum { get => (double)GetValue(MinimumProperty); set => SetValue(MinimumProperty, value); } + public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); } + public double SmallChange { get => (double)GetValue(SmallChangeProperty); set => SetValue(SmallChangeProperty, value); } + public bool IsSnapToTickEnabled { get => (bool)GetValue(IsSnapToTickEnabledProperty); set => SetValue(IsSnapToTickEnabledProperty, value); } + public double TickFrequency { get => (double)GetValue(TickFrequencyProperty); set => SetValue(TickFrequencyProperty, value); } + public bool IsAuto { get => (bool)GetValue(IsAutoProperty); set => SetValue(IsAutoProperty, value); } + public double AutoValue { get => (double)GetValue(AutoValueProperty); set => SetValue(AutoValueProperty, value); } + public string? AutoReason { get => (string?)GetValue(AutoReasonProperty); set => SetValue(AutoReasonProperty, value); } + public bool IsApplicable { get => (bool)GetValue(IsApplicableProperty); set => SetValue(IsApplicableProperty, value); } + public string? NotApplicableReason { get => (string?)GetValue(NotApplicableReasonProperty); set => SetValue(NotApplicableReasonProperty, value); } + public string ValueFormat { get => (string)GetValue(ValueFormatProperty); set => SetValue(ValueFormatProperty, value); } + + /// Formatted current value (read by the template). + public string DisplayValue { get => (string)GetValue(DisplayValueProperty); private set => SetValue(DisplayValueProperty, value); } + + /// "Auto · 41" pill text; the "Auto" word comes from the catalog (Common.Auto). + public string AutoText { get => (string)GetValue(AutoTextProperty); private set => SetValue(AutoTextProperty, value); } + + /// Tooltip of the slider track: what moving it does. + public object? SliderToolTip { get => GetValue(SliderToolTipProperty); set => SetValue(SliderToolTipProperty, value); } + + public override void OnApplyTemplate() + { + if (_slider is not null) + { + _slider.ValueChanged -= OnSliderValueChanged; + _slider.PreviewMouseDown -= OnSliderTouched; + _slider.PreviewKeyDown -= OnSliderTouched; + } + base.OnApplyTemplate(); + _slider = GetTemplateChild(PartSlider) as Slider; + if (_slider is not null) + { + _slider.Value = IsAuto ? AutoValue : Value; + _slider.ValueChanged += OnSliderValueChanged; + _slider.PreviewMouseDown += OnSliderTouched; + _slider.PreviewKeyDown += OnSliderTouched; + } + } + + /// Returns the control to the advisor's value. + public void ResetToAuto() + { + IsAuto = true; + Value = AutoValue; + UpdateTexts(); + } + + private void OnSliderTouched(object sender, RoutedEventArgs e) + { + if (e is KeyEventArgs k && k.Key is not (Key.Left or Key.Right or Key.Up or Key.Down or Key.PageUp or Key.PageDown or Key.Home or Key.End)) return; + IsAuto = false; + } + + private void OnSliderValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (_syncing) return; + Value = e.NewValue; + } + + private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var s = (AutoSlider)d; + if (s._slider is not null && !s._syncing) + { + s._syncing = true; + s._slider.Value = (double)e.NewValue; + s._syncing = false; + } + s.UpdateTexts(); + } + + private static void OnAutoValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var s = (AutoSlider)d; + if (s.IsAuto) s.Value = (double)e.NewValue; + s.UpdateTexts(); + } + + private static void OnFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((AutoSlider)d).UpdateTexts(); + + private void UpdateTexts() + { + var culture = Core.Localization.Loc.Culture; + DisplayValue = Value.ToString(ValueFormat, culture); + AutoText = Core.Localization.Loc.L("Common.Auto") + " · " + AutoValue.ToString(ValueFormat, culture); + } +} diff --git a/src/Titano.Ui/Controls/BrandMarkIcon.cs b/src/Titano.Ui/Controls/BrandMarkIcon.cs new file mode 100644 index 00000000..1a95125c --- /dev/null +++ b/src/Titano.Ui/Controls/BrandMarkIcon.cs @@ -0,0 +1,61 @@ +using System.Windows; +using System.Windows.Media; +using Titano.Core.Branding; + +namespace Titano.Ui.Controls; + +/// The Titano mark drawn as vectors from geometry (plate optional). +public sealed class BrandMarkIcon : FrameworkElement +{ + public static readonly DependencyProperty ShowPlateProperty = DependencyProperty.Register( + nameof(ShowPlate), typeof(bool), typeof(BrandMarkIcon), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)); + + private static readonly Brush Accent = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Accent.R, BrandMark.Accent.G, BrandMark.Accent.B))); + private static readonly Brush Sun = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Sun.R, BrandMark.Sun.G, BrandMark.Sun.B))); + private static readonly Brush Plate = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Plate.R, BrandMark.Plate.G, BrandMark.Plate.B))); + + public bool ShowPlate + { + get => (bool)GetValue(ShowPlateProperty); + set => SetValue(ShowPlateProperty, value); + } + + protected override Size MeasureOverride(Size availableSize) + { + var s = double.IsInfinity(availableSize.Width) ? 16 : Math.Min(availableSize.Width, double.IsInfinity(availableSize.Height) ? availableSize.Width : availableSize.Height); + return new Size(s, s); + } + + protected override void OnRender(DrawingContext dc) + { + var size = Math.Min(ActualWidth, ActualHeight); + if (size <= 0) return; + var scale = size / BrandMark.Canvas; + dc.PushTransform(new ScaleTransform(scale, scale)); + if (ShowPlate) + dc.DrawRoundedRectangle(Plate, null, new Rect(0, 0, BrandMark.Canvas, BrandMark.Canvas), BrandMark.PlateRadius, BrandMark.PlateRadius); + // Below ~24 px keep the stroke at least ~1.3 device pixels. + var stroke = Math.Max(BrandMark.StrokeWidth, 1.3 / scale); + for (var i = 0; i < BrandMark.TickCount; i++) + { + var (a0, a1) = BrandMark.TickAngles(i); + var (x0, y0) = BrandMark.Polar(a0); + var (x1, y1) = BrandMark.Polar(a1); + var figure = new PathFigure { StartPoint = new Point(x0, y0) }; + figure.Segments.Add(new ArcSegment(new Point(x1, y1), new Size(BrandMark.RingRadius, BrandMark.RingRadius), 0, false, SweepDirection.Clockwise, true)); + var geometry = new PathGeometry([figure]); + var pen = new Pen(Accent, stroke) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }; + dc.PushOpacity(BrandMark.TickOpacity(i)); + dc.DrawGeometry(null, pen, geometry); + dc.Pop(); + } + dc.DrawEllipse(Sun, null, new Point(BrandMark.SunX, BrandMark.SunY), BrandMark.SunRadius, BrandMark.SunRadius); + dc.Pop(); + } + + private static Brush Frozen(SolidColorBrush b) + { + b.Freeze(); + return b; + } +} diff --git a/src/Titano.Ui/Controls/Chip.cs b/src/Titano.Ui/Controls/Chip.cs new file mode 100644 index 00000000..78ba79e5 --- /dev/null +++ b/src/Titano.Ui/Controls/Chip.cs @@ -0,0 +1,29 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// 24-px pill (DESIGN §4). Selected or recommended chips use the accent border and text. +public class Chip : ContentControl +{ + public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(nameof(IsSelected), typeof(bool), typeof(Chip)); + public static readonly DependencyProperty IsRecommendedProperty = DependencyProperty.Register(nameof(IsRecommended), typeof(bool), typeof(Chip)); + public static readonly DependencyProperty RemoveCommandProperty = DependencyProperty.Register(nameof(RemoveCommand), typeof(ICommand), typeof(Chip)); + public static readonly DependencyProperty RemoveCommandParameterProperty = DependencyProperty.Register(nameof(RemoveCommandParameter), typeof(object), typeof(Chip)); + public static readonly DependencyProperty RemoveToolTipProperty = DependencyProperty.Register(nameof(RemoveToolTip), typeof(object), typeof(Chip)); + + static Chip() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(Chip), new FrameworkPropertyMetadata(typeof(Chip))); + } + + public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); } + public bool IsRecommended { get => (bool)GetValue(IsRecommendedProperty); set => SetValue(IsRecommendedProperty, value); } + + /// When set, a small ✕ button removes the chip (filters, tags). + public ICommand? RemoveCommand { get => (ICommand?)GetValue(RemoveCommandProperty); set => SetValue(RemoveCommandProperty, value); } + + public object? RemoveCommandParameter { get => GetValue(RemoveCommandParameterProperty); set => SetValue(RemoveCommandParameterProperty, value); } + public object? RemoveToolTip { get => GetValue(RemoveToolTipProperty); set => SetValue(RemoveToolTipProperty, value); } +} diff --git a/src/Titano.Ui/Controls/ControlState.cs b/src/Titano.Ui/Controls/ControlState.cs new file mode 100644 index 00000000..d3e1d837 --- /dev/null +++ b/src/Titano.Ui/Controls/ControlState.cs @@ -0,0 +1,28 @@ +using System.Windows; +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// Attached brushes that let one control template serve every button variant (DESIGN §4 states). +public static class ControlState +{ + public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.RegisterAttached("HoverBackground", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty PressedBackgroundProperty = DependencyProperty.RegisterAttached("PressedBackground", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty HoverBorderBrushProperty = DependencyProperty.RegisterAttached("HoverBorderBrush", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.RegisterAttached("CornerRadius", typeof(CornerRadius), typeof(ControlState), new FrameworkPropertyMetadata(new CornerRadius(6))); + public static readonly DependencyProperty AccentProperty = DependencyProperty.RegisterAttached("Accent", typeof(Brush), typeof(ControlState), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits)); + + public static Brush? GetHoverBackground(DependencyObject d) => (Brush?)d.GetValue(HoverBackgroundProperty); + public static void SetHoverBackground(DependencyObject d, Brush? v) => d.SetValue(HoverBackgroundProperty, v); + public static Brush? GetPressedBackground(DependencyObject d) => (Brush?)d.GetValue(PressedBackgroundProperty); + public static void SetPressedBackground(DependencyObject d, Brush? v) => d.SetValue(PressedBackgroundProperty, v); + public static Brush? GetHoverBorderBrush(DependencyObject d) => (Brush?)d.GetValue(HoverBorderBrushProperty); + public static void SetHoverBorderBrush(DependencyObject d, Brush? v) => d.SetValue(HoverBorderBrushProperty, v); + public static CornerRadius GetCornerRadius(DependencyObject d) => (CornerRadius)d.GetValue(CornerRadiusProperty); + public static void SetCornerRadius(DependencyObject d, CornerRadius v) => d.SetValue(CornerRadiusProperty, v); + + /// Fill colour of slider tracks and progress (accent = Auto, sun = manual). + public static Brush? GetAccent(DependencyObject d) => (Brush?)d.GetValue(AccentProperty); + + public static void SetAccent(DependencyObject d, Brush? v) => d.SetValue(AccentProperty, v); +} diff --git a/src/Titano.Ui/Controls/Converters.cs b/src/Titano.Ui/Controls/Converters.cs new file mode 100644 index 00000000..8a5f2ace --- /dev/null +++ b/src/Titano.Ui/Controls/Converters.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Titano.Ui.Controls; + +/// null → Collapsed, otherwise Visible. +public sealed class NullToCollapsedConverter : IValueConverter +{ + public static NullToCollapsedConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value is null || value is string { Length: 0 } ? Visibility.Collapsed : Visibility.Visible; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} + +/// true → Collapsed (inverse of BooleanToVisibilityConverter). +public sealed class InverseBoolToVisibilityConverter : IValueConverter +{ + public static InverseBoolToVisibilityConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value is true ? Visibility.Collapsed : Visibility.Visible; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} + +/// 0 → Collapsed, any other number → Visible. +public sealed class ZeroToCollapsedConverter : IValueConverter +{ + public static ZeroToCollapsedConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value switch + { + int i => i == 0 ? Visibility.Collapsed : Visibility.Visible, + long l => l == 0 ? Visibility.Collapsed : Visibility.Visible, + double d => d == 0 ? Visibility.Collapsed : Visibility.Visible, + _ => Visibility.Collapsed, + }; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} diff --git a/src/Titano.Ui/Controls/EmptyState.cs b/src/Titano.Ui/Controls/EmptyState.cs new file mode 100644 index 00000000..36753796 --- /dev/null +++ b/src/Titano.Ui/Controls/EmptyState.cs @@ -0,0 +1,17 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Empty state: the mark, one sentence and the action buttons supplied as content (BRIEF §0.2 rule 6). +public class EmptyState : ContentControl +{ + public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(EmptyState)); + + static EmptyState() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(EmptyState), new FrameworkPropertyMetadata(typeof(EmptyState))); + } + + public string? Message { get => (string?)GetValue(MessageProperty); set => SetValue(MessageProperty, value); } +} diff --git a/src/Titano.Ui/Controls/Field.cs b/src/Titano.Ui/Controls/Field.cs new file mode 100644 index 00000000..98477d1e --- /dev/null +++ b/src/Titano.Ui/Controls/Field.cs @@ -0,0 +1,32 @@ +using System.Windows; + +namespace Titano.Ui.Controls; + +/// Attached field helpers: placeholder text and an inline leading icon for text inputs. +public static class Field +{ + public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached( + "Placeholder", typeof(string), typeof(Field), new FrameworkPropertyMetadata(null)); + + public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached( + "Glyph", typeof(IconData), typeof(Field), new FrameworkPropertyMetadata(null)); + + public static string? GetPlaceholder(DependencyObject d) => (string?)d.GetValue(PlaceholderProperty); + + public static void SetPlaceholder(DependencyObject d, string? value) => d.SetValue(PlaceholderProperty, value); + + public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty); + + public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value); +} + +/// Attached glyph for buttons: renders an before (or instead of) the content. +public static class ButtonIcon +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached( + "Glyph", typeof(IconData), typeof(ButtonIcon), new FrameworkPropertyMetadata(null)); + + public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty); + + public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value); +} diff --git a/src/Titano.Ui/Controls/Icon.cs b/src/Titano.Ui/Controls/Icon.cs new file mode 100644 index 00000000..f87b2542 --- /dev/null +++ b/src/Titano.Ui/Controls/Icon.cs @@ -0,0 +1,79 @@ +using System.Windows; +using System.Windows.Documents; +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// Renders an on the 16-unit grid, scaled to the element size, in the inherited foreground. +public sealed class Icon : FrameworkElement +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register( + nameof(Glyph), typeof(IconData), typeof(Icon), + new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( + typeof(Icon), new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty SizeProperty = DependencyProperty.Register( + nameof(Size), typeof(double), typeof(Icon), + new FrameworkPropertyMetadata(16.0, FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty StrokeWidthProperty = DependencyProperty.Register( + nameof(StrokeWidth), typeof(double), typeof(Icon), + new FrameworkPropertyMetadata(1.5, FrameworkPropertyMetadataOptions.AffectsRender)); + + static Icon() + { + SnapsToDevicePixelsProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(true)); + FocusableProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(false)); + } + + public IconData? Glyph + { + get => (IconData?)GetValue(GlyphProperty); + set => SetValue(GlyphProperty, value); + } + + public Brush Foreground + { + get => (Brush)GetValue(ForegroundProperty); + set => SetValue(ForegroundProperty, value); + } + + /// Edge length in device-independent pixels (default 16). + public double Size + { + get => (double)GetValue(SizeProperty); + set => SetValue(SizeProperty, value); + } + + /// Stroke width on the 16-unit grid (default 1.5). + public double StrokeWidth + { + get => (double)GetValue(StrokeWidthProperty); + set => SetValue(StrokeWidthProperty, value); + } + + protected override Size MeasureOverride(Size availableSize) => new(Size, Size); + + protected override void OnRender(DrawingContext dc) + { + var glyph = Glyph; + if (glyph is null) return; + var scale = Size / 16.0; + dc.PushTransform(new ScaleTransform(scale, scale)); + if (glyph.Fill is not null) dc.DrawGeometry(Foreground, null, glyph.Fill); + if (glyph.Stroke is not null) + { + var pen = new Pen(Foreground, StrokeWidth) + { + StartLineCap = PenLineCap.Round, + EndLineCap = PenLineCap.Round, + LineJoin = PenLineJoin.Round, + }; + pen.Freeze(); + dc.DrawGeometry(null, pen, glyph.Stroke); + } + dc.Pop(); + } +} diff --git a/src/Titano.Ui/Controls/IconData.cs b/src/Titano.Ui/Controls/IconData.cs new file mode 100644 index 00000000..9c756621 --- /dev/null +++ b/src/Titano.Ui/Controls/IconData.cs @@ -0,0 +1,30 @@ +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// A 16×16 icon: a stroked outline and an optional filled part (DESIGN.md §5). +public sealed class IconData +{ + private Geometry? _stroke; + private Geometry? _fill; + + /// Outline drawn with a 1.5-px round pen in the foreground colour. + public Geometry? Stroke + { + get => _stroke; + set => _stroke = Freeze(value); + } + + /// Solid part filled with the foreground colour. + public Geometry? Fill + { + get => _fill; + set => _fill = Freeze(value); + } + + private static Geometry? Freeze(Geometry? g) + { + if (g is { CanFreeze: true, IsFrozen: false }) g.Freeze(); + return g; + } +} diff --git a/src/Titano.Ui/Controls/JobBar.cs b/src/Titano.Ui/Controls/JobBar.cs new file mode 100644 index 00000000..e0f232a6 --- /dev/null +++ b/src/Titano.Ui/Controls/JobBar.cs @@ -0,0 +1,34 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// 40-px strip under the title bar: current job, progress, time left and a stop button (DESIGN §4). +public class JobBar : Control +{ + public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(JobBar)); + public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(nameof(Progress), typeof(double), typeof(JobBar), new PropertyMetadata(0.0)); + public static readonly DependencyProperty IsIndeterminateProperty = DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(JobBar)); + public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(JobBar)); + public static readonly DependencyProperty StopCommandProperty = DependencyProperty.Register(nameof(StopCommand), typeof(ICommand), typeof(JobBar)); + public static readonly DependencyProperty StopToolTipProperty = DependencyProperty.Register(nameof(StopToolTip), typeof(object), typeof(JobBar)); + + static JobBar() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(JobBar), new FrameworkPropertyMetadata(typeof(JobBar))); + } + + public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); } + + /// 0..1. + public double Progress { get => (double)GetValue(ProgressProperty); set => SetValue(ProgressProperty, value); } + + public bool IsIndeterminate { get => (bool)GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); } + + /// A job is running: shows the progress fill and the stop button. + public bool IsActive { get => (bool)GetValue(IsActiveProperty); set => SetValue(IsActiveProperty, value); } + + public ICommand? StopCommand { get => (ICommand?)GetValue(StopCommandProperty); set => SetValue(StopCommandProperty, value); } + public object? StopToolTip { get => GetValue(StopToolTipProperty); set => SetValue(StopToolTipProperty, value); } +} diff --git a/src/Titano.Ui/Controls/NavRail.cs b/src/Titano.Ui/Controls/NavRail.cs new file mode 100644 index 00000000..30e69ca1 --- /dev/null +++ b/src/Titano.Ui/Controls/NavRail.cs @@ -0,0 +1,43 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Attached state of the navigation rail (DESIGN §3: 128 px, collapses to 48 px icons). +public static class NavRail +{ + public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.RegisterAttached( + "IsCollapsed", typeof(bool), typeof(NavRail), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits)); + + public static bool GetIsCollapsed(DependencyObject d) => (bool)d.GetValue(IsCollapsedProperty); + + public static void SetIsCollapsed(DependencyObject d, bool value) => d.SetValue(IsCollapsedProperty, value); +} + +/// One rail entry: icon, label, optional attention badge; active = card fill + 3-px accent edge. +public class NavRailButton : RadioButton +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register( + nameof(Glyph), typeof(IconData), typeof(NavRailButton)); + + public static readonly DependencyProperty BadgeProperty = DependencyProperty.Register( + nameof(Badge), typeof(int), typeof(NavRailButton), new PropertyMetadata(0)); + + static NavRailButton() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(NavRailButton), new FrameworkPropertyMetadata(typeof(NavRailButton))); + } + + public IconData? Glyph + { + get => (IconData?)GetValue(GlyphProperty); + set => SetValue(GlyphProperty, value); + } + + /// Count of things needing attention; hidden when 0. + public int Badge + { + get => (int)GetValue(BadgeProperty); + set => SetValue(BadgeProperty, value); + } +} diff --git a/src/Titano.Ui/Controls/StatusGlyph.cs b/src/Titano.Ui/Controls/StatusGlyph.cs new file mode 100644 index 00000000..d5d13bc1 --- /dev/null +++ b/src/Titano.Ui/Controls/StatusGlyph.cs @@ -0,0 +1,42 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Status vocabulary of DESIGN §4: colour is always paired with a glyph and a word. +public enum StatusKind +{ + Analysed, + NotAnalysed, + Proxies, + NoProxies, + Rendered, + Synced, + Remote, + Analysing, + Warning, + Error, + Running, + Queued, + Done, + Failed, + Paused, + Online, + Offline, +} + +/// Glyph + text in the colour of the status kind. +public class StatusGlyph : Control +{ + public static readonly DependencyProperty KindProperty = DependencyProperty.Register(nameof(Kind), typeof(StatusKind), typeof(StatusGlyph), new PropertyMetadata(StatusKind.Analysed)); + public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(StatusGlyph)); + + static StatusGlyph() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(typeof(StatusGlyph))); + FocusableProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(false)); + } + + public StatusKind Kind { get => (StatusKind)GetValue(KindProperty); set => SetValue(KindProperty, value); } + public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); } +} diff --git a/src/Titano.Ui/Controls/TitanoWindow.cs b/src/Titano.Ui/Controls/TitanoWindow.cs new file mode 100644 index 00000000..aa79b438 --- /dev/null +++ b/src/Titano.Ui/Controls/TitanoWindow.cs @@ -0,0 +1,138 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Shell; +using Titano.Ui.Interop; +using Titano.Ui.Theming; + +namespace Titano.Ui.Controls; + +/// +/// Window with Titano's custom chrome: 34-px title bar in the Chrome colour, brand mark, title, optional +/// title-bar content and drawn caption buttons. The maximise button answers HTMAXBUTTON so Windows 11 +/// snap layouts appear on hover. +/// +[TemplatePart(Name = PartMaximize, Type = typeof(Button))] +public class TitanoWindow : Window +{ + public const string PartMaximize = "PART_Maximize"; + + public static readonly DependencyProperty TitleBarContentProperty = DependencyProperty.Register( + nameof(TitleBarContent), typeof(object), typeof(TitanoWindow)); + + public static readonly DependencyProperty IsDialogProperty = DependencyProperty.Register( + nameof(IsDialog), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false)); + + public static readonly DependencyProperty IsMaximizeHoveredProperty = DependencyProperty.Register( + nameof(IsMaximizeHovered), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false)); + + private Button? _maximize; + + static TitanoWindow() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(TitanoWindow), new FrameworkPropertyMetadata(typeof(TitanoWindow))); + } + + public TitanoWindow() + { + WindowChrome.SetWindowChrome(this, new WindowChrome + { + CaptionHeight = 34, + ResizeBorderThickness = new Thickness(6), + GlassFrameThickness = new Thickness(0), + CornerRadius = new CornerRadius(0), + UseAeroCaptionButtons = false, + }); + CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, (_, _) => SystemCommands.CloseWindow(this))); + CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, (_, _) => SystemCommands.MinimizeWindow(this))); + CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, (_, _) => ToggleMaximize())); + CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, (_, _) => ToggleMaximize())); + UseLayoutRounding = true; + TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display); + } + + /// Extra content placed in the title bar between the title and the caption buttons. + public object? TitleBarContent + { + get => GetValue(TitleBarContentProperty); + set => SetValue(TitleBarContentProperty, value); + } + + /// Dialog windows show only the close button. + public bool IsDialog + { + get => (bool)GetValue(IsDialogProperty); + set => SetValue(IsDialogProperty, value); + } + + /// True while the pointer is over the maximise button (non-client, so tracked from WndProc). + public bool IsMaximizeHovered + { + get => (bool)GetValue(IsMaximizeHoveredProperty); + set => SetValue(IsMaximizeHoveredProperty, value); + } + + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + _maximize = GetTemplateChild(PartMaximize) as Button; + } + + protected override void OnSourceInitialized(EventArgs e) + { + base.OnSourceInitialized(e); + ThemeManager.ApplyChrome(this); + if (PresentationSource.FromVisual(this) is HwndSource source) source.AddHook(WndProc); + } + + private void ToggleMaximize() + { + if (WindowState == WindowState.Maximized) SystemCommands.RestoreWindow(this); + else SystemCommands.MaximizeWindow(this); + } + + private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + switch (msg) + { + case NativeMethods.WM_NCHITTEST when _maximize is { IsVisible: true } && ResizeMode is ResizeMode.CanResize or ResizeMode.CanResizeWithGrip: + if (IsOverMaximize(lParam)) + { + IsMaximizeHovered = true; + handled = true; + return NativeMethods.HTMAXBUTTON; + } + IsMaximizeHovered = false; + break; + case NativeMethods.WM_NCLBUTTONDOWN when wParam == NativeMethods.HTMAXBUTTON: + handled = true; + break; + case NativeMethods.WM_NCLBUTTONUP when wParam == NativeMethods.HTMAXBUTTON: + handled = true; + ToggleMaximize(); + break; + case NativeMethods.WM_NCMOUSELEAVE: + IsMaximizeHovered = false; + break; + } + return IntPtr.Zero; + } + + private bool IsOverMaximize(IntPtr lParam) + { + if (_maximize is null) return false; + var x = unchecked((short)(long)lParam); + var y = unchecked((short)((long)lParam >> 16)); + try + { + var point = _maximize.PointFromScreen(new Point(x, y)); + return point.X >= 0 && point.Y >= 0 && point.X < _maximize.ActualWidth && point.Y < _maximize.ActualHeight; + } + catch (InvalidOperationException) + { + return false; + } + } +} diff --git a/src/Titano.Ui/Controls/Toasts.cs b/src/Titano.Ui/Controls/Toasts.cs new file mode 100644 index 00000000..19f1da3e --- /dev/null +++ b/src/Titano.Ui/Controls/Toasts.cs @@ -0,0 +1,79 @@ +using System.Collections.ObjectModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Threading; +using Titano.Ui.Mvvm; + +namespace Titano.Ui.Controls; + +/// One in-window notification (DESIGN §4: 420 px, accent left edge, one action, 8 s, hover pauses). +public sealed class Toast : ObservableObject +{ + public required string Title { get; init; } + public string? Message { get; init; } + public string? ActionText { get; init; } + public ICommand? ActionCommand { get; init; } + public string? ActionToolTip { get; init; } + public TimeSpan Lifetime { get; init; } = TimeSpan.FromSeconds(8); +} + +/// Bottom-right stack of s with auto-dismiss. +public class ToastHost : ItemsControl +{ + private readonly Dictionary _timers = []; + + static ToastHost() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastHost), new FrameworkPropertyMetadata(typeof(ToastHost))); + } + + public ToastHost() + { + ItemsSource = Toasts; + CommandBindings.Add(new CommandBinding(DismissCommand, (_, e) => + { + if (e.Parameter is Toast t) Dismiss(t); + })); + } + + public static RoutedCommand DismissCommand { get; } = new(nameof(DismissCommand), typeof(ToastHost)); + + public ObservableCollection Toasts { get; } = []; + + public void Show(Toast toast) + { + Toasts.Add(toast); + while (Toasts.Count > 3) Dismiss(Toasts[0]); + var timer = new DispatcherTimer { Interval = toast.Lifetime }; + timer.Tick += (_, _) => Dismiss(toast); + _timers[toast] = timer; + timer.Start(); + } + + /// Pauses or resumes the dismissal timer (hover pauses). + public void SetPaused(Toast toast, bool paused) + { + if (!_timers.TryGetValue(toast, out var timer)) return; + if (paused) timer.Stop(); + else timer.Start(); + } + + public void Dismiss(Toast toast) + { + if (_timers.Remove(toast, out var timer)) timer.Stop(); + Toasts.Remove(toast); + } + + protected override void OnPreviewMouseMove(MouseEventArgs e) + { + base.OnPreviewMouseMove(e); + foreach (var t in Toasts.ToList()) SetPaused(t, true); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + foreach (var t in Toasts.ToList()) SetPaused(t, false); + } +} diff --git a/src/Titano.Ui/Icons/Icons.xaml b/src/Titano.Ui/Icons/Icons.xaml new file mode 100644 index 00000000..96d567b8 --- /dev/null +++ b/src/Titano.Ui/Icons/Icons.xaml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Interop/NativeMethods.cs b/src/Titano.Ui/Interop/NativeMethods.cs new file mode 100644 index 00000000..68aea192 --- /dev/null +++ b/src/Titano.Ui/Interop/NativeMethods.cs @@ -0,0 +1,45 @@ +using System.Runtime.InteropServices; + +namespace Titano.Ui.Interop; + +/// The few Win32/DWM calls the shared UI needs (window chrome and theme). +internal static partial class NativeMethods +{ + public const int WM_NCHITTEST = 0x0084; + public const int WM_NCMOUSEMOVE = 0x00A0; + public const int WM_NCLBUTTONDOWN = 0x00A1; + public const int WM_NCLBUTTONUP = 0x00A2; + public const int WM_NCMOUSELEAVE = 0x02A2; + public const int WM_GETMINMAXINFO = 0x0024; + public const int HTMAXBUTTON = 9; + + public const int DWMWA_USE_IMMERSIVE_DARK_MODE_OLD = 19; + public const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; + public const int DWMWA_WINDOW_CORNER_PREFERENCE = 33; + public const int DWMWA_BORDER_COLOR = 34; + public const int DWMWA_CAPTION_COLOR = 35; + + [LibraryImport("dwmapi.dll")] + public static partial int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size); + + /// Sets a 32-bit DWM attribute; false when the OS does not support it. + public static bool TrySetDwm(IntPtr hwnd, int attribute, int value) + { + if (hwnd == IntPtr.Zero || !OperatingSystem.IsWindows()) return false; + try + { + return DwmSetWindowAttribute(hwnd, attribute, ref value, sizeof(int)) == 0; + } + catch (DllNotFoundException) + { + return false; + } + catch (EntryPointNotFoundException) + { + return false; + } + } + + /// COLORREF (0x00BBGGRR) from RGB bytes. + public static int ColorRef(byte r, byte g, byte b) => r | g << 8 | b << 16; +} diff --git a/src/Titano.Ui/Localization/LocExtension.cs b/src/Titano.Ui/Localization/LocExtension.cs new file mode 100644 index 00000000..5d7af581 --- /dev/null +++ b/src/Titano.Ui/Localization/LocExtension.cs @@ -0,0 +1,49 @@ +using System.ComponentModel; +using System.Windows.Data; +using System.Windows.Markup; +using Titano.Core.Localization; + +namespace Titano.Ui.Localization; + +/// +/// XAML access to the string catalog: Text="{l:Loc Library.Filter.Year}". The value is a binding, so +/// changing updates the whole UI without restart (BRIEF §16). +/// +[MarkupExtensionReturnType(typeof(string))] +public sealed class LocExtension : MarkupExtension +{ + public LocExtension() + { + } + + public LocExtension(string key) => Key = key; + + [ConstructorArgument("key")] + public string Key { get; set; } = string.Empty; + + /// Optional format applied to the localized string (e.g. "{0}…"). + public string? StringFormat { get; set; } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + var binding = new Binding("[" + Key + "]") + { + Source = LocSource.Instance, + Mode = BindingMode.OneWay, + StringFormat = StringFormat, + }; + return binding.ProvideValue(serviceProvider); + } +} + +/// Indexer source for bindings; raises a refresh on culture change. +public sealed class LocSource : INotifyPropertyChanged +{ + private LocSource() => Loc.CultureChanged += (_, _) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); + + public static LocSource Instance { get; } = new(); + + public event PropertyChangedEventHandler? PropertyChanged; + + public string this[string key] => Loc.L(key); +} diff --git a/src/Titano.Ui/Mvvm/ObservableObject.cs b/src/Titano.Ui/Mvvm/ObservableObject.cs new file mode 100644 index 00000000..3257d5fb --- /dev/null +++ b/src/Titano.Ui/Mvvm/ObservableObject.cs @@ -0,0 +1,39 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; +using Titano.Core.Localization; + +namespace Titano.Ui.Mvvm; + +/// Minimal INotifyPropertyChanged base. +public abstract class ObservableObject : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + + protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null) + { + if (EqualityComparer.Default.Equals(field, value)) return false; + field = value; + OnPropertyChanged(propertyName); + return true; + } + + protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + + /// Signals that every property changed (used after a culture switch). + protected void OnAllPropertiesChanged() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty)); +} + +/// View model whose computed, localized texts refresh when the UI language changes. +public abstract class LocalizedViewModel : ObservableObject, IDisposable +{ + protected LocalizedViewModel() => Loc.CultureChanged += OnCultureChanged; + + public virtual void Dispose() + { + Loc.CultureChanged -= OnCultureChanged; + GC.SuppressFinalize(this); + } + + private void OnCultureChanged(object? sender, EventArgs e) => OnAllPropertiesChanged(); +} diff --git a/src/Titano.Ui/Mvvm/RelayCommand.cs b/src/Titano.Ui/Mvvm/RelayCommand.cs new file mode 100644 index 00000000..ba45ffbb --- /dev/null +++ b/src/Titano.Ui/Mvvm/RelayCommand.cs @@ -0,0 +1,70 @@ +using System.Windows.Input; + +namespace Titano.Ui.Mvvm; + +/// Synchronous command with optional can-execute predicate. +public sealed class RelayCommand(Action execute, Func? canExecute = null) : ICommand +{ + public RelayCommand(Action execute, Func? canExecute = null) + : this(_ => execute(), canExecute is null ? null : _ => canExecute()) + { + } + + public event EventHandler? CanExecuteChanged + { + add => CommandManager.RequerySuggested += value; + remove => CommandManager.RequerySuggested -= value; + } + + public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true; + + public void Execute(object? parameter) => execute(parameter); +} + +/// Asynchronous command that disables itself while running and reports failures through . +public sealed class AsyncRelayCommand(Func execute, Func? canExecute = null) : ICommand +{ + private CancellationTokenSource? _cts; + + public AsyncRelayCommand(Func execute, Func? canExecute = null) + : this((_, _) => execute(), canExecute is null ? null : _ => canExecute()) + { + } + + public event EventHandler? CanExecuteChanged; + + /// Raised on the UI thread when the command throws (other than cancellation). + public static event Action? Failed; + + public bool IsRunning => _cts is not null; + + public bool CanExecute(object? parameter) => !IsRunning && (canExecute?.Invoke(parameter) ?? true); + + public async void Execute(object? parameter) + { + if (!CanExecute(parameter)) return; + _cts = new CancellationTokenSource(); + RaiseCanExecuteChanged(); + try + { + await execute(parameter, _cts.Token); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + Failed?.Invoke(ex); + } + finally + { + _cts.Dispose(); + _cts = null; + RaiseCanExecuteChanged(); + } + } + + public void Cancel() => _cts?.Cancel(); + + public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); +} diff --git a/src/Titano.Ui/Themes/Controls.xaml b/src/Titano.Ui/Themes/Controls.xaml new file mode 100644 index 00000000..aabdc7bc --- /dev/null +++ b/src/Titano.Ui/Themes/Controls.xaml @@ -0,0 +1,1391 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Tokens.Dark.xaml b/src/Titano.Ui/Themes/Tokens.Dark.xaml new file mode 100644 index 00000000..849678cc --- /dev/null +++ b/src/Titano.Ui/Themes/Tokens.Dark.xaml @@ -0,0 +1,70 @@ + + + #1F1F23 + #1A1A1E + #26262C + #2F3038 + #383943 + #2A2B32 + #3E404A + #535663 + #F2F3F5 + #A9AEB9 + #7B818E + #4CC2FF + #6FCFFF + #3BA9E0 + #0B1B24 + #404CC2FF + #1F4CC2FF + #F5A524 + #35C48F + #E8B339 + #F0625D + #5AD1C8 + #F2F3F5 + #1A1A1A + #99000000 + #3E404A + #141417 + #1FE8B339 + #1FF0625D + #1F35C48F + #26F5A524 + #C42B1C + #66000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Tokens.Light.xaml b/src/Titano.Ui/Themes/Tokens.Light.xaml new file mode 100644 index 00000000..fa38b096 --- /dev/null +++ b/src/Titano.Ui/Themes/Tokens.Light.xaml @@ -0,0 +1,70 @@ + + + #F3F3F3 + #FFFFFF + #FFFFFF + #FFFFFF + #F5F5F5 + #EBEBEB + #E5E5E5 + #D1D1D1 + #1A1A1A + #616161 + #9E9E9E + #0067C0 + #1975C5 + #005AA8 + #FFFFFF + #E8F1FA + #F0F6FC + #E08A1E + #0F7B4F + #9A6700 + #C42B1C + #1A9E95 + #1A1A1A + #F2F3F5 + #66000000 + #E0E0E0 + #E9E9EC + #FFF4CE + #FDE7E9 + #DFF6DD + #FFF1DE + #C42B1C + #33000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Typography.xaml b/src/Titano.Ui/Themes/Typography.xaml new file mode 100644 index 00000000..2a9a3f3f --- /dev/null +++ b/src/Titano.Ui/Themes/Typography.xaml @@ -0,0 +1,85 @@ + + + Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic, Leelawadee UI, Nirmala UI, Tahoma + Segoe UI Variable Display, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic + Cascadia Mono, Consolas + + 18 + 16 + 14 + 13 + 12 + 11 + + 4 + 8 + 12 + 16 + 20 + + 6 + 8 + 12 + 12 + + 32 + 28 + 38 + 34 + 40 + 56 + 30 + 128 + 48 + 320 + 200 + 116 + 180 + + + + + + + + + + + + diff --git a/src/Titano.Ui/Theming/ThemeManager.cs b/src/Titano.Ui/Theming/ThemeManager.cs new file mode 100644 index 00000000..085ddd4e --- /dev/null +++ b/src/Titano.Ui/Theming/ThemeManager.cs @@ -0,0 +1,112 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; +using Microsoft.Win32; +using Titano.Ui.Interop; + +namespace Titano.Ui.Theming; + +public enum AppTheme +{ + System, + Dark, + Light, +} + +/// +/// Loads the Titano design system into an application and switches between the dark and light token sets +/// at run time (DESIGN.md §1: dark is the client default, light follows the OS when System is chosen). +/// +public static class ThemeManager +{ + private const string Base = "pack://application:,,,/Titano.Ui;component/"; + private static ResourceDictionary? _tokens; + private static Application? _app; + private static bool _initialized; + + public static AppTheme Requested { get; private set; } = AppTheme.Dark; + + public static bool IsDark { get; private set; } + + public static event EventHandler? Changed; + + /// Merges typography, tokens, icons and control styles into . + public static void Initialize(Application app, AppTheme theme) + { + _app = app; + var merged = app.Resources.MergedDictionaries; + // Controls.xaml merges Typography.xaml and Icons.xaml itself so its StaticResources resolve at load. + _tokens = Load(TokensFor(Resolve(theme))); + merged.Insert(0, _tokens); + merged.Insert(1, Load("Themes/Controls.xaml")); + + ToolTipService.InitialShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(400)); + ToolTipService.BetweenShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(100)); + ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(20000)); + + SystemEvents.UserPreferenceChanged += (_, e) => + { + if (e.Category == UserPreferenceCategory.General && Requested == AppTheme.System) + app.Dispatcher.BeginInvoke(() => Apply(AppTheme.System)); + }; + Apply(theme); + } + + public static void Apply(AppTheme theme) + { + if (_app is null || _tokens is null) throw new InvalidOperationException("ThemeManager.Initialize first."); + Requested = theme; + var dark = Resolve(theme); + if (dark != IsDark || !_initialized) + { + var merged = _app.Resources.MergedDictionaries; + var index = merged.IndexOf(_tokens); + _tokens = Load(TokensFor(dark)); + merged[index] = _tokens; + IsDark = dark; + _initialized = true; + } + foreach (Window w in _app.Windows) ApplyChrome(w); + Changed?.Invoke(null, EventArgs.Empty); + } + + /// True when Windows apps are set to dark mode. + public static bool SystemPrefersDark() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"); + return key?.GetValue("AppsUseLightTheme") is not int light || light == 0; + } + catch (System.Security.SecurityException) + { + return true; + } + } + + /// Colours the DWM frame (border/caption) to match the current tokens. + public static void ApplyChrome(Window window) + { + var hwnd = new WindowInteropHelper(window).Handle; + if (hwnd == IntPtr.Zero) return; + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE, IsDark ? 1 : 0); + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE_OLD, IsDark ? 1 : 0); + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_WINDOW_CORNER_PREFERENCE, 2); + if (_app?.TryFindResource("Color.Chrome") is Color chrome) + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_CAPTION_COLOR, NativeMethods.ColorRef(chrome.R, chrome.G, chrome.B)); + if (_app?.TryFindResource("Color.Stroke") is Color stroke) + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_BORDER_COLOR, NativeMethods.ColorRef(stroke.R, stroke.G, stroke.B)); + } + + private static bool Resolve(AppTheme theme) => theme switch + { + AppTheme.Dark => true, + AppTheme.Light => false, + _ => SystemPrefersDark(), + }; + + private static string TokensFor(bool dark) => dark ? "Themes/Tokens.Dark.xaml" : "Themes/Tokens.Light.xaml"; + + private static ResourceDictionary Load(string path) => new() { Source = new Uri(Base + path, UriKind.Absolute) }; +} diff --git a/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs new file mode 100644 index 00000000..e942c6eb --- /dev/null +++ b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs @@ -0,0 +1,126 @@ +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography.X509Certificates; +using Titano.Protocol; +using Titano.Testing; + +namespace Titano.Server.Tests.Hosting; + +[Category("server")] +public sealed class SystemEndpointTests(TestContext context) +{ + [Test] + public async Task HealthReportsOk() + { + await using var server = await TestServer.StartAsync(context); + var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus); + Assert.Equal("ok", Assert.NotNull(health).Status); + Assert.Equal("ok", health.Checks["archive"]); + } + + [Test] + public async Task ServerInfoCarriesFingerprintAndApiHeader() + { + await using var server = await TestServer.StartAsync(context); + using var response = await server.Client.GetAsync("/api/v1/server/info"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single()); + var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo); + Assert.Equal(1, Assert.NotNull(info).ApiVersion); + Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs + } + + [Test] + public async Task HttpsServesTheAdvertisedCertificate() + { + await using var server = await TestServer.StartAsync(context); + var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo); + string? seen = null; + using var handler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, cert, _, _) => + { + seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + return true; + }, + }; + using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) }; + using var response = await https.GetAsync("/health"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen); + } + + [Test] + public async Task CertificateIsReusedAcrossRestarts() + { + var root = context.CreateTempDirectory("restart"); + string? first; + await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"))) + first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint; + await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")); + var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint; + Assert.Equal(first, second); + } + + [Test] + public async Task UnknownApiRouteReturnsJsonError() + { + await using var server = await TestServer.StartAsync(context); + using var response = await server.Client.GetAsync("/api/v1/does-not-exist"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError); + Assert.Equal("not_found", Assert.NotNull(error).Code); + } + + [Test] + public async Task AdminPanelIsServedWithEtags() + { + await using var server = await TestServer.StartAsync(context); + using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin"); + Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode); + using var page = await server.Client.GetAsync("/admin/"); + Assert.Equal(HttpStatusCode.OK, page.StatusCode); + Assert.Contains("app.js", await page.Content.ReadAsStringAsync()); + var etag = page.Headers.ETag; + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/"); + request.Headers.IfNoneMatch.Add(Assert.NotNull(etag)); + using var cached = await server.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode); + } + + [Test] + public async Task I18nEndpointFallsBackToEnglish() + { + await using var server = await TestServer.StartAsync(context); + var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString); + Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]); + var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString); + Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]); + } + + [Test] + public void LinuxRefusesSqlite() + { + if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows"); + var options = new Titano.Server.Configuration.ServerOptions { Database = Titano.Server.Configuration.DatabaseKind.Sqlite }; + Assert.Throws(options.Validate); + } + + [Test] + public void EnvironmentOverridesDefaults() + { + var root = context.CreateTempDirectory("env"); + var env = new Dictionary + { + ["TITANO_DATA_PATH"] = root, + ["TITANO_HTTP_PORT"] = "9090", + ["TITANO_TLS_MODE"] = "proxy", + ["TITANO_DB"] = "postgres", + ["TITANO_SERVER_NAME"] = "Studio NAS", + }; + var options = Titano.Server.Configuration.ServerOptions.Load(env); + Assert.Equal(9090, options.HttpPort); + Assert.Equal(Titano.Server.Configuration.TlsMode.Proxy, options.TlsMode); + Assert.Equal("Studio NAS", options.ServerName); + } +} diff --git a/tests/Titano.Server.Tests/TestServer.cs b/tests/Titano.Server.Tests/TestServer.cs new file mode 100644 index 00000000..2e099360 --- /dev/null +++ b/tests/Titano.Server.Tests/TestServer.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Titano.Server.Configuration; +using Titano.Server.Hosting; +using Titano.Testing; + +namespace Titano.Server.Tests; + +/// In-process Kestrel on ephemeral ports with temporary archive/data folders (BRIEF §20.1). +public sealed class TestServer : IAsyncDisposable +{ + private readonly WebApplication _app; + + private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https) + { + _app = app; + Options = options; + HttpBase = http; + HttpsBase = https; + Client = new HttpClient { BaseAddress = http, Timeout = TimeSpan.FromSeconds(30) }; + } + + public ServerOptions Options { get; } + public Uri HttpBase { get; } + public Uri? HttpsBase { get; } + public HttpClient Client { get; } + public IServiceProvider Services => _app.Services; + + public static async Task StartAsync(TestContext context, Action? configure = null) + { + var root = context.CreateTempDirectory("server"); + var options = new ServerOptions + { + DataPath = Path.Combine(root, "data"), + ArchivePath = Path.Combine(root, "archive"), + HttpPort = 0, + HttpsPort = 0, + TlsMode = TlsMode.Auto, + Database = DatabaseKind.Sqlite, + }; + Directory.CreateDirectory(options.ArchivePath); + configure?.Invoke(options); + var app = ServerHost.Build(options, []); + await app.StartAsync(context.Cancellation); + var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses + .Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal))) + .ToList(); + var http = addresses.First(a => a.Scheme == "http"); + var https = addresses.FirstOrDefault(a => a.Scheme == "https"); + return new TestServer(app, options, http, https); + } + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await _app.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs index 8530989f..9982419f 100644 --- a/tests/Titano.Testing/Assert.cs +++ b/tests/Titano.Testing/Assert.cs @@ -7,12 +7,12 @@ namespace Titano.Testing; /// Assertions with messages that state expected and actual values. public static class Assert { - public static void True(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + public static void True([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(false)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) { if (!condition) Fail(message ?? $"Expected true: {expression}"); } - public static void False(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + public static void False([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(true)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) { if (condition) Fail(message ?? $"Expected false: {expression}"); } @@ -22,13 +22,13 @@ public static class Assert if (value is not null) Fail($"Expected null: {expression} was {Format(value)}"); } - public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class + public static T NotNull([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class { if (value is null) Fail($"Expected non-null: {expression}"); return value!; } - public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct + public static T NotNull([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct { if (value is null) Fail($"Expected non-null: {expression}"); return value!.Value; diff --git a/tests/Titano.Testing/ConsoleReporter.cs b/tests/Titano.Testing/ConsoleReporter.cs index d9828784..41101711 100644 --- a/tests/Titano.Testing/ConsoleReporter.cs +++ b/tests/Titano.Testing/ConsoleReporter.cs @@ -13,6 +13,8 @@ internal sealed class ConsoleReporter(bool verbose) : IDisposable switch (r.Outcome) { case TestOutcome.Failed: + if (GitHubActions) + Console.WriteLine($"::error title=Test failed::{Escape(r.Test.FullName)}: {Escape(r.Message ?? "failed")}"); Write(ConsoleColor.Red, "FAIL "); Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); Console.WriteLine(" " + r.Message); @@ -50,6 +52,11 @@ internal sealed class ConsoleReporter(bool verbose) : IDisposable public void Dispose() => Console.Out.Flush(); + private static bool GitHubActions { get; } = Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; + + /// Workflow-command escaping (https://docs.github.com/actions/reference/workflow-commands). + private static string Escape(string s) => s.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal); + private static string Ms(TimeSpan t) => t.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture) + " ms"; private static string Indent(string s) => string.Join(Environment.NewLine, s.TrimEnd().Split('\n').Select(l => " " + l.TrimEnd('\r'))); diff --git a/tests/Titano.Testing/TestRunner.cs b/tests/Titano.Testing/TestRunner.cs index 1745aad5..813b5f9e 100644 --- a/tests/Titano.Testing/TestRunner.cs +++ b/tests/Titano.Testing/TestRunner.cs @@ -43,8 +43,10 @@ public static class TestRunner } if (selected.Count == 0) { - Console.Error.WriteLine("No tests matched."); - return 2; + // An empty project is not a failure; a filter that matches nothing is a usage error. + var filtered = options.HasFilters; + Console.Error.WriteLine(filtered ? "No tests matched." : "No tests discovered."); + return filtered ? 2 : 0; } var stopwatch = Stopwatch.StartNew(); @@ -284,6 +286,7 @@ public static class TestRunner public int Parallelism { get; private set; } = Math.Max(1, Environment.ProcessorCount); public bool List { get; private set; } public bool Verbose { get; private set; } + public bool HasFilters => Filters.Count > 0 || Excludes.Count > 0; public static Options Parse(string[] args) { From 749eafeebd7d3d33c84e644fd5317e7cf8078e43 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:36:42 +0000 Subject: [PATCH 017/188] =?UTF-8?q?feat(motion):=20add=20B=C3=A9zier-eased?= =?UTF-8?q?=20virtual=20camera=20composed=20with=20stabilisation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BezierEasing evaluates CSS-style cubic-bezier timing curves (Newton with bisection fallback) with linear, ease-in, ease-out and ease-in-out presets. VirtualCamera interpolates centre, roll and geometric zoom between keyframes and returns one view-to-source affine composed with the inverse stabiliser correction. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/BezierEasing.cs | 84 ++++++++++++ src/Titano.Core/Motion/VirtualCamera.cs | 87 +++++++++++++ .../Motion/VirtualCameraTests.cs | 123 ++++++++++++++++++ 3 files changed, 294 insertions(+) create mode 100644 src/Titano.Core/Motion/BezierEasing.cs create mode 100644 src/Titano.Core/Motion/VirtualCamera.cs create mode 100644 tests/Titano.Core.Tests/Motion/VirtualCameraTests.cs diff --git a/src/Titano.Core/Motion/BezierEasing.cs b/src/Titano.Core/Motion/BezierEasing.cs new file mode 100644 index 00000000..c9957084 --- /dev/null +++ b/src/Titano.Core/Motion/BezierEasing.cs @@ -0,0 +1,84 @@ +namespace Titano.Core.Motion; + +/// +/// Cubic Bézier timing curve from (0, 0) to (1, 1) with control points (X1, Y1) and (X2, Y2), as in CSS +/// cubic-bezier(). X1 and X2 must lie in [0, 1] so time is monotonic; Y values may overshoot. +/// +public readonly record struct BezierEasing +{ + public BezierEasing(double x1, double y1, double x2, double y2) + { + if (!(x1 is >= 0 and <= 1) || !(x2 is >= 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "Control-point x must be within [0, 1]."); + if (!double.IsFinite(y1) || !double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y1)); + (X1, Y1, X2, Y2) = (x1, y1, x2, y2); + } + + public double X1 { get; } + + public double Y1 { get; } + + public double X2 { get; } + + public double Y2 { get; } + + public static BezierEasing Linear { get; } = new(0, 0, 1, 1); + + /// Starts at rest, arrives at speed. + public static BezierEasing EaseIn { get; } = new(0.42, 0, 1, 1); + + /// Starts at speed, arrives at rest. + public static BezierEasing EaseOut { get; } = new(0, 0, 0.58, 1); + + /// At rest at both ends: chains of these segments are C1-continuous. + public static BezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1); + + /// Eased progress y for time fraction t ∈ [0, 1] (exactly 0 and 1 at the ends). + public double Evaluate(double t) + { + if (t <= 0) return 0; + if (t >= 1) return 1; + return Polynomial(Y1, Y2, Parameter(t)); + } + + /// Curve parameter s with x(s) = t: Newton's method from s = t, bisection when it stalls. + private double Parameter(double t) + { + var s = t; + for (var i = 0; i < 8; i++) + { + var error = Polynomial(X1, X2, s) - t; + if (double.Abs(error) < 1e-12) return s; + var slope = Derivative(X1, X2, s); + if (double.Abs(slope) < 1e-9) break; + var next = s - error / slope; + if (next is < 0 or > 1) break; + s = next; + } + double lo = 0, hi = 1; + s = t; + for (var i = 0; i < 60 && hi - lo > 1e-14; i++) + { + if (Polynomial(X1, X2, s) < t) lo = s; + else hi = s; + s = 0.5 * (lo + hi); + } + return s; + } + + /// B(s) = 3(1−s)²s·p1 + 3(1−s)s²·p2 + s³ in Horner form. + private static double Polynomial(double p1, double p2, double s) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return ((a * s + b) * s + c) * s; + } + + private static double Derivative(double p1, double p2, double s) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return (3 * a * s + 2 * b) * s + c; + } +} diff --git a/src/Titano.Core/Motion/VirtualCamera.cs b/src/Titano.Core/Motion/VirtualCamera.cs new file mode 100644 index 00000000..00b14553 --- /dev/null +++ b/src/Titano.Core/Motion/VirtualCamera.cs @@ -0,0 +1,87 @@ +using Titano.Core.Imaging.Geometry; + +namespace Titano.Core.Motion; + +/// +/// Virtual camera pose: view centre in normalised source coordinates (0..1 across the frame), zoom ≥ 1 +/// (1 shows the whole frame) and roll in degrees (positive turns the camera clockwise on screen, so the +/// content appears turned counter-clockwise). +/// +public readonly record struct CameraState(double CenterX, double CenterY, double Zoom, double Rotation); + +/// A virtual camera keyframe; shapes the segment from this keyframe to the next. +public readonly record struct CameraKeyframe(double Frame, double CenterX, double CenterY, double Zoom, double Rotation) +{ + public BezierEasing Easing { get; init; } = BezierEasing.EaseInOut; + + public CameraState State => new(CenterX, CenterY, Zoom, Rotation); +} + +/// +/// Ken Burns style pan/zoom/roll: keyframes interpolated with per-segment cubic Bézier easing (centre and +/// roll linearly in the eased progress, zoom geometrically so equal steps look equally fast). The pose +/// becomes one affine that is composed with the stabiliser correction, so the frame is resampled once. +/// +public sealed class VirtualCamera +{ + private readonly CameraKeyframe[] _keyframes; + + public VirtualCamera(IEnumerable keyframes) + { + _keyframes = keyframes.OrderBy(k => k.Frame).ToArray(); + if (_keyframes.Length == 0) throw new ArgumentException("At least one keyframe is required.", nameof(keyframes)); + for (var i = 0; i < _keyframes.Length; i++) + { + var k = _keyframes[i]; + if (!(k.Zoom >= 1) || !double.IsFinite(k.Zoom)) throw new ArgumentOutOfRangeException(nameof(keyframes), "Zoom must be ≥ 1."); + if (!double.IsFinite(k.Frame + k.CenterX + k.CenterY + k.Rotation)) throw new ArgumentOutOfRangeException(nameof(keyframes), "Keyframe values must be finite."); + if (i > 0 && k.Frame == _keyframes[i - 1].Frame) throw new ArgumentException("Two keyframes share a frame.", nameof(keyframes)); + } + } + + public IReadOnlyList Keyframes => _keyframes; + + /// Pose at a (possibly fractional) output frame; held constant before the first and after the last keyframe. + public CameraState Evaluate(double frame) + { + if (frame <= _keyframes[0].Frame) return _keyframes[0].State; + if (frame >= _keyframes[^1].Frame) return _keyframes[^1].State; + var i = 0; + while (_keyframes[i + 1].Frame <= frame) i++; + var a = _keyframes[i]; + if (frame == a.Frame) return a.State; + var b = _keyframes[i + 1]; + var p = a.Easing.Evaluate((frame - a.Frame) / (b.Frame - a.Frame)); + return new CameraState( + a.CenterX + (b.CenterX - a.CenterX) * p, + a.CenterY + (b.CenterY - a.CenterY) * p, + a.Zoom * double.Pow(b.Zoom / a.Zoom, p), + a.Rotation + (b.Rotation - a.Rotation) * p); + } + + /// + /// Maps view pixel-centre coordinates (a frame-sized view) to source pixel-centre coordinates: + /// x_src = C + R(roll)·(x_view − view centre) / zoom. + /// + public static Affine2D ViewToSource(CameraState state, int sourceWidth, int sourceHeight) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight); + var centreX = state.CenterX * sourceWidth - 0.5; + var centreY = state.CenterY * sourceHeight - 0.5; + return Affine2D.Translation(centreX, centreY) + * Affine2D.Similarity(1 / state.Zoom, state.Rotation * double.Pi / 180, 0, 0) + * Affine2D.Translation(-(sourceWidth - 1) / 2.0, -(sourceHeight - 1) / 2.0); + } + + /// + /// The single view→source map for an output frame: the camera view composed with the inverse of the + /// stabiliser correction (which maps source to stabilised coordinates). Feed it to + /// . + /// + public Affine2D ToSource(double frame, int sourceWidth, int sourceHeight, Affine2D? stabilization = null) + { + var view = ViewToSource(Evaluate(frame), sourceWidth, sourceHeight); + return stabilization is { } correction ? correction.Invert() * view : view; + } +} diff --git a/tests/Titano.Core.Tests/Motion/VirtualCameraTests.cs b/tests/Titano.Core.Tests/Motion/VirtualCameraTests.cs new file mode 100644 index 00000000..2bf2c91f --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/VirtualCameraTests.cs @@ -0,0 +1,123 @@ +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class VirtualCameraTests +{ + private static readonly CameraKeyframe[] Path = + [ + new(0, 0.5, 0.5, 1.0, 0), + new(30, 0.3, 0.6, 2.0, 5), + new(75, 0.7, 0.4, 1.5, -3), + new(100, 0.55, 0.45, 3.0, 0) { Easing = BezierEasing.Linear }, + ]; + + [Test] + public void EasedPathHitsKeyframesExactly() + { + var camera = new VirtualCamera(Path.Reverse()); + foreach (var k in Path) Assert.Equal(k.State, camera.Evaluate(k.Frame)); + Assert.Equal(Path[0].State, camera.Evaluate(-10)); + Assert.Equal(Path[^1].State, camera.Evaluate(250)); + } + + [Test] + public void EaseInOutPathIsC1Continuous() + { + var camera = new VirtualCamera(Path); + const double h = 1e-5; + foreach (var frame in new[] { 30.0, 75.0 }) + { + foreach (var component in Components) + { + var at = component(camera.Evaluate(frame)); + var left = (at - component(camera.Evaluate(frame - h))) / h; + var right = (component(camera.Evaluate(frame + h)) - at) / h; + Assert.Approximately(left, right, 1e-3); + Assert.Approximately(0, right, 1e-3); + } + } + + // No jumps in velocity anywhere: neighbouring derivatives differ only by curvature × step. + foreach (var component in Components) + { + double? previous = null; + for (var t = 0.0; t <= 100; t += 0.05) + { + var d = (component(camera.Evaluate(t + h)) - component(camera.Evaluate(t - h))) / (2 * h); + if (previous is { } p) Assert.Less(double.Abs(d - p), 2e-3); + previous = d; + } + } + } + + [Test] + public void EasingPresetsBehave() + { + for (var t = 0.0; t <= 1.0; t += 0.01) + { + Assert.Approximately(t, BezierEasing.Linear.Evaluate(t), 1e-9); + Assert.Approximately(1, BezierEasing.EaseInOut.Evaluate(t) + BezierEasing.EaseInOut.Evaluate(1 - t), 1e-9); + } + Assert.Less(BezierEasing.EaseIn.Evaluate(0.5), 0.5); + Assert.Greater(BezierEasing.EaseOut.Evaluate(0.5), 0.5); + Assert.Equal(0.0, BezierEasing.EaseInOut.Evaluate(0)); + Assert.Equal(1.0, BezierEasing.EaseInOut.Evaluate(1)); + Assert.Monotonic(Enumerable.Range(0, 101).Select(i => BezierEasing.EaseInOut.Evaluate(i / 100.0))); + // CSS "ease" reference value: cubic-bezier(0.25, 0.1, 0.25, 1) at t = 0.5 ≈ 0.8024. + Assert.Approximately(0.8024, new BezierEasing(0.25, 0.1, 0.25, 1).Evaluate(0.5), 1e-3); + var overshoot = new BezierEasing(0.3, 0, 0.6, 1.6); + Assert.Greater(Enumerable.Range(0, 101).Max(i => overshoot.Evaluate(i / 100.0)), 1.0); + Assert.Throws(() => _ = new BezierEasing(1.2, 0, 0.5, 1)); + } + + [Test] + public void ZoomInterpolatesGeometrically() + { + var camera = new VirtualCamera([new CameraKeyframe(0, 0.5, 0.5, 1, 0) { Easing = BezierEasing.Linear }, new CameraKeyframe(10, 0.5, 0.5, 4, 0)]); + Assert.Approximately(2, camera.Evaluate(5).Zoom, 1e-12); + Assert.Throws(() => new VirtualCamera([new CameraKeyframe(0, 0.5, 0.5, 0.5, 0)])); + Assert.Throws(() => new VirtualCamera([new CameraKeyframe(3, 0.5, 0.5, 1, 0), new CameraKeyframe(3, 0.2, 0.5, 1, 0)])); + } + + [Test] + public void ViewMapsToSourceWindow() + { + const int w = 1920, h = 1080; + Assert.True(VirtualCamera.ViewToSource(new CameraState(0.5, 0.5, 1, 0), w, h).IsIdentity(1e-12)); + + var zoomed = VirtualCamera.ViewToSource(new CameraState(0.25, 0.5, 2, 0), w, h); + var (cx, cy) = zoomed.Apply((w - 1) / 2.0, (h - 1) / 2.0); + Assert.Within(479.5, 539.5, cx, cy, 1e-9); + // The view's left edge lands half a view-width (w/4 source pixels) left of the centre. + var (lx, _) = zoomed.Apply(-0.5, (h - 1) / 2.0); + Assert.Approximately(480 - w / 4.0 - 0.5, lx, 1e-9); + + var rolled = VirtualCamera.ViewToSource(new CameraState(0.5, 0.5, 1, 90), w, h); + var (vx, vy) = rolled.ApplyVector(1, 0); + Assert.Within(0, 1, vx, vy, 1e-12); + } + + [Test] + public void ComposesWithStabilisationIntoOneAffine() + { + const int w = 640, h = 480; + var camera = new VirtualCamera(Path); + var correction = Affine2D.About(Affine2D.Similarity(1.01, 0.004, 1.5, -2.25), (w - 1) / 2.0, (h - 1) / 2.0); + var combined = camera.ToSource(42.5, w, h, correction); + var view = VirtualCamera.ViewToSource(camera.Evaluate(42.5), w, h); + foreach (var (x, y) in new[] { (0.0, 0.0), (320.0, 240.0), (639.0, 100.0) }) + { + // Stabilised coordinates of the source sample must be where the view looks. + var (sx, sy) = combined.Apply(x, y); + var (tx, ty) = correction.Apply(sx, sy); + var (ex, ey) = view.Apply(x, y); + Assert.Within(ex, ey, tx, ty, 1e-9); + } + Assert.Equal(view, camera.ToSource(42.5, w, h)); + } + + private static readonly Func[] Components = [s => s.CenterX, s => s.CenterY, s => s.Zoom, s => s.Rotation / 100]; +} From 64e4fb3df67d34fb5b20244de411b192478ba7eb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:37:15 +0000 Subject: [PATCH 018/188] feat(codecs): add managed JPEG decoder and pixel conversions Baseline, extended 12-bit, progressive and lossless (SOF3) Huffman decoding; 1/3/4 components with Adobe CMYK/YCCK; all integral sampling factors with libjpeg fancy upsampling; restart resynchronisation; DCT-domain scaling. Full-size blocks use a port of libjpeg's ISLOW IDCT, so output is bit-identical to djpeg on the cjpeg fixtures. PixelConvert maps interleaved 8/16-bit samples to linear ImageBuffers and back, gray/RGB, Exif orientation and clamping. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs | 74 ++++ src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs | 241 +++++++++++ src/Titano.Core/Codecs/Jpeg/JpegIdct.cs | 169 ++++++++ .../Codecs/Jpeg/JpegLosslessDecoder.cs | 136 ++++++ src/Titano.Core/Codecs/Jpeg/JpegParser.cs | 400 ++++++++++++++++++ src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs | 378 +++++++++++++++++ .../Codecs/Jpeg/JpegScanDecoder.cs | 260 ++++++++++++ src/Titano.Core/Codecs/Jpeg/JpegTables.cs | 96 +++++ src/Titano.Core/Codecs/Jpeg/JpegTypes.cs | 153 +++++++ src/Titano.Core/Imaging/PixelConvert.cs | 390 +++++++++++++++++ .../Titano.Core.Tests/Codecs/CodecTestData.cs | 167 ++++++++ .../Codecs/JpegDecoderTests.cs | 79 ++++ tests/fixtures/codecs/jpeg/b411.jpg | Bin 0 -> 2169 bytes tests/fixtures/codecs/jpeg/b411.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/b420-nosmooth.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/b420.jpg | Bin 0 -> 2265 bytes tests/fixtures/codecs/jpeg/b420.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/b422.jpg | Bin 0 -> 2630 bytes tests/fixtures/codecs/jpeg/b422.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/b440.jpg | Bin 0 -> 2744 bytes tests/fixtures/codecs/jpeg/b440.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/b444.jpg | Bin 0 -> 3449 bytes tests/fixtures/codecs/jpeg/b444.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/cmyk.jpg | Bin 0 -> 5736 bytes tests/fixtures/codecs/jpeg/gray.jpg | Bin 0 -> 1562 bytes tests/fixtures/codecs/jpeg/gray.pgm | Bin 0 -> 2758 bytes tests/fixtures/codecs/jpeg/p420.jpg | Bin 0 -> 1992 bytes tests/fixtures/codecs/jpeg/p420.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/p444.jpg | Bin 0 -> 3651 bytes tests/fixtures/codecs/jpeg/p444.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/pgray.jpg | Bin 0 -> 1477 bytes tests/fixtures/codecs/jpeg/pgray.pgm | Bin 0 -> 2758 bytes tests/fixtures/codecs/jpeg/r420.jpg | Bin 0 -> 2395 bytes tests/fixtures/codecs/jpeg/r420.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/jpeg/r444.jpg | Bin 0 -> 3236 bytes tests/fixtures/codecs/jpeg/r444.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/make-fixtures.sh | 75 ++++ tests/fixtures/codecs/png/adam7-16.png | Bin 0 -> 5265 bytes tests/fixtures/codecs/png/adam7.png | Bin 0 -> 2780 bytes tests/fixtures/codecs/png/gray1.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/gray1.png | Bin 0 -> 241 bytes tests/fixtures/codecs/png/gray2.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/gray2.png | Bin 0 -> 308 bytes tests/fixtures/codecs/png/gray4.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/gray4.png | Bin 0 -> 685 bytes tests/fixtures/codecs/png/gray8.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/gray8.png | Bin 0 -> 1205 bytes tests/fixtures/codecs/png/graya.pam | Bin 0 -> 5563 bytes tests/fixtures/codecs/png/graya.png | Bin 0 -> 2152 bytes tests/fixtures/codecs/png/palette-adam7.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/palette-adam7.png | Bin 0 -> 920 bytes tests/fixtures/codecs/png/palette-trns.pam | Bin 0 -> 11047 bytes tests/fixtures/codecs/png/palette-trns.png | Bin 0 -> 727 bytes tests/fixtures/codecs/png/palette4.pam | Bin 0 -> 8296 bytes tests/fixtures/codecs/png/palette4.png | Bin 0 -> 691 bytes tests/fixtures/codecs/png/rgb16.png | Bin 0 -> 4841 bytes tests/fixtures/codecs/png/rgba.pam | Bin 0 -> 11047 bytes tests/fixtures/codecs/png/rgba.png | Bin 0 -> 3575 bytes tests/fixtures/codecs/src.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/src16.ppm | Bin 0 -> 16485 bytes tests/fixtures/codecs/tiff/deflate16-pred.tif | Bin 0 -> 5288 bytes tests/fixtures/codecs/tiff/float32-pred3.tif | Bin 0 -> 8876 bytes .../fixtures/codecs/tiff/gray-miniswhite.tif | Bin 0 -> 2916 bytes tests/fixtures/codecs/tiff/jpeg-rgb.tif | Bin 0 -> 4768 bytes tests/fixtures/codecs/tiff/jpeg-ycbcr.tif | Bin 0 -> 2800 bytes tests/fixtures/codecs/tiff/lzw-pred.tif | Bin 0 -> 3670 bytes tests/fixtures/codecs/tiff/lzw-tiled.tif | Bin 0 -> 5064 bytes tests/fixtures/codecs/tiff/none-strips.tif | Bin 0 -> 8542 bytes tests/fixtures/codecs/tiff/packbits.tif | Bin 0 -> 7942 bytes tests/fixtures/codecs/tiff/planar-zip.tif | Bin 0 -> 2430 bytes 70 files changed, 2618 insertions(+) create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegIdct.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegParser.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegTables.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegTypes.cs create mode 100644 src/Titano.Core/Imaging/PixelConvert.cs create mode 100644 tests/Titano.Core.Tests/Codecs/CodecTestData.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs create mode 100644 tests/fixtures/codecs/jpeg/b411.jpg create mode 100644 tests/fixtures/codecs/jpeg/b411.ppm create mode 100644 tests/fixtures/codecs/jpeg/b420-nosmooth.ppm create mode 100644 tests/fixtures/codecs/jpeg/b420.jpg create mode 100644 tests/fixtures/codecs/jpeg/b420.ppm create mode 100644 tests/fixtures/codecs/jpeg/b422.jpg create mode 100644 tests/fixtures/codecs/jpeg/b422.ppm create mode 100644 tests/fixtures/codecs/jpeg/b440.jpg create mode 100644 tests/fixtures/codecs/jpeg/b440.ppm create mode 100644 tests/fixtures/codecs/jpeg/b444.jpg create mode 100644 tests/fixtures/codecs/jpeg/b444.ppm create mode 100644 tests/fixtures/codecs/jpeg/cmyk.jpg create mode 100644 tests/fixtures/codecs/jpeg/gray.jpg create mode 100644 tests/fixtures/codecs/jpeg/gray.pgm create mode 100644 tests/fixtures/codecs/jpeg/p420.jpg create mode 100644 tests/fixtures/codecs/jpeg/p420.ppm create mode 100644 tests/fixtures/codecs/jpeg/p444.jpg create mode 100644 tests/fixtures/codecs/jpeg/p444.ppm create mode 100644 tests/fixtures/codecs/jpeg/pgray.jpg create mode 100644 tests/fixtures/codecs/jpeg/pgray.pgm create mode 100644 tests/fixtures/codecs/jpeg/r420.jpg create mode 100644 tests/fixtures/codecs/jpeg/r420.ppm create mode 100644 tests/fixtures/codecs/jpeg/r444.jpg create mode 100644 tests/fixtures/codecs/jpeg/r444.ppm create mode 100755 tests/fixtures/codecs/make-fixtures.sh create mode 100644 tests/fixtures/codecs/png/adam7-16.png create mode 100644 tests/fixtures/codecs/png/adam7.png create mode 100644 tests/fixtures/codecs/png/gray1.pam create mode 100644 tests/fixtures/codecs/png/gray1.png create mode 100644 tests/fixtures/codecs/png/gray2.pam create mode 100644 tests/fixtures/codecs/png/gray2.png create mode 100644 tests/fixtures/codecs/png/gray4.pam create mode 100644 tests/fixtures/codecs/png/gray4.png create mode 100644 tests/fixtures/codecs/png/gray8.pam create mode 100644 tests/fixtures/codecs/png/gray8.png create mode 100644 tests/fixtures/codecs/png/graya.pam create mode 100644 tests/fixtures/codecs/png/graya.png create mode 100644 tests/fixtures/codecs/png/palette-adam7.pam create mode 100644 tests/fixtures/codecs/png/palette-adam7.png create mode 100644 tests/fixtures/codecs/png/palette-trns.pam create mode 100644 tests/fixtures/codecs/png/palette-trns.png create mode 100644 tests/fixtures/codecs/png/palette4.pam create mode 100644 tests/fixtures/codecs/png/palette4.png create mode 100644 tests/fixtures/codecs/png/rgb16.png create mode 100644 tests/fixtures/codecs/png/rgba.pam create mode 100644 tests/fixtures/codecs/png/rgba.png create mode 100644 tests/fixtures/codecs/src.ppm create mode 100644 tests/fixtures/codecs/src16.ppm create mode 100644 tests/fixtures/codecs/tiff/deflate16-pred.tif create mode 100644 tests/fixtures/codecs/tiff/float32-pred3.tif create mode 100644 tests/fixtures/codecs/tiff/gray-miniswhite.tif create mode 100644 tests/fixtures/codecs/tiff/jpeg-rgb.tif create mode 100644 tests/fixtures/codecs/tiff/jpeg-ycbcr.tif create mode 100644 tests/fixtures/codecs/tiff/lzw-pred.tif create mode 100644 tests/fixtures/codecs/tiff/lzw-tiled.tif create mode 100644 tests/fixtures/codecs/tiff/none-strips.tif create mode 100644 tests/fixtures/codecs/tiff/packbits.tif create mode 100644 tests/fixtures/codecs/tiff/planar-zip.tif diff --git a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs new file mode 100644 index 00000000..00f32884 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs @@ -0,0 +1,74 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Managed JPEG decoder: baseline, extended (12-bit), progressive and lossless Huffman streams; 1, 3 or 4 components +/// (CMYK/YCCK via Adobe APP14); any integral sampling factors; restart intervals with resynchronisation on corrupt +/// data; DCT-domain scaling for thumbnails. Exif orientation is not applied. Malformed headers throw +/// ; damaged entropy-coded data yields a partial image plus warnings. +/// +public static class JpegDecoder +{ + private static readonly float[]?[] LinearLuts = new float[17][]; + + /// Reads the frame header only (no pixel decoding). + public static JpegInfo ReadInfo(ReadOnlySpan data) + { + var parser = new JpegParser(JpegDecodeOptions.Default); + parser.Parse(data, headerOnly: true); + return parser.Info(); + } + + /// Decodes to interleaved gray or RGB samples (8-bit, or 16-bit containers for higher precisions). + public static JpegImage Decode(ReadOnlySpan data, JpegDecodeOptions? options = null) + { + var parser = Parse(data, options); + if (parser.Frame!.Process == JpegProcess.Lossless) return LosslessToImage(parser); + return new JpegRenderer(parser).RenderInterleaved(parser.Info()); + } + + /// Decodes into a linear-light (samples are taken as sRGB-encoded). + /// Return gray images as three identical channels instead of one. + public static ImageBuffer DecodeToLinear(ReadOnlySpan data, JpegDecodeOptions? options = null, bool expandGray = false) + { + var parser = Parse(data, options); + if (parser.Frame!.Process == JpegProcess.Lossless) + { + var image = LosslessToImage(parser); + var channels = image.Components == 1 && expandGray ? 3 : image.Components; + return image.Pixels8 is { } p8 + ? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Components, outputChannels: channels) + : PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Components, maxValue: (1 << image.BitDepth) - 1, outputChannels: channels); + } + return new JpegRenderer(parser).RenderLinear(expandGray); + } + + private static JpegParser Parse(ReadOnlySpan data, JpegDecodeOptions? options) + { + var parser = new JpegParser(options ?? JpegDecodeOptions.Default); + parser.Parse(data); + return parser; + } + + private static JpegImage LosslessToImage(JpegParser parser) + { + var raw = JpegLosslessDecoder.Finish(parser); + if (raw.Components is not (1 or 3)) throw new InvalidDataException($"JPEG: {raw.Components}-component lossless images have no colour interpretation"); + if (raw.Precision > 8) + return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, raw.Precision, null, raw.Samples, [.. parser.Warnings]); + var bytes = new byte[raw.Samples.Length]; + for (var i = 0; i < bytes.Length; i++) bytes[i] = (byte)raw.Samples[i]; + return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, 8, bytes, null, [.. parser.Warnings]); + } + + /// sRGB-decoding table for codes 0..2^precision−1. + internal static float[] LinearLut(int precision) + { + if (LinearLuts[precision] is { } cached) return cached; + var size = 1 << precision; + var lut = new float[size]; + for (var i = 0; i < size; i++) lut[i] = (float)ColorSpace.SrgbToLinear(i / (double)(size - 1)); + return LinearLuts[precision] = lut; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs new file mode 100644 index 00000000..5a41440f --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs @@ -0,0 +1,241 @@ +using System.Runtime.CompilerServices; + +namespace Titano.Core.Codecs.Jpeg; + +/// Canonical Huffman decoding table with a 9-bit lookahead (and a combined run/value table for AC). +internal sealed class JpegHuffmanTable +{ + public const int FastBits = 9; + + /// (length << 8) | symbol for codes of ≤ bits; 0 = longer code. + public readonly ushort[] Fast = new ushort[1 << FastBits]; + + /// Exclusive upper bound of each code length's codes, left-aligned to 16 bits. + public readonly int[] MaxCode = new int[18]; + + /// Symbol index = (code >> (16 − length)) + Delta[length]. + public readonly int[] Delta = new int[17]; + + public readonly byte[] Values = new byte[256]; + + /// For AC tables: (value << 16) | (run << 8) | totalBits when code and magnitude fit in the lookahead. + public readonly int[] FastAc = new int[1 << FastBits]; + + /// Builds a table from the 16 code-length counts and the symbols (DHT layout). + /// The lengths oversubscribe the code space. + public JpegHuffmanTable(ReadOnlySpan counts, ReadOnlySpan values) + { + int code = 0, k = 0; + for (var len = 1; len <= 16; len++) + { + Delta[len] = k - code; + for (var i = 0; i < counts[len - 1]; i++, code++, k++) + { + if (len > FastBits) continue; + var first = code << (FastBits - len); + Fast.AsSpan(first, 1 << (FastBits - len)).Fill((ushort)(len << 8 | values[k])); + } + if (code > 1 << len) throw new InvalidDataException("JPEG: Huffman table oversubscribed"); + MaxCode[len] = code << (16 - len); + code <<= 1; + } + MaxCode[17] = int.MaxValue; + values[..k].CopyTo(Values); + BuildFastAc(); + } + + private void BuildFastAc() + { + for (var i = 0; i < Fast.Length; i++) + { + int e = Fast[i]; + if (e == 0) continue; + var len = e >> 8; + var rs = e & 0xFF; + int run = rs >> 4, s = rs & 15; + if (s == 0 || len + s > FastBits) continue; + var m = (i >> (FastBits - len - s)) & ((1 << s) - 1); + var v = m < 1 << (s - 1) ? m - (1 << s) + 1 : m; + FastAc[i] = v << 16 | run << 8 | (len + s); + } + } +} + +/// Thrown inside a scan when entropy-coded data is corrupt; the scan decoder resynchronises. +internal sealed class JpegEntropyException(string message) : Exception(message); + +/// +/// MSB-first bit reader over entropy-coded JPEG data: removes 0xFF00 stuffing, stops at markers and then +/// feeds zero bits, counting them so that consumption past the real data is detectable (). +/// +internal ref struct JpegBitReader +{ + private readonly ReadOnlySpan _data; + private int _pos; + private ulong _bits; + private int _count; + private int _padBits; + private int _marker; + private int _markerPos; + + public JpegBitReader(ReadOnlySpan data, int start) + { + _data = data; + _pos = start; + } + + /// Marker code that stopped the reader (0 = none, -1 = end of data). + public readonly int Marker => _marker; + + /// True once bits beyond the entropy-coded segment have been consumed. + public readonly bool Overrun => _padBits > _count; + + /// Where marker parsing continues after the scan. + public readonly int Position => _marker > 0 ? _markerPos : _pos; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Ensure(int n) + { + if (_count < n) Fill(); + } + + /// Next bits (1..32) without consuming; call first. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly int Peek(int n) => (int)(_bits >> (64 - n)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Consume(int n) + { + _bits <<= n; + _count -= n; + } + + /// Reads 1..16 bits. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReadBits(int n) + { + if (_count < n) Fill(); + var v = (int)(_bits >> (64 - n)); + _bits <<= n; + _count -= n; + return v; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReadBit() + { + if (_count < 1) Fill(); + var v = (int)(_bits >> 63); + _bits <<= 1; + _count--; + return v; + } + + /// Reads an -bit magnitude (1..16) and sign-extends it (T.81 F.2.2.1 EXTEND). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Receive(int s) + { + var v = ReadBits(s); + return v + ((((v >> (s - 1)) & 1) - 1) & (1 - (1 << s))); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Decode(JpegHuffmanTable t) + { + if (_count < 16) Fill(); + int e = t.Fast[(int)(_bits >> (64 - JpegHuffmanTable.FastBits))]; + if (e != 0) + { + var len = e >> 8; + _bits <<= len; + _count -= len; + return e & 0xFF; + } + return DecodeSlow(t); + } + + private int DecodeSlow(JpegHuffmanTable t) + { + var code = (int)(_bits >> 48); + for (var len = JpegHuffmanTable.FastBits + 1; len <= 16; len++) + { + if (code < t.MaxCode[len]) + { + Consume(len); + return t.Values[(code >> (16 - len)) + t.Delta[len]]; + } + } + throw new JpegEntropyException("JPEG: invalid Huffman code"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public void Fill() + { + while (_count <= 56) + { + if (_marker != 0 || _pos >= _data.Length) + { + if (_marker == 0) _marker = -1; + _padBits += 8; + _count += 8; + continue; + } + int b = _data[_pos]; + if (b == 0xFF) + { + var p = _pos + 1; + while (p < _data.Length && _data[p] == 0xFF) p++; + if (p >= _data.Length) + { + _pos = p; + continue; + } + if (_data[p] != 0) + { + _marker = _data[p]; + _markerPos = p - 1; + continue; + } + _pos = p + 1; + } + else + { + _pos++; + } + _bits |= (ulong)(uint)b << (56 - _count); + _count += 8; + } + } + + /// Discards buffered bits and locates the next marker (for restart processing). Returns its code + /// (-1 when the data ends) without consuming it; steps over it. + public int FindMarker() + { + _bits = 0; + _count = 0; + _padBits = 0; + if (_marker > 0) return _marker; + var p = _pos; + while (p + 1 < _data.Length) + { + if (_data[p] == 0xFF && _data[p + 1] is not (0x00 or 0xFF)) + { + _marker = _data[p + 1]; + _markerPos = p; + return _marker; + } + p++; + } + _pos = _data.Length; + _marker = -1; + return -1; + } + + /// Consumes the marker found by and resumes reading after it. + public void AcceptMarker() + { + if (_marker <= 0) return; + _pos = _markerPos + 2; + _marker = 0; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs b/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs new file mode 100644 index 00000000..41c8c826 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs @@ -0,0 +1,169 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Inverse DCT. Full-size blocks use libjpeg's accurate integer algorithm (jidctint ISLOW: Loeffler–Ligtenberg– +/// Moschytz with 13-bit constants), so output is bit-identical to libjpeg/djpeg. Reduced sizes (4, 2, 1) evaluate +/// the low-frequency n×n coefficients on an n-point grid in float (DCT-domain scaling for thumbnails). +/// +internal static class JpegIdct +{ + private const int ConstBits = 13; + private const int Fix0298631336 = 2446, Fix0390180644 = 3196, Fix0541196100 = 4433, Fix0765366865 = 6270; + private const int Fix0899976223 = 7373, Fix1175875602 = 9633, Fix1501321110 = 12299, Fix1847759065 = 15137; + private const int Fix1961570560 = 16069, Fix2053119869 = 16819, Fix2562915447 = 20995, Fix3072711026 = 25172; + + private static readonly float[] Basis4 = JpegTables.BuildBasis(4); + private static readonly float[] Basis2 = JpegTables.BuildBasis(2); + + /// Transforms one block into n·n samples, level-shifted and clamped to 0..2^precision−1. + /// 64 quantised coefficients, natural order. + /// 64 dequantisation factors, natural order. + /// Output block size: 8, 4, 2 or 1. + /// Sample precision (8 or 12). + public static void Transform(ReadOnlySpan coefficients, ReadOnlySpan quant, int size, int precision, Span output) + { + var max = (1 << precision) - 1; + var center = 1 << (precision - 1); + if (size == 8) + { + Islow(coefficients, quant, precision == 8 ? 2 : 1, center, max, output); + return; + } + if (size == 1) + { + output[0] = Math.Clamp((int)MathF.Round(coefficients[0] * quant[0] * 0.125f) + center, 0, max); + return; + } + Reduced(coefficients, quant, size, size == 4 ? Basis4 : Basis2, center, max, output); + } + + /// Port of libjpeg-turbo jpeg_idct_islow (columns, then rows; PASS1_BITS 2 for 8-bit, 1 for 12-bit). + private static void Islow(ReadOnlySpan c, ReadOnlySpan q, int pass1Bits, int center, int max, Span output) + { + Span ws = stackalloc int[64]; + _ = c[63]; + _ = q[63]; + for (var col = 0; col < 8; col++) + { + if (c[8 + col] == 0 && c[16 + col] == 0 && c[24 + col] == 0 && c[32 + col] == 0 && + c[40 + col] == 0 && c[48 + col] == 0 && c[56 + col] == 0) + { + var dc = c[col] * q[col] << pass1Bits; + for (var r = 0; r < 8; r++) ws[r * 8 + col] = dc; + continue; + } + var shift = ConstBits - pass1Bits; + Butterfly( + c[col] * q[col], c[8 + col] * q[8 + col], c[16 + col] * q[16 + col], c[24 + col] * q[24 + col], + c[32 + col] * q[32 + col], c[40 + col] * q[40 + col], c[48 + col] * q[48 + col], c[56 + col] * q[56 + col], + out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7); + var round = 1 << (shift - 1); + ws[col] = (o0 + round) >> shift; + ws[8 + col] = (o1 + round) >> shift; + ws[16 + col] = (o2 + round) >> shift; + ws[24 + col] = (o3 + round) >> shift; + ws[32 + col] = (o4 + round) >> shift; + ws[40 + col] = (o5 + round) >> shift; + ws[48 + col] = (o6 + round) >> shift; + ws[56 + col] = (o7 + round) >> shift; + } + for (var row = 0; row < 8; row++) + { + var w = ws.Slice(row * 8, 8); + var o = output.Slice(row * 8, 8); + if (w[1] == 0 && w[2] == 0 && w[3] == 0 && w[4] == 0 && w[5] == 0 && w[6] == 0 && w[7] == 0) + { + var dcShift = pass1Bits + 3; + o.Fill(Math.Clamp(((w[0] + (1 << (dcShift - 1))) >> dcShift) + center, 0, max)); + continue; + } + var shift = ConstBits + pass1Bits + 3; + var round = 1 << (shift - 1); + Butterfly(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], + out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7); + o[0] = Math.Clamp(((o0 + round) >> shift) + center, 0, max); + o[1] = Math.Clamp(((o1 + round) >> shift) + center, 0, max); + o[2] = Math.Clamp(((o2 + round) >> shift) + center, 0, max); + o[3] = Math.Clamp(((o3 + round) >> shift) + center, 0, max); + o[4] = Math.Clamp(((o4 + round) >> shift) + center, 0, max); + o[5] = Math.Clamp(((o5 + round) >> shift) + center, 0, max); + o[6] = Math.Clamp(((o6 + round) >> shift) + center, 0, max); + o[7] = Math.Clamp(((o7 + round) >> shift) + center, 0, max); + } + } + + /// One 8-point ISLOW pass; outputs are scaled by 2^13 (CONST_BITS) before descaling. + private static void Butterfly(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, + out int o0, out int o1, out int o2, out int o3, out int o4, out int o5, out int o6, out int o7) + { + // Even part: the rotator is sqrt(2)·c(−6). + var z1 = (i2 + i6) * Fix0541196100; + var tmp2 = z1 - i6 * Fix1847759065; + var tmp3 = z1 + i2 * Fix0765366865; + var tmp0 = (i0 + i4) << ConstBits; + var tmp1 = (i0 - i4) << ConstBits; + int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2; + + // Odd part (figure 8 of the LL&M paper). + tmp0 = i7; + tmp1 = i5; + tmp2 = i3; + tmp3 = i1; + z1 = tmp0 + tmp3; + var z2 = tmp1 + tmp2; + var z3 = tmp0 + tmp2; + var z4 = tmp1 + tmp3; + var z5 = (z3 + z4) * Fix1175875602; + tmp0 *= Fix0298631336; + tmp1 *= Fix2053119869; + tmp2 *= Fix3072711026; + tmp3 *= Fix1501321110; + z1 *= -Fix0899976223; + z2 *= -Fix2562915447; + z3 = z3 * -Fix1961570560 + z5; + z4 = z4 * -Fix0390180644 + z5; + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; + + o0 = tmp10 + tmp3; + o7 = tmp10 - tmp3; + o1 = tmp11 + tmp2; + o6 = tmp11 - tmp2; + o2 = tmp12 + tmp1; + o5 = tmp12 - tmp1; + o3 = tmp13 + tmp0; + o4 = tmp13 - tmp0; + } + + /// n-point IDCT of the low-frequency n×n coefficients, evaluated at the centres of n output samples. + private static void Reduced(ReadOnlySpan coefficients, ReadOnlySpan quant, int n, float[] basis, int center, int max, Span output) + { + Span g = stackalloc float[n * n]; + Span f = stackalloc float[n]; + g.Clear(); + for (var v = 0; v < n; v++) + { + var row = g.Slice(v * n, n); + for (var u = 0; u < n; u++) + { + int coef = coefficients[v * 8 + u]; + if (coef == 0) continue; + var value = (float)(coef * quant[v * 8 + u]); + for (var x = 0; x < n; x++) row[x] += value * basis[u * n + x]; + } + } + for (var y = 0; y < n; y++) + { + f.Clear(); + for (var v = 0; v < n; v++) + { + var w = basis[v * n + y]; + var row = g.Slice(v * n, n); + for (var x = 0; x < n; x++) f[x] += w * row[x]; + } + for (var x = 0; x < n; x++) output[y * n + x] = Math.Clamp((int)MathF.Round(f[x]) + center, 0, max); + } + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs new file mode 100644 index 00000000..3ae36db9 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs @@ -0,0 +1,136 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Lossless JPEG (SOF3, ITU T.81 Annex H) as used by DNG raw tiles and CR2: predictors 1–7, point transform, +/// 2–16 bit precision, one or more components (interleaved or in separate scans), restart intervals. +/// +public static class JpegLosslessDecoder +{ + /// Decodes a lossless stream to interleaved samples with the frame's own width and component count + /// (DNG tiles often encode e.g. two components at half the tile width; callers re-map the sample order). + /// The stream is malformed or not lossless. + public static JpegLosslessImage Decode(ReadOnlySpan data) + { + var parser = new JpegParser(JpegDecodeOptions.Default); + parser.Parse(data); + if (parser.Frame!.Process != JpegProcess.Lossless) throw new InvalidDataException("JPEG: not a lossless (SOF3) stream"); + return Finish(parser); + } + + /// Applies each component's point transform and packages the samples. + internal static JpegLosslessImage Finish(JpegParser parser) + { + var f = parser.Frame!; + var n = f.Components.Length; + var samples = parser.LosslessSamples ?? new ushort[checked(f.Width * f.Height * n)]; + foreach (var c in f.Components) + { + if (c.PointTransform == 0) continue; + for (var i = c.Index; i < samples.Length; i += n) samples[i] = (ushort)(samples[i] << c.PointTransform); + c.PointTransform = 0; + } + parser.LosslessSamples = samples; + return new JpegLosslessImage(samples, f.Width, f.Height, n, f.Precision); + } + + internal static int DecodeScan(JpegParser parser, ReadOnlySpan data, int pos, JpegScan scan) + { + var f = parser.Frame!; + int width = f.Width, nf = f.Components.Length, stride = width * nf; + var samples = parser.LosslessSamples ??= new ushort[checked(stride * f.Height)]; + var comps = scan.Components; + var tables = scan.DcTables; + var ns = comps.Length; + var index = new int[ns]; + for (var i = 0; i < ns; i++) + { + index[i] = comps[i].Index; + comps[i].PointTransform = scan.Al; + } + var predictor = scan.Ss; + var initial = 1 << (f.Precision - scan.Al - 1); + var interval = parser.RestartInterval; + var total = (long)width * f.Height; + var reader = new JpegBitReader(data, pos); + + long mcu = 0; + int x = 0, y = 0, restartRow = 0, expectedRst = 0; + var first = true; + while (mcu < total) + { + var end = interval > 0 ? Math.Min(total, mcu + interval) : total; + try + { + for (; mcu < end; mcu++) + { + var at = y * stride + x * nf; + for (var i = 0; i < ns; i++) + { + var s = reader.Decode(tables[i]!); + var diff = s switch + { + 0 => 0, + 16 => 32768, + > 16 => throw new JpegEntropyException("JPEG: bad lossless difference magnitude"), + _ => reader.Receive(s), + }; + var idx = at + index[i]; + int pred; + if (first) pred = initial; + else if (y == restartRow) pred = samples[idx - nf]; + else if (x == 0) pred = samples[idx - stride]; + else pred = Predict(predictor, samples[idx - nf], samples[idx - stride], samples[idx - stride - nf]); + samples[idx] = (ushort)(pred + diff); + } + first = false; + if (++x == width) + { + x = 0; + y++; + if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data"); + } + } + if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data"); + } + catch (JpegEntropyException ex) + { + parser.Warn(ex.Message); + if (interval == 0) break; + mcu = end; + } + if (mcu >= total || interval == 0) break; + + var marker = reader.FindMarker(); + if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) + { + parser.Warn("JPEG: restart marker missing; scan truncated"); + break; + } + var found = marker - JpegTables.Rst0; + if (found != expectedRst) + { + var lost = (found - expectedRst) & 7; + parser.Warn($"JPEG: {lost} restart interval(s) lost"); + mcu += (long)lost * interval; + } + reader.AcceptMarker(); + expectedRst = (found + 1) & 7; + x = (int)(mcu % width); + y = (int)(mcu / width); + restartRow = y; + first = true; + } + return reader.Position; + } + + private static int Predict(int predictor, int ra, int rb, int rc) => predictor switch + { + 1 => ra, + 2 => rb, + 3 => rc, + 4 => ra + rb - rc, + 5 => ra + ((rb - rc) >> 1), + 6 => rb + ((ra - rc) >> 1), + _ => (ra + rb) >> 1, + }; +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegParser.cs b/src/Titano.Core/Codecs/Jpeg/JpegParser.cs new file mode 100644 index 00000000..ec660afd --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegParser.cs @@ -0,0 +1,400 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// One frame component and its coefficient (DCT) storage. +internal sealed class JpegComponent +{ + public int Id, Index, H, V, QuantTable; + + /// Component size in samples: ceil(X·H/Hmax) × ceil(Y·V/Vmax). + public int Width, Height; + + /// Blocks covering the component (non-interleaved scan extent). + public int WidthInBlocks, HeightInBlocks; + + /// Allocated block grid, padded to whole MCUs. + public int BlocksPerLine, BlocksPerColumn; + + /// Quantised coefficients, 64 per block in natural order, blocks row-major. + public short[]? Coefficients; + + /// Quantisation table latched when the component's first scan starts (natural order). + public ushort[]? Quant; + + /// Point transform of the lossless scan that carried this component. + public int PointTransform; + + public int DcPred; +} + +/// Frame header (SOFn) with derived MCU geometry. +internal sealed class JpegFrame +{ + public required JpegProcess Process { get; init; } + public required int Precision { get; init; } + public required int Width { get; init; } + public required int Height { get; init; } + public required JpegComponent[] Components { get; init; } + public int HMax { get; init; } + public int VMax { get; init; } + public int McusX { get; init; } + public int McusY { get; init; } +} + +/// Scan header (SOS) resolved against the frame. +internal sealed class JpegScan +{ + public required JpegComponent[] Components { get; init; } + public required JpegHuffmanTable?[] DcTables { get; init; } + public required JpegHuffmanTable?[] AcTables { get; init; } + public int Ss { get; init; } + public int Se { get; init; } + public int Ah { get; init; } + public int Al { get; init; } +} + +/// +/// Marker-level JPEG parser: tables, frame and scan headers; dispatches entropy-coded segments to the DCT or +/// lossless scan decoders. Structural errors throw ; once a scan has been +/// decoded, later errors only end parsing with a warning so that partial images survive. +/// +internal sealed class JpegParser(JpegDecodeOptions options) +{ + private readonly ushort[]?[] _quant = new ushort[4][]; + private readonly JpegHuffmanTable?[] _dc = new JpegHuffmanTable[4]; + private readonly JpegHuffmanTable?[] _ac = new JpegHuffmanTable[4]; + private readonly List _warnings = []; + private static JpegHuffmanTable? _stdDcLuma, _stdDcChroma, _stdAcLuma, _stdAcChroma; + + public JpegDecodeOptions Options { get; } = options; + public JpegFrame? Frame { get; private set; } + public int RestartInterval { get; private set; } + public int AdobeTransform { get; private set; } = -1; + public bool Jfif { get; private set; } + public int ScansDecoded { get; private set; } + public IReadOnlyList Warnings => _warnings; + + /// Interleaved samples of a lossless frame (point transform not yet applied). + public ushort[]? LosslessSamples { get; set; } + + public void Warn(string message) + { + if (_warnings.Count < 64) _warnings.Add(message); + } + + /// Parses a full stream. With it stops at the first scan header. + public void Parse(ReadOnlySpan data, bool headerOnly = false) + { + if (Options.Tables is { Length: > 0 } tables) ParseCore(tables, tablesOnly: true, headerOnly: false); + try + { + ParseCore(data, tablesOnly: false, headerOnly); + } + catch (InvalidDataException ex) when (ScansDecoded > 0) + { + Warn(ex.Message); + } + if (Frame is null) throw new InvalidDataException("JPEG: no frame header"); + if (!headerOnly && ScansDecoded == 0) throw new InvalidDataException("JPEG: no scan data"); + } + + public JpegInfo Info() + { + var f = Frame ?? throw new InvalidDataException("JPEG: no frame header"); + return new JpegInfo( + f.Width, f.Height, f.Components.Length, f.Precision, f.Process, ColorSpace(), + f.Components.Select(c => (c.H, c.V)).ToArray(), RestartInterval); + } + + /// Colour space after applying the option override and libjpeg's marker/component-id heuristics. + public JpegColorSpace ColorSpace() + { + var f = Frame!; + var n = f.Components.Length; + if (n == 1) return JpegColorSpace.Gray; + if (f.Process == JpegProcess.Lossless && Options.ColorTransform == JpegColorTransform.Auto) + return n switch { 3 => JpegColorSpace.Rgb, 4 => JpegColorSpace.Cmyk, _ => JpegColorSpace.Other }; + var transformed = Options.ColorTransform switch + { + JpegColorTransform.None => false, + JpegColorTransform.YCbCr => true, + _ => n == 3 + ? Jfif || (AdobeTransform < 0 ? !(f.Components[0].Id == 'R' && f.Components[1].Id == 'G' && f.Components[2].Id == 'B') : AdobeTransform != 0) + : AdobeTransform == 2, + }; + return n switch + { + 3 => transformed ? JpegColorSpace.YCbCr : JpegColorSpace.Rgb, + 4 => transformed ? JpegColorSpace.Ycck : JpegColorSpace.Cmyk, + _ => JpegColorSpace.Other, + }; + } + + private void ParseCore(ReadOnlySpan data, bool tablesOnly, bool headerOnly) + { + if (data.Length < 4 || data[0] != 0xFF || data[1] != JpegTables.Soi) throw new InvalidDataException("JPEG: missing SOI marker"); + var pos = 2; + while (true) + { + var marker = NextMarker(data, ref pos); + if (marker < 0) + { + if (!tablesOnly) Warn("JPEG: missing EOI marker"); + return; + } + if (marker == JpegTables.Eoi) return; + if (marker is JpegTables.Soi or (>= JpegTables.Rst0 and <= JpegTables.Rst0 + 7) or 0x01) continue; + if (pos + 2 > data.Length) throw new InvalidDataException("JPEG: truncated marker segment"); + var length = data[pos] << 8 | data[pos + 1]; + if (length < 2 || pos + length > data.Length) throw new InvalidDataException($"JPEG: bad length for marker 0x{marker:X2}"); + var segment = data.Slice(pos + 2, length - 2); + pos += length; + switch (marker) + { + case JpegTables.Dqt: + ParseDqt(segment); + break; + case JpegTables.Dht: + ParseDht(segment); + break; + case JpegTables.Dri: + if (segment.Length < 2) throw new InvalidDataException("JPEG: bad DRI"); + RestartInterval = segment[0] << 8 | segment[1]; + break; + case JpegTables.App0: + if (segment.StartsWith("JFIF\0"u8)) Jfif = true; + break; + case JpegTables.App14: + if (segment.Length >= 12 && segment.StartsWith("Adobe"u8)) AdobeTransform = segment[11]; + break; + case >= JpegTables.Sof0 and <= JpegTables.Sof3: + if (tablesOnly) throw new InvalidDataException("JPEG: frame header in a tables-only stream"); + if (Frame is not null) throw new InvalidDataException("JPEG: more than one frame"); + ParseSof(marker, segment); + break; + case JpegTables.Sos: + if (tablesOnly || Frame is null) throw new InvalidDataException("JPEG: scan without frame header"); + if (headerOnly) return; + pos = DecodeScan(data, segment, pos); + ScansDecoded++; + break; + case JpegTables.Dac: + throw new InvalidDataException("JPEG: arithmetic coding is not supported"); + case >= 0xC5 and <= 0xCF: + throw new InvalidDataException($"JPEG: unsupported coding process (SOF 0x{marker:X2})"); + } + } + } + + /// Finds the next marker at or after , skipping garbage; returns its code or -1. + private int NextMarker(ReadOnlySpan data, ref int pos) + { + var start = pos; + while (pos + 1 < data.Length) + { + if (data[pos] != 0xFF) + { + pos++; + continue; + } + int m = data[pos + 1]; + if (m == 0xFF) + { + pos++; + continue; + } + if (m == 0) + { + pos += 2; + continue; + } + if (pos != start) Warn($"JPEG: {pos - start} extraneous bytes before marker 0x{m:X2}"); + pos += 2; + return m; + } + pos = data.Length; + return -1; + } + + private void ParseDqt(ReadOnlySpan s) + { + while (s.Length > 0) + { + int pq = s[0] >> 4, tq = s[0] & 15; + var size = pq == 0 ? 64 : 128; + if (pq > 1 || tq > 3 || s.Length < 1 + size) throw new InvalidDataException("JPEG: bad DQT"); + var table = new ushort[64]; + for (var k = 0; k < 64; k++) + { + table[JpegTables.NaturalOrder[k]] = pq == 0 ? s[1 + k] : (ushort)(s[1 + 2 * k] << 8 | s[2 + 2 * k]); + } + _quant[tq] = table; + s = s[(1 + size)..]; + } + } + + private void ParseDht(ReadOnlySpan s) + { + while (s.Length > 0) + { + if (s.Length < 17) throw new InvalidDataException("JPEG: bad DHT"); + int tc = s[0] >> 4, th = s[0] & 15; + if (tc > 1 || th > 3) throw new InvalidDataException("JPEG: bad DHT class/id"); + var counts = s.Slice(1, 16); + var total = 0; + foreach (var c in counts) total += c; + if (total > 256 || s.Length < 17 + total) throw new InvalidDataException("JPEG: bad DHT counts"); + var table = new JpegHuffmanTable(counts, s.Slice(17, total)); + (tc == 0 ? _dc : _ac)[th] = table; + s = s[(17 + total)..]; + } + } + + private void ParseSof(int marker, ReadOnlySpan s) + { + if (s.Length < 6) throw new InvalidDataException("JPEG: bad SOF"); + var process = marker switch + { + JpegTables.Sof0 => JpegProcess.Baseline, + JpegTables.Sof1 => JpegProcess.ExtendedSequential, + JpegTables.Sof2 => JpegProcess.Progressive, + _ => JpegProcess.Lossless, + }; + int precision = s[0], height = s[1] << 8 | s[2], width = s[3] << 8 | s[4], n = s[5]; + if (process == JpegProcess.Lossless ? precision is < 2 or > 16 : precision is not (8 or 12)) + throw new InvalidDataException($"JPEG: unsupported precision {precision}"); + if (width == 0 || height == 0) throw new InvalidDataException("JPEG: zero image size (DNL is not supported)"); + if ((long)width * height > Options.MaxPixels) throw new InvalidDataException($"JPEG: {width}x{height} exceeds the pixel limit"); + if (n is < 1 or > 4 || s.Length < 6 + 3 * n) throw new InvalidDataException("JPEG: bad component count"); + var components = new JpegComponent[n]; + int hMax = 1, vMax = 1; + for (var i = 0; i < n; i++) + { + var c = s.Slice(6 + 3 * i, 3); + int h = c[1] >> 4, v = c[1] & 15; + if (h is < 1 or > 4 || v is < 1 or > 4 || c[2] > 3) throw new InvalidDataException("JPEG: bad sampling factors"); + components[i] = new JpegComponent { Id = c[0], Index = i, H = h, V = v, QuantTable = c[2] }; + hMax = Math.Max(hMax, h); + vMax = Math.Max(vMax, v); + } + if (n == 1) + { + // A single component is always coded non-interleaved: its own factors are irrelevant. + components[0].H = components[0].V = hMax = vMax = 1; + } + foreach (var c in components) + { + if (hMax % c.H != 0 || vMax % c.V != 0) throw new InvalidDataException("JPEG: fractional sampling ratios are not supported"); + if (process == JpegProcess.Lossless && (c.H != 1 || c.V != 1)) + throw new InvalidDataException("JPEG: subsampled lossless streams are not supported"); + } + var unit = process == JpegProcess.Lossless ? 1 : 8; + var mcusX = DivUp(width, unit * hMax); + var mcusY = DivUp(height, unit * vMax); + foreach (var c in components) + { + c.Width = DivUp(width * c.H, hMax); + c.Height = DivUp(height * c.V, vMax); + c.WidthInBlocks = DivUp(c.Width, 8); + c.HeightInBlocks = DivUp(c.Height, 8); + c.BlocksPerLine = mcusX * c.H; + c.BlocksPerColumn = mcusY * c.V; + } + Frame = new JpegFrame + { + Process = process, Precision = precision, Width = width, Height = height, Components = components, + HMax = hMax, VMax = vMax, McusX = mcusX, McusY = mcusY, + }; + } + + private int DecodeScan(ReadOnlySpan data, ReadOnlySpan s, int pos) + { + var frame = Frame!; + if (s.Length < 1) throw new InvalidDataException("JPEG: bad SOS"); + int n = s[0]; + if (n is < 1 or > 4 || s.Length < 4 + 2 * n) throw new InvalidDataException("JPEG: bad SOS component count"); + var comps = new JpegComponent[n]; + var dc = new JpegHuffmanTable?[n]; + var ac = new JpegHuffmanTable?[n]; + var tdTa = new int[n]; + for (var i = 0; i < n; i++) + { + int id = s[1 + 2 * i]; + JpegComponent? match = null; + foreach (var c in frame.Components) + { + if (c.Id == id && Array.IndexOf(comps, c) < 0) + { + match = c; + break; + } + } + comps[i] = match ?? throw new InvalidDataException($"JPEG: scan references unknown component {id}"); + tdTa[i] = s[2 + 2 * i]; + } + var p = 1 + 2 * n; + int ss = s[p], se = s[p + 1], ah = s[p + 2] >> 4, al = s[p + 2] & 15; + + if (frame.Process == JpegProcess.Lossless) + { + if (ss is < 1 or > 7) throw new InvalidDataException($"JPEG: bad lossless predictor {ss}"); + if (al >= frame.Precision) throw new InvalidDataException("JPEG: bad point transform"); + for (var i = 0; i < n; i++) dc[i] = _dc[tdTa[i] >> 4 & 3] ?? throw new InvalidDataException("JPEG: missing Huffman table"); + var losslessScan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Al = al }; + return JpegLosslessDecoder.DecodeScan(this, data, pos, losslessScan); + } + + var progressive = frame.Process == JpegProcess.Progressive; + if (progressive) + { + if (ss > se || se > 63 || (ss == 0 && se != 0) || (ss > 0 && n != 1) || al > 13 || ah > 13) + throw new InvalidDataException("JPEG: bad progressive scan parameters"); + } + else + { + ss = 0; + se = 63; + ah = al = 0; + } + if (n > 1) + { + var blocks = 0; + foreach (var c in comps) blocks += c.H * c.V; + if (blocks > 10) throw new InvalidDataException("JPEG: too many blocks per MCU"); + } + var needDc = ss == 0 && ah == 0; + var needAc = se > 0; + for (var i = 0; i < n; i++) + { + int td = tdTa[i] >> 4, ta = tdTa[i] & 15; + if (td > 3 || ta > 3) throw new InvalidDataException("JPEG: bad Huffman table selector"); + if (needDc) dc[i] = _dc[td] ?? StandardTable(dc: true, td); + if (needAc) ac[i] = _ac[ta] ?? StandardTable(dc: false, ta); + var c = comps[i]; + if (c.Quant is null) + { + c.Quant = _quant[c.QuantTable] is { } q ? (ushort[])q.Clone() : throw new InvalidDataException("JPEG: missing quantisation table"); + } + c.Coefficients ??= new short[checked(c.BlocksPerLine * c.BlocksPerColumn * 64)]; + } + var scan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Se = se, Ah = ah, Al = al }; + return JpegScanDecoder.Decode(this, data, pos, scan); + } + + /// Quantisation table for a component that never appeared in a scan (rendered flat). + public ushort[] QuantFor(JpegComponent c) => c.Quant ?? _quant[c.QuantTable] ?? new ushort[64]; + + /// Annex K tables for streams that omit DHT (Motion-JPEG), as libjpeg does. + private static JpegHuffmanTable StandardTable(bool dc, int id) + { + if (id > 1) throw new InvalidDataException("JPEG: missing Huffman table"); + return (dc, id) switch + { + (true, 0) => _stdDcLuma ??= new JpegHuffmanTable(JpegTables.DcLumaBits, JpegTables.DcLumaValues), + (true, _) => _stdDcChroma ??= new JpegHuffmanTable(JpegTables.DcChromaBits, JpegTables.DcChromaValues), + (false, 0) => _stdAcLuma ??= new JpegHuffmanTable(JpegTables.AcLumaBits, JpegTables.AcLumaValues), + _ => _stdAcChroma ??= new JpegHuffmanTable(JpegTables.AcChromaBits, JpegTables.AcChromaValues), + }; + } + + internal static int DivUp(int a, int b) => (int)(((long)a + b - 1) / b); +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs new file mode 100644 index 00000000..1140772f --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs @@ -0,0 +1,378 @@ +using System.Buffers; +using System.Numerics; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Turns decoded coefficients into pixels: (A) parallel IDCT of every block into per-component sample planes, +/// (B) parallel bands of rows doing chroma upsampling (libjpeg "fancy" triangle filters for 2× factors, +/// replication otherwise) and colour conversion (libjpeg's fixed-point YCbCr tables, CMYK/YCCK → RGB). +/// +internal sealed class JpegRenderer +{ + private const int BandRows = 16; + + private readonly JpegParser _parser; + private readonly JpegFrame _frame; + private readonly int _n; + private readonly bool _fancy; + private readonly int _max; + private readonly JpegColorSpace _colorSpace; + private readonly bool _invertedCmyk; + private readonly ParallelOptions _parallel; + private readonly byte[]?[] _planes8; + private readonly ushort[]?[] _planes16; + private readonly int[] _stride, _validW, _validH, _hf, _vf; + + public JpegRenderer(JpegParser parser) + { + _parser = parser; + _frame = parser.Frame!; + var options = parser.Options; + _n = BlockSize(_frame, options.MaxLongEdge); + _fancy = options.FancyUpsampling && _n > 1; + _max = (1 << _frame.Precision) - 1; + _colorSpace = parser.ColorSpace(); + _invertedCmyk = parser.AdobeTransform >= 0 || _colorSpace == JpegColorSpace.Ycck; + _parallel = new ParallelOptions { MaxDegreeOfParallelism = options.MaxDegreeOfParallelism }; + Width = JpegParser.DivUp(_frame.Width * _n, 8); + Height = JpegParser.DivUp(_frame.Height * _n, 8); + Channels = _colorSpace == JpegColorSpace.Gray ? 1 : 3; + if (_colorSpace == JpegColorSpace.Other) throw new InvalidDataException("JPEG: component count has no colour interpretation"); + + var count = _frame.Components.Length; + _planes8 = new byte[count][]; + _planes16 = new ushort[count][]; + _stride = new int[count]; + _validW = new int[count]; + _validH = new int[count]; + _hf = new int[count]; + _vf = new int[count]; + for (var i = 0; i < count; i++) + { + var c = _frame.Components[i]; + _hf[i] = _frame.HMax / c.H; + _vf[i] = _frame.VMax / c.V; + _validW[i] = JpegParser.DivUp(_frame.Width * c.H * _n, _frame.HMax * 8); + _validH[i] = JpegParser.DivUp(_frame.Height * c.V * _n, _frame.VMax * 8); + } + } + + public int Width { get; } + public int Height { get; } + + /// Output channels: 1 for gray, 3 otherwise. + public int Channels { get; } + + /// IDCT output size per block (8 = full size, 4/2/1 = DCT-domain scaling) for a requested long edge. + public static int BlockSize(JpegFrame frame, int maxLongEdge) + { + if (maxLongEdge <= 0) return 8; + var longEdge = Math.Max(frame.Width, frame.Height); + foreach (var n in (ReadOnlySpan)[1, 2, 4]) + { + if (JpegParser.DivUp(longEdge * n, 8) >= maxLongEdge) return n; + } + return 8; + } + + public JpegImage RenderInterleaved(JpegInfo info) + { + RunIdct(); + var length = checked(Width * Height * Channels); + if (_frame.Precision <= 8) + { + var pixels = new byte[length]; + Render((y, rows) => + { + var dst = pixels.AsSpan(y * Width * Channels, Width * Channels); + for (var c = 0; c < Channels; c++) + { + var src = rows[c]; + for (var x = 0; x < Width; x++) dst[x * Channels + c] = (byte)src[x]; + } + }); + return new JpegImage(info, Width, Height, Channels, 8, pixels, null, [.. _parser.Warnings]); + } + var pixels16 = new ushort[length]; + Render((y, rows) => + { + var dst = pixels16.AsSpan(y * Width * Channels, Width * Channels); + for (var c = 0; c < Channels; c++) + { + var src = rows[c]; + for (var x = 0; x < Width; x++) dst[x * Channels + c] = (ushort)src[x]; + } + }); + return new JpegImage(info, Width, Height, Channels, _frame.Precision, null, pixels16, [.. _parser.Warnings]); + } + + /// Renders straight into linear-light float planes (sRGB transfer removed by table lookup). + public ImageBuffer RenderLinear(bool expandGray) + { + RunIdct(); + var lut = _frame.Precision == 8 ? null : JpegDecoder.LinearLut(_frame.Precision); + var outChannels = Channels == 1 && !expandGray ? 1 : 3; + var image = new ImageBuffer(Width, Height, outChannels, clear: false); + var storage = image.Storage; + var plane = image.PlaneLength; + Render((y, rows) => + { + for (var c = 0; c < outChannels; c++) + { + var src = rows[Channels == 1 ? 0 : c]; + var dst = storage.AsSpan(c * plane + y * Width, Width); + if (lut is null) + { + for (var x = 0; x < dst.Length; x++) dst[x] = ColorSpace.Linear8((byte)src[x]); + } + else + { + for (var x = 0; x < dst.Length; x++) dst[x] = lut[src[x]]; + } + } + }); + return image; + } + + private void RunIdct() + { + var comps = _frame.Components; + var center = 1 << (_frame.Precision - 1); + var jobs = new List<(int Component, int BlockRow)>(); + for (var i = 0; i < comps.Length; i++) + { + var c = comps[i]; + _stride[i] = c.BlocksPerLine * _n; + var length = checked(_stride[i] * c.BlocksPerColumn * _n); + if (_frame.Precision <= 8) _planes8[i] = new byte[length]; + else _planes16[i] = new ushort[length]; + var blockRows = JpegParser.DivUp(_validH[i], _n); + for (var by = 0; by < blockRows; by++) jobs.Add((i, by)); + } + var quant = new int[comps.Length][]; + for (var i = 0; i < comps.Length; i++) quant[i] = Array.ConvertAll(_parser.QuantFor(comps[i]), q => (int)q); + + Parallel.For(0, jobs.Count, _parallel, () => new int[64], (j, _, block) => + { + var (i, by) = jobs[j]; + var c = comps[i]; + var stride = _stride[i]; + var rowOffset = by * _n * stride; + if (c.Coefficients is not { } coefficients) + { + // Component never scanned: flat mid-grey, like zero coefficients. + if (_planes8[i] is { } flat8) flat8.AsSpan(rowOffset, _n * stride).Fill((byte)center); + else _planes16[i].AsSpan(rowOffset, _n * stride).Fill((ushort)center); + return block; + } + var blocks = JpegParser.DivUp(_validW[i], _n); + for (var bx = 0; bx < blocks; bx++) + { + JpegIdct.Transform(coefficients.AsSpan((by * c.BlocksPerLine + bx) * 64, 64), quant[i], _n, _frame.Precision, block); + var at = rowOffset + bx * _n; + for (var y = 0; y < _n; y++, at += stride) + { + var src = block.AsSpan(y * _n, _n); + if (_planes8[i] is { } p8) + { + var dst = p8.AsSpan(at, _n); + for (var x = 0; x < _n; x++) dst[x] = (byte)src[x]; + } + else + { + var dst = _planes16[i].AsSpan(at, _n); + for (var x = 0; x < _n; x++) dst[x] = (ushort)src[x]; + } + } + } + return block; + }, _ => { }); + foreach (var c in comps) c.Coefficients = null; + } + + private delegate void RowSink(int y, int[][] rows); + + private void Render(RowSink sink) + { + var bands = JpegParser.DivUp(Height, BandRows); + var count = _frame.Components.Length; + var ycc = _colorSpace is JpegColorSpace.YCbCr or JpegColorSpace.Ycck ? YccTables.For(_frame.Precision) : null; + Parallel.For(0, bands, _parallel, band => + { + var rows = new int[count][]; + for (var c = 0; c < count; c++) rows[c] = ArrayPool.Shared.Rent(Width + 1); + try + { + var end = Math.Min(Height, (band + 1) * BandRows); + for (var y = band * BandRows; y < end; y++) + { + for (var c = 0; c < count; c++) + { + if (_planes8[c] is { } p8) Upsample(p8, c, y, rows[c]); + else Upsample(_planes16[c]!, c, y, rows[c]); + } + ConvertColor(rows, ycc); + sink(y, rows); + } + } + finally + { + foreach (var r in rows) ArrayPool.Shared.Return(r); + } + }); + } + + /// Writes one output row of component at full output width. + /// holds at least Width + 1 values, enough for the 2·w samples a 2× upsampler produces. + private void Upsample(T[] plane, int c, int y, int[] dst) where T : unmanaged, IBinaryInteger + { + int hf = _hf[c], vf = _vf[c], stride = _stride[c], w = _validW[c], h = _validH[c]; + var cy = Math.Min(y / vf, h - 1); + var near = plane.AsSpan(cy * stride, w); + var width = Width; + if (hf == 1 && vf == 1) + { + for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x]); + return; + } + if (_fancy && vf == 2 && hf <= 2) + { + var upper = (y & 1) == 0; + var far = plane.AsSpan(Math.Clamp(upper ? cy - 1 : cy + 1, 0, h - 1) * stride, w); + if (hf == 1) + { + var bias = upper ? 1 : 2; + for (var x = 0; x < width; x++) dst[x] = (3 * int.CreateTruncating(near[x]) + int.CreateTruncating(far[x]) + bias) >> 2; + return; + } + if (w > 2) + { + H2V2(near, far, w, dst); + return; + } + } + if (_fancy && hf == 2 && vf == 1 && w > 2) + { + H2V1(near, w, dst); + return; + } + for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x / hf]); + } + + /// libjpeg h2v1_fancy_upsample: 3/4·nearer + 1/4·further, alternating rounding bias. + private static void H2V1(ReadOnlySpan s, int w, Span o) where T : unmanaged, IBinaryInteger + { + var first = int.CreateTruncating(s[0]); + o[0] = first; + o[1] = (3 * first + int.CreateTruncating(s[1]) + 2) >> 2; + for (var i = 1; i < w - 1; i++) + { + var v = 3 * int.CreateTruncating(s[i]); + o[2 * i] = (v + int.CreateTruncating(s[i - 1]) + 1) >> 2; + o[2 * i + 1] = (v + int.CreateTruncating(s[i + 1]) + 2) >> 2; + } + var last = int.CreateTruncating(s[w - 1]); + o[2 * w - 2] = (3 * last + int.CreateTruncating(s[w - 2]) + 1) >> 2; + o[2 * w - 1] = last; + } + + /// libjpeg h2v2_fancy_upsample: triangle filter in both directions (9/3/3/1 weights). + private static void H2V2(ReadOnlySpan near, ReadOnlySpan far, int w, Span o) where T : unmanaged, IBinaryInteger + { + var thisSum = 3 * int.CreateTruncating(near[0]) + int.CreateTruncating(far[0]); + var nextSum = 3 * int.CreateTruncating(near[1]) + int.CreateTruncating(far[1]); + o[0] = (thisSum * 4 + 8) >> 4; + o[1] = (thisSum * 3 + nextSum + 7) >> 4; + var lastSum = thisSum; + thisSum = nextSum; + for (var i = 1; i < w - 1; i++) + { + nextSum = 3 * int.CreateTruncating(near[i + 1]) + int.CreateTruncating(far[i + 1]); + o[2 * i] = (thisSum * 3 + lastSum + 8) >> 4; + o[2 * i + 1] = (thisSum * 3 + nextSum + 7) >> 4; + lastSum = thisSum; + thisSum = nextSum; + } + o[2 * w - 2] = (thisSum * 3 + lastSum + 8) >> 4; + o[2 * w - 1] = (thisSum * 4 + 7) >> 4; + } + + private void ConvertColor(int[][] rows, YccTables? ycc) + { + var w = Width; + var max = _max; + switch (_colorSpace) + { + case JpegColorSpace.YCbCr: + YccToRgb(rows, ycc!, w, max); + break; + case JpegColorSpace.Cmyk or JpegColorSpace.Ycck: + { + if (_colorSpace == JpegColorSpace.Ycck) + { + YccToRgb(rows, ycc!, w, max); + for (var c = 0; c < 3; c++) + { + var r = rows[c]; + for (var x = 0; x < w; x++) r[x] = max - r[x]; + } + } + var k = rows[3]; + var half = max / 2; + for (var c = 0; c < 3; c++) + { + var r = rows[c]; + for (var x = 0; x < w; x++) + { + r[x] = _invertedCmyk ? (r[x] * k[x] + half) / max : ((max - r[x]) * (max - k[x]) + half) / max; + } + } + break; + } + } + } + + private static void YccToRgb(int[][] rows, YccTables t, int w, int max) + { + int[] y = rows[0], cb = rows[1], cr = rows[2]; + for (var x = 0; x < w; x++) + { + int yy = y[x], b = cb[x], r = cr[x]; + y[x] = Math.Clamp(yy + t.CrR[r], 0, max); + cb[x] = Math.Clamp(yy + ((t.CbG[b] + t.CrG[r]) >> 16), 0, max); + cr[x] = Math.Clamp(yy + t.CbB[b], 0, max); + } + } + + /// libjpeg's fixed-point (16 fractional bits) YCbCr → RGB tables for a sample precision. + private sealed class YccTables + { + private static readonly YccTables?[] Cache = new YccTables?[17]; + public readonly int[] CrR, CbB, CrG, CbG; + + private YccTables(int precision) + { + var size = 1 << precision; + var center = size / 2; + CrR = new int[size]; + CbB = new int[size]; + CrG = new int[size]; + CbG = new int[size]; + const int half = 1 << 15; + for (var i = 0; i < size; i++) + { + var x = i - center; + CrR[i] = (Fix(1.40200) * x + half) >> 16; + CbB[i] = (Fix(1.77200) * x + half) >> 16; + CrG[i] = -Fix(0.71414) * x; + CbG[i] = -Fix(0.34414) * x + half; + } + } + + public static YccTables For(int precision) => Cache[precision] ??= new YccTables(precision); + + private static int Fix(double v) => (int)(v * 65536 + 0.5); + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs new file mode 100644 index 00000000..9e90a42b --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs @@ -0,0 +1,260 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Entropy decoding of DCT scans into the components' coefficient arrays: sequential (baseline/extended) and the +/// four progressive scan kinds (DC first/refine, AC first/refine). Corrupt intervals are skipped by resynchronising +/// on the next RSTn marker; without restart markers the rest of the scan is abandoned with a warning. +/// +internal static class JpegScanDecoder +{ + private enum Kind + { + Sequential, + DcFirst, + DcRefine, + AcFirst, + AcRefine, + } + + public static int Decode(JpegParser parser, ReadOnlySpan data, int pos, JpegScan scan) + { + var frame = parser.Frame!; + var comps = scan.Components; + var kind = frame.Process != JpegProcess.Progressive ? Kind.Sequential + : scan.Ss == 0 ? (scan.Ah == 0 ? Kind.DcFirst : Kind.DcRefine) + : (scan.Ah == 0 ? Kind.AcFirst : Kind.AcRefine); + + var single = comps.Length == 1; + var mcusX = single ? comps[0].WidthInBlocks : frame.McusX; + var mcusY = single ? comps[0].HeightInBlocks : frame.McusY; + var total = (long)mcusX * mcusY; + var interval = parser.RestartInterval; + var reader = new JpegBitReader(data, pos); + var state = new ScanState(scan); + var expectedRst = 0; + foreach (var c in comps) c.DcPred = 0; + + long mcu = 0; + while (mcu < total) + { + var end = interval > 0 ? Math.Min(total, mcu + interval) : total; + try + { + for (; mcu < end; mcu++) + { + if (single) + { + var c = comps[0]; + var bx = (int)(mcu % mcusX); + var by = (int)(mcu / mcusX); + DecodeBlock(ref reader, kind, c, (by * c.BlocksPerLine + bx) * 64, 0, ref state); + } + else + { + var mx = (int)(mcu % mcusX); + var my = (int)(mcu / mcusX); + for (var i = 0; i < comps.Length; i++) + { + var c = comps[i]; + for (var v = 0; v < c.V; v++) + { + var row = (my * c.V + v) * c.BlocksPerLine + mx * c.H; + for (var h = 0; h < c.H; h++) DecodeBlock(ref reader, kind, c, (row + h) * 64, i, ref state); + } + } + } + if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data"); + } + } + catch (JpegEntropyException ex) + { + parser.Warn(ex.Message); + if (interval == 0) break; + mcu = end; + } + if (mcu >= total || interval == 0) break; + + var marker = reader.FindMarker(); + if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) + { + parser.Warn("JPEG: restart marker missing; scan truncated"); + break; + } + var found = marker - JpegTables.Rst0; + if (found != expectedRst) + { + // Intervals between the expected and the found marker were lost: leave their blocks untouched. + var lost = (found - expectedRst) & 7; + parser.Warn($"JPEG: {lost} restart interval(s) lost"); + mcu += (long)lost * interval; + } + reader.AcceptMarker(); + expectedRst = (found + 1) & 7; + state.EobRun = 0; + foreach (var c in comps) c.DcPred = 0; + } + return reader.Position; + } + + private struct ScanState(JpegScan scan) + { + public readonly JpegScan Scan = scan; + public int EobRun; + } + + private static void DecodeBlock(ref JpegBitReader r, Kind kind, JpegComponent c, int offset, int index, ref ScanState state) + { + var block = c.Coefficients.AsSpan(offset, 64); + var scan = state.Scan; + switch (kind) + { + case Kind.Sequential: + DecodeSequential(ref r, block, scan.DcTables[index]!, scan.AcTables[index]!, ref c.DcPred); + break; + case Kind.DcFirst: + { + var t = r.Decode(scan.DcTables[index]!); + if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude"); + c.DcPred += t == 0 ? 0 : r.Receive(t); + block[0] = (short)(c.DcPred * (1 << scan.Al)); + break; + } + case Kind.DcRefine: + if (r.ReadBit() != 0) block[0] |= (short)(1 << scan.Al); + break; + case Kind.AcFirst: + DecodeAcFirst(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun); + break; + default: + DecodeAcRefine(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun); + break; + } + } + + private static void DecodeSequential(ref JpegBitReader r, Span block, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int pred) + { + var t = r.Decode(dc); + if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude"); + pred += t == 0 ? 0 : r.Receive(t); + block[0] = (short)pred; + var order = JpegTables.NaturalOrder; + var fastAc = ac.FastAc; + var k = 1; + while (k < 64) + { + r.Ensure(16); + var fast = fastAc[r.Peek(JpegHuffmanTable.FastBits)]; + if (fast != 0) + { + k += (fast >> 8) & 15; + r.Consume(fast & 0xFF); + if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range"); + block[order[k++]] = (short)(fast >> 16); + continue; + } + var rs = r.Decode(ac); + int run = rs >> 4, s = rs & 15; + if (s == 0) + { + if (run != 15) break; + k += 16; + continue; + } + k += run; + if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range"); + block[order[k++]] = (short)r.Receive(s); + } + } + + private static void DecodeAcFirst(ref JpegBitReader r, Span block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun) + { + if (eobRun > 0) + { + eobRun--; + return; + } + var order = JpegTables.NaturalOrder; + for (var k = ss; k <= se;) + { + var rs = r.Decode(ac); + int run = rs >> 4, s = rs & 15; + if (s == 0) + { + if (run < 15) + { + eobRun = (1 << run) - 1; + if (run > 0) eobRun += r.ReadBits(run); + return; + } + k += 16; + continue; + } + k += run; + if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range"); + block[order[k++]] = (short)(r.Receive(s) * (1 << al)); + } + } + + /// AC successive-approximation refinement (T.81 G.1.2.3), following libjpeg's decode_mcu_AC_refine. + private static void DecodeAcRefine(ref JpegBitReader r, Span block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun) + { + var order = JpegTables.NaturalOrder; + var p1 = (short)(1 << al); + var m1 = (short)(-1 << al); + var k = ss; + if (eobRun == 0) + { + for (; k <= se; k++) + { + var rs = r.Decode(ac); + int run = rs >> 4, s = rs & 15; + short value = 0; + if (s != 0) + { + if (s != 1) throw new JpegEntropyException("JPEG: bad refinement magnitude"); + value = r.ReadBit() != 0 ? p1 : m1; + } + else if (run != 15) + { + eobRun = 1 << run; + if (run > 0) eobRun += r.ReadBits(run); + break; + } + // Skip `run` still-zero coefficients, refining the non-zero ones passed on the way. + for (; k <= se; k++) + { + ref var coef = ref block[order[k]]; + if (coef != 0) + { + RefineBit(ref r, ref coef, p1, m1); + } + else + { + if (run == 0) break; + run--; + } + } + if (value != 0) + { + if (k > se) throw new JpegEntropyException("JPEG: refinement beyond spectral band"); + block[order[k]] = value; + } + } + } + if (eobRun > 0) + { + for (; k <= se; k++) + { + ref var coef = ref block[order[k]]; + if (coef != 0) RefineBit(ref r, ref coef, p1, m1); + } + eobRun--; + } + } + + private static void RefineBit(ref JpegBitReader r, ref short coef, short p1, short m1) + { + if (r.ReadBit() == 0 || (coef & p1) != 0) return; + coef += coef >= 0 ? p1 : m1; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegTables.cs b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs new file mode 100644 index 00000000..6e3d6f0a --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs @@ -0,0 +1,96 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// Constants shared by the JPEG encoder and decoders (ITU T.81 Annex K). +internal static class JpegTables +{ + public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dnl = 0xDC, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC; + public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE, Com = 0xFE; + + /// Natural (row-major) index of the coefficient at each zig-zag position. + public static ReadOnlySpan NaturalOrder => + [ + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, + ]; + + /// Annex K.1 luminance quantisation table, natural order. + public static ReadOnlySpan LumaQuant => + [ + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99, + ]; + + /// Annex K.1 chrominance quantisation table, natural order. + public static ReadOnlySpan ChromaQuant => + [ + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + ]; + + public static ReadOnlySpan DcLumaBits => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; + public static ReadOnlySpan DcLumaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + public static ReadOnlySpan DcChromaBits => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; + public static ReadOnlySpan DcChromaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + public static ReadOnlySpan AcLumaBits => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; + + public static ReadOnlySpan AcLumaValues => + [ + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa, + ]; + + public static ReadOnlySpan AcChromaBits => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; + + public static ReadOnlySpan AcChromaValues => + [ + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa, + ]; + + /// Orthonormal 8-point DCT basis: Basis[u * 8 + x] = c(u)/2 · cos((2x+1)uπ/16). + public static readonly float[] Basis = BuildBasis(8); + + /// DCT basis of an n-point reduced IDCT evaluated with 8-point normalisation (DCT-domain scaling). + public static float[] BuildBasis(int n) + { + var b = new float[n * n]; + for (var u = 0; u < n; u++) + { + var cu = u == 0 ? Math.Sqrt(0.5) : 1.0; + for (var x = 0; x < n; x++) b[u * n + x] = (float)(cu / 2 * Math.Cos((2 * x + 1) * u * Math.PI / (2 * n))); + } + return b; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs b/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs new file mode 100644 index 00000000..a8514b3b --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs @@ -0,0 +1,153 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// JPEG coding process declared by the SOF marker. +public enum JpegProcess +{ + /// SOF0: baseline sequential DCT, 8-bit, at most two Huffman tables per class. + Baseline, + + /// SOF1: extended sequential DCT (8 or 12-bit). + ExtendedSequential, + + /// SOF2: progressive DCT (spectral selection and successive approximation). + Progressive, + + /// SOF3: lossless predictive coding (2–16 bit). + Lossless, +} + +/// Colour space of the encoded components. +public enum JpegColorSpace +{ + Gray, + YCbCr, + Rgb, + Cmyk, + Ycck, + + /// No defined colour interpretation (e.g. two-component lossless raw tiles). + Other, +} + +/// Overrides the colour interpretation of a 3- or 4-component stream (TIFF knows it out of band). +public enum JpegColorTransform +{ + /// JFIF/Adobe markers and component ids decide (libjpeg rules). + Auto, + + /// Components are stored as-is (RGB or CMYK). + None, + + /// Components are YCbCr (or YCCK for four components). + YCbCr, +} + +/// Frame facts from the headers, available without decoding pixels. +/// Full image width in pixels. +/// Full image height in pixels. +/// Number of encoded components (1–4). +/// Sample precision in bits (8 or 12 for DCT, 2–16 for lossless). +/// Coding process. +/// Colour space the decoder will assume. +/// Horizontal and vertical sampling factors per component. +/// Restart interval in MCUs declared before the first scan (0 = none). +public sealed record JpegInfo( + int Width, + int Height, + int Components, + int Precision, + JpegProcess Process, + JpegColorSpace ColorSpace, + IReadOnlyList<(int H, int V)> Sampling, + int RestartInterval) +{ + /// Chroma subsampling in J:a:b notation for three-component images ("4:2:0"), otherwise a factor list. + public string SamplingNotation + { + get + { + if (Sampling.Count == 3 && Sampling[1] == Sampling[2] && Sampling[1] == (1, 1)) + { + return Sampling[0] switch + { + (1, 1) => "4:4:4", + (2, 1) => "4:2:2", + (2, 2) => "4:2:0", + (1, 2) => "4:4:0", + (4, 1) => "4:1:1", + (4, 2) => "4:1:0", + _ => Factors(), + }; + } + return Factors(); + } + } + + private string Factors() => string.Join(",", Sampling.Select(s => $"{s.H}x{s.V}")); +} + +/// Options for . +public sealed record JpegDecodeOptions +{ + /// Default options: full size, fancy upsampling, automatic colour transform. + public static JpegDecodeOptions Default { get; } = new(); + + /// When > 0, decode with the smallest DCT-domain reduction (1/2, 1/4, 1/8) whose long edge is still + /// ≥ this value. 0 decodes at full size. Ignored for lossless streams. + public int MaxLongEdge { get; init; } + + /// Triangle-filter chroma upsampling (libjpeg "fancy"); false replicates chroma samples. + public bool FancyUpsampling { get; init; } = true; + + /// Colour interpretation override (TIFF photometric). + public JpegColorTransform ColorTransform { get; init; } = JpegColorTransform.Auto; + + /// Abbreviated table-specification stream (TIFF JPEGTables) parsed before the image stream. + public byte[]? Tables { get; init; } + + /// Upper bound on width × height; larger frames are rejected before any allocation. + public long MaxPixels { get; init; } = 1L << 28; + + /// Worker limit for the IDCT and colour stages (-1 = all cores, 1 = single-threaded). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// Decoded JPEG pixels, interleaved, top-down, Exif orientation not applied. +public sealed class JpegImage +{ + internal JpegImage(JpegInfo info, int width, int height, int components, int bitDepth, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList warnings) + { + Info = info; + Width = width; + Height = height; + Components = components; + BitDepth = bitDepth; + Pixels8 = pixels8; + Pixels16 = pixels16; + Warnings = warnings; + } + + /// Header facts of the source stream (full-size dimensions). + public JpegInfo Info { get; } + + /// Output width (smaller than when DCT scaling was used). + public int Width { get; } + + public int Height { get; } + + /// Output channels: 1 (gray) or 3 (RGB; CMYK/YCCK are converted). + public int Components { get; } + + /// Significant bits per sample: 8 → ; more → with values 0..2^BitDepth−1. + public int BitDepth { get; } + + public byte[]? Pixels8 { get; } + + public ushort[]? Pixels16 { get; } + + /// Recoverable problems (corrupt entropy data, missing restart markers, truncation). + public IReadOnlyList Warnings { get; } +} + +/// Raw samples of a lossless (SOF3) stream as encoded: interleaved, as in the frame header. +public readonly record struct JpegLosslessImage(ushort[] Samples, int Width, int Height, int Components, int Precision); diff --git a/src/Titano.Core/Imaging/PixelConvert.cs b/src/Titano.Core/Imaging/PixelConvert.cs new file mode 100644 index 00000000..4a416d6a --- /dev/null +++ b/src/Titano.Core/Imaging/PixelConvert.cs @@ -0,0 +1,390 @@ +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace Titano.Core.Imaging; + +/// How integer samples relate to light: sRGB-encoded (display referred) or proportional to linear light. +public enum TransferFunction +{ + Srgb, + Linear, +} + +/// +/// Conversions between interleaved integer pixels and planar linear-light s, gray ↔ RGB, +/// Exif orientation, and clamping. Interleaved layouts: 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA. Alpha is +/// never transfer-encoded. Row loops are parallel for large images. +/// +public static class PixelConvert +{ + private const int ParallelThreshold = 1 << 16; + + /// 8×8 Bayer thresholds in code units, centred on zero (ordered dither). + private static readonly float[] Bayer = BuildBayer(); + + /// Interleaved 8-bit samples → linear buffer. + /// 0 = natural (1/2 → 1, 3 → 3, 4 → 3); 3 expands gray; 4 keeps alpha. + public static ImageBuffer FromInterleaved8(ReadOnlySpan pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int outputChannels = 0) + { + var outCh = OutputChannels(channels, outputChannels); + CheckLength(pixels.Length, width, height, channels); + var lut = new float[256]; + for (var i = 0; i < 256; i++) lut[i] = transfer == TransferFunction.Srgb ? ColorSpace.Linear8((byte)i) : i / 255f; + var image = new ImageBuffer(width, height, outCh, clear: false); + unsafe + { + fixed (byte* p = pixels) + { + var ptr = (nint)p; + ForRows(height, width, y => + { + var row = new ReadOnlySpan((byte*)ptr + (long)y * width * channels, width * channels); + Scatter(row, image, y, channels, lut, 1f / 255f); + }); + } + } + return image; + } + + /// Interleaved 16-bit container samples (values 0..) → linear buffer. + public static ImageBuffer FromInterleaved16(ReadOnlySpan pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int maxValue = 65535, int outputChannels = 0) + { + if (maxValue is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(maxValue)); + var outCh = OutputChannels(channels, outputChannels); + CheckLength(pixels.Length, width, height, channels); + var lut = new float[maxValue + 1]; + for (var i = 0; i <= maxValue; i++) + { + lut[i] = transfer == TransferFunction.Linear ? i / (float)maxValue + : maxValue == 65535 ? ColorSpace.Linear16((ushort)i) : (float)ColorSpace.SrgbToLinear(i / (double)maxValue); + } + var alphaScale = 1f / maxValue; + var image = new ImageBuffer(width, height, outCh, clear: false); + unsafe + { + fixed (ushort* p = pixels) + { + var ptr = (nint)p; + ForRows(height, width, y => + { + var row = new ReadOnlySpan((ushort*)ptr + (long)y * width * channels, width * channels); + Scatter(row, image, y, channels, lut, alphaScale); + }); + } + } + return image; + } + + /// Linear buffer → interleaved 8-bit samples with per pixel + /// (1 from RGB takes Rec.709 luminance; missing alpha is opaque). + /// Add 8×8 ordered dither before rounding (breaks banding in smooth gradients). + public static void ToInterleaved8(ImageBuffer image, Span destination, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false) + { + CheckLength(destination.Length, image.Width, image.Height, channels); + unsafe + { + fixed (byte* p = destination) + { + var ptr = (nint)p; + ForRows(image.Height, image.Width, y => + { + var row = new Span((byte*)ptr + (long)y * image.Width * channels, image.Width * channels); + EncodeRow8(image, y, row, channels, transfer, dither); + }); + } + } + } + + /// Allocating overload of . + public static byte[] ToInterleaved8(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false) + { + var result = new byte[checked(image.Width * image.Height * channels)]; + ToInterleaved8(image, result, channels, transfer, dither); + return result; + } + + /// Linear buffer → interleaved 16-bit samples (0..65535). + public static void ToInterleaved16(ImageBuffer image, Span destination, int channels, TransferFunction transfer = TransferFunction.Srgb) + { + CheckLength(destination.Length, image.Width, image.Height, channels); + unsafe + { + fixed (ushort* p = destination) + { + var ptr = (nint)p; + ForRows(image.Height, image.Width, y => + { + var row = new Span((ushort*)ptr + (long)y * image.Width * channels, image.Width * channels); + EncodeRow16(image, y, row, channels, transfer); + }); + } + } + } + + /// Allocating overload of . + public static ushort[] ToInterleaved16(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb) + { + var result = new ushort[checked(image.Width * image.Height * channels)]; + ToInterleaved16(image, result, channels, transfer); + return result; + } + + /// Encodes row into interleaved 8-bit samples (codec edge helper). + internal static void EncodeRow8(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer, bool dither) + { + var w = image.Width; + Span offsets = stackalloc float[8]; + if (dither) + { + for (var i = 0; i < 8; i++) offsets[i] = 0.5f + Bayer[(y & 7) * 8 + i]; + } + else + { + offsets.Fill(0.5f); + } + var srgb = transfer == TransferFunction.Srgb; + var colour = channels is 1 or 2 ? 1 : 3; + for (var c = 0; c < channels; c++) + { + if (c == colour) + { + var a = image.Channels == 4 ? image.Row(3, y) : default; + for (var x = 0; x < w; x++) row[x * channels + c] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[x], 0f, 1f) * 255f + 0.5f); + continue; + } + var src = SourceRow(image, y, c, colour, out var luminance); + for (var x = 0; x < w; x++) + { + var v = luminance is null ? src[x] : luminance[x]; + var e = srgb ? ColorSpace.EncodeFast(v) : Math.Clamp(v, 0f, 1f); + row[x * channels + c] = (byte)Math.Clamp(e * 255f + offsets[x & 7], 0f, 255f); + } + } + } + + /// Encodes row into interleaved 16-bit samples (codec edge helper). + internal static void EncodeRow16(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer) + { + var w = image.Width; + var srgb = transfer == TransferFunction.Srgb; + var colour = channels is 1 or 2 ? 1 : 3; + for (var c = 0; c < channels; c++) + { + if (c == colour) + { + var a = image.Channels == 4 ? image.Row(3, y) : default; + for (var x = 0; x < w; x++) row[x * channels + c] = a.IsEmpty ? (ushort)65535 : (ushort)(Math.Clamp(a[x], 0f, 1f) * 65535f + 0.5f); + continue; + } + var src = SourceRow(image, y, c, colour, out var luminance); + for (var x = 0; x < w; x++) + { + var v = luminance is null ? src[x] : luminance[x]; + row[x * channels + c] = srgb ? ColorSpace.Encode16(v) : (ushort)(Math.Clamp(v, 0f, 1f) * 65535f + 0.5f); + } + } + } + + /// Single-channel buffer replicated into three channels. + public static ImageBuffer GrayToRgb(ImageBuffer gray) + { + if (gray.Channels != 1) throw new ArgumentException("Expected one channel", nameof(gray)); + var rgb = new ImageBuffer(gray.Width, gray.Height, 3, clear: false); + for (var c = 0; c < 3; c++) gray.Plane(0).CopyTo(rgb.Plane(c)); + return rgb; + } + + /// Rec.709 luminance of an RGB(A) buffer. + public static ImageBuffer RgbToGray(ImageBuffer rgb) + { + if (rgb.Channels < 3) throw new ArgumentException("Expected RGB", nameof(rgb)); + var gray = new ImageBuffer(rgb.Width, rgb.Height, 1, clear: false); + var r = rgb.Plane(0); + var g = rgb.Plane(1); + var b = rgb.Plane(2); + var d = gray.Plane(0); + var i = 0; + if (Vector.IsHardwareAccelerated) + { + var wr = new Vector(ColorSpace.LumaR); + var wg = new Vector(ColorSpace.LumaG); + var wb = new Vector(ColorSpace.LumaB); + for (; i <= d.Length - Vector.Count; i += Vector.Count) + { + (new Vector(r[i..]) * wr + new Vector(g[i..]) * wg + new Vector(b[i..]) * wb).CopyTo(d[i..]); + } + } + for (; i < d.Length; i++) d[i] = ColorSpace.Luminance(r[i], g[i], b[i]); + return gray; + } + + /// Clamps every value into [, ] (NaN becomes ). + public static void Clamp(Span values, float min = 0f, float max = 1f) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + var lo = new Vector(min); + var hi = new Vector(max); + for (; i <= values.Length - Vector.Count; i += Vector.Count) + { + var v = new Vector(values[i..]); + // Max(v, lo) with v as the first operand maps NaN to lo on x86 (maxps returns the second operand). + Vector.Min(Vector.ConditionalSelect(Vector.Equals(v, v), Vector.Max(v, lo), lo), hi).CopyTo(values[i..]); + } + } + for (; i < values.Length; i++) + { + var v = values[i]; + values[i] = float.IsNaN(v) ? min : Math.Clamp(v, min, max); + } + } + + /// Size after applying an Exif orientation (5–8 swap width and height). + public static (int Width, int Height) OrientedSize(int width, int height, int orientation) => + orientation is >= 5 and <= 8 ? (height, width) : (width, height); + + /// Applies an Exif orientation (1–8) into a new buffer; other values are treated as 1 (copy). + public static ImageBuffer ApplyOrientation(ImageBuffer source, int orientation) + { + int w = source.Width, h = source.Height; + var (ow, oh) = OrientedSize(w, h, orientation); + var result = new ImageBuffer(ow, oh, source.Channels, clear: false); + if (orientation is < 2 or > 8) + { + source.CopyTo(result); + return result; + } + for (var c = 0; c < source.Channels; c++) + { + var src = source.Storage.AsMemory(c * source.PlaneLength, source.PlaneLength); + var dst = result.Storage.AsMemory(c * result.PlaneLength, result.PlaneLength); + if (orientation <= 4) + { + ForRows(oh, ow, y => + { + var sy = orientation is 3 or 4 ? h - 1 - y : y; + var s = src.Span.Slice(sy * w, w); + var d = dst.Span.Slice(y * ow, ow); + s.CopyTo(d); + if (orientation is 2 or 3) d.Reverse(); + }); + continue; + } + // Transposing orientations: copy in 32×32 tiles so both sides stay cache-friendly. + const int tile = 32; + var tilesY = (oh + tile - 1) / tile; + ForRows(tilesY, ow * tile, ty => + { + var s = src.Span; + var d = dst.Span; + var y1 = Math.Min(oh, (ty + 1) * tile); + for (var x0 = 0; x0 < ow; x0 += tile) + { + var x1 = Math.Min(ow, x0 + tile); + for (var y = ty * tile; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var (sx, sy) = orientation switch + { + 5 => (y, x), + 6 => (y, h - 1 - x), + 7 => (w - 1 - y, h - 1 - x), + _ => (w - 1 - y, x), + }; + d[y * ow + x] = s[sy * w + sx]; + } + } + } + }); + } + return result; + } + + private static ReadOnlySpan SourceRow(ImageBuffer image, int y, int c, int colourChannels, out float[]? luminance) + { + luminance = null; + if (image.Channels == 1) return image.Row(0, y); + if (colourChannels == 3) return image.Row(c, y); + var r = image.Row(0, y); + var g = image.Row(1, y); + var b = image.Row(2, y); + luminance = new float[image.Width]; + for (var x = 0; x < luminance.Length; x++) luminance[x] = ColorSpace.Luminance(r[x], g[x], b[x]); + return default; + } + + /// De-interleaves one row: colour through (indices clamped to its range), alpha scaled. + private static void Scatter(ReadOnlySpan row, ImageBuffer image, int y, int channels, float[] lut, float alphaScale) + where T : unmanaged, IBinaryInteger + { + var w = image.Width; + var top = lut.Length - 1; + var colour = channels is 1 or 2 ? 1 : 3; + for (var c = 0; c < image.Channels; c++) + { + var dst = image.Row(c, y); + if (c == 3) + { + if (channels is 2 or 4) + { + var a = channels - 1; + for (var x = 0; x < w; x++) dst[x] = Math.Min(int.CreateTruncating(row[x * channels + a]), top) * alphaScale; + } + else + { + dst.Fill(1f); + } + continue; + } + var s = colour == 1 ? 0 : c; + for (var x = 0; x < w; x++) dst[x] = lut[Math.Min(int.CreateTruncating(row[x * channels + s]), top)]; + } + } + + private static int OutputChannels(int channels, int requested) + { + if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels)); + if (requested is not (0 or 1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(requested)); + if (requested == 1 && channels > 2) throw new ArgumentException("Use RgbToGray to reduce colour to one channel", nameof(requested)); + return requested != 0 ? requested : channels <= 2 ? 1 : 3; + } + + private static void CheckLength(int length, int width, int height, int channels) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels)); + if (length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small"); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ForRows(int rows, int rowWork, Action body) + { + if ((long)rows * rowWork < ParallelThreshold) + { + for (var y = 0; y < rows; y++) body(y); + } + else + { + Parallel.For(0, rows, body); + } + } + + private static float[] BuildBayer() + { + // Recursive Bayer matrix: interleave bits of (x ^ y) and y, least significant coordinate bits first. + var m = new float[64]; + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + var v = 0; + for (var bit = 0; bit < 3; bit++) v = v << 2 | (((x ^ y) >> bit) & 1) << 1 | ((y >> bit) & 1); + m[y * 8 + x] = (v + 0.5f) / 64f - 0.5f; + } + } + return m; + } +} diff --git a/tests/Titano.Core.Tests/Codecs/CodecTestData.cs b/tests/Titano.Core.Tests/Codecs/CodecTestData.cs new file mode 100644 index 00000000..3f637bd4 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/CodecTestData.cs @@ -0,0 +1,167 @@ +using System.Text; +using Titano.Testing; + +namespace Titano.Core.Tests.Codecs; + +/// Shared fixtures, synthetic images and image metrics for codec tests. +internal static class CodecTestData +{ + public static byte[] Fixture(string relativePath) => + File.ReadAllBytes(Path.Combine(TestContext.FixturesDirectory, "codecs", relativePath)); + + /// Netpbm P5/P6/P7 (PAM) reader for reference images; samples are big-endian when maxval > 255. + public static Pnm ReadPnm(byte[] data) + { + var pos = 0; + string Token() + { + while (pos < data.Length && (char.IsWhiteSpace((char)data[pos]) || data[pos] == '#')) + { + if (data[pos] == '#') while (pos < data.Length && data[pos] != '\n') pos++; + else pos++; + } + var start = pos; + while (pos < data.Length && !char.IsWhiteSpace((char)data[pos])) pos++; + return Encoding.ASCII.GetString(data, start, pos - start); + } + var magic = Token(); + int width, height, channels, maxVal; + if (magic == "P7") + { + width = height = channels = maxVal = 0; + for (var t = Token(); t != "ENDHDR"; t = Token()) + { + switch (t) + { + case "WIDTH": width = int.Parse(Token()); break; + case "HEIGHT": height = int.Parse(Token()); break; + case "DEPTH": channels = int.Parse(Token()); break; + case "MAXVAL": maxVal = int.Parse(Token()); break; + case "TUPLTYPE": Token(); break; + } + } + } + else + { + channels = magic switch { "P5" => 1, "P6" => 3, _ => throw new InvalidDataException(magic) }; + width = int.Parse(Token()); + height = int.Parse(Token()); + maxVal = int.Parse(Token()); + } + pos++; + var samples = new int[width * height * channels]; + for (var i = 0; i < samples.Length; i++) + { + samples[i] = maxVal > 255 ? data[pos + 2 * i] << 8 | data[pos + 2 * i + 1] : data[pos + i]; + } + return new Pnm(width, height, channels, maxVal, samples); + } + + public sealed record Pnm(int Width, int Height, int Channels, int MaxVal, int[] Samples) + { + public byte[] Bytes => Samples.Select(s => (byte)s).ToArray(); + public ushort[] Words => Samples.Select(s => (ushort)s).ToArray(); + } + + /// Deterministic RGB test card: smooth gradients, saturated colour bars, seeded noise and + /// text-like one-pixel strokes (the four content classes codecs struggle with). + public static byte[] TestCard(int width, int height, int seed = 1) + { + var rng = new Random(seed); + var rgb = new byte[width * height * 3]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var band = y * 4 / height; + int r, g, b; + switch (band) + { + case 0: + r = x * 255 / Math.Max(1, width - 1); + g = y * 4 * 255 / Math.Max(1, height - 1) / 4 * 4 % 256; + b = 255 - r; + break; + case 1: + var bar = x * 8 / width; + r = (bar & 4) != 0 ? 230 : 25; + g = (bar & 2) != 0 ? 230 : 25; + b = (bar & 1) != 0 ? 230 : 25; + break; + case 2: + r = rng.Next(256); + g = rng.Next(256); + b = rng.Next(256); + break; + default: + var stroke = x % 7 == 0 || y % 9 == 0 || (x + y) % 13 == 0; + r = g = b = stroke ? 20 : 235; + break; + } + var i = (y * width + x) * 3; + rgb[i] = (byte)r; + rgb[i + 1] = (byte)g; + rgb[i + 2] = (byte)b; + } + } + return rgb; + } + + /// Smooth photographic-like content (low-frequency gradients); compresses like real photos. + public static byte[] SmoothImage(int width, int height) + { + var rgb = new byte[width * height * 3]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + double u = x / (double)width, v = y / (double)height; + var i = (y * width + x) * 3; + rgb[i] = (byte)(127.5 + 120 * Math.Sin(6.1 * u + 2.3 * v)); + rgb[i + 1] = (byte)(127.5 + 120 * Math.Cos(4.7 * u * v + 3.1 * v)); + rgb[i + 2] = (byte)(127.5 + 120 * Math.Sin(9.3 * v - 1.7 * u + 0.5)); + } + } + return rgb; + } + + public static double Psnr(ReadOnlySpan a, ReadOnlySpan b) => Psnr(a, b, 255); + + public static double Psnr(ReadOnlySpan a, ReadOnlySpan b, double peak) where T : struct, IConvertible + { + Assert.Equal(a.Length, b.Length, "sample count"); + double sum = 0; + for (var i = 0; i < a.Length; i++) + { + var d = a[i].ToDouble(null) - b[i].ToDouble(null); + sum += d * d; + } + var mse = sum / a.Length; + return mse == 0 ? 99 : 10 * Math.Log10(peak * peak / mse); + } + + public static int MaxAbsDiff(ReadOnlySpan a, ReadOnlySpan b) + { + Assert.Equal(a.Length, b.Length, "sample count"); + var max = 0; + for (var i = 0; i < a.Length; i++) max = Math.Max(max, Math.Abs(a[i] - b[i])); + return max; + } + + /// Seeded corruption: the input truncated at points plus single-byte flips. + public static IEnumerable Corruptions(byte[] valid, int cases, int seed) + { + var rng = new Random(seed); + for (var i = 0; i < cases; i++) + { + yield return valid.AsSpan(0, rng.Next(valid.Length)).ToArray(); + var flipped = (byte[])valid.Clone(); + var flips = 1 + rng.Next(4); + for (var f = 0; f < flips; f++) flipped[rng.Next(flipped.Length)] ^= (byte)(1 << rng.Next(8)); + yield return flipped; + var garbage = (byte[])valid.Clone(); + garbage[rng.Next(garbage.Length)] = (byte)rng.Next(256); + yield return garbage; + } + } +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs b/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs new file mode 100644 index 00000000..d161083c --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs @@ -0,0 +1,79 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +/// Decoder output against libjpeg-turbo's djpeg (accurate integer IDCT) on cjpeg-produced fixtures. +public sealed class JpegDecoderTests(TestContext context) +{ + [Theory] + [Case("b444", "4:4:4")] + [Case("b422", "4:2:2")] + [Case("b420", "4:2:0")] + [Case("b440", "4:4:0")] + [Case("b411", "4:1:1")] + [Case("p420", "4:2:0")] + [Case("p444", "4:4:4")] + [Case("r420", "4:2:0")] + [Case("r444", "4:4:4")] + public void MatchesDjpeg(string name, string sampling) + { + var data = Fixture($"jpeg/{name}.jpg"); + var reference = ReadPnm(Fixture($"jpeg/{name}.ppm")); + var image = JpegDecoder.Decode(data); + Assert.Equal(reference.Width, image.Width); + Assert.Equal(reference.Height, image.Height); + Assert.Equal(3, image.Components); + Assert.Equal(sampling, image.Info.SamplingNotation); + Assert.Empty(image.Warnings); + var diff = MaxAbsDiff(image.Pixels8, reference.Samples); + context.Log($"{name}: max |diff| = {diff}"); + Assert.LessOrEqual(diff, 2); + } + + [Theory] + [Case("gray")] + [Case("pgray")] + public void GrayMatchesDjpeg(string name) + { + var image = JpegDecoder.Decode(Fixture($"jpeg/{name}.jpg")); + var reference = ReadPnm(Fixture($"jpeg/{name}.pgm")); + Assert.Equal(1, image.Components); + Assert.Equal(JpegColorSpace.Gray, image.Info.ColorSpace); + Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, reference.Samples), 2); + } + + [Test] + public void ReplicatedUpsamplingMatchesDjpegNoSmooth() + { + var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { FancyUpsampling = false }); + Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, ReadPnm(Fixture("jpeg/b420-nosmooth.ppm")).Samples), 2); + } + + [Test] + public void ReadInfoParsesHeadersOnly() + { + var info = JpegDecoder.ReadInfo(Fixture("jpeg/p420.jpg")); + Assert.Equal(61, info.Width); + Assert.Equal(45, info.Height); + Assert.Equal(JpegProcess.Progressive, info.Process); + Assert.Equal(JpegColorSpace.YCbCr, info.ColorSpace); + Assert.Equal(8, info.Precision); + var restart = JpegDecoder.ReadInfo(Fixture("jpeg/r444.jpg")); + Assert.Equal(5, restart.RestartInterval); + } + + [Test] + public void AdobeYcckIsConvertedToRgb() + { + var image = JpegDecoder.Decode(Fixture("jpeg/cmyk.jpg")); + Assert.Equal(JpegColorSpace.Ycck, image.Info.ColorSpace); + Assert.Equal(4, image.Info.Components); + Assert.Equal(3, image.Components); + var source = ReadPnm(Fixture("src.ppm")); + var psnr = Psnr(image.Pixels8, source.Bytes); + context.Log($"YCCK round trip PSNR {psnr:F1} dB"); + Assert.Greater(psnr, 30); + } +} diff --git a/tests/fixtures/codecs/jpeg/b411.jpg b/tests/fixtures/codecs/jpeg/b411.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7331b1e5c601901df5aa4f3e685bc9fa5f23aaa0 GIT binary patch literal 2169 zcmbW!dpOg59|!Q??BL9nY|extNrlKFH?kViqnZ$j4r0V+nTicbMrh<1w>w%AI$#cW zVs4Rjk|9jUIZ;kwj=y{Axt`~`p1+>wd4I3(=b!KA`@KG|>kD>)p8=#D4vzyM5CDJ( z7XbDEHUJDNjL1fX!C-KN1OfqvBc#N{MI~gUWMyQeq@`t1XgOJ=JW5(xPDxH4qoAm$ zD7#5nRarq5t)Qr|@d!kC6#+*`A`p@aNNJ?P{~VA5pu~WkfCUs{1&E*^P!t4w38)L_ zghPG?_-7y@P~niGV&W2#!Ui@H5P|%h9u9}Wgx%r7a{z{dZ`!iQ3L)p@C8|l$J9!H#tgN0xeW1ZQZ7$yIs$CuZihCGpx-)Til_;c)Q~#2+k*6T;0x| zJAc9FqOV^t<#Gr$^vc!i(Kljl#xmlPQ|_durDtSj<>lXJJt%ls_^7n3oLx~_RsH8* z4KEv;UNv)H^V-@wK6Z9>^9KfphDS!nzKnmJnVtJFzpyA+THbI$0O&84u>OMmhYKZi ziNIh`nCONJB0?2zC<+GOvInur%1P9VB&TT@DYn^~dGA@hxR%keX?bsQs{~rxcwp4O7cr%Y?39mrDv7rqb6AjeBz4&;L%` zd33x_ZqNcqL5%%*6OO=fy{#TFCxXakOtlPuP_loiH6yQm6e91Iu`GHtk+G>NK}%%AS{KW&PUFHK$0^%CTSpkqMTjYNx7TZ zzu!CNyJ-lA%MsOyI1*U@nMe&P8YxrbMET8z!hajx1sEdOZkuV3s}>FzSZ!A1x=E0@u(T zYsa(cq8cC|vulna(21o_g&v)uJw0%_TsV`!av~1|u=BY$a%Y{(b5{aDAn$Z-4i5x| zcVLEA6DWkGTFZ5uqUl;_5eTr#mOC5O7vpHTg-ggV$-&m*1{U4h@zPj)OX6O=V6{`D z&HJFk+R32`7GgT&{(~Kli`m2~%F1;_O5@}Wli0+;s<9~~AyP7VcQCIu#S&Sg=tU$x z>Lq@hxHxaj!k0?Y1rr#zpR+t{d|7BuZ`Vv z6`xcNtO#&4Dj&M{q_xbfsoXI3IF*9ldSZPdCp#>Mcg^$ddeD%8%)2=iXEhf$^Vgd? z`{LNuo~{Or$Z8Af8m4gtW^VYU1}S{#XA4%hAqGjB8Z@MU=tdA3&!#kJxmO{HJB zW@2DCoc(srd(!m}QB;4LahPGd!Q-7Jt4>Ns0+USk$Gd($&poq`qS{fXCkQ)zicysC zM$g*xM4{cL4&UwXs!HbTQh5_+m(>$zjOVWY=!4IFsj1a@u<%Jh9^@bXF|npJak!#} z*}fyR${gl920e%Sj4JncNk2o;`KJ9D-Q$`@GDt7zS7fnUH7f{e4j*#*v^)m75PPm` zFf}FaImGn^aW6^wTLnw!~^;Zw{>-s>?hkh68Q_AcTX-n z;nJRa6r61$vexNIrfV;z*PnQ28@XSc)z1oNzbLZ}x(k!btQ*ie$pM<{;UCC7(Pt`` zCui|zDsGkWPy2;n<#UEjLwqF!E@>y)x-*j4#-dk?suLs<@vK60&_FLBDlW&VPeKpM|3EGhwmiq$;Fi6C%`#k?|V_DLs4ex>?l;1pe1_4I3 z(>q=cx5_M_o4eBYsaMIa#8!;=ZQy7o&-?_E!hynaSjz5N|`n>HEP zQx$Ed{e16{LcIKwTPgL-m#?fULtKjcth?`MKQ7zz{j2veF-fjj^M0ZorNb`q?ic>N zogO}nRkC=^LV{%H9#3S?+Go{Xtt8p|Q8Dpl*K#2P{%I%;_YG#`NqA}iWfoJ|Kt$SvQPD_mXfKemwz!e`%PTl4Z z1mSR0x!X!_z@15~UF_!EtcTzB_V?9=A864%9#y2~u1QtM`adBN$pAL5a4Tgr^ A&j0`b literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b411.ppm b/tests/fixtures/codecs/jpeg/b411.ppm new file mode 100644 index 0000000000000000000000000000000000000000..e05451f934756db614eb5e00da121ae3b9459c77 GIT binary patch literal 8248 zcmeI!_fu0_+c)rqM?sMi0;EGi3B9*a6_An;iZp>FC|yKI0HvvP5J81d#EwW;R1guc zi-=f`jUq@d3B9Nk^_+8`yz3d~@%bCxnS16l-}(NwueoNez4vYtQ4@WVk+G5G5s!UJc}}!LsRAl3BpTvUVlJ8lT%rVCHVrB>3%+UMbc;fV8cdy^8k@J9SUjUxc9>dq8*4#5 zCfdCeohf5Eo{2o4LWI5}bF2tr5a%e@#j+rUctW;Vy zRN%o;z9fIO;&XRNX$B z9?wypPbE&%NYI+&c4(a{wm}mY(7+bI@4}29kO=dqG-FuR92qTCW-CNvwfQot{Fv1YRt*&C$BkkXLTqNyF~7`YMpg# zbV80%%~bYXh{kF0jjHftS28$N%;@UK$o#0N0*KA#9*Ign%FZ~($xM#UIvvG^^4XjM zPV@!NzKhWTmtq2;n;a+TRy4gK#`y``>?y~*J=y~L5T)^vtqFB=v?d}6lTmV0YT*gqT~lKcbOn(}j7>R+-c3#imZblMW6p4_jIGN76I8L~*}ge+5E zSfzD2rL;oy)Hdg|d(4y?R%)$(S{=kr=0cp5!syhZl;q6Rl&rMWY^Wfa!%c}UOpSrc zQiGr?X~E^`A&n{Y+o{e?X)aJliUssM)v`0qsyA61>Pyl2l&Z^1mglDsr&CGLda@X_ zks|&*RYH&oHl106{wQ7Fe0BqMhKDZYLzuJES_K~3M~D$4?)JP8Ejd7e^G79E5q98+@fG z6uMLpboZ>=EiSdO$f==__9&0q!F7FJ=mzs+3FSkv$-6?Mw_L;FLYdKG)L036{0wH5 zi&-ngLhD61!5JWVK>#5x{twiZ8Fcw9=IR`zQ_%zIR`x>=e`LXr!@eM~fb%$Untk_#p9eAcD2GlLc6WtxPbImxO660H+Eg`(SEInMRfPGq z9P#a{)M^ECtx{T00sgov*xd3zwzLYw9!`lr;z>N_LmEwkzi8eW(rxb1yW9JVTf;4n zrrVx(nqYb~*Lt^J_qlh&_x{beJ9SWe^R?K<>V&rVr2C0+Er*jIA4|J;IO9Ql=EDT2 zs5PSGUS#P5_SuJ=x<*E0TTo@a_l@Sg4{uvNy=(KVbyr85-Md!8`!=}`_vE`DkS6YJ z`|Vrn7HG9ic;39pa;(#pS^Lt-{J7|mGhgY)*m|UUp?OOu4C8WOO4+qUZSR6 zV|Z_{({J%Bo#-zwFkic{-(KSWehY*~zC)WvfBZ4_bNj@c*yOzU)B>dZxtl!LqcYU1 zI^3r{@pVLlGx#vyphEDN3E)9oV9tnkcaVYraC)0)j^Sh(g&2Tr}23@kdBAV~XGU6rj~lifjE!f)Rk4`T?PNKQa8ju(Qj!xfT5U z7sA3<(()vvurj6ig=f6@!DQ(pWw{%2U1)ZmYl2`2oxSu+*xcnqE2lXNxlr8Kf|%u` zsQI|W^|YfuGLL_a&i=xIa=yi!S&I9mbUD6Z!?kwV;pUq2jaB-?C5NY9ogS}H?=RTB znYDhmuh&|oIG1=CV+d+*;BP>`S|TyP`e@6zy}C6WI*7b_^sUX9QDarCU< zM9z9*(O>CM@!uIG|72bkctKYMzO{nAxBlLD{W}w8vmo@LVCS8mCa(o9E&rIk5=g%m z$owfly%ER`{s%YoFMdowoDe9i|10&&h5#w}E&&uxej{Nee^Ww#{!LbH{5RBuE_zZA z%QJwaC-or0f|<(tF167O)sc0T;Wb!xzwPqvd++%C@s^BZi!$gXSFqDv_8IlZA^4<@W{kO`ohA=)zxDD?8I-A z^CLJM=Ko;jasP{e<^6`iPyU9V#zBM`JdTgWPPm{(ozP=+-S5FT{v=_B2f-5f=GESp zF9Ke_6iK6W{1uqWme^gbJDVl zD9jMvr&nh8Fu`|OCt@D)&pKW(EAiJN^4~|E4)@$_1&x)0hKkVz^!O4M=FqIn;6V29 zV9xAx@!Gd53ln4WR!dGs6^l@kkQ+de$Dyt0 zZZXYXXq(!{t*Rdg!?LO~B;puGX^McGbwKfKB}Xju{$Y84kJ0NfZ=N@u1H8uqcJN;>3I}-nK*|h%@go^G%T1tFLbXbX@sS>6p5Xh z!SQBQzO11q_{rT*BA(pX|L__qE@*@(HA+Gb5+tC0DYr=iV+8HJt{b&N+L*yCPotM6 zkh6DK)(yUvf|d)=>aqfF47o6ko#Ua0do%mrr+k?`yRm$Ec4m>!o12?mnwef$oms%i zN)d4=JPN6*D38ahB9ZbkG9(;MMM8E?mheRyw+xA4CkX0arAf00Ik?izGE1UT^CE~j zVZvv+DsK<2pJw^%T@!ZvwTvKpG!S8X1aT`*wO` ztze8dIx#&y&L4v(WNK z_UL01(y}vH{G<$OL5?_t+%tw^Ok(|)l*7LgW|uI$dD)3&EdQ>n<71!Qf`&T5t=gqU zy{SnRh&QD=K60$T_t47X$?t2$^NTYOe`a!KjyK91Kx2^dL@Wj?4JneyIE);G$I8n~ z50PX?AVu^T4m~N4pT@|JE6C5OPni-vX)28vsEiwfQT5HUhFcdYM1ia3_=3{F6sd1q zb$G`6&0F`bSBwwcATEKYi5gT88z72~C`%4V+YF=a$8gkd+RS+pZyYr^Ci{6tZsNMT zPrZk);O+xK>!axj^5lrZ%%sZ7yw0b=1LM3ytKW|=eo5`0=k-jF|H`E`UX@kNN#)aj zhQ8YYtOJNno=B@`T}D-KzP|;_mSiIjjyr`rD&Q95=A*pq3-oJ@Q&a_Bp@9 zuWIX5w+J8h@HCV{p4KkNCg)tE)t8!_a{zK|y#3RtvsYac%MO+hfvg4~8347P{h1lCqQ0d#15G@Yuzy6pRq?u{LMg z?HD-m==G6?%PtwdTdfimV$Fe3jazwvY3@FIstf>uj!ueOx1ZN7zU^2)9Q(-zSoq@2 zgUEI-PhNkXQ&V~2ii(_~zM8g{lGa2v?2xmu8L(9h<8&rUsg;rFJU#pH9HKCcUv zO6>qm{|`G&u;Zvpez^J30OJ7dP1^E6-U07$9Dj6>^ZwP|$DV*{3*6}E9oAy>p1ObG;AtJ8;I3$=1W;{$#nU(I9LGkxbo(^{Fkf=Zjq9LP(CL0B-~ICQ?3h1T?jJ z)x_`BvsMEzZ=TtoWR#U>e}*o+#}YWkBSI>z3U4}IEYeDgjz(E209OO?-A0o4E+<|I z$$GQo1HH0LM7T0B)yV(M(l zV&J_>t3W%fqTs&*C2Vi0;+_suwJ|o%N5W=3QQ*M2JDsy-&b>NV6q}^8K9Qyu~ZU@i!#rc{TnPX6{S{lw8 zYL&Rpt*)I(h@2X$<{iMKOx zR+s~xIt)AF`=F^(_3PP~^SeQa6IM$dY=3;Zyf!}fR1C|)8cS&+rq$-AoY~>p<+ifM=goFa5!YKe4K*jT%;eEjZ54YBrQ0rz z8S?4V8GLuJ`=oQiDVM}39luNdC)%#YB?K5*s{;xNTr|j)nYt`{>}Aukq4?oek2VWnsR8i&6@AZn=ALp)4sf7YC?L&<2v~AO zngX0PBlZ}}Z38V8>F?sIN3-vG0nGprO6WF^>Aar%duy-S=i93}YKUuL04~Ha>{U)> zu48b4%K?||s$PKJQ_lZ7|M*T4JR?L%fBenitq1A49cnL3TqMuW0??eiuoC^L2J zpDOO*za!FaQ@WWf~O~(j_Lzt zGoTfRw|U7fnK^yuP0U$86UD>sR_;2u(-C_T48mV#-m?VSTzYyEntR!zIZy2>SEts2 z0irA%^uRVvu=!F%Tvd2Yp?9(UHb*}>rZF(TU~}b$=k1yN#Q;66W6o3$MfohR-N&i^ zy`}X>tvnpJ$y0#s1LliI{x9q4Etayvp*wU_eQ8I%>^WNdirg|-Sm!7We+Hn8#NO`- zZ+zx+1%n10wz0AjsH%)8a5#NxS6;mKVH>cs-mLBct*u0{uu{K#hbF<(T0g>v%3-;b z?oEo{;g`QBMjIepfO`?4w0TF{Qo`53P|O3)&7p#~?=#!|#OYQ*KF1-vBclrL>SlVp zEo!?xR>DSB^rTKx0Iy?ZtIg^Nd0`~dZH06j72on0f}t=_(JYn);$q!n)*@Zd;wXI4W!H#UT(Ng)6W(xz&Yw!X00Q*u|lK{#8BK@~Pi zFb+PT>Rp^2q$vlo;ynXAbeFP!l$+Lb)h@y>S}18xoL(5bN_qB2vm*Rhw)zZf-9Sf^ z{@9kc;WrAkq6;+GPFpMwC^Ikn7PQ3F#e1-o0YQ5kSyM!*=g2@a^Iom%4L`8A*!S=r zJmr{;fBW%@>&GKcg}W*MKvxxC2p<@WZdyutTBsNj0j!LGxjvxuUl^$ft$TQ>&G!P5x7`c4S_7pR4X<9t)zU zgt%BLZg(}3t8~5yeMowF-nNh~zQg7ZqX)^ivK$fut;mU9mX1o>kNWKF)O_{-0L5jv AM$BX3af08il!fraX7I>aQv(GZp|nKsAdbPu1&F?-`frvQ^!Vt#g8UITxX7EqsFo1)^+@#PD8nmp zs59~CzfzEOn^DK}kmXxYhl`Q>cA)l`B6saU?XE!NLdOiUYY{n325HTR^h^31p&R;9 zP`iH69fRO|2*3MC{|9J4=q=LW9m=r}W%mhf&qrAb&{lE;U4djw>l0=Sh(8TbzYu6O zLJzQKA#L+7^I20UmK@Di;LV2#ES?Gby{Sbno84_;@yvmJ-_hcME4v-?Hopb=nz#6| zu7{dm2xDE0H9xtA)sSdj38kAK$Y34Z!rHl&T~fd*EMyn$VW;o4$T(z?_=jau4LjzT zMQk%G9QvCPc-1WEHr=a@;r)>5*lEsrVnK&`%vsO}bJLG3`Vfma%qEFhNC_J?#@2*p z*kINIe768Pj%o;P|HIJXC(&VwW)t0R8`EhW@W>|cg`L|=`z1Xb>$eMR`t2Pcp1l>{!CLBICUay? zI1-_+jz~!DsHx^?sW|{}Rgi|iRFf++;PMdx0weBch{*jw3iwD5=wSrDwdOvv33$%o zK3WjawJhLo$cKAwWx)Ah|N0Q_$u<7f&<4LFP>OHaX20@mzXLh`2eY(tN;E2Y+RZT&wuW;S}4p@GRyZCm1+g(4`d;W{x_?khzzO)a1 zCjI`n0WMzXkAReZ^PvepjY)sa8GnuWk^ksKeMLk}A|t=xA{F>3B`s12F{Aj9byUAi z^ni2ZdzYx*C6TX|M!jAY)wVjiJt(pzIO=+A#Mw2G=aM2Cp|tQ5=@Iq0VaM{qYYW4V z7DZIQ*$B+{2;`4QlsWq9lDs4k``o_A<=;K*2jaebkxlDiPYKG6X z%$02!9_^Vc9%L?qo@LlS&vba5$$pb%(U(R3luhC1AOyKcMfMzJ&fLiy@Ff@glLPd& zsv*o)HFletylsZEeU`ah30ZF!+T@Fzw)aCz3tmFr`Hy@Gx_k<|q2Pi$A%z`r`4{60 zE+rQi#vZ~hQHMjk%F8Wnoh(1~u zTXkZ6<)~VW%sJQ9v!pmtg(GoXWw0G_q>|@tcvxnlGIyG;Z*mDbNn4bZHHG)~Px$YvSpl$_Wkgv?J#AiE|$w6N*zqULwYo1Q|e z8XovHKZXQgyMg!MVGB!J9_so+g(M zO`N_{PJ&aGBd4uY&GgYG)9I5&GY!VS>JjRbNc9PQ&@m0}&S>2gYu}TgJ3boT?IU)) zhiGlTv0GnT+jCHXL)Tl^pryB3mbc&ZyM500*4glzHBqtj-ue^w0_*PwoxZ*J(t{P}uUfaX zIo-Z#-_f?9v(5QYyUXJ{)F&OZ7k4PH?$SPV5FlO~3R1Suho;)VbUXOB9cXv`fDn&W z$R}fju3_S19=&S-vVOvcoVx~H9uK)ce!cw3o0X66uX^%e^`m>fUH8K~TcGt1Pi=g3 zCb_d2itjkS`N^5=rzcY%9xLuVP}*Hy-dS|`QSpH%B?q7GD(^0UYP(a9KTkjVEC#y% zbangdppHk&I-hwxd9?IJ_loZOZm+tQ_dd6QK6P6{yeAAnH*@p}WvrVv(`7jO81t)3 zNBvk={a9mupBggw`~}fJg&Q2f4+$y5LlCupkTx)6Ht?A_*l#`DZNq!EfPdRb(6(G~ z$DQB4diatb|4KOjbcEncxS%nN-w?!a3=^G>71pc~9or(>y;WRVI+VQQ)5cOk>Tdq# z1H8CHg7sA+;nl*3hT(vdL)=rJR-Wl!eTDCPnYa4<;G!0>$0a_eP38V-(Dd~X{r!+x z?=Z7}&~#vkF65EL0;+5X38{E<$N2NUi~vJ{8o~*G;6*=8#7a}isJT?al1Z(ka>!mP zc92OHDtZ?wKe&%}L8}#AD`lO*k{hA2*0r)rzsb+7Q=DHvd2Oxga>8ii<}ZJ3m+s9I z?y691sZ?z*Q*QZFk#|&{Ql(677>$F@%c3sGqua*TUXz5kk4Cg9!`oG>?@e+$CRW@Y zUDhYD>X+N{6%GQWqeNySmRc($45id;T26w#DG~pUB7dspL=1k0q6d3ohTg^vzJu0( zl5F@aP3TiYN$=I0dev#~e#?BX&gxaKP#1cr3;fmj0qVjqbtx3CZi-c(4N~6?_;n}d z$Mbk~Pv*qkyqV7G@AvmA|DJk$6#C~y?$?)jKc1yS>dwE^-Ivt2L_e%BbRs;_>&5`Aw>LdH}KgeRyV z6JrTP$Bsi3ybK}>*^sdkhm{){s%S_B*nCi&Y8@$biZY@&b*(0Ft)~J{fc}4zP_Pmrnx|X*54~E1pMnO+Q-hRgnbDX6Hz88!ij{i( zqvX#@(x}WpA<+}4(2!U-Ar*fSi)MclPeOdf$p2_If@(7#&$7j8+ZoL#8R;--7!;9g zY(gg*%~J5+=m;SjD<=`Z;EczN$$TRc53i)7ghZwkM-!k;q-@+UjqrYly`tK&U&t8{ z5v8AKqeCQ_k|2?{{&jYZKbMcTQIZ#apcs8J!H`!TVuaztA!#Y^SH;X#2yrW)h(RXmkzT?&8UWkWGVtr#ABvSNI$IcDylAzLY{_j6ag$pju40{GuX@!8`0&KRIxes zb-vU1ai<}P?MEI-_L(5*Lk{xD^3je<68cDc1gB z+($8W2o9qhE1MzQ9p_*G{O!N@O+~&lJPhh zJ*sasfie;rV@He(dE4mY`!&V{n&Tq|zm#Bn&}K|c98jIBy%HasBr#@4ab_|j1T;uQ zNtq-*D*Y>auiRWDpboyJD_>G1lf)^N@%XTm3QdmMjttSprMfEd{HY=Q*eA?Kk!nye z#a9W36#Rers;|RJ{@6EtA_+}1!Qn9sGa3zNZH!>dX8;8JpBPV~C|{ZAQAnT2BU_GB z$RZ*^pf5HwRN|2eU4&c*C&tq!7`lC#*58ikOiAXB@__u~ylDYtc!D9Cy?(lFeaI#i z#ZrhdnKB_La44BM`8`^jhfJF_FYU*D5SjAcF-AX_kHcmuN-i8_j40`YeFRvp7}1;_ zMSc@fXZa-9JUlwnFC7|`^QQZy-*}^+B$KvuLt|Zlr&}TLrhq(ezL}m2)r^I}QrQ9w z zNM**8)!n?hJT`)l#Yu=1KGsA|u^1s4OK3zMX0L);A*L$@RB4~d;D8xlikY4u{}hYx zA|Y;K9BynhPm1Tu2!aX1Cn-wO|7&bS-9Iw|3CFs`6HoqmH)(35$tLTgh>YK?F)-T_ zjk7Yuqe;CmTc7?KW?L92VL25s#lrodDy`AOGz-45wUB`M3@F0+8sZJ4ANkl(slJGZ z@9(Dx1hCm;KyAelz#B!MV6<~cc26x(Uvua@hChEV`?@_~x_ST` zCva)bS-#UivV9)cC>oFez=5aUr>1jyl5ICGnY+*}P$xdmw$EMs#ICo$_TfT63t#VN zWU6=C_|*x-<2$RjopVV5=77lsywIl)oX%ZNIAja-=c56N0Qk{@2d)nbeUszuxvLq} zg=qcnS#Nn^HxI3--AK;nc!J1ef^_YZc8A*cwY_G5Y2^k2;xsN}FZa0gl(+<^n=SL& zz;uly3S;^%Sl$_k8NIUpRGR5}rzIdV&Pbi09(3rtkk!fpoCOi43uBnGdGBONU1cE$ zRv|o>2I~PVc;?vGLVB>pX^j;yTotxV*BG29y?e+}NVlB!13DCMzzUo@lQJ}!`1!@| z^IR=!wgZ-7jhslC{5SXeHlGArK;r0YyP))5dNhCHUMcsfw*W3MlIaZkgWA4k^tEie z9z~1x2mvcX!CA!FUkSe+ZLj=u#ah1%5w!CjsO#lS)60%{d9NT)y!sBV7+wS3LkyHqrsU)ZqaWJ*X~~x9Bmx3h7g|X zxPF^+Vny^iF9fD=S)2212?&2B?(D6+@@jwG_66R{fK4#Q zJ!5&y?SrT5(~7c|2L)^Ud4Xkj{yhBhWYhhMl0xp%60hVOmzdp)OV7ofKgO-K0@ik5 zp$`b$=NpmB2`lGjhRt^uR=@sGezvdTd;~Va88|NiUd3*E|L{t?oLF{*n{YHBG1$=a zN_t~!!JTwYPP&cnexHN_H?L<0k2c2EmMqENy*$fD(rVG*CxATQ8UDHQua=y~vVg*HwudD!W&+K}RcCG_Upcp?d1r9g zYBFtCsAt=uf^BYb2mG_RS^>*|`v$_s!`>COfz8EE`^rPsSy%(tC0dD0(>G-YAA5C7 zX31=qfyI7W8;w)4&9=RC{&VF8;tx5zp3RBZJ}&sS6Nim)ta@I|taa4W0EMe^ zt2dP0XWkL`3}tL0GO556*d0x6x?z5$8GFLi1XSsCwU`S^xqo=0xFI1nbUJvoc(}#n z(GmYYtbw^90{{dNMTmM<^z3w6wTa>omyCxy;mc-a*OI$uHkWQ&8sX*&To;1RaZlx$ zebu3v`3pmRBQ(8&z=Or@w>d3I&Iv5QL{flXv|bze#U1LaJe!Q&i;JR@7P+k=UADdp zoeauKBD!KRz|mn&7pp^^qV6fbwvpjQW`cE_7G1J$ZFPN+$V^zN?E|-sg9o^c?&)^> z=OAc15K>_ZENpG(>*|8jhBq&h?j7>pvz`*WG=Sh4MjH+qmPSka%TL9i%$T+yHP5Vx zST_{@@k;KWY@i(*O-o9!d=+{}n*QPGo~A_rv(OVP@&dxOL*ps(o2A!dt)fHMW4uB% zl-!>!MqSyKsY`&1IY(2|5Xh3gz6}(dk1fn)`Gkfr7Q5=!fg`g~WA}?26U@9hZU!E{ zEoezSS;^gbd_y}0xH$qUSJU-kcGcCbbzPZvBjyEeGWJfutT>ujw9$q8{KR=D zZEQuT$C0oVDR%2>*OqFz{S7f>ns741*|ukB-cc4J><7}i$hY7zQ;- zN@i}bog*-Nap>;-T?gMBsq@gV;-Xwaj68d*A74&BQW>~?9l_TV*qebBnG4Hb?7DTx zW9$BaY;Obmm0DMchAw1&nFH>QMtK`lAQpeYfF87 zO!JNGw#~Ky-a3{J0NZ=`R^h^&hM4M=dQM#Q;w&eZPbW@RELr;~6yYT6*+pmwGKE5f-8H5n<8V33x1Vk3GcHLxlwwgcUEHX&g zylju%{(7Ir9_OnA%kPjmfC+B_aNgrtJ-hWs4ZhyS9k_>J_Io5ASdnzivg;D_zKtEQ zcLWC`Lhl{g|L=NrgZ4FTZ4ek}cxYvGsz2UxY@1#lZbi__bb7!9$1F40y4YpgF+#n8)#tZmsIAlP+8kl7bJ#B<%I7Im^C0 zv*o+rIvU;z*Z{q2o6Fz(NglfPGMK=ROWqq2xGTV~Ui0qc>uQvu){mC)OYhE zrw^x$ZYJfqXkh^hFj5z8dSW}EPEv=YBSoP->fDK^WlceND+(DTB^rx2y{^O+-Pn3; zmA(zr4wzbj^W@H|`BzSR99jcB*A!#sGQh87bqnQwd30)?dvIhT(qS2>MbM!UImZBF{iHNi3DIl7?UxTywpyu0+Szm5l&YnYH=(dzi&Z>!fI zDsJc4h2z*7D?;rr+uXcleIwUueSu?gYzpv?0kYyB`zXivE=h?*y5(lGvNM@?ZSUN* zIseqQ z>N%&*#AiS{YzDsN0zkX|+Yk*H6nj3+a z#wmxw1qCjd+nv%`Ea2^}dw0>`$KaVmKIw}98EFCxs6d`P`F!=e#)z_D9rw&)1I}`A zg#A}vnzAFO@nqO8qybpu0w&_eWGVM%x4lfW-RG?xhsFbh5%{@B-W_zhlFxRluH#0|6_soz^ezTXY}eCe;Nd vn{&WIFYwIfGxYqxzN5i`R!o8^2{{@iy-B~iosn|bwS?scVls{HJGA{DGRMKW literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b420.jpg b/tests/fixtures/codecs/jpeg/b420.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0181451ddc96c4775df870307f6ce0cb2820d3ca GIT binary patch literal 2265 zcmbW!c{tSH9tZI6n9V-MGK|uMks=La$rhy|Bt&Qwm7VN0C_+eODWfb?@{_E^giM$k z$Oa9;sPen1V_2L>qsd`J)&3F0;Z7~Y&v z(C+|$2gC>F4GHHL5ESBFs1^hGK)%4&|M@RJ62p_Uh{CA3Su})a;14g`NEg2S=xq1UGjN zPcLsD-_Q#eiDBUpm*V0Rt|eZ-ag&sO=Wa%3RyO%z{-c7zqT-U$%BpA8)aNy|b*~$n znp@s5THAVh-}m(o41QpaPfSit&&+=MJh$|1nZ2_5eQo{6FBb>^|6%d!AJ~7nkUSS3 z1OkS@f4M+>VZ04SLZI>*F!2Mn@Uy`Z3iw!lNt3j^iUt8i&EqVob0OV=D6H1F($X*5 zZ`uC_yZVo0|Azg?#RP=GAl~PJk$^G4%A#YUdl5b5%`DDl)|I=96{C@R~)_b0EvqN^y2dWYWz8Rz1*50CpLQO2ExB!FY{dcp& zf10tAjbyspp|S}#lw%C1W>+59vyyzo_AgsUc}RK}-l(V znKnJ;Z_v|0AeC1V$qTxl{8;s(tiGqUL>1lZx_a6H?tSYI*Zrf`>zuD7F0YxZNuV-5h+#Vb@Q)(&E z72i$RI<74p{sA?7&132|9-oZI>wcFSTSK&rqTWT?=7m!n`sJzJi&*l`^6Zmw>ZylX z-U*2wn9~<#&%7Ka@5vPOl2lPWcA@lJQGVv))HCOo7kbO@<$gvWJ+oA5^hq9P^ z8>NJOEh3=!3b9iJx=nAmNZRwp6pDW=nqGSIEl)^F9x>N>#^RdHIL(&cY?JF1nMd) z?+`ATAUrA5qUC-~A;Lv_H`wUVzW%aH1!Xjh=qYFOZ8_2Tr+rWZB>jXyX?RSE;m7mW zhxv3;lEmjl<9|N7&o|_U?^5bvb0)Q@by$bC{8q9At;z3&0nnoEE{;85zbnnT3$51R zU;8Xa`pDV}ywO=s!~X*9-pPP+qjtqzKK)>QMnaOln2kstHEig;OaMEB#s%W(U49fi zM%dZK#Ye$A!!*7@F$T>TUFYbFIg$8hjdi~E_2p@sSPWbtes}AdA4;zzG}m9U9?q?~ zRUG8&()l%P8})^wrsHUEC-4D??^Gq*)r&S`e2x3h*Fc03Yk&To5Yw?JXd6N=4^tZ;6s~+pp~vU{hyu5 zs0Z?7ESU?~*7)gpxMr#}Gl&OkWe;#F>H{XkrbzRBIt5q&=IL-yyAI~3+;y6=qoAzr&CKvD> zgKyBZJGp>>EFFNE^6!bu7*>SV4|tI*q0c-X^eo#|ynFIh zo>q0l@pV&W;e(E*sFJ@7`c8Lv+xyFiE2J+cH=v3aCS1`d&7b)V)ItLR+xIZ1?+l?x zT6UHAR+>6vO5IDunPX>@*dQ<|x5vJ6U_~B0I#%o%ahpDp8}4Qh>((m2f1)aVy70?B zty%hFHz|q8{7f@77S8`_J*L#TlVetS>@?1s?yykZ+l{+sIhy&xwT3P&?Z7-daD$@V zs$9kKT792v@_D}FiGq)U;rt0~>~>=V{}T{U4DM0S`Gr}s$lk`zpqMS~GzTtlqt>>w zC#SVW&;LU!XLNXld^h1iCgrm%*0$}3XN7;T=Aj-W)bC*ROT6NEi@0Za^LP?|*hcaT!{qQdo?G&{D literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b420.ppm b/tests/fixtures/codecs/jpeg/b420.ppm new file mode 100644 index 0000000000000000000000000000000000000000..4fada5ab5b4e6f186d7dd6d67951067ef2d3d686 GIT binary patch literal 8248 zcmY+GbyQS)`?t4*fg((IF*Cr>IYW00-6$;>pp*fkA`E391_+3aq}YKX2p$DdQdCfK zV0ur`c#eAFIsEW>{(0ZMK5MVJw8mt$4S6I9M7shmz#EjXycIjov}MDS>j|XI1uHP~KCiy!(n$ zT(we6z0$U(bwT&n`8`zjdaUgJOvUY)ip%r$&h6`M->x_6RizK8Y7ecaeo>{2sS;;Y zu|j2pR2e#_w0T)+;~z>YKa`aK=uaispX*^iH$%T`LYI-yc`QUmf(WV5X&uO@0c6+& zGGqxEu+i*u(tPit+35j!;SGJ_3ws<0dl&-07Y@G@1*_WutKJ2@ycb%L20fnvEzW|S z$c7c8nU}VGybkd)FX{;Pc?#{YxuQ7ygDH6zd>DI z!=1WdHvKTuk1+ianBEvnXA(~5!?eUuf*gvOhrm`K8s8zC|AMan7pkgE`&*UvryBLo zt<>)@>I#}RhogdIDxXH<>e9yzXrE1JgO;>jYx+9}+FKXuYc{RJhuRuIZ3&_^Z=*em zq~D99H6+k#l4#dbsFw~_)C&5(EA&0p^n?a# z+&!(x$CPc)DIslS|5p@trAGGy<)7P!i*Qqf7RJHt}X8Fff%N3aA0*WceF(pJMpTe4=v&In<;;BJ!EE=oZ1uN%9&FjX&GKOs^X?92{VvPuB+IKQ7M1%g%QBc}k6NC|W}f6Q zPZTioPBD*^unwJNrIoSvRk3zoXT{gBVw#wd4=lo(ErMFjd^*hCJ1y+rSz7k6j6X09 zhb;|8&Gp7Dbh(yPz9mJ>B*>Y_IVNP8ss6j=#-Em|f3ep6%L0_We^>Qd+2p;n#d{v= zr9gOt7#|_tdxq@IrFl>2_1s@ z4zHSB?CVKhSN5?h)7a$)*`-5w zwZ0LJKA{i1{hGbJ+PvI<^K$C)a(L@y)9=L`W*d!qGRE23TsCdSizM{MNxe}DFX*C| z#tM7$clM^AUhDt%UauVaV|~>3O_9r6A{U^M3S<5ITGWJY^r(LHuxa#1 zX7qq{RF7SBr%QCZd&~>(=%)eE_rjtYqM~YcMBUgKd1X&j)xM~T)X1^}k>@j`N{&Po zACEej7ny%L>Uc?1=DFyDr7`=5zrA%`52}zNf4F+^_U^I-s1hs*Z-9=0x4g-S#Lq{8>(D+wp)` zxjt`lJi2pTdUNduIjkX$*)Yd=G*5prpU%rCiSse?eCR^{mgT(l-}6-d%3JqOJ^)m# z0u}!%SN_~|X+@)I5nd%nS4s$#B2qb@S~kNdn=~lf zq*Yx=x?Z;P*2Va`vbef)(N8M(JUAEId@j1BB(%N6>+MDNo^t!%a@No#*2hYVPZy0p zm+Fp{(xxwxgk?DCMZ{tS^!M_uKQF5Nb8+M9#SK8iKS0Azpm9aHaaOHCqS3&IH_V{x zxa8YBTEh&ZValj})V%%^tD)Df;jLrCZ_afcUJWk;8lHvK-;1uT-C2JtvHnJ4-Icu! z*AlLuPp&CXt2uw9zPRA_Nlx{#lednR+&WrTd!)SXU`5@&%k{giH^$dB#y8f*He8Q* zQXBKUW_xGT_Rcz=&RdS%wXE)2Mt$|hgAGO>8w|eO)|hzb_(w~&ww=#y-?!NH zwKDr!^ao#Pe|n+)rHwY;M&Y*Ng)JEH8En1Dk-j*Yh;w{hjUa z>tcJV<9lw!_f$u|xx8!O*51JzN$*NCdx{GNica+$E$+=a*?08Rz>zb98RrMm$_Msb z`4E3=Frr}~_}+l;i%bpYnhD*KPi~y5;Mt#@J8z_!4GPPMnmGr-al=zSh``_83oZ zY}#mi+-%~rWJV%KELS1WM<))1blnP9_45U|GrCG zY2kc(TJdkob@8>n$%>ib)BLa5;?YCkmo)is=ECQ5e~dIP_P$WO{cXOtYk9b3e!NmR zmipt5U3@8v|A!I(ho0!CvG@;j@rsRf*=6pV-}1NMmF4X#%Td2C#(ZCj{k{|pSX%;C zmH^WfU>XBV!(RtWE5OVTa6JP!Rs;5pfbAW?=D)G62Ye4vhYlin&Un5Pf#*z^bRmrS z)2CAn#b-=qO=jX}7J?RAeyhuPbHrqG!s~K&iqlaaol7prs~&3CJe04w05=@BG&q|* zaF2fAUi8@O>TS16cl=8l1NYX(+b)d+$t6b93i8A}o+~F!NvT|!fneTUv7EZ}=y)YM2_So@8{AXV9^OhD)}RhUD5Gmx zI{>z2CIkC1B0~(QgOt!wGJTlP4$4hnEZn4lopf+yE!x7*M#2ftk$%qWM@hkM_biM) zXcLDRhz~mIpY$|8&?p}WK0MPiWBN~q^?E<*4Sh1`8)3Y9>vHU$p;#G65=)69kT55v z$VDU&)S3~y$(L_R7rLc$-SXLPg`!(N*9k7XLgDZ@44w{O3zmREV{k|$0jY`fz)@bI zv2r{{OhStZDEV6OXqmFb4fFm~3`oMtFen)eHH(EvOf-2h^u;2 zokk{4wY45&dv@uXNU&rv0V~ELWdw{EX~@@%`bMpm6Z(aC5uX4G334e)I%08cbudmQ zLrOucT!dQ`5oU!rIf&zlJmhmP#Bzy93QDA6DJYQ0rg>}giP1%2sW=Q4heczsBqWZ4 z#1Yj|-bm_eC_#qCPh;>?XgnW@7bEdPfOXk$C=n$`lci9SWD7+GL5pHB|9O zEs=~UkzvI$0=Q)VW%^{>%cEXiuk}oLc=9xvI8DGx2m}GjlnY6ir!|U6AJ>>?2r>ad zF2YEMm{(Un#LDClsT2W%NKl3mNl~B-Ef9LlDqe!%f=IF~kt|BZvl37?qX1DDItoid z;gP?BrL4UI3P;pLvXRtRP$GyVPN0dS2;wxH$VU+PfYl{~kGs$^GzEldi8N^-94F9Q z!=^9QkR>BT$s8V3V8k-Kbl&dkR8iZjEH9tedPaOakw?PM;McH8LWBhuvU8r+Bqn|S z|FA7@{AX|{C`U@AC^3i>%P~S35|l&5LYH}Yn@qAG`GvhK7thMYGNDv~#Y6s=H9as` zA{Ij=U=c`!GoI3hAc)th#t_EWI!FF0oWIt#$%j2S5Jwi1Ndh88LPZPAHD}^T%Z+H+ zI6}6FlCOPcAwedwAN`Ww{_3!o?^}kx9D|YJkRS#*i_wz6Y=m2Pf1@ zh_hm}{F6oPfBMrUptb}gizPTvh66$PtV|sg*e=PR&Pvu4QAj1S1)*?3Bv43%7{V4T zUIT|kta0r* zN+Uus3YX6#6d+P6Ajrh_qa%48FAsZrbu)D4(1>{~Y!(Hd!;nF!m1N8A@8m`~VMvIV zOcNA5!aRtY{cQdVTP)QUNhu-_CzE2NAoLfu(E9(yo)`TOTL2{?ka#p1Nm&a9hehGA z1T+x^2_O@?(3pA58aWokVb<<41mTz4mVJpNF_sL%aG)kmfrg1q)cJ9wl?IIbGgkI% zoG_q(B$fVZ`_+@fz7E|Cx&n<-;1DtlY!-)+AdH1ucYY(^ljFvO*oA5QB9E{HA{RcJ z*Q`k*R-k7TSe_gslfk8+2B^^BiJj&Yza#<0%WIK}=cN+G+H7i&NN_w!3r?ZIi8w5B zO%*JL0*8i>3GZ>J6&!jNkCx+6^BBzRnlo$I7XAOlmTKapTW|^_Tx6m-vxC0aK#_c) zNJMz404ouYK)K`BFDE-59rJeR)@4XB1Q3rF2&(Xq2_E!j>kuPG*SlHn8v!^5K$M1lxrC`QIFQg4Cy{sroS z2)?#06bo3{SJR5so`^XiL?)&vKWaa4QgDCjVpg!5`6T=@o;Z)eOV--f>D_^!Ct*Y| z5{S~8r4ocTurKkZ3-|TG5h8B}E91gtT#e~zx3QVZj<*G_{=E!)2~J-~B#9}wIWmc> zt~0SYY>9S5fa#PF_#&)Cf&!QDieK0R@qZ|Yaz0f$Lt2udW+mz%Uvo|tw7k?M5zFU5 zP|g?3i)MLz@zjD0M%ISn32>MOR9#JntV<*kH3%x|6gz@Wx2EPC6|rPU{=QXn29A?J z5i@|rC6mvI=mjiX4#CbN5F#XO#t_ZlMVhNYCDwg|#qjbw~wl`JU}uI znFG-Rx#t&2Nz3~@c37XGl?aYqB9kR(*es1OvW3KhMK95+XE2?7E%6uyoYtBLv5NzS zH&=(!C33B)3Hb5?9TciB&mmW&IB>>CG51a|`}??5I3wdJ_%lmlnOHEVM?ED+z(~LI?JI$C^3O9C+Nsg6cCCM zQz7zj=wj(s#e3q9MT|m%6^rTMyvy)Z!K=q($vNv30PeS2EW-%jb^UwXNbN+BtC{~*Ar-W%ptEFGzW~f_7O}g zg1e5eddvd5*xTOvIKI@k?YA@j6zwdm_WClx?gqU(zXl8rdyIV8{;uotv#w0X@OGAa zAJwpv&gj)O8^oJ`!u#|QQ$|d#4O?{d=ynZKyT39+>(?8Y}Qs*(z>zj#nbumk`%U?YFm-FJ?cs#%ARYK859IBf^4 z{x~$o4eq;bdT%cwhRsq=kAwE+X4ZH|jo+$40|1i+Bm^T*nICxK_vjcaA=tt!B*Hw< zli8K=w9c$)C~4?f%)Q+VAGQH9lkL91nSSH;rZwp`8PM``bBu6voI2Guda(7ff3XX~ zBFNbc53IZAQ-9O2ier?d1#F1*44|*0UofqC;oQzU+-e2@4kj>f7Gpf`CI3+O=iC<8 zE&6s;Z9A;~Xzrl2aH_~L%@lyKHo)B0lb!`%=#08u;dzb(ARHMuXAK-R+sT zgBjMrF60VgXDV013pJ9ySOV$Zcv)zr_UftkjI$pjK7BMJFtiKA*i)Xc71kgNU5Ij}<@^1WPOF%D3%S9W2-ig03b^hhxsrn42pMx?b2w{EP zI-$GpUQJTTA^SK_h^d`2^<7czXx07BvlYjD1CICy@3#ppw$6JR`S^xk1p^?{0gB@W zixRiAeKsD&!Mg+1jl@-*Q^hYP&bNi&oQwc%Tfm{vx~Sa#XYZcEz91w@8s><5tS!wkL9|hIBljMa|-`j`S^<8@f)G}#eq9hZG5Z% zom}gK#kQHBPd`8A7Hk9nMeNXti%&aJZeR2%3}-lLuiK;rtQ#nO*qV6%Ui6KEfLIR_ zniCTEs;E4VnON@5@!7(%0`y{uQ5QVRZ}~J9S!ACHNiwG?`G5K-eKzeTgII-!@`!> zCPQTi3xmmYh`GD{Qdh{+uUVa05fMynWW1?QUGTYgAx%Rm4FLuiHd8ak&~W7BvyZ#F zg+-G&5xaF!s$nL2Bc)HkoXIo#9DQJeuNego0Ofx9XNmcJ3C#zcoR7x^7%0;_j&*l! z?=CYgIO-pk9ks)Bqh?vet_r{8XHnO<7kbj&gLGB4`fISC#y)FwX(%$ub|KIc{k_Qm z>|y-v7XgjOi1GGN+%_AFP%Yamvv}dz4?Ra76>m>ARMxNqv~!L2PGohRv(BIaYVHQc z9N*-RCt5C994NEemF?}fMwn#op3B^mOU`(I@U;ipVr}$_LbkOYF6-X=sFazT@415v z06E@!Yog1m?JvGgXgU=bZoXxM4nV5eT~}#eTxgi)xPexPy?WKY>Acq&4>&8yCBR{e z&V%rVDrQxcSEV*UGTDqL0UNsxG(V51%`@E*r)6>*U$l#RA2k!ApxzsuZ?EE=`Xlz0x0<~H;0&D2M#{v zW{tc(-Wp}>u`Adi&er}z()$}a)!DQ|768qbN+km7pRzx_js5NZ_Tpq?+e8o6Ho8#` zJc*Y))R*}rM%TsNP(Om@&e1h+GayKDP1WRpWI z!9Ehltd1*6GYK2I{Mc&4=93X_CE@-D47S&8tNeVrrNn2y56ad}-Llx>=-8?ECC(Xf z6mJuN7@_4obhj01o||Qo zDjRG`xOvq#H*&cVmBjDb_{4Zzfrpq60 z*Rnq75M~6Zy**riC+t@H{wKT4*>(`L9-uZ-+EHk6xNiFuH+2h7v|cjPZtBYIGP^x* z(yzL0#YgB{1;DI1ti#2uk|L{u;@|_JRHpL=4cNekxk^$)Z4^uk|086CWa9XW{nPX>U#5%S`uW z_nvqn%H>|Mzeoc#wYDmU8|$@ZT~M6(+LQJ;#EQBn(jr91;#O$IS#s&utgm_-)H8Ml z#hCe(vCoy$E6dDFVx1gzIt1tgSaX2!a9iW6?a%6b%blULAYG;&K)B|5p*8T@Z29|0 zQ_J+gun@HW1((tbwkJnRyHnkQnQ#ORPQ%y%hR`dHTd6zk>`w&6l(?mENJnnD zS4NP24W_Lsv^TGDaNqOhxT}m!K-L~_D@}Cw$p_b*i_4u(CRs-rsG(0q?5y6IQ)qJd zoNKP9HYwamKifOzoO{+?|7(S28HF)PxOGZ&0C~hD{jNtN@5INffWVIl?ebH@pHH*| zp^VKotjqHc7&v|>M`u_2fqJ&Op)&^K3?ZDcD##_|R=ZyE-C&WE5JXo2CQc7jFway4 z=N@$R+aKucPt!iGyXRp*&2^u1#lD$_8=#&@gQ=XJBFcgCu-t>}(0!inBml@Y-Fr+Y zwXf)4nH8;4xKgzMfnuQ**FyU@9h>1U3h#5;ta_bjY%K9!-LkYN*&8DzW1$$X^Z z?P0@=LiWJSqT@0|>Q-5IpJ?^1*UDU~um^mE)r6?Bn4?*o0X7x2$H=4CXxZB^$!k0NoAvJJt=O z0iQZ!pV$Hf-L1e5E2{_gcb-~2t#&Us8xd>DQ1UZ1eCYb1-KO=+@rS3w!z{Ga%r%iC Z$^EzW>vBm43fS>hMnFcC-Cfs;{{wDIx2XUC literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b422.jpg b/tests/fixtures/codecs/jpeg/b422.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0624bc3a5a60a77f2afdfd6022673c785400b22f GIT binary patch literal 2630 zcmbW1c{JPU8pnT;2(_=Vw5o(uDQc@-E=q-~hK{|crFK$F8U{&Csl6&1YqdwiD6QI; z+QOi*VBnNN^gTTTd zRv#eC&dCY-F5oYLIKb?XT-+ykc-ak2LI4NodwNbz2!!38z&-~c!ki*<8m3TDdv7lJ z2rI z*ne;dv$;4R5HN)68yAQJ%idsN2&bF|RK(Pt%R53;UNezf%q*w0uIB_?%Yh;86Zwt@ zrl3t%-28_2o$S8@`}zMO`zP4HxF!KUFo=D5U||3WFbcY4@neFcFZvk=#|1dzkz+|f z@oK!9eP3L#M+SZ8=)#fmf|nq9C1u5n5a2qy|G47Qsmsmf6Mxw({?AH{vg^uVW%+<8@`?v2<@15aEK{ZF_gmE~U37%Sao!ewK>` zhUs zTRRKjZq9)SYVT0(Ez@0R79AbI1k~9?uk4ReK_5xy=%P>a)=joNn>(``hGKG}UOm?B zSR<@XE$2H(dNcH|llpP83Jfl0k`W8|NU8QF?fUG0Q4MXHK`dfNCQ940W@(s9{37osrOa`&p*u2ctk!3K^AM) z?47#K0zNMwzm~;+4q^ea3_Q)^81os)i(IG>Qg$^! z6#vqR1whD%1jBL`FyN&AdQW=!+13URdEu(_aToFk!L^Mr+|Bs?Fx7-}Gmz>%O0GMr z8`Zz`TAHYzt-9@Z3bZAHGU7X(B>EElB$(#p)--L9&~pbh&onE(bUET$)K02$ck-a5 z{)*SQr_AE6QBh1)%znCnL#DI)kg@||2VEb;Oi=fa^3}W+x=<<^TW~l@oPfZ| z#c2LYr8&0Is;Tcj$$2;y5E9>a{lI%uKG*1`rJw@1?%D2AuXIV)+m!Q|69|e9zX`Uf z2{w9{cuViC%Iys3M2!TqGxL{d(omrt}s@CFO$TVdC#~X zdko%eNp6%C3-nZ>G^K_$#-$w4iY@;gQ;FAjq7aZA&-dGj|hzSh-KN&7Yx?G)_TG3cv;mqgd;phs$rqcu${ z@*RbcoPOrXyR*;VWc&<=D?a!Tpx3i(YS@gFHjxUJaE4Kjm9h{muZv~+pEEQUYEKym ztj-bR)l)i*3vR@m`>+|k7i|5UfO_Q|EQF?qh2rGWhBb6Tl+1Lo5i{ZWTJB6*9ph7f zW6la~Ux%6#77Kssw0Sdzdu#+ckkt(joTyXlUbdS=b*nZvoS*klx9iff33*}>T4hvN zYS>}f-doG(3pJI$ByLtH-a#i!!;aMQYNJW6+nThMIPx~~~2uscWW@xuU=c5a_uOPub> z;5`qbVaTCJa9PvT4Dn^kZ|JzZqu98qD|QEIhc@mWYsYeG>dF0-<{Zp?$ZwITwd40k zO>m*MI4u?KBCBjeanu>B>UWEg%fhzd3sNX{@2`hmZ+89OyD8U8ho{huav zjfB)_%JR8;dIre{=2<57z;8$namQ*z|*GB0alWtNYhsbJ<8TZ#x zBDL@A_~K^z*3#Ik@^avuxmCJQ$BjJuIq(&GJG-ZHbHlLc#v zmw%A*ojaqtweJ7MDsrtCe!u6T4*H9&nJnaNX7o#kVXyHd!8lxL;iB2Wtps}JI%l>* zGC2KXF3~{Nh1@x?)H0bger9I9bHc>komhP>w#jwqImwn{H*5cZ{AJmOp#DilwPEI$ zKXi3ec#YM)MzyU-#IL{kOwRkKmC0KrX$(wTU9j<2Ds$;swyn=h g+G5-=D$lj^TbGpF59+cFoaay>adV_wzq8)|1N3m)`v3p{ literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b422.ppm b/tests/fixtures/codecs/jpeg/b422.ppm new file mode 100644 index 0000000000000000000000000000000000000000..37088094fc44a8e1d0133eeea9c8e689230aa8d1 GIT binary patch literal 8248 zcmeH}`8yQs_s8$io^1xRuV%s64Q4E5-^P+8kx?qjlWL|?+GM1Zl8~*U#h#>OrxKMA zT976CFpFWVrKfeiJ%7jdb6>9?&QIrhpZhxRbIxYwdZr1<%zQn=+;*x?M=!CPu!cVQvXI657DtLv1YxrWi>jn>Rp-D z9<1`stkSI(#oJj0J6SoqS-1DHZvMkeKg3Ep%1Vf2T|C2zjbX){XP&;qicDY~O=5D> znBg~=dv7y$=dn12tbk&sZz;>?3DdpW+_j!*|AJ}rie=TxWOlGjJ}~vWS-Sm9?ID(? zfQ1*aP*SG)JX3j*xo(-c>IYNd7fV5b{d{&Q_8p{^q-2|HK5gL0? zm;K3z{n6CD!@|9FquXmccB7N~Ggo%CC%e*zUFOFw31k=TV(08(-`>Z*xu2cRbxVnG zOFY589L2s6!;U%6j*4eTUS%IkcITzD58ZSRyW<|3%idAQ<`lF2O4+{UY_A%&+f#R^ zMt8f{ZW~(J7M*Of4{nA%Z2f*VeV9!Vu!$mf%#0g+j;;E|Rq>nKnxAf~ez~uN1pZpV z`MH|2tjJkZ<;XNRQ)tcvE^t&cXo$)gpmTZ*IUg879ju@hYtBns&I`w&I@h2Y4^GAA zz{guTCEGcLJ304u2j1Sxxv`&PY#DuzzHZ0+FHWd{Dk9K&2g&_a(oeF`zp|?g~RILn0(+EbqDJ8add__Jy(_PV%`NxlKH9=74&W8+;N|S*-3j4khVjx4aFdR36OQpN zp615#xzXo&XD;%NU*;XX#ygb8+n>qXdz-f_mls&T^S{sAQo{8v<9bwcUFvuaFL*XD zd6q3)W;@UL1J~dqSGSj|{h6mZ&czFPsA;aoELVBy(E4TG>hHXjKe-Ak_`g?1|6I%e zrp#Z2@n;cyDULr$;E$2{Lt6X+J^m--=nrNw9hUqS8~!T?exq~DGdF&%C%@8%U*;E6 z62vbGj>!v+z8l8R3Xjg@MW-B(PCUuK9L>LQjvsr0A9XqUWFr4qO3dMOe)z4Jusi%c zd3;V$%=QQTt&jLV6@0InXxC>kPK|uqX1-M$-{Kvg@iE%)6JLLTPaok^Cip~g3|1Bm zU*M~LJ*)IRdd;usRloTw*Cff;Cd-wsFTql$5oy!dR4FlKigJCDmNKA|(ru93%}DBE zCcod1(rSCX-af6`KJ}?f>hn$4>wJ?c0+SvGr##r1S`d_+wL9ZhNJ>&j$$_|H(}W$xqx~kr_~y@_O<$SC;8EPS^izs)}Xsb@izPhsh{ z{CrM+)~=$=UB&6a#n*S0WNgn#+?$_rC^z|3Uebm9q}c3pm+tc8b50}_9KTw0_*&t? z)WUt)1$*)fcNFLO-@oluk?&nm==QAC?Rl|fL%#W|JZ8&X*NX_j-^|y}HrAE|W zJ6atVQG4!W9shXMsf+bdN#%!clpn~b3cFdgJG&~dpdzTWd}n!C$fJjQDl5bDN&+5L z1(a8Kyr{Nst2TdE&1kJMYpZ5Lu8>zM zfYzT1t>4zPE-1B4LE8r5ZJ)7kCh^Uq+8tebZ{HcU_L{f!TDHBldE4aBR`1weW!L`5 zslC+uP1)90Wqz-pY=844ptUThrDR9LU2b#k@i$pV8?PO2xg6Db<#b03zau)f{q)85 zGjSbJ@g1j<+mB?u4bN}e^PqLx!w%Q-PmV?Jt;)KctJ*d-xA}B5us*#q{qWY}eTV7C z4y~R}e18XGv=ctrj+kyo%(f~owXXfQ4g7iw{=5ZBpX4f^e!=>_!24%0{j-GrIa1#; zrGHv;@EvXFjn;6x?$A4b~L^&7hz zIGnX_`1av}j1&DSF~e8mhA+kqoQdl`d~NW^waS-l!^XzsEa7IU+C9dY^N=@=+C#B%zj|bbX(7S z*eGkUTdZ}KJ>D!S4Um*>lilAsm*cyb5wwsPF&}?MayCYEGENqKeERGmNp$2=B7f=H zg<1ZUnd3>*2h(Tv-;(XWGZUIS!zr2$EMM63NE}cr^RJh=*UwuuF4;89x;IGNTBRF4 z%&4>xkPQX{O8&~KiB{M2L1g_{r4j3 zw*)8eA^qvo`8BKeW8Uc3u-Wf!i{I}z{A#!T+2;7`m5cm2`%jJ6pIUEuEn8mAmX~dn zm+q543k#X{4@$w@{@}n8@Bbk5p-u$!Yj(p#J zd05GxtxuLc8kRlUzWX(Q-(I!s^g_Pzv7FQddKhPK)5{psC6$X3vwQQ%{MC+MqsSQnK`6orr0YhfRL4a6 zlcL?zlcn>*3F+8(@%V3%NHihs7tDOb{P%Ew1^);3Z;ZmDQ3wqeJgE+Wm7p;aELw!c zO#TIpnS_{UnYQo4iZD1a8Y4tvq!`46F>HiGo694Lx^W^YYHAWC9>+_Bc0D~8>uXQ5 zonPu|i!gsv5QHea1cw(OOa|41WVGCA?8hmjM2r@Ru;Ov7po5hqf4gr=L==lKA|ZNO zh@YCkiX_-^ftyTPAr(zbNCXpNkx(QR3#C&+!T)6c@3;TgB>%JI|JzAIMvze&aCMT3 z23Zk>Sg(b{64a46I2%WPh#?3ts&fSRzes{a12aN_i&P9U9p3IFj4BZ&c=#j=I}2AE z*F+9)rOsz5Ew!v$n1G9POQj;bC8i z1v2!TMY4DtA(+HSrMT&Lrdhw*LxqzFsSqU-qs0=acyit1#QND$8_C!c(bRn3lx$EW zofFQ^4T|R`WGIv|8lz7jQ_uvIIvh$MkT3`uOwkvEeT6415{Of(8eJ$_FN!*Z!%VGU z6l%5X$IR$qM=6@)becq$G-iwZxX*05Tu0JP7#XLH&JsuFm4_xRhezUHJ&*Kodd@Hy z(IgIQl18aSfi|j3o%~)Uc#8UX1ocsbk;ycsrRp;x;+GcYUHQA+U!^$dsOH3|mS9G2 zaEjC?LJDU#Ezdoj5sXWw#>a#s<5J=03BmZZ3`y2NVbw4&CB%9aEs`MtM@Pa@7?isX zxe*Q>BVfk0sdGwDAsn@!rXhfsrdhn_5M?S**?RRw6?O4y^>I96VjF($hVop?df6oY z%Xc-w40Y)z>tlD!mwURTquf4)!J2mc_f-w3$#xFiK)A_!tg4OTm9$OA)CA zFOv$#5FKK?Y#J$H>;R&yWneqkkh-7S7 zJTWN{NCi^akmNH>(^z>OQj+|jtp7NiAom4!Wrq@^whFwVp%NucVujatgb}EVvtB86iZaoLn%>KqX__wFePHj zF$gglHHJrz5#VDqq?7=ihMJZ*v_}vIP{au$QA}3p*MJEO*NZk|zop}3?=(gyV8bK0 z@hR%?f^ECtY-8&_w#OSYGa(u`hQy0;q;V8XgfNsUANqoOEY#}h!3}*vk4+GyBE)2u z$qjku4%rk!A|MDxu#+OBbOALeT{kh~xFCBj91{;s2|kGjhol3ef`K2>FHh*x*HN`C z;mvfQ>|sK3#_7gj)1SJIoY0E%KyAhX903rEeIJgVo{XfNwOUK_VuPqK!#Ykux!n`N z^-d$O{_u873uQz)tsosylIxRpX0ty^9e5iXehPf~%A~fzuTmS}&?^;nRuek@X|J}g zylx${&&bI^Ptihc)kO5$_nd~C4yShL8{2Gv@cga2_cv9TJeDMW)&lG7=<9ioPN}r? zmv*gJ^|2*>?rlu4^;xsYS?e-6Vd>D9&cj8~-md<8b@a%qYCP^0A}Tw*$7AU^ zn!t>#p{~6en`Ks)hG;xVxMd3L)BwbpWD<{xpWG{|-(O<1N?i-P${M3tWK(dHlG1hc zenfz^iPZ`RLxV)j?YnB#`A)a(l_|jihGZoWqj_}h_)KL$sTnY^F|coc6yPsjAPr` z%{lDbH~?R}3h2VMGR*IJ1%il!1UK}m>5Pi`=z8&`8V6khQW;{lQa{l&;W53i*{}F? zh!yvczAKSb7gjvHd-xLd+$Lw89pSVCY{RbDf<~uj8TvO4`g+sI;IN0q*tPO{)8Z=o z+>^m}TYRua5JJ33Ope~=k(g(@{cM%gLF6`r(d)TAfo+AB4?PSWG?X9&u%i1)?c1P= ziooOpd$kRjAjaSN!-;}y{JmV$Y9`zPucGNs*_v&8tAX`0Q~UDiP-}!aU~bg#*VFkF z_pr|A-ayA9q9MO8gT}_SipfpKZHmM?~10AVZC8 zTMw1z6Yn~b(R0vwigj&EY~=DH7I&%Ee#7c*Rd z0joQ%t|#P$1p4ID{;mhDiOp^@FX`&rOt-LS(Z z#w%g%5l!#ByV49UAKP*g1lomiAF*k$iki^N}|eBtu02;^D;gKzDqYw zKICt^ZVfoQ*{dYrYBBTn^N`YmAyx=YK!QN;@2t3|-*lOnXR1WcT37zq@Wq{t*&b@< zf9o>BDwO)?-eMGFIF}HB5m6nF1ZzL;uWj>s9H)QSk7gShY)@DV#-kb=U2ax}@{hWj z*;p#L7^!w}?}?5#XKlI|?%=h_SKZHnTIN(yVcZc#PSpYiNY$0Wjy`vcOG|ZL#8OZ4 zowgm@LEptB6fm=kjjC^X+}cEQL?|iPlXVMiQkSAW_gyXVHzDY1f-?b54_IkU=C#p? z6CUdHxoC?}Kdy)ESSb>wwc?u9x+r-UoM99Vo;A;1{IB4RU!MSS|ZU*mLTc34l7A6E+*ux{u^a zBWvEDxx0s<6}(d=zy;NM@I{tZ$tm(VGhk@0MZ`nEr!!4|Tl$gzl~7YlpRL*(&1gL2 znSuSn=96UshQ?MFFn?={>x6`Fw_+)6 zu_E+G)O2&6KMQ+60E((GU_!*d3a+a#uP6_wCjy$1!U`sW(#a_s4rppQTxpM>TU)Mk z)F)K3pC-eyN3Xs%Q2`;x5WH~HbA&Su_Dy{kpPcjeFg09hfkxyQB!4?Rb$!DbKe`1% z6?hmj1g8fwF-apAnzrju4(x^Pa#6f*d3NsL$U{yM8o*co^%TS5p>s}&aY3{W-vPnW z(FcKS7GEvJYZutF3$6#iz@?JG{Y?{RKbWZE&B+8$9AoTSM~iPmu4AU75tW2qtqpYJ zb#F|DFWh9N9uM}>rvZ!As-@mHODQ#_8%qv{utFmc;Xd>VZp_rFrs?<>?hKW{tt1=( zjmOGgxK?$BHf^`EqZ5?KVD-S2j#P5NBhTk%XtJ^H`aL$rL+Mp__0w8IUYMgaTrDUb zaLcRu*9r*@nL785hj>|R09H^~&)M>S&kQ{G%-3I`sg4I~Yk`f5MU-}I4x{ph%?&3b zC@)<1sH@FgujpEbvf6E>49ztRBNZIbO0_8cdg9Mj>RBfvjHf5&q}SF&>+?lMFK;m( z+Y(7u2H;|l%R7Gd+>xPp{8=>sHha>~`fR!Hd$niF=X20l2Qr+u-zdV%;@yR!nUmss ztb5u(m8JrM^o*L0WPFMF_~AgFzm-}TN84M+D%&?V0e`PIvQI}D9NTZQ)7&!EEis++ zFxlwdRu}6n-el4m1yjJN_IlOn(OvBHKp(5eG`GS7-P^YJ+MJ#&C%*BtU$--a)o3fw7>2K>UF`@9sZ4Fn=;Lis=n@&=gAnYj9LQVD4nYvoNM-Pl|2Rm7#ap2VM;5$2Sr4S$7G<)c%rQ_j- z=lMA$x^SB|JiSXuPuUhu20#~3FKAtCW>$YW(;C6Sf7;P9b*ZO0>9(!5A{Gr!Zgm)5eeaZkOZy{7@KRLWB234O~Gd-16Z^u-$k1m|(%GOvIB+#p=$OH|9i`UBJrF z5LSW1qjH1#nYd?>=0+w&5N2ojka4$yUUo_=Jk;4?TNv7BGiErU`wBk!yyXR3f>Fpx z*1?1BId;VjS}pY(tBOM6kNDYY5;oc-^!cY;TGTtDK1W1ln^c{{)4;}9p8a}wa zC3W{kdtVQweQbQ+v69~1br;O{9CCElBLiPcod-TC?{>XP-*D9!XltrNwUyw*Cpufb z8}ob$>@`eI9IQgJ~(K zOsDic54hiXt<(~&v}X_1N^?b#&Go56!(HdSIr|aj|S$4$gMsHN4YN~?m z7N+%_(j4RbQ`A@osH3+Fi?&+nfn`Y{Ex&_b>Q2_xSffH;p83diP_92V>oK PnH#P=vfaDLuJr!^9;LO- literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b440.jpg b/tests/fixtures/codecs/jpeg/b440.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e7294bbdb6989a095226222d11a31d3946665383 GIT binary patch literal 2744 zcmbV~cR1Va8pnUJ_oxa{<88%$Q9EYes)}f7t)M97Md=%-WKRIQ?_R;XFE ztMm|Ctu$6Ci4i+F={wH3uJhM9=lfjG{m=7#?(6%x?wdA2n+NzzjSF)p&Kl7=xDi>J(7EGjN}Ra#bEQ(K3tZ+O@E zp`){_yQjDB<1l_?bZmTLa%zF_mAJUHyt4X@ytTcvOWE5$IQ+o{0vP|qqSrsc{)3C3 z&c(pQ#K^?@gA2qEOuvl$Ow4ChSWaEEV7=ula8C6;+iAn}{Hk_#Ni|E7psU{y2Nc`}mGaRKne8vd#Qg z*mLma?JFD6#7MBf?^Rbq`ZqiuTqYe+pG0NttQ!aq^)rjaCCc2>BQEb&-tY4LuH9;9 zZPxl}?{4e4>Cil_zpZ=6=cbJK^zd``mqp|}gP+=1^B|zP%n?-Gq_x87Y4SfC%)o_cX?NZPcB>^R|QeyRJz}Hdo#GCWwTK$~3BZ=TR!l!n$ zY4koE4)tzyKnNz4FPWl_NeSWBcmCtaAL^PRCAV={!lJsljGzGS%gx23Z)RQi^nZv@yL>r+=)R zV2Rl>aJv>ir+kS`*8i?7heDuI{mL%Op>7p!mhQd_T|rRL&p-by+TowtGzje$LE6%45Hh z!^y+rExW^G;S|sNqHTgocPt+_wKeYS;>~iG$2IfFG=TLazT&Rk;`^kl|`_xXALTa{na?9IYLyDuy8(CL~Jz2yxu2YvH zLyKrYFH*VZKxBci-$L5HN)9Z}imXHk5__Q-<+ooncRhY}MOvEtZ5#0;IP zshey+@80JE3lJM^lc&ZNncEb}S~(6X4Jh7-%=7#fs!p;?s($2!&-9(`YYL+nh&JFd z^mS-}apSOJB{Yy@R*4rR68e6UzkvyL1}rrp#(so=G2=!PYq3Hm`@5_i4q_^(fTrj6 zK5q>ACFQ)v7zSI)<-#Vi3Wt^rkbqQ2f5mJHr~vO@W>uFN}99|RWl3@`8_z^MYx+Q z#wbBPPE{eaL#jcsJh-rK?pTWA?-ZK0?>e=$jSw)ZR+nZM1qO}xK2QE5rZWw$eNZp2 zvGDsN;>;+kmoprUub0ZCJd;6t?*{pdr{_r2QJNc%B$5vOrf2|nTVf4WnqoVX8nbjp z7oLkU(87&)xKP1%dXKAr`Gho#ReQnJgxK2mvbP1|VTYJDe>dim1dl}Nwh3R=$R+U@ z9kVUOqx3qR}vy@G}5g~gwjWhyUZircW@XB z8s*0gA&aY-1x+?Ek1jE zA9ZY&N7kxtUC$lL4!<&B-eXwP{BUF7tTX4SkI%x@_$kHrHf@4c@-1pzOp>k*s^y)O zzPdCYOU68wx4(0kc7GE+qNdmD?DM%<1^d2=nD)Zgo}kc;5y^I!(=fO6GVS~P)ERC@ zT~+qG(G!RgQcurW>&_L2EltH@Gpqg3PV+P%C_B||?d3-Qp3n!vw`r3`vc}RoC?)zg z>Qs7ylm64JSTiUbn^c$vWnD&tYtgEhbK)}Q(oy{%1AAz_yDUFk`_6Sv3Oj81YPgKP<+Dot&k+bQfdcuEg!vov2_Q5H zV@(58vc7ma{_;%Dlh#Z`O?~cd^*LUR4**)}y8~5v5w2w#EIq$i?wIS#0!BB@~S^we{(IqMXGpv+_TA(Hu+E0s}-04 literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b440.ppm b/tests/fixtures/codecs/jpeg/b440.ppm new file mode 100644 index 0000000000000000000000000000000000000000..edb57f279b96509057d29f10c3777c467e458fed GIT binary patch literal 8248 zcmW-lcT^ME`-exG2!f=~OlHyx9VwxMNRv<$TtTUdZB>e0*Hr<#f(i($YegxFT||mq zEL0IeQ6Pczo)AD?ch}u7zwGavdva#pKW0Aj+~>VF=O+5v_)1{hqhQ1?6url0&F-uW7|>l+~bz3N-eT~ zGhcgl#@dTBR$ewwyKc7NmU+xQ^QZ^rfe$Tx9$UIUvGjau<=bK5+G)vsYsu=jU=Nu& z3e8v&3xd?jN^fR6K4a#TnfZ4!;D?x?J8UU&*nI-CwH&*?61VmoCa20_Lk(tiEjIlYcHwQz!bVI&D<#IjlzvhOBw zZZ2it%3xhz&c2k*J(J7)eI2JVpIx?@b7G^@@txem`&fI6xI2rP1;^RjN;x@|?Dc0^ z>n^g_T;XKaa+2%0i8naOx7o>!ti(sG*fwV5Yi4){BfO98HNbWnOC zdiwSF`gR8Sy$tn#w!o*2&ufkMy}#J^_EO&M3|{>Tzp8Bi$~^CLYyHmT`Ic|=JDD4F zVyFMH{l5El2ktq_+gswd{iI)Rh2Offyq_=nuDar%S{IOX)j#=KK*}xOl>5Gk4|%a| zK9TJ{^Sgb*`gptnp6e$+hQOC5;n7t-G_4P!=Mi*%_;Fu{FMc+E`C9$(GY9z7K9Hg1*iTMz@7?2id9mGr{Lavrwy@a8(J{{#@E^tTA1sP( zNao*7<6qB;ty&RxIydU_n%MK37gX$uD%})!@|W0>0}GDqN+>Fh`Qf#q(k4e4BUv@V(u`w>@aa`ET*ubs@es34}zl{m*i}Csp#~zMD$6{eQ zpRD1Nw0zuntlcEv=3A`g-?6~|VgVp+8pxP7%lO+m{hM9-7kt_{n68F0B#iVicKT>o#lhK%v-nb;~UTWHn%#7-+%(FR5t5#;6-Mp;4 zaLMtl=_S9UA3L0KxFBQSvGnaF>6=S4@+#AF&!ug+oVL0;J+&?~>Grbp+i58c>G6%3 z;g2$dUu5`qr26)x`t_vF>r40T&)^Pa&_*-J(sW3jPSm91CerM_q}hB=xB4f2#&jA0 z^oZ`c)5ADc5v~%OZW9y4bHtapNaZ}00 z{IdLwzvbnh%gwFIU00X4;%Z)6!-geya~Iv)$Zy;f)v`J4$)eLw>brqguUbBy;|B{ zIlW+%S|ni>jdJ%7x)t_&7rhTCcpF^!Cama1Q`|if=yO&sWFS+n;M&b44g>~6Q zRT~PQo+wP1=&{% zvl{j+zF)Agv54QeFS>Pqe>8?htU;x`IQX|EAA(i-(GgAKC7ZGyW-OF(zCf`7cwf#H=QltUUp-X-w>?p3Xk`{ySzW`GEnaFsgx@?$&!@P6=jH~3^7(>rz#!3SJ?bhVfDXCiy75_o7H@s zSu<{1t;1YV6R*hO>M?TlFsDw)t^4e9wa=rj$EUU{ptgNp?TfJ5#|x^P;_F%#)wV9F zxwow5>hi1AtFBh9s=bh3eJP{rjoR=odWK|$^ABQ;x2)NL=X+j6QV z_xIY>m#${kTuZO5O{>3<*ie`Bpf>*bjihIFac!69w_ovlbH%B*j{d%uJ6P>1sBsn7 zaTT=;O&y}Cg><#{##-C2wKM;&HUCjF!>o1Ms`Y=f9)6qs@C&BZNNP5aTU1D^gx(@# zw0!0?zjtZw^=x|U`=C3ZsV%VSNmRo#eq-Ch#;1$#HzYUKWi(Y~w_IA)ayhT{%Es1n zn;uu@w-oPuaP(lq;obLlZGBZx(zyNPgPo_Eww`WUf4(W>O3P2R50})pCf78k-+Gc- zcXwW6^ZbVm;cX8hJDWm!n*I8kSp5$i2OC{RnjA&VG+8r2(d?jXwl}ocO*GqlZL#{R zWyZfP0MIdQ*73u#^Xsh6uXY_1xb|^khZ^jVvbx3W9)Z)_LHC{k@9zG9?!KVz&d{D$ z3tqkAzkZqU`dQMO`^g=3X*9j8l4I?~dwU9Z_U|fv z^K1E=Un@GcpYB|LzAK};C%Lv~*|o0py6)_I18H}=A|LlgJ#UZd=!$*$GPtA5|5KO8 z=T6U&cF)mvM^OhN?&u{o`&`4*n@O7NU42c=4frk z$c-$)nY@uRxx&hABjrbj%8NuLJH)$>4CI{{*>hrOciGUk-vl{l$FeVuWmO5XtA>8A z{giZbh~FxVd^R-yaer9*F#p-7z;0#mhe5BwPu{~rbA=;pkpPql@TyTnH_A2&Y^O%7 zzl~V_7@6_E5df0@0ZS(-G95#v2R#^2487~ZsQw>+rb+=be-TGO3HG8~zo8jsn$@y&U$sJ!x9*i8g zI$C&DxTjwD%k8nv4U+W_L^&c1oYSYY^(^>K^n#Cm8Y9Z88_zXrdE$n zt(cm~{9`ipuZg9AFAv~(1Ad->k0-$M0K8lQo+IGH20|VHAq_xiJrG(81l|S$uLD8V zK+r{KG=wCYkB&v4qA*ktgp7o9MVTI=OTOY)bEVI?%BOykN4&8n`X9}npU+;3nEPAA z%-`O_wXVkA?O)Lhn4DesXH-bA2=5+&Spd zHsILa@BUaTr;X|85*1ylagb|?Vx{SpI%1&e)h`X|j~ewyy}HMs?$)b&HQH`68ABt1 zcobpa={O3^ARt5pL_q|EjAYONkws+W6A}Ca0*w$XC&O}@9K`BCy6I8@QPeO_Ln6x= zh)NF0wG@S#A~({c5=5ngWm$x|#cIX4N}<&#lq!W%sn97@N-PD2VFX73 zX+*jM6(NIkQ-y?pAgrMhb*48kh*A*N{r@LOsi2%DL-A@lQ~DommYfbNV2YdyYDGA$ z0H>GX)n6dF8c`WQg_@xdDaj-ynV^DDBax~n;-yS04S}VC32Im)A&-m6#!;$73#mpZ zDkW@CD?x<@k}K(QwVhOl*GL%(HC3*G)C#dgqmya{Vy#r9(V2!+t#+W$VTg{W5NJf| z96AAl=vXRf`Vt6M(})@qUM4|JBx_KT4kG^-n<}H5B%#ZgBn6G3prUffR3YdjSgpYH zOHh9yDwUAN0Lzt3`Txg;$qI;JATc#0Sk9QK!8@Axt0A2fHky);Qj}UyH%wJ1VVzn@ zQfP=OIa{f6km`s!F+-_B)oM_!7?WvKGL1m0HgVUPhD@a;K^&CCgiw152s$vVAs8Vc z1UiudK^g>7&Y{XtP>DtVBacVrL{wyAi`S583dli+gLODig`-L7B#j!UmNMls6Dgv4 z6l+k?Bqrt(B@8JbmWa$%lBrS{kyFSztec9Al_EMLUi+UX@T4A8jiPc5S*%rJaK_-RBgb`D07{{EKI!TF$n5;kv8knvi*clv%;~0_}Lz6NDMgT0VS;a>tpaH(#9oY& z$3atUP=T;au~iTxr44Byi5Sr<$TAtC5kun=@^_<@q*gM7df2p1m^gnEqEf9XHeIUF zN;G=SkI+$rFuQDOQNYdhw`KI4;+7Npz5modeFCL72s&JCjjoA`v99uyl$FfkhUfL@|hJ9OtM-Sd|P?$XOGA!D0#L%b%1H z#Z1}f36MO2gGDGsgCh*0I3;MVrFxB{v&6`>fn{n2#R#g=UPg<%50l3^5YTKphq7=_ukBodZLz%y*I zco`8Hhv6|iA|qpD9L5g@s3Q}NtdUtZ6L?zr|41u8ZfGDR5I zKz(}3ziKIEL`5--I|@}4wS+pV#ZPG*2GnHDm{K|+nNm)TYm8ErL8AFOEY~_(`*}Hd z`_BlZl5DtC)SeA+9N1nq9&CqU61$2GwGbVz`r3CmA#HQ5!6!IQsO`I8QwpgM`qJ zR4*AR{+)YsuXq1z=O;>hkBF`iQ+nUHepHC~BCYR4e}?k?vLEl3Dzq`GQTI<%QU4pB z{yu2<=fl4$(ZHy_XH=~CS22Axp!F!{Sm(Mf2LK2Pg19_jyJK!=>W1ZVb2Ag&cxWkeXd91LoqSyfkiRC9r@30J3sim=FN+r zUMvZ44D-ZiraH?H4fpv9-!IWJ0AOiIOmdv##CFl>rp9X_5B-?7@o_dJz@jCpt`WUo zMmvlFfYfD{)LFLI7!6 !1_~z#0hU0rP@gzUB&4`8}d7eLMmyfJ>gswNdWq{=Vn) zdG0*|764Je8Bcl_()=Lv*>#^*djRm73-R26zGcm-Uweku)x^woUlPWS<)bCY^&feH zuAH9j$)TBRalRn2DgH{S>z;=>`wqJvqym7yHJ&rewlwPC0nYCQXjvfO!UY`TQP17% z)o=HgHs@ZSYYqlD%#N{(y0oCA)aAhNk(+yyq7xaeNz9N!r)@{MhihYwxIyq{{sKo} zZV_wEVCl8{%kJ_3k0talCSZLh`_Nd)tKP%)tHb^MtdSTfsMu|9-!JXWOY8Ha14Brz zfmTT8!HZ)RH~J5kY)y>c5x+7wlz-BrrX}OIil0iE0GSOCA}zg2=WovUi$9pokGJQI z{oXxx=*|06j~AnU&VW|{5Lo7M`n2EqJIn7JOUmEBA}AX1dHD17u5CB>a!NPM z+8XKe?$G6%OX`XPw(W>d3$^hqn76q9RL8l5-525-iW4(dMS6JwwBv3^%6yKzKh*gv zKZpa&+>z`fENgzXwz)k1P%1af6JWUmGY3j9x8z)CT>N-P>VjC5bTB!nt*E-lv*=7j z!9tr5FDqQ4bHs&^nybX3Mce#t3yH#|&#nX`HzUYC@)nf@hfPW}9d0B!`$a-qF?Tw@+@<;0QfF08&}b&pe3-nWk;r?)K%&dmy1;ul=+Uwl5W z=2pa+Af6LrHW106T@AQnDC+z6>(e-IPacN4VU62`kn^_|oH=BFGLXQX?-3N?iJo_= zdl=ty#QH?DXXhLMnCos$vH&Wmm#))p)qC8D@aM!uc_hU93DR1`E8k6S{nM92baVlB z{Ji)adVXNV^N-2xGpvD(R7U=C|L)YA+KpYxoKI9+U|tvy9%BA}L$5JMDp)6p4oA|{ zoEIe8Nm50%)aLTpO*8^9cP>CS0}MHzyOTe^h`ALJ<(9ITInUqbnB^Ho?ql`pM^OPz z5$;aW2{TJ5RnqkXEpvOY)&K=EPtT;(bJ}0+zOJZza5cF)5uqh=9M`zb?b!XKDW~=6 zng-L_;tX)-JA^#RDY+bR;eKip0x%o_Ak@M6{)X$1HdnQ8YKbJUQyBhBDQ-8@f7#`f zF;xCE#2kAtBj89{RIbymnx(&e-uJd3B_$g13dM2D{P&L@=sD$mGuZ?70oW^;-ouAl zesMYW@nn56$9Hc+>hj>Qvq5LyAH8rp>o*2K;Q;J3_mJOzI#w2OWDoabILurC&CUsT z-%6@j9~tyZLI?*S3J*T$*l|y?|B0U+u(FF{!aOVJ&eQs65 zyIvd*+xJU)W+;)wv!vc$bha|!@YSf(hmzxpQdX~D!-C*3)z7A z>+N;*Db=smx2@pC%){U~0BgAXdbwli{iNUL<4N<0k;}trnv#xE|2-|6ZiLx$7kg7e zsjTBJm8aY)kW zpZYmjc)5|*?!e18^y)XM%b-GA0El12TEEi$NyM#zl=kDZPPn_x$;oxhO!JU$>G-}y zbHn8&!49BcfRJclEbaNXUyTFVgE5gaGnUWwiU6Jmz4?uFO}%b{h6nOC%!`fS)_HfG zXZ&`><#>7wZF!^#HHiw?-A`(Ll+u1Dye<^93k|>!0H8kL@}u~he;pm-2fM6a7CO(- z{gQW6mCt_Zkx!Y6eM1~@MALa~%Cl#y>K{ZsaO`*ScVLG9cXfv?jRZg3sNI2)?I{t*Q7T;oJ#s@p->95pEVK z!6BV{gQF}A$rtCoP?!`Wxt9mAmypV7I;N>=lF^jSz z)njMV?F0qLrDGVM31aY zk8n5eAbne7+?{LTmvdGvWY1!RQ3#4%uTPLlYojmZCwZ)0#58qEk>l|L%$(1=J429J zi=(_YrSdO@x83%=px@t{9p>Q%kynI=RRjH5om6J3kQ4O`I9DV z^aAz{Lb8Zn3^19%Y4FBHpivy5Cb|J@ibLX7*-r2J_YvpiO-vVn1p>p-pBB;DeHtF2 z@16!eiAx5emY6R|;>a_nCCMXK$d^-+*+h3BcoEPVpi?F&9@CrbVZed@-yfAPtG|u~ zYdgFpWItflK5C%%tUCHxA!B-^YJrPb4&h5+_S#DYu<$Av8KATh<|jkY#L>{iFrSHun8!Frh&*B+Dox z>&Z#hu{Bu-V;NzLS#F*4yq^1cJ+J4F=e|GJ>-zq4eXq~!`~F-PYl8I+IB9MQH3dK* z0012=fHege103u}V*6P+I5;@Dc)7SZIl1_Fj&bvz;1f7;f{&kHKoBAgSN80Gk2e8$bEg4n!;P_*_kRyuIvga>cl#^Fe*U;3`zG8gM#MJCM z)ZE&}_KuysgQLeiPcQHLKE5HLVd02}5s{CdJbjjsnDiW(nU$TBo0nhk5>;MNiGEd8 z-SD;%+tmE7<^9JleD|lG-oF0fuOp*l;}eqv;`jN5#iivH(&{#4=g02eKJ|e1lM4i} z|BZE2{|5VCTt^{**f==YIkl)5?8Y)Ua*zvjhhI8w>belOSfMo-^TFO69=y?$={g zuWu$)v4G!h&{L6;eD@dQQ;hJLof5$zwDBb{6(!)}TP*)3t0d`sq5nG4sVPz`KzecP zR`(p$q%rZA2y{oob2Y2an<~|>#F0>4-W}yplbbIJhhUb=l{S z3Q=_UR5(<&#(xDl+92w-rF|FG9V;ob#l81Lmj%p^Zij8ZE7-9iS!b2cAfZiDlQPZT zq=^T(MCsS{>bZ=Mr7S?o&;CABw4?Qg(_ zxV?EJsVBm`XdaC43?DWpm$%KN1!TQ-*43+cpnknOEC}fuWlEReYDVyOI4Q65oX6>x zxVeg0T6LLxw(vYP6%%>`mS)FaViVt%X|k}z`)JU;ZS^4h;bJB4Uy({IN}PY5+CaDH zf6i<%(7Lk99Mlgzl={jvI10EnnZ8EH6Ne7YxEZW182l)Y(;j1rw~JMM4?GYGOQUTU zvH%looTazq2ABnWP-4iI)Fnt#?syvP2^+J3Tlj;qe;H9E#92T_lQ6U6=*ZlR*5yPE z{^9+auE+wA*m4#y703|UrR}HSC?@l`4M}EkWo%q`DMcQ`0s>e7={gN@g9W6&c1@$G z)4hrN^t3G&u*U+J8PeP0u3M$MBP%tud)pShkH5J>QoPP8914XXbX}t1Rn~cwISs>3 z$#XK9ogY>V^=yN}eB4p-1?J^g^EDW4c19w%BWL;tI?J7ymoq7L_2h>zidVA+~oMR zy>?na8m}1SO6+(}=@#>nM@8Lo?T}w7v^3F$uO5pX4ZyC2HAY;wv-OhsJv=arZJMWi zNL=u7AHV{*?@g=c6BXQ49e+5MkeNSqz;iVv@G1eXLD0iznt;D5{KHGI zH;({v>(w(eEGZga(O2+TS)!j!LO%)!K*gt~z^XGcXB2$I0{tPRguLT{){irT)l^Xqn4Wp+#*6ui(Yld4odt+DHM&sk7ROcBkl{Yk*+81n(~ z1m}>-?76NU5#ww^;QZsS$e8j&gI@ZO$ZvIIh(PW>($0J>&}j;_8Zbe>PxX8Sb9Qo~ zzEmrilX!rDyzLx7b_T8J)Wq5zrb3?n3Nvr4Un{VgQ^b5(ZJu1;d#^jFZ<&n$97;0U zI5A|48gHdUNuF?af=U#}pJ7h_CJ(B0^UHMFOk2C^`8>D`rLKXE^1*FHfjxtC#t{mwL&RW z9|t=iL02`aCFio5-fLv@Xou|0$qV{UPPUt_NKNaTO`DJq3X=s)hRj*G(MxBs#dUsk zh50#{|M?XC;xiLYFk{52U|GDrd_iy3*W}(+X?L{#UAL#wyf1Hm2-;1q5>tOxa&9E# z7ByRk;&7q2dI3Gupw(A6XKXCpTJoV&mGi{v$b!$V3yJPQ=4rTV8agK`=3-ZOO{OacArWz;&jLYB%M~9Uc4o^_=aBr7cXdr`|wijb8Nm&=A~iPxFc&?Qg~BPY}c$} z;Yf_D$HnjRRw2vQ zg&bQqfYu|EaqUr`4qYRno%TuRheKh~^COb{4??@K!yEpd@82CNzNkRk^Q}oi6juzd zYCM~q3%m`-6H&L?#hU~e1=Utr63vLBupH!}V5Hg)?5-x}X@!}jg+e99$gjY1gFz15 zj>&#YS~W(LW9R6ydm*rhbgDanvI7;q)}VI&m^kp+bbn~_&v<;gnf5_*u;)Z}5^ZqJ zbdz_)#{t_{j=A@`BEX)ct}r$DF=3O5C9Bi0jM9DoKLTB!M%zt|^pAuc7K&cdHCBVF zGf_cf!Tq?)w#n)13BhWQ_dQ}~@aOtuC#&UcF~(9AB}DYV^TI~-y-o07ON9Rb_z?T@ z#>St^n4}srC3Jyxc%9~e9Kw<0pZl>1rU%8!Nny8<4^_1CRx~ySz=gd|Do?V8nSvf(v&J$SuKI{ibDX71B2 zMNdA9=C}6YGvK-n@?iGsVWjh$VQ9Oig>^~V|B(fTQT59B+mr3oTzLmSTKc2Sz!6p5 zUe|!3Hs#{ZHw)>%!<{GEY=6CMXRK}2Ar+FXsi2@$8x@7oQjmw6f4TEEU>~uJdHz4L z@TuN!Z2s5*ZXm4&_}+m;y5P$1XP7CF3c9iQKZLJe%i!_Ic$a=RXV6lmd8n>=@ zn%g`F&KLh8BB;UK`WeRjX8&h$i%g3Z+zMKQQBv3+`#6lsv+gI=+%8zkifRwT;XA-b z-$Ozy`DT0kYCjV{?dW*r_*LhKUd-t?LgqI4%AMTo079m~A=cGGug85WA_2#zRwRdU tM}g%&4PW-FkTE-7fXn literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/b444.ppm b/tests/fixtures/codecs/jpeg/b444.ppm new file mode 100644 index 0000000000000000000000000000000000000000..2d0ce918d258fbe616c8415416af257bdd4ffb30 GIT binary patch literal 8248 zcmeI0_g53xw#QFGFX_D#Na)gpgl1O=*g!;tfC^Srf;bjt90}^&nX!$7WoEpVQBfF2 z>`1YIQbO-YO9<&b5ELtD9`~2K)_d#z0q=*q*ZJYB{lhumv(IPmeb!0fICFyCLc^Rx z!or*Z_zD5j_F&2xVnKijEHDxwY6?W=4#X_Tpf|L~AJP#DX%7d@(V%WV^!YOIECy1s z9P(f_q--tZPAVwLfLz-IxwIYpa|bxL8*(}ia`FK9`FrrA5F$JR$v+PAPl9jGKyuE3 z9T&llt6=kWkZ}{b{x(P{gCsnJ#FvBEr;ueeU~wIY7C|`eU~VS}=!19J0`pNkp0{NDUpWV4=o5QA0lH-XK(0 z7^))@**YK9un6^nhkPE7s#=A9l!U&w9(6YZb$b))#%A=D9mq?&P!|N~GyBk|zeSxW zK>d6Kb>tZOyOYT8P9ygfp#;C7c3wheUqf!aiQ0Gzoq89MdLOywF=|B>D((d`rVhDO zgqq)k;&vfIdr?6HXkRg!Ekm)@C^sF7WI*F4kf=8(#7C6V7nH3P1%60J}4k)gI~5GM`nyfL#;Idd_24u3|q-WS6C|%hK7U z8`;+~JuhdoF70HU7qEZ%hJEr|*6{+?k4IR-W9)BFdgPyG@B5XV^BXJs5^Kjb*5;e6 zj9cvWWgaQ_*olu=@f9rIGuE9%i$oY!4NSp&IF!gByrUgu8heUWpf9;x!rTP9U+{ya8C0) zPTc}-O$_H*ET>{Q_dx=;ESYnM&nex&y}l{@(hknWY|gnH?&-bU;|DoEALjg6$Spj| z%|8*Ae~R6jxlqQ77pwk*Woh<`jrcyJgW_F+9B?pYuqH7XCd&+ zlsGjtPUgXrvg3z+{PM~;-g6$Wj<=+N7u^&e-o*>+<^}b~`3}cY5B1peLRw6awGUmN&0Hu0})OZ#Vb`uW}Ir}OwH4)A|Il=crHUs#x) zf1ICxlK;(_^qlkQ*%$dcuJX5B=VuhBufLO)a+ja*kRM;c=RM;utK~1LPm30%hjpff zb@PMz_&!5?_GlVQp5~_ElXZNonU9?0!{76rrulYX(;z_b6_WeeHutSl?gTlMZxx~f~*_4>BYGz ze+$;#5v;zS8&{qiQ!Q9pD_B&Q8`ZEUv^{5TXKr9muJ=GLOCs=)3+U=xqIM6~C_qi* z!l!Z_Kjqra2mn-QwJn%-6uyHACou&UywF4ys%b(Qt647a;8B2sh35r@zkDM+nJ+wEQ1IgsVd1gD zZ%-EFpBC;bDimB0?zkk(zE-fgSeQ{#n0lum<-RcSapCgHg4h?rn3n~M8w;YF3pt$y zVLb&wuZ6xNLQh!%TPbAfg%pDjHzCBlDL{NEaGEKwvlc+1=d5<;J~^F#3qNPUp0kk8 znW*Q~jPr7Kk;L=Y5#OSLz@pyJqV}k>O$&y+!3`_q#*A(8JEt3O5Z5NK*UZH0TJjAU>(-d(Es5W) zp}^wa(3|ZMH$@AI>lYTkjQjKD%0D|-Uu#Re^&q+AN_xrd%;Lvc#kaC~ZHe|`UN*AM)0W83ADgc~Jm{<@j*_l?v`SGV829aD8Z zx$$;PU1>;dad^WGZqqfN_UjRyHv@W$g9mSUkCw0%CGMKP;kv&Zb+_Qg5*JH}!@Clj zkGFtbjiV;SogjqSnuITfv=nAZ8;Z)Q|Jb4lM;k3)tl-6WOtv2tH|1xfLkZGJ+ul;hr&Bd5!qtxp_5ixsqdg|vROZ=G^!euHct z$2IHlEi(5uDZ6#lr)?;ptv9T#J+e(SueEMb>&vB$uVPys#y3A+Eqc7Bxg@pa`i7Q2 zH?|e+srqqu^M!+rmv+?`9j^cB_g6;>T7`$&e>%}{{B+y4q87oq#)6A2+x~1zD{kF* zvwclTd(wm6l(Oc;%C2SAEz24^xsCNf-J;;WHs67E#z;e?RK!v=5w%TpW1GFXm1t># zO*J`Bi|nl;U~K}>5v#5Ev!i4RCbnQC7NXcp6Kfd~1#3|3IW*!sG!Qt{6FS@$IovdF zxPIYC-O{laF|vE{lB&ef2dRo*H%b58JXpSY_{s*!*`4Bx+ob1n#(p{`6&5Ij-^dGo z>^l6Dq~Q3d;PlAe3nP0jOVf%a{E~s}lK$<*{h7BV5l@D)o)0g2)|n_8N_g>lQIjsB zc_gxJ)Td7zAePYO!*tDnw@FNy7-1VFD6<&$R_ydqY&RnYw#I2Y(|bp=1!kT=nZ|Ku z6Va@tOej6gBVOhKpYgsxb5F>42WPxFazYd}QMY*V>0)zLtg(8P>Ha!X8DCw$K~t4E zd34L$n_ErSc9?!UVmg&)I=ap9!)e{|QP7M`^>ex`1fwJgb6nlw|HY%NK(7Hza%&$6D~GJW>&`_lsJiLKV3k9|0M-1_4& zYtrd2N6yR~K4;zXyLHF!pTECo-EhUqE4FUGZ(US66LZJPsj#l7wMM;ovv9yVzxLDI z*I$^!A0x+Ryyfr1P~~LN(8nxphL1Sub2WLHoJdzth#H2ghQgE+Jf!YG&ES}vOal~)if%R`O&>8j zBi7vJIrCZKDmBw(6F{a3kQtD24N+#qs4M{nMa_ili&AS)Yjj$T!k`{AsYhp}{zoH` zHUDu?HAJG0%urJ)DiX;^rmJvN6@zGylhty9&P3H{h#G~v+DO!n;S4$hk)$P&loX1A zMAs0>Dmq0^z-x(aN}57V)@X?aHASwVnhgYnnyS^R=^7o$prXt4ShI?vQPDIyqE5rm zsMK1WQuDvcibm0p z-Q;g*N()7+A!~>H*8h4f+O^}mV26B*sKsGWlqYUK~Y(gBU zRbzBA^4s?~vw<|AQhG|YRF#G~u4J3!Y=s&v*OS!-vaWwZXH;mF3YFaSQK`@=yNwzH zj^;*UVBFo zJ@nLJDaJU)9Da|`Yw#K~Lp4So*P5`ObPS0eFV{kJ2DU*BlWLsI6aFTXN^DT7^`-%x zX=GeEtW-}ZC)l_UG8yTLVZ&fJ54T_z4MWDmScG6YLyto!F$^Wcdjf@!P%vLzXpI=M z#@zsSGvde^3{~p~*Wl@5hKJgppj06Z5{9OS{CNVQ3ZWaNz(UI2lQ?_14$#*5tSahOHW7j_NTMsgHVa z5*Mstk)?R1f$66vP-Nb|BXBz<1EqB99mJ2l!@i%uj%#UVB~?F$8P^yYv(FUiFnn^{ z>$TDKlOj}SV42hujb>b9(2uEPDy2@MAJQ7+GVP$Z+Z>py1H%K0BVgeeR}$XK%acjM z&^+CB1hSaQkWneaG}D^0=!3Dc*Ul=l|M&;0 zL5kL^ymexLR@Cq{3f}3lh(-bJ3hG{V2r}TsoJ=vlqjH120F-@Ngz_) z-IxfP8=2~Wq%&Ytu_Hr2yA_tE!cs;N9x5tYO{dPVO*pumIA@g1*5XjFNseY`nug+| z7(tlF8Il3`sM38*?jcjbRSKe6KTL7adAW-j_;EB^PV*Auy@oyDCOT4w`Jkp-+uZxa z)H);K-4w35&&~K&LDU#Ly2r_KIpU4P%QOiW>yff453}msh)z5yF^;H)RkBY*D#es( zy2iKVmP^N2dN)9U;6>OVf5ab-Plh62U$kR5zyU)Rv3KlK~io|YFK<(?;S{MM%2mm7k z9sgDDoSriF{m^yLg~7mwyJj0mO0Y4l?=SVM)nqg(qDMj#?B_-}C2zHvJ}eT=?;K2Nc5neJ z5eC+vzyB`<~8u}acsx_(a7V3pF z#Fj#~cfn!rd9@WIUR;5;!$~f)p$-ahzToi8xUEmNx)Xsz(U^ekXV>IYa|PF9%5U40 z3%DHTxr;%uZQn&?Z%t60KLwS%6^caLopY?W=JoY2eF;NR!xjK1TgSF#t)IW^dbeYE z*#d7EJ*mvEaVHNEB9e6DiI5&e=TxER3`dUgrEJx4mU)_4|G8 zfeXNrI0$z!_zes-MD;ylJ_P{2A{F4tHXTbFwOcyH(S!6*n~?cn{wjyDP1Pl+(czd@ zI1$WYgZM0L+k%G9*q({)eH#xz0)xSlm5y~$k2~X9R4IeOk+jGKc2P^PZ}K`N>&L8n zWW|dz z)Npz(NIV9dsqig7fS2s1!3DkVkJTh>1t<*g3kK3f1GRpGm$BVJ{`PA!>A()!wY;%r zY3uKx+LHyAEJuee1UF|%IM^|{v2Ohd07K(lncxwSPHpeHOKNh0J4Z!0W#!s^&F(3q zRNbI-ZQ2RAF_6e~a1AkZ!M1H8UBnKth1h`PBS4$frB7(Df%hfkIsPkO@@zy=vd3(3 zUqbhWgMdi_u5ch;(DTgw(RJq@xTpPHAgXh3f8i!)gn`&B2;0r3BT90Q*;p0y5;!>H z+<~(V5NC>dVyf>rS4BipcH{ylq|xRhAuK3#JS!k~%PTotvWP)^R?}J9)?#P{B zNhVmB1ZfBveH7Gt(V-vU01Sm(yWaM;d;b%fycF8X&jy(SJI)$V?cVd)v$d72nzO{t zh6IQUK!f{`bzke3gXQyLfEyFKB@a}wdMmi?MWBh`hxT9MGIt@UL=JZ?YWoLhs`Iah z+RaAT#vV$#32QH*bU$XbMJyo2uE54_0AooV$_&M){5GGtz{Ara{RpzmQ7lV+DM@Ix zgMzg?XK}?0t`sTr`ldFSTrePf2?$&4tleB~_@+^}O|)PYSico4Npe+Zyeg%L{;+Mu z;6XruD-;c8wzYPx8L3~`xoj0kUP}pH3jP4yx*bjO&7Dz8&|&idCmsA{GiuJ1)C4rl zR$~;yK5@Iv1Bza~?bS@7w1?Zm2uE@w9Jt9qpL1t)P0v_jEyNzc(SQ_yP_1Zu>et(| zcm&u3M?1h`xsI)Q(7$%Vz;B`iL!%<0;at!XF?hwM-um4$0tIY62zKqa`wcSK6;b;s zXJF&Ez>fn6zW6H2gAe;V9#VQkmjQbmSQO#Oi+FLr1R2mp*AuyOtm7b4Ra56 zT$KdA9({R_QZHWD=jjQe7Q1=}LyK`Of8*p236HZ5*+fTy*}kpL6Is6#HP0KMAmMnD zEx#AB zEljqLJz!fydeTT8u5hdM4FDtM~1pxP(c zF+Cr>W;ZbIe*N}P{X=&N#u4ho0CSex8IxXG^Ca^0rpN>kFTgWnv3()WuR17ng1*@r zwKE?Cr`R?y#D5a%?~|WLW`Py!?eVTq8gS^392if)eXTtn>062iZ0((27+pI^& z7Oep5_J9S!&u#fJ_I_sr&~|tLyXxHA?mzVDKws8&Cn^8gyTW11{wi98Bbo?S z!trlMwWf@2AkQu_{&Cp!Kp#Nr-$i_2;OLy zwFk7Yb>-e&)`Oy@$tZUwY*_|)>>1w2?0Tx$+!~)sXR;99bHEcnkv6lx*tv;} zcL_}gK5pQqYyDMF(;Kft`ho0UQOQ~0>#_bAsuM9i^fu0OOP!|nE)RM;^RSgNSA7@=pnNQPyosUP|+A;&hY5cmpws4{yre< z1n`drm*{n$HjC8jns@$ycXR-L(ZHBJVA|IBWncSshbFckz@nT{Nbu!&@8F`L4+qO> z0U#yE$5s;8>kXlNRPFazK1qlJ^?hud=MI~iHx*L`Sq+t=H!6l@YTDn70 zdWna>-+Ax<_nkBM%-lQkefQ3pnRDiD`fdq8p{=f^4#2_!{1|H&LsU#$IqxCoJ-yx=PoEFfwRK~3(n=~; zULBJ9zVAOmzjb!q%>u}9vF=O6p~M9M6aa{3jX;(xlD{=Up(QABumfoNcF#50g^$lyzW+CXOsG2%L0?X@jRjqP zbOK7eKF~PJHayil2{sc?k50I;b@xB@GzUs;9L%*s=53GcFU-D?7nbHE(cBJQhlc9n zXRb{dPn_IVa@f@#-T|g?PueO47IH(~c&@sy1NFn-7QZw8Zc*saayxYgXw`nrffSB< za<6RV_T$U(8m6i|{6^%m@%)r;m4$7g881XS`wmdIqw-3|ejI1Co!Ot~%J@9g=pl#B zGuN9NX1()YJ5U8V_5;j|tQOrTXINWHCgn-<;>XV_1=UmEp)prH5ev$Q-%p}SZh{|! zw}PwRWs4*nFA2Ph_E%{7wrjDuX&&?Q9@gtqiaUS;jz95&>C&I3@y6Z!TQ}yK*MtrI{mpCj zAhvg-Jd)*@d80p7FHWicFon!STjQ#6K;CrF=r#r?u1{1ndU@?S6+5LP`8eW4jMG+a zArJ<^?l1s=O6w1ScQ4g$LHDN1ODf$JaOim0?z6sKHzMsWp^qDP0EyGR{LpCxzIS7D z%Gm?MNoy~==gEil%wLYQ`dB=YC=}Hw4I&|Wl+^Q(Kx!@z3IJ8F7UvQ` z$|fNQ@HDYYtGqcB*f68#SykfTxU8O_#jLHt zD&gK#AzB*5iRh^@L2mtccbQyIUe{$7i5tKW#qOrco>7H>@u0^e@_noLPvs{CAjJn- z`uf~{Y7bP!G|>hvuBv`^v#>!AG8(ENoUQ<)=L65{HB0gkV*?!a#EG4Q9z@c_YncG8 zzBAH8%=1~wk#ri;Ui@Fj)akP&2foXuRRMk?i#gWb3?>hnWox?ip8c-(ySxKD);+3! z1)mTy_JTSt>$n9Fs+z^)8-Ky!3=<1VAm~06@>oA@vqO^zJnmPz$z)jxbhVF5EtrDD z5#AJ7&OTWk6|xAdKU(!jOzfe$G5=0?Xx`RU7NA>uut#@m@c4IotgfK_PN0>-nVh!t zdW9G&!_V+j9Ym=c=VvBW-x&e}|1M~s9kU}N#|=x)b>!llc|+5N|I+07 z6_@V5MYMcArbgi}`Klfp_(fj>(fI$U^RoRkkc8ewN)X;%Dz%eBv z;uhy;gX#uee&( zo;l{b!ZDAlPtMSd0hi8me9V6{apDYIe+WLkD3}V&p83-fm@HGV&R}M!-{^0?)Pf6E zq8?!76aajIK87eu7^prNmFvCq$)oN@S2s^eCB3X)cv`iZo#)zvc#8KB8s;<4#`(2p zRLQnS%~gxUX7wlALbdQSN;%b8$3NnbX{69W(OP77%A#+K06psq9j;ha73ve@K35na z#_UmSXkppI$fDAAIC}I%Yj?iZy+dAR;pY?gzGEhzl<4#G**JR~gNo`_%`|TA=<@9{ zu_>B5e5c671hOw_y-LZ-9&1rCw!SaZIMKn4C^x-iuxOD5igt>Vi!1FZF>Oj-(14c) z&UN|?sK+Rh-wW+SYq0xfUf)y$?)K<&vSB1{m}o<|JnVU(`I7N!L$lZ5#j$LLbr&llTn_z@XgecZnwu`^2N6^l@AWV8eR;Nt;+Vq zt#wdSBOjE(6m(lh9Jo1am|>HJ=i*%Ky+#=+hI`Xx4>O-;#VDyr&iizq-Un&#wQ|d%bna5X}E!vP54_!LfXW?F#JI(oG8Ds;?wwRw?op@yFy$;rXb*4f*$=E*r zMg7?@4iY~q*OUSlwTIv@9+<#F`OUVHzo|EOZ`U6;TiFHI)_f2QvJOUL34aufUm}g=K8@;Dh??m@y_gk#8o(mJ$acNfq6hgPiMW~-gJTxjeN-I z(TYf( zi*&;%!)?Y<)LH4*0hbp6eGe&~r`A+q#CXliYCQXlQk%+WwDg(M-GUW`q8U?ytvD%x z=!wCGb(naWTVzUJ-JCtYP-Ubp1w_PS44&2q^iLt0oA-D9tDzvmIVWE0H}~jsdkKeS z`?RxO*3=4QHB);;{n%*`HSY41n>5&}r6dL`Ap(tBfKC-)$&h}FUhd?*8EYV;NZ0Zo zgu4{!%9;NKZUmq_)YUlHdN_Rxrcxr9^YvRBlg3{xa|PKIypv)PzKUc|r-V8B z9HZY9@s}5LlRvJTYZ&)*GI&ptIzOozkLFhc> zVHK*2SK87#f96kW%e=as4Ec~*!TGroD@~Ipe1Rv(2*@^|i?33nbpQBK5#E3W+`bc1 zy>hMl;W8%68BQQypxiEQ=>@qdZ<@A_*X<7-7p1A^WS|4(t`KI(Z8ca`Q4Olee2Id= z*bmf_Pm9-yG{gV6#fgcH#gf_bGBz)c#>FGy>@5BK$(@Qyj6f;Kyax9gcHzWQh=TPd zb6axHmo`O=DR$1*(jSN1B;BZfMx8)GCT0=zL&JI}cn4~~Ml}DDl0zK?^i^~edH~m#W$d$pZ{p3;AF68>cyj_2>Fb%a?EqKgj4We zwN^mW6AvjO{jvR$dl$u4=XiM~!y>nerUqhdE1IU9U)DO%O$b2-Xv`oM5 z(1jft&9ZBK81R5BGWbqZo9&hXnI;YMlBL5i#16>lG;R^p9w0)sI0w!Nc17W0gw&kQdA?84&Ab2%V#S3mDc%F(C5S-F=rca5o_n1?~4@<5`PrG8>bUf z3Zd*Uw$oHMP_^Jv;El`e6id$O{mWF&RpN$xk)8QAmE+T8ok5|{AopurJjGzul|HaW z&w>MSRB2(+sAOerEYN%85<@%?T0UoNTVL`9eRsq@f7daH=f!IDM$Sus07{w`-<)k2-oh#4i< zz9S9CHIo=O-Mx+JC;X3&H$}3AX0MP=?gEv~ctabEXfpZvXMDk8EWYt(*U!$j%xE=M z*tGGj8<4~j1EAO-z8)<9GgUpx6`0R0bo|k358gq%6cUo5HOpsM6ZciPm_NltD#5SJ zh}Ns6zPB*D@K5%SJwe(e-v^b8{!^$x{z~~th~9MQ_nqz%u#Za>O3jyI5)zCJ>KbOpZ}s%@PLk{RfXu(C+vhfFwqR$yId?+oW5=oaM<0H}hk_#&uFDV;60gfv&3iuRG=CcJqHHZ%THg@WdPdd>P z+gb5#R9-|qHB&?r<=u!Y831ShwkMU<=8XwNBTQSEPX12DV+vTLLe$zD7|KhM>~3az z2j09INSU!EO}*j}$_V9I<{%a1lGyn(mf3hYK6xzDC#XAi;~^TTD8HL%VP@cW2T+<9 zq|5(g>*-Q&NR6!iV7oOGy@XvILo9tnINJSIk~otHqV?QoaNCum_*5g(d6U)6qb}VL zrBh#5*J=#SFO3Jc{7jD>s{tLnHXN=s(Ebd=hQXbr_1)`7%ue_0qRW&gXC3YjM)P~4 zH2DF<*CPOmir;??I^8rT$zA(pnNTohVsVH{ z%%iCFa=v$`V=vj0U@#qt+EaRiE;-K?ZR95+op@E*kA$5tejk)SVvpLk;Wd0{th8AJ zRc1+xNN|lke}h8FgPYOxYNyup06h6B$H|Oyl2X|W^nr(Tm@R!s)SAo4whNC9wb+jH cP*!ZpdhtHUoN^VA(UMN`6v~hhM|U^#KgGJ;Q2+n{ literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/gray.jpg b/tests/fixtures/codecs/jpeg/gray.jpg new file mode 100644 index 0000000000000000000000000000000000000000..86533a0fc0614a44475a268b0a5a24ea112f2c82 GIT binary patch literal 1562 zcmV+#2Icwx*#F=F5K2Z#MgRc;000310RRC1+W5_|G)qX2mmbr zJplm`0RO}Q9{>OW1pxs80RaI300000000010s{mE1_uZU3Jd?l0JRVR0s#X90t5pE z1q1{D00Dgg0s{a95d{(Xb($mz{*4NnC+Tr5kuh6|e{y*)%>#F|%FmrZC@kl{{Zp-0B!#OU03;v_kVzY@>aAj`)~gMq9m`hbRYQ&!T$gP{{YZU zb=CM7-wHfhy3Mwg{fRlhxQFc##H^<=WrqBNfCk1Slfc0|5Kl>G;eA^E%U!#NPq=Gs z4~;@rLaPbf%eS0vA(4R#k_w#kudy5BAA>ZTTP;@WUbjmbCMvQjyOK~y&+@94`9w13 zjtb!NKs^tL{wnxmT(P|H<&L2w`rfIgTuEnUEhi5u>~Xkd005O>2_rjO8NsicbgQ`K zxYp+aM2Ewd0zFnqB4k@q9hBs-85xbnS0f|bSE>9Z_@m)(33#K!9xK(gh-~x=sV*Uk z@s*e}h~+{yfLMIM^&JL!b6;57{?We=G(Q(uX;<3xkYC(JC5j*H`=;Km%^F~ch{3GM4Nk{Gv(zBI zu#N@rV-{4?8Qq859@zPauI&;P8&?8UQh#_dmzt=%y0p?RyiIxHX|8NO-Twdy46Idj z*Jf4_w6LB;YNU`Q2ltJ&6fgso8myikv$URQG~Wre)Lo(4|R1DrJ4x59P-McIf z;5&2J-1vJ%@bAZ~Uxv0iV%X@Hc5_}_{f<{c*9&fL7E~@>;~=12f&9MvI)<;PczLxC z_)o0ny7R649ch1kqKV;29^BhYB86!P-zI*|84S!wBc0i8*m~ECu5`F8JVP`|ajI(9 zPh&Le^5q!FL$WsL+E6^T^EPfF2_&<#8yeivSa`}W21gS&h3zDDhQdi%voJ}WCvtko zrWGKlUP;bW?W?eB?*1kChFH!n`~zmuX|p7Xp_U;efVauHpD@O9?Bgr*D+YCHM_$w| zyb&Labh%Sa@lLF^@?Yv|8Kj;zlW&*zhB8^6ac;jx6^e#vD;#nEiNcxDrs(jqGqKP?jWMFy=;Pj3$keLsW-Kp+)zLiO~D0a zM>DOo{aW49RMe*RoS9qK(tB#=%)c-%EzW8FgE?nDKR@4x=kW4EK<|n|!XnYTP-yfn zZ>WzC40hy*pML-xel#%X*sQr3(>CFM^EA8`h#XM=h!cMAu3u~<@Ea_(GdS$Rc8<##<5%mI78@jPB0s4pxO zfPT>rd{uSz`I_3gx?e8TH#FGsFEwBchzp9o(0cC&R6>$9n>fzy$5v{%ETh7;>Hfe`c+R-7Gc66(HdXzoA zAZy>CW<;YN0WZdMdV|qqG@8s7Fu$d>t*zZ&W6$a8R`sfSRDDCenxQKLnxVmA?I^f0 zvti6+Fiu;?$HynGPF}k-@SM5{{08P&Z*U!!Ql}ts2|gTH71M6WSy|frzR(7XD6p- zu3w+Ib?esc+rK_|aQDgG#fJ|cK7KL}ZeiisqQPi1Tddz}rlxORzj5pK%*^ba`!jd$ z&)$3dXm0Mer@uXVJiqW{eqrVDv&H4rwdZSVYcF2DeD!L2+FpO-rd@vL&fU9U&cnF} z59jBeK3aS_|8j2W*^+H}$@XGp<@uY}E9);`y?*=V&D+1dd-v}B`}dyThWt8|LZRrA z$*zp)Ejr7XX^cjtP$(o4tFTxs5f@3G*=#GeW!sD2H#asmHaGw47^zUmm2!o`Xf%LN z!)UOd0^rLe{xZq(ip_p*v)_XI|1t7^<_q)i^n`eNLXn8bh|t&&lv38!(JfOL%sP|B zGHRxi$aHcR84#CHl|VdMR$%|A8{`+2*0K-}EIqEUgUFhrQFTdwF< z$iNp?XVP99%cfB>XiPFqBoq`2CB-Yx=U0~&m;bu?@$LA90Te3XMeu zN28UU3T20M0Q_Z+>&;dJoyf`t2mo1JCXwWq6fZ8mp0}+o%x`}D_~*y<4~Ko+;ht`X zy$~og0udP+BJb&vEBZRD#&M%z!ZJi;WHN|!GT|J*4Ez%c_Hg$>91laFkdfhCGI>vDmtxXn8MRKBwPYqhq7eyzNL(N+5egQT zmzUSp7G7^`e%k!}_fK3(%TKY0v$aXbb~;t|;yqJ&4MP1s5`>5=0G#7mihgm}aY#|d zk3&L-S~w?8F+1{1dxJ7a6}Z#s3F^X@%kiO9bA{9qd)6|LACR!E93XDXcA-~kc7~lC z(r6*!{zE3f#q&_rMfUb!_$7lZG9e{Jr(^*B#Tji$dk!BEreY5M9GE)X>g){_5!HgA zNCIBqL)nYf)$BjvP@~hPdIiuGbyKsrf~yxR=vLmB#YI^p#`^J z$xNhYb~O^S0@F<;A|8HUCZMCZ6V1|sDCh0^<_qj_x|+&?x<&KKGx@NHv?0j^B046e zlIB2mscUTvh>26CH$c3ytDDq}u+ufAvXCg0zC|zai5VLuxP&?K(psr(S9vp;D%i&< zE4DCQ;Po6z0N%0oe41}!WQMt~V7FhAoaPdqtLBml&}kXzEkOi~PFNZPM`vRBY<}2&1aDd& z<<2k2OASV$DCJo8F1S;?h!G!2xZG(CfRz#yZI1ZdiyEbC6uMWX#!ym}0CtD(p1!6g zObYr;kK*KsGwCW|4+KZ=Hq{11C8`>w+YZ2#+?s7p?y~kySS+$8#c+tn#Z_r|2pC11 zdunft8LLABSbl%4gG020OFHTcq~U2lTidiSc;MBh{7~p_{4kU6<$WFya`?pNQ9~4d zM|)joqVG?7a!C+0b&}Z%iw&k`GI$Xln(=eH5A21fv)Lz^8RF9F0Qe5BH3OZKXotKpE0Vmu3$rm z(h*g%FSJ6Acgys|CRf69*^{g+rx=`=Q;~qh4P4Fwjztvr(w$+hL-j?$!f@I^OObO# z|F9klaosg}K?lzX0yJa0F(+wa+CkWPNW%&7 LP|-1r5T@YYWX-=X literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/p420.jpg b/tests/fixtures/codecs/jpeg/p420.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cd78ae91398b194888c52360eb18e6939fc75b82 GIT binary patch literal 1992 zcmb7EX*gVI7XE5gswnrCt!zb6GTPSGFfFmf8cU-{TI;AFh_+Nx_BFN$5nIvGme>Um ziLTbsh!(UoBGQ&8iA0DkLPWxl5HeGJnPklTobx@;{qddWyYGA6^Pa;W=T8I3*6OGg zK%oFYAqVg$fH}ZnuvjbxhkS5299}?(Ab^Aji6kfli%=-A2n>r#$V!TeNsGfUl}?qG zlarU17nM|GDAE|RG^G>pQ)D1I-H z0RRIqyL3MX28&0baRLM+DTUnsPY&#*u>7Y$2!jG>2m>Ky=4wP2iRWmHI0PRl7)lwa zI(p6}*2E~R_qm76l6r`=g68qO)6K8nloh_7DD>{&M!d7G%v1iwthr(t?^sb8r1QWh(RzZrB~IH@VQ^J=}cHoNMf7i(STQn=Hrw3qk>)mDz|_c5G9nr`tj~ybE2`ci1xGFb|9Wp`)320_&r5TV?nJy>+fvRZxonY6-XptsCy?iJC z`bgq|C$|)#D+Wf3^TY(>*K1x<)|}1O~hX7+K zW_VGZByRVr;t}U6-X1!77d=5#ZRWbSV%t{0cwurs10N4Xb;1XqY}SW&Oi8(ad`d_) zI=iZF8$Ur>x-iRRGn@WMY>is!wjDJa8rRQu{Nkkk@JKT8Mq}rr<)*${S4x0TdP>77-NuL=CY52Bv6Z>55*fqB^>IX3ktOrZ*=kpVz$x zDI78P3CXJ*{nSFd33|Zi=Wo>u?3DACV@x_ojook2FMqxJZK&zHn>>+q63I8SZ2E1x zSou#C)$cz-JJ>jGujMsaYJhRX{1c&S;k8vOiO%_0GJJlSN$by^dLhAOBw7WbOJuIr z$+i#`92-vu(~Whhk+1ZF*mp$4mNnAJJzufa&IJtWAKDOii~7(=@9vTjEeJLIa3c{% z`#tX0?RRIsj`a>qDLIi=w8VtlBW>+CA!U9mHWVr0fBns%W+QjF_`Y^Qp8xxYPeU5T%y94XkhTu?a z@QsDdCPX_1gqRqE!R}8L3I@AY@=B`YtwJ2`jKXKDo6z~d69AQs@?uu=P=e~UiopgA z*6_O3t=N{Il%q=|@wk~z+nLR$~y3CzakD94w z6M~gY=8nFYKGDNm$7VLuuS%^8rfkgqaE9UWF3gMKs+19=Ys9kg|3?UZ%iiz4hh}i0 z%&Z|oPEOwv&h&j$qsK$)L5}6_cC`pb-=Rif_bIpXp3*mls8U4-lEsJzQ`vj zw6hN9a6xLE{-Zlm^xj56mJt9D)l4F1hZSnKj3`Ef5qF^xz4mtltPSX9&YUFP%$`=e zg9n{YTIki)DH9I*Udw}g`N1^0%WYojv5Nx^6*!v?0(*e>gj@SOwLFIQY zee5Mxgh%}bO$gCm%!(w>db%f@`Q&}Tx@5W&VTL{R; zFf%jN)8GR2YMfwx=!fm8_1T@5k2bgNY@6iFkS?}2wRr};?Txx@qSry>b=K3FhP8eu z=>Sqy`{>sd_j=D0Ji6RiePc<(dAa9<9bSJCeKGLol-eYRoa{3tziY?3IWbnK5!UJR zs;n_FJ=XI^+B3^6k{}^f#&1C>u~bLPg#l_N>d2!tL$+OEF*Vr1bKS?N_wHGk5(m96foW&n!N2M eeRtO0EHL}2dAENTq_SE#qi*2SB7TbW0zkrQDR5yOzwqaRo zgB-F^h}yuzY?vo(n5As|%m6+b0Apsrpf&J%2k_hp=yg@O@2>K@o9Z2RwcFlmcYHSg z7Npu9rq;MywKj3nnIzRyscOeF)v}IkPS4tsk)xJYvf)TMkX{KS)ohHf+Z1(4HMCJR z`1&UQc9nom6~DV1ydG?Hd8lIhSk<_Hv)*$x>g&ynKh)?$YK*bX)Q_s~N;IB=vop zjoO0#a00z{0X^{ob+dHtE90y4AOL)SC;09zNN0>rOQOz|LpoLI;Ib_6>En>R9B57s z^mqZ}#97dZ3hg7+pwv2@1D7CiS0T~OkX>!ykWTQ<+n~U1ZQovy=TjZWmpV4DAr=E* z;}M9#JBa=`ME4VzF%70JfXPA~ycC330)f{+8b3i>|JK>`F9_I3Sy!R_vzhu!o%&6O zx(uhvQB(nz$|2C^$+RgN?IV*uWg^WsoYfNoS9fOL8d1d6c38>ggidiBj6(bM*8I#=#oh#7nxnuQDQ9=%F|1 zfw!qX-4w4rvd1&B>npPJ0NH7nY%@+V_(Y{oP-xQ>@;rsaqY%Ut^dcFyN`ibNYyBc= z{6pUMFIjb?<=>kue{Ht>Q^Rsq$5H{a5+kj77^``_^(@hPl4|`?*JjMnX3*63rKRn2 zJL^7o%PyAXeILua0hV`mTHX$~?2NH!-(%67WN{_U?80HQ>Z9i6C(O^Dv^aCpqBP&C zu+aK=iFIa~O?tWQp=#Ux^|tYiHZiT%VVzb%w=I3UEm(c#p3lrY-k7=%ntF_wI(#rQ z{%oN;Wk#Phr?4$Z0&~2?0#>*DLm%&lf! z>wNdt`r)nqi?v-X^5^ErZ`-5Rv?G^bkuqeI2ouS}M{$VJY)aHDBYILl`jbiYxOw!b zb+{YUiHpV6CDlGisSuWw2IS0m-8 zPVzTI$}%chhD{X`Q~8vXd3x%!e%eRlw0D+iLpJHJ9a3L7r#Ge+S2~4>kn(}*e zN_#@`wf%=K9ZarGPp-^JF3(Cnlbup>BDE+tt*|ilWO+(vO>$CQ%Dzjf30G5NucgMe zCCA=46nFbj?A?P=U57#+rug-xx%6jPKRsgfDpP+v#c<*vb1IoJlR{ZY#q!dS;xw=< zO?^3S%UYW1_cWCsX&Zi}0YKimO8&ZP-um{uzd?C_!tz#7`HR>*5vhPr%U{sTpE1gx zFfVv#TQFpw|JteGh3lz)_kv!Zg6^P#JG=64?#^#X%x^r9SD&0$my%bNkynwGf9_cR znVf=>{DR`b{M?GXjM}`Uy1adt^7dTKkH4P3yFD-V=E;~_c`dYy^!YLH*G)#P2TYhT$@@ciT0+sKlfWJ-w|2qY2s9oP! zyS}C7AB~z{;F_<9>Sb(|j94k8RSWbgIYyOp=9QB+72^&SqplT$?iDXxs~)rJdjl_Y z2iN=_QPmb-)4Z>yaer0)p{n|W=d05zs}EOJ9XWsIWYyWCy0azKr^+ji)>dWIS7%(V zPHC(>c)c>Qy&|ErBKEg)p*^)>_s_AOUGjTSZq-*~@$$0Oz-7~sYQ}gK?Nc>*s*bpD z0V}wG6xV{~H5#im>fdX&{;b~ezv|8FRa=1ee>b%MrPlsKz5T0B+Y+o*ifI)QTX~f0 zY)11e^V+1zwfEN7#&$FfxitOZ*7U-yrQfTq&%doJsQI^u>uvF^&3oIf?rXWUuciLL z_1d)d3&(%EnA=ftyzx|CBx*o?SD0cf<5!hry=~-Kh@Rdp$03*PAy1eLsP|?;HEpw)8D&_DR5f0%R{2*E>(?ou~IsF?&Cm^uDuxG_vE-8<$5f zJs!St?|JRr^UAOLN$`XFySjdhdvqi5QETF(#{G}4COy7<=uvh0qjNcZCHW6?3m+aS ze|Eh1@zJ8btdd7Z%O4)Cd6aqiQOfn+gd4rP?mYH?@W}bz1FN32d*5UJzT4+2ZJ~=O>cYsoVXHl$KYOcjr+%&_6$}hyf}Si@YLzClcmF%#Y2aRMlzHs9nLsAoL)1WdSzt) zwV~Z@gFAm4^zI(^=zr(&WZ3EHpv%i4&)$CLKL$MB4%&SjGMgASn;te^7-sT^>9P^h z@(5;i5d3ve{pXO{|AsdHI}E5zt#6rHSD*eHH2niM{RK6%h@BDPXL+Q#15TjKaFd-+Yt+zZDz z&>N&{`+@$N=eI4vQopZZy%|zb$9M=7LXWvv%?}X3OY3~=a z?$2kO1{dt#&KP}~)tj2vo152Nm}Br~D56<{d=9fT1N$djzD>+a>7$zN||NH1mc&Xh^cG$~4(=dymEO~1=dez35=XCa|) zZcqPo(u=9IQBJ|oWZuB%VP_%0&~WMUy$gi7d&d+@*=?FP}T4LtWCLr;?HW)#+~8bk)qKz2AQ& zvSn7BKMgrQ^>{xGd4HM;zS@evx-Nb9`}!+<^-K8bYUJ8#%-1iwl>w}ofQ>Q+fRzzo zZULCt0;Z0DNdVwh1UO#;9GZb09f18!z^)UpxeIuoq`l2Tu^n)1I|ADtKj(;>@g;Ni zGexCFl4b+W@3x{R_UuOv6L;b`5BI*TVWm1{`!MQVaF^X-m)$fjxomE5fwg$pb$IW- z9a!AyThrox?q*Kp&g3PK_ZdSyp%Mnz|Ag^X64icnSnszE?Z4r{#K&+a!#>Y zy|P-nx>~=oc5y3_s!FB;bTUArZp9m@V-3`Z3;^$;Y1p`(@d`v91(Dxs(uOo>!k(19l_J!JYSTP3~ zq!C^G5C!p(fqqY7j$p!PjcY#{J@}yaYKA^IO?x$A(D%$O``>r5i#)<2pDN)~L=qBT zjF(AB0*z>8a2W+6*r7eYhqTgySR8>a z3Sd$hQnZZb|LHOzD0$d>!rQIiK$nY!OR!)eLQ9H43t;9Pt-Z^n8+_8+d7O}s{33v_ z@v*W2o6Eo6@8iheJULt-fr#ZGu|z|*sLA8o%a^| zI8GCZRmUM=I0Qz?t_AbO5T7DYQVdc^fQd=aMJ#LuhFk?K+AIeT;)H0}B3MfbhRbMB z{tob5JY`vlJqlI`b>uRLRDl$&I)CPrJ?uW|<@B7X{Of?o(I5$2Lxw?$VCGz{Ju9Sk zK3Vy0;PX%`Jj5ywyEtHd<;VM^c{zGv5yg>1#4;Tvwq#M8EBFsvAQf_Ci(IK(BIYYZ z3knejjYMIQ2&}Si1e63r5a9?E8mtX>#S)$%QBpjDPlj>n5ar27U^swHo$1J4q!xSR|ZSiB|i$*;|NQsx6mkFG?VC{*Jk~Wqln5URH1P2r?ve8G%>?LspPz z8N^hizGsctDkctau`?1BPXZT-(XvsC>;H_U^F=hSguxY4q++5(h?L2YJf7?F;=}*M z5X(hksj})N;li>&iH-Sx>GpmF={G)UoQvTq;G$)SP>SY{S=FwO#mK~30vU8c4q-3B z<`*G+1(MD8T$VqP^Or=TF9Pw3vhe?ek&EF7CJaReXgkfn>hqN$1 zFtBfU=n4iQg<+J~e89er_Ay$C4P8=)NHlR`BA#uHn~XG*H0kliNdg5-qR^5nv6n69 z=gS^GEbwrDuE*qHaa!P!xNohh*2kjcA}x^= z%#|szAxdn~B9h1TT9rMO3I0DeUn-nah;d*u6oLw)Xut?tl#-AkbR9H773mA6y@FxC zptYqGn2d}UgP@aGsuVDwoqBXK&xP~1cpPoa4V_~MGDSOi%V zJFyqax*q2^dcS6x@le<~kd_FETE^@0LDsX|5?1JKbJ!<*!n6V-TtW!Ni1|^I%Jq@` zaz0)#k5b5KA{mJaZ6Qmm^pO-8friJW-7 zr6#O&0wG(~5=jtCi(u}I^Yo`P-H*=&M?5A{q&VDn3Uv{NlB20IwBvsZkbGUPKg1`0 z=E3KLaIOf!d2ikL&tQs(LtT>_3Fq-Ei+aL2)EXNv`{?m==>?a|=ZeJwDPPW=QV3>w zVh#nWO+@KvAh&}s5GF|54@GmE^pV)Y|kSOCKJaI<+RARLI#>s45k!gCUWWZfI!gAYgC=0*1zTA<=C(rIP4n1XzYa z@TeFW75QU}UWez~qck3lD8j>dFoXb(km;+=J0X9ZRg=Cz{aAwt#Wcl|_J=W#neo!s zk8(o2UK>%R2*{ES>N}dO+=L>yAy;$n{|q1Th+`5x={$lh!Y$5ei-(L_{~65`iitcv z>c=6G>I;rYv>+4Bh-T!nDTU;dm_JE@Z6(5?Fenv@VPctdO(d8? zFhpwjnbIG?VIw-&84`0Dsy>C);F}WGH__W|M-J;uLZ|{fO^Cw@@gM;c@--Uv<2+RH zO846`ex3`TnAKfbb6~Smdb^VRydN`kmv9s=2)T?UOF^(Dn3Yf~nFncRqsKW2fmBPp zqO&MR$mSf|)<@!H98DfiOCW&>xKQ~LWm=3~Sc(vdo=Ze)GR2=fxs1Qc<1NhyI1_dd zGsErr;OqOHO8CWPBMghn*A(-85*4mxJIeGqS0>-#j#b;2(A zjaTTa0QZ;fcB29K*TEjrYk{9Xdh|`~9_5CNPdQ9|3>Y1*>l)1QNa!+fe}mI|Mx&1C z8%<*@KI*uSe1 z3w!@3UHCci^T*6r$*hp8;LZpqe+d^G+#Y2T^WNm&VE}-OrM3+jcE-NqmhW&D{elxH z76jG<08CBXqt_=_Qq39(TdW!Wpq3iC)nd2Y=A?IP}n))yN^@6~sX2=)zRv3gIpT{Y{T zKDux#^z43yNr(k9&C_!xf99d@(6ht=20#sQaSCy=nY;96^k`qDdjSh!5#*|i27p^Z z*Do8?}eslnJ(XsuO%l+Bh$ELt0TXU3~v99#wAF};}pY!{z)X27UqBRoF zE*|FP4i&m28mnp=Y~SjkMd|UV8H?zy52%F#I%fI^8zS^>+{KlO&(9Cm#WReez35?9 z)Ka4a`H43(scm(h`w#l=GKEo_BTG)v)A|o|0-LQ=wQW=})vWSN#;G`Lt`*=< z0?3{avrMM{)R}udNmncZl8Fj|g|w;tG26n`O%3n6#h}h9b2R(+Yf(kn z&U<%&ZA?^khs*9wRNfjqTXV|CJI&GV#17v}4jDbcHBD|O%mEk!fbZBuuk%XIHutCv zNeV;Te7g8#w))w4X^$V+ZpS7oH`S0_%gS?hRrmKbm-_B5^a%@6w;nk0xxp9AjpG zK0kKCHOv?Qiafm8^|zj#*poefz9TC%IC`Nu9TjZy*G0L6a8tl{D6R`h1C~* zvkJ}k1gg<})fjt-LFYY7n*6SwG)TS_nCO53yeOIh4E@ond-nqBIl2AOB*R^FgIJ_b zJ~8Ww>)msVV=w^NzsubOpf#~t-bH_Yv8Ue@fpoFMMOs@u$!RR4r$0()w^1k1H*P(- zBep-`+8e*lk7@S`b_ctegCq6Lx)WMndX0|k8S^zHTNwjB49L5hJN^6Ld?=YY9u;Ar z102+2@Xp$)%>j)PY+VtvD&Oaf6~ZdsGjPXt%9D^ASLo%9 ztg94&sH+WAR{b)w=-;+VjesoYmR!R^;V&Y$w#X93wB%+MXkx;>va z)EHQnRM^$-WQ01~86^gK4<_Fji@h^h{(J|BWPnyV z78qEgo5S8a{yMpf3~bGg@jVjc^D3$H-Jz!=1zpCQx7*rma4=M#DH>YHn4Bqm;Sbl# zi1XO%?D`>ou#@&%F{RK1pc|s0^evja{E6pY_eKwN9;DbuSyO|^)I#Lpsog^#v+jgp zX-+2F5?D_8)Z(!i&UM$TOaP16t`hF(TVc{La{9_-_3gGj#Q|`07clv#d*rjDZC!g? zZzXnE1E%@_%2WmZJonlqzhmw3HAVoA257o#>%Gcsf0@+ra9^{xs(B2}H4tUq5>-;Fk?6vX+Qj@X$(3BJ9nVWi;x`M``|tcmMZ(i!XY*}|a;=i)egxEX+n#5+!v zJ+E^<-hcE;lA&9nUsSgB&T_jf{<-m+yUrT{T84nC^1@t8U{)*aj08g|wXt8b}}FaQWgjnm%b zKB@B0D`3StZo{y)7~V>_c-l1MdU!=~KvGdiT)Knjy<^1_mA`)||2^4&b;!_<3241I z)^RKB!n5?YLpE;qAOr;fPgV|>njXF#Q{%2dv)K+yck+K%ce~y%=Rwj%hi!yCrk+0A z%u8(2&RV3F*&ZwjN(rGjc&eJc&Fc|YyttoGsSlv(AQdv85~|}+L_5-^f8m)2MW3$I=8y$bJiz+?3BAR0ifa=OSl$t|%s=3}fI>dwq|+ga|AdEKU_#FR?y(D{08l1?c@)z=5Z-m&^{lBXGSt%E06nn@)rl41N63Rr2{JWld2y?UAq_N=oZ$!A?M3n|Cy?aFo$t@qhD*l&Oi z=luRD<@KG2D~6EGhxd8dspE$8@6}rzt93e>=;W^thvkPQHpCXzI2M#&*NXMTwLVT40&&(nr&1)w=4Gf z(dMJNF`b8Mf=Sj6D3mvnde-LfY1;8Tqp~1WNJeNdW5Xs+(Wj0bS8Ls~N`vB$1o?TO z==la|ZC(wPo+Xu$B?J|u8`^HJXtV&gzcoDXq-Xd(7dI>b9A_rx5R(KopMAENr8znl z2S?R;R$ldPes}I=vSpZ^79pO=YVfYU>|T>)oe*d4oDt}l>EiM!|7js3yTapG5ZbhS ze{6ox&a12wHw>@ca=vymygJKeCkYIk*d5rvr;&eRaIoNJq?H9-4=}=RZE>vT?3pXl zJIe%U(UB%hsA>(mx`0aHpSNSV7IUtf19NqsBesHY_>oD^q1SuGwdpeK21S!$~Qq^%mV z@{g}WTG{0f93dL}(=6>x;ZKs{%lmo%e9!$n&*$Ff-1~gaIp1@?=j?vm9S2Zm#-_#q2m}Bi)&O=# z00RI5W()fbVF{E2$`&{W2aE#&M+^KtKQ(1wpYqtt3DdQ>Ej;lvIv5uy=%X2jCkJvwx;b z$jKuGZ`I*-=Ey?-a+IUt818+pP@_06LpPZ_(O2U9n*m`+(B|_k@@)6&lMq@k?BrL4 z)KhJDD}oQb*ccY6Xt1c#qVzrf5bUJbJ^9{mqxspbl2;XFX?;B~dJ!0T3%z|2hO_uV7dX93KiJuBt{*XW0&Cc?^PqDVILZ()&D% z-&m$(iyYGQQNikH3aQ_9cRpcqz{n-3P(y#Vdfx|P!&2|fCF-^}QGVG`xY@ormev(V z@$JbGm%h-^pHF_jx}U&5F&C;4M;$)WmX~DV$zN&xIPJrg9sLWNi5c@$hlj4$%(fEz z&SEVV1cWYszd9vkYb1>A5j^eBvRE4p01y}q3PT|NfdK@D08khjgI7`2bH|EH^l%v1 zkS9}-T)o5=#Uz*Pww$kGb(R$$KFOYpHB!9V-64tdO+m6iNqtzzTOM@D}3I^t0?T;wkQs8{Hqx!vkaLva*#nq+QwE4?L!T3A9V;5}?@&%C|exD_x zJSZ;bh*~+@m6peA8Fn)->fW{pW@QFcl!y6WHvM%2>#^eVdvtoyV|{?cpU@z1`Q#M? ztSt#ySMp)~()~CUb*)pwYvgT*bLyR8&yp7kBuy8pqW60F{_cWb)!wW-NgLD3$fE^aZ+@ESU?gM^_V-`=x^$F|Dj>Y<&q_BvQYZeBwp3wIqf>mETN5KaUP@prEN z!5xim;KjGn;~~S6pVCm<-T_p}fyf#=;QHkSP!=rQ*1uc3-@a^bEdwLsTfdKxP{~7PT$$ z&x+_H`T|S5wH=>gcJ0%ncRMl*&M%U?5O)6eU?$rw*iMR^nWMp=am}Hk5G@Jb=8~cu zPgGEy`n|)?o_-Zfhkfsfn`;%~Q|W1!SCaR|zj)6m*tp^8|!{vzmIhMHzUjtMRk} zG@+I-RdN;V`&L7hr~KUP(1_*L%`w%%YWzT6`OcY)w^o`C^^^N1*Na`fxJ<1N|Gatj zQ<-!o_u0U=4g6o%XhNBQ>ou0BOSEt+8CvT zlO}ff)q!LJy@+Gg?-==$AJSN{vveaFSM^w4&JvhP#*-~obUq7xd|*|g`sQS#$hhJG z7t|}A<9#DeF{VSCS=6yQb=2nk-Bf=J=hE?l^mBRddWu~leRT2U#b@y{aEeVNh#XcV z^tmL5z|Rr8te$b(ScR~~7}HP`E)@XwbnXX`N?qHo34L&y^Dsq5`?CGZ+2{_!vXXXZ0@{P#^dmMSS&Gjj9`{6a zPO2uVwbQz#Gs0C94Zj;qi7q|P^RwPB7EZ?M95l`=l+)?qd3*2_m(1b->0N+8kS#Jf z;9DD}dA|=S1vwa_4#}s_8(v_`zoBAa-ypkwZg$9E`P*#cfhhfloKt<1ni3&`k zyXW^%oByqaMEpwTv|9JsoWC@3FKSQOZf%^sy1s;q{*L;_1VkojPk(&&FL_67eqGsM zbxEhOX!9@Z7}0!vrsUJcPm*5G-iEGLr`FcykGkZv5HIg}%wITgu(kBVwdB`EdIQpk zUqs%M7H`P7#CyXZ2nEb1mLRR2aluPJ5d8XmJF`voF;>#oGy_%&WlEGV9B^iBdxrAx z<7jk(p-calgr-0J1PmO&|~pA%7#j3=J)(p zxlt8-9+eIWbbAG6k&m0p-RTcv1Km9EmOYU`hqx{PHl;=g)=wFCwu|{l7L5l(xtj%P zCXK|F@Ot?j?CKZ)vNdg)02+^eke@+SrvEp_;mYBAZhAvf#qJ~nPvL_<fV~CC;LR*;snLp`y;&jy8E-2aJ|lm`z`nZ z(V6KCL)R0<*^?G)g=1HW)5k4#&^)EPfJurGI?N->KTU1)R@g+AIaRIy$3lbLg>Sb% z-?oU(+GhwKZP*CUGV58kJzcDKEFNmf8vwliR%}@1wU=>J7kb|Luz8=UqmIIbKJOyK zNNL1(!1KbOrj6H>BFfNvFO3=7Cla@yrA7mkDFYXLq7 z>P$yxptUTxly89NrN&8JTVxYoL}Op*CJ_kU1s-gMAAP=%0dk2Fs5y1IT+EsI-G_)) zS}=?^kt%W*HDDg(Vs`bJT?t0(Ae(+IGc2laADZeY)H`8_plM7G=qZ<-ZQ-Q}GQBc0Q?l|+HavD+07pnom;S}%b5wRqf_axZa2w0RAz2Zb@1^>! zA4Pkf@M(!+K;t^{NhCYFg4H}9O!Z2^e);*(G!8hlDiW4!j;8tQNmz@;5MIvKrY=UF zYiw^Mq3W&ZefO*5mV=o7G$|o#6Me9b((}4;b#o{;sM=k4Nxe2e-FU(+qC5r+!6c=D z1*>CC%q_C<&4q4)Hg@)zmXd}>aEuwQ^D2Fw8W>gcl))HbBY|R}00G#P@?T~HcomeM zO&U{-1;&4Tg8CM#Bx$156bD?>puTTWxfF3SJn)=8)QJ2T64Vyi0n|+u4qAxQxj@%% z-0(gEZk&RTwN1~5!SzyD+!Lkl(Fv zn&Ib3IiYk4^>NINknVA_i1fgRZi&jL;@V3{sEGax0{chd=-;a0Ks&#gq+I!b?)_V4{R-HtS z3nzpzJIrNPSeOd{Q%LZ)3;5s;#yk-gEYOjGiUx)mV2BO+13_mnqBR6a!w{kfL`@WU zvk38Q38+W_4-*l0S0Zk$L0nGX zbXN$bbrwb%j%k{Qsf)(EiNU_)VXD4EmnEYgq+ssxF}E_%#hIADwqY*qME|zO>ue7C z)M4~5-=lvzjyZk;ee`Ec?rC&RAtviQde=qt_RHu^Md)=m(EK~-)%P*U<>>FK(7b1u z*w^Ujdd%D=G*^ZRYe&!QMo;fYPa8tB6&QvV4V%!!F${Vf?fDVo{1szw#UKIOYRCHO z%${&#zxQN~V%bI#TSH|lyx9XRcK394M=)C!;wuSbH$<@CM6q8iV!d3#u3E}^l*qc5 z%)YyZeRD0lXanoY7WSp>?DN^I{C%ub2iPZ%uullt!XH@QpI{w4$=a9C$~wp1ae=k< z5^K{{_PSD5+Aa3#d+g-LtYsCfxM%Feuhf9NT#4`OR@TfeRzMHShQMc-%}}!; zJqu@HqsQ6q6Kv-%Y==n}0&pggoUhKD33twz2gi)%7)TryjWf*P_OrR&0o;xtt~7+( zJe%7vhx>Xy_jxq;*%D60GS1`WoV&@K+pD?P)4A8yb1rY@{;{1?DBzsg%RPC3`%^CW z#4(QWpPbwuIR}5?>^;NTb&j*+JZH-voQ+pG=_Q=ho7|Lp+!c>FOUpS+o^oPdau?Kc zBN{ki&D_uyPH-nDpohyI;4+7}R27%33&WYYo?{&M2`=gj2RX$BfM<2&eRJh~^yIz6 z@GN+qkrJn7@J3j?;c4*$!MwL2ytdGI8JE{IFRm^+?oBN31&>#`JnnIF-2D{ZoiyH! z^}OOuaaXp+U);(2Z4WR10PojB@xL66|M564??>LzpLmB(#qBTT3C{C&{t>tB3NN#W zxAq2)e}}i~L3~nqT*6ac+zVdp8{WeD_((C2Ba07fHIy&q zq>1M8>ldcIUY!0So?p3~|0pT#PDh zn8*MAMB0)6;2-#vzvpb)?h9$#|KM-A%+D-JTYH_q<~D!T1OAF9Y4Mf(*ysF3uhXL% z_>rQtFlqX%R{o4`zF!}oHJI)*!l!BYBtsf@G~M$Z-|Z9M=^Nk9%0~dfH#@->XTb+| z!I-DOgcIn=0wql_#1Qne1>FIHj$lDch@d%4&=?`8juO0Bl=Uo5P`+&U!$iT|m4aJq zvP#!xUE3hIv?=@d?OBC_tkZi1Kkv^vaVYD!P;l(H;P8)v11AN0^98$p6Kp>(*m6;@ z;hKP7DoDMVwep@|`D4M-%H6R~1u-wPqG|=HZ3Bt$8!iOn&_tJ#7GV+Qy3jf;rkIOsqE@bEB?-QOnDE#F} z-if@tydQ)|e-a)#CEQ;i%s!vD^AF*+E5gl1!i*b2{vF|(`@-ZhVM3KK?s;D9o4n{c z;oK%+xFm0OTV6<)FrYWjSDwcl$@A9a!3H6IREU0;=kY1ed%AGnuV?n2&fiv8u<7^0 zomUDrUoA{8KDYMX>5Rwc);!KnEYFXwzOeXp{({~V!0Rsj8iu?d| zK2v=br!I7}6nc&qx_>Ni{91st76MT6)xP+XOYyjS@u*jc30JHq7b_^ma(bzPSt9o< z>6u>IIkU7av_ukKB8n`jSzP)mw)ACYgO`f;UMty9T+F{-vb^Zl!rMhFp4?vg z?0RBl(c+gkVw$eaY%7Y8mHM}p1a*}#d#(k^i)o4ys=CBSe-kp7V#i87CQ4ksmfBC2 z0J}=7W96hv#b=L-33TNIrgEHEVTQ}KtjeBg6`g_QEi)>_vns{2s~W>A-$YitTu@Q5 zxUw?7s(g9n{gsuasb$4$pIl#GR+{zXVrKcDS&vR0t@`no2d55K{qy*Q(VYCc0R*89E;qke`X|lrJT7f_`P1=jTxHf)pZyfUyS#Tmf z)TpL54l|pEe4F|Ln>uGUwagMrIbv}{Q*D&!RcvE9PgI#8zP-Hhep17OHR7A;lIv?_ z=QG8>rOK}5)}P819nGo#NgzIXs{YtX@sXb!_xxI)moMIOwqeKl`h%C6w*1+=>56pq zy}G1|npJniORE~=>za8_8#$e#1r2qfVlk(=ncE`s>lDxKkuZiDr)io9IuYK|=rtzt zm=HOCX|kIX0nl%?8<=$N|LD>84m)5W4H#&BN@m}nckc+hw=b}#Go+_=c5ib;Z~cOv z*D>ACV*9FiJ#`5K*OPi5t?sT!mtV~2FU{z=x4Zk-4az?b$j@)<{f`6P`GONUpM4X%1LG{356&U5*Kvfia{`h#l+ z7k2geb#~2d?_qRy`}Ovdh6lY=gI*dr&LsCT%iZ3|oj%I#zYHS4s1;bgIGW$PSVlcY zjaZ8YvJ6u#{q)fh*64trr7OtN7BVUg8x=*4)+`)-WwS-5>ZO+Qm6nHTmaFSb7dPmx zXPVA!8oRh(b7r^UOqS{N;rAzwzB_bWefYHI%<<8qKaTD@X+ChyvhDI{%2i|9HCAIz>F z%`ShN9VX34s|7etS)C`px=nuan3_OOeZWk;BTQMyQ-*2Qo`9*Y;K`PmQ_>KtB-APn zw>Csts~1~e#aizrSj&^GcT>LIUitUkHP#Cm*2^2MC3~!wwpxEbW<9sxdhFPz6UVLR z{yDkh)YPHVliBCK?YU&#c;%bm(&t@QtxK<4*Huk@cV}wVOKW18HK}ZB@#{~sYORYz zUuV@%hBsSj9aCZbQ+`8}bfp!i{u->c;@?kteVFw4IOY2Hq~o_K2Lc3>$z&KJ*o+L5 zYzDyuDul(8O+>Pe3~6jef^-DfHdn#WFjY&0)p&}EPSv{+M*?wbB59n$?9-7(x+$YN z?2wM2AEv1KV6By;?o?25Ix5+=UrUCyRIGv+G)TcJn0^*dm5DUaO&>SF>Os6&OC9O+ z9{C{051M^+wgc4O1~pML>^Gvtj=V=}2Gj<_ph9a_Y7J_QPODXGbxP>}82=6Ue|uO% zqNu4P9f_`{Kx!gI3&Sc3q*FmE6|B{eGzyx==2fs-OVTSfM5+cR+PsoN)|04eGD!lLP|BPSHKz_NvDF9S~bmffL24%sUh2L+r;LLYN|q`)@oFm|2h5-)X@J1 z{NHc>4g25G{ugKdO_G0K$$!bozgY4AO#Xi-2~4HH1R{mx1yOKxm;w9HVGNl>qf_)` zq86f?nOLnmY_=&i0qQ3~de}%MDlvXqD#?PwtGwt+JYB`a8FUo2oTk>Hl`3DO0qxEL=lPEffWg+t zWD1$0C6F|pgdPS}L#B^H(4Z~;B$9!sqtbK)U%5ZFpFkR85OhqU(u1j%yIVdmN6eH_ zJyqR9vRGi1iK5dhyvRBV-9%=Xuq*`yt;MiZkfRc&TCneJB}PwI$_Z^I%11q8Sc4hU zo0wV^bw~%Bbkp?1M4iS*q4m_6$OAT{y1{WpzjjD&G-yV&y(aTGk%GtJ1ANFh?`c#b z*~67ifT%uHDwT*=kZC3oTkS<}XOQ$TM$Le~5ov?43c?!*1OtVxqv2F8Y#jrw#@Pxw zS*^jTG$f^#p_J3*My66jQjLs}{YOYXBV?ulA}HwaI~uGaFl?}Ou);txnlL5c(^mg+^-}RH&840i9Xf*Dr@C{$z#+ znFv8x$eT*RkO(Al5T5A9plczl2}kIMsVXv7%cPFu2z_L{hCJftZDNp=M23!F`x>g; zk76X!lpi3|kgrzdWg3Q*M#iX|XdLy_3@K@NC6%J05)35r5Y|lvkqk8dAqu1!l9&VD&~wZ6q0n@R~N(kcMI~nDCI91gS{wdKfkna5`^_$%Cz? zdg;CY3(k93XCzp3SnUwesKE}Z%q*jlpw{?V#;{tow@FUZ>+u@1w^5-S(dacJx)Fog z_E72+DwP5cQ5gg}6-Opfs5k}&g0UpL7YQOVU?Y~&%Yw`_$kuL|Fi^J-K?9Mr>=7@5 z2FKE{X?mDBGL2zmU!<`<`!_@n7^cE{s;?ZP z*}`t3Knj9U!%%m_iZ1%w_auvsXfgN1AaV&RgbB`j40cApx`^zU5dxgtfU})l6-V}N zU(H2y2cG60w$gsbK?m_tNp*1jhwr7XD6lRYiD#iITx1u~Z52V!<97fj9GJ5P3@6k) zo%yySrri?&q?suCyFM5ijlN}aifXH}<(Y?~=0WCvGwIgwzk;@!sg@ZL& zz;dXyIkHW$Mr1?GTLq$15!UaU^xMU+eVUmeAU4I`&K}e+XnBm06=R!$8(6;4k>rB7 zPj7k}S^M{{E>A~9NF<885PZs(n76cy@2jWzpaQ}GZ8jL&-C@mbxr>pYaR8<{Q^}xu zp}22J$78m{4glXU7oXYoU5g}>$67`bdxMwQEm`3do(gU|HvYZ)t%2XNE*tPO-2+0L zDnlA>xHb;2XuIN6=i=m!gMm8)UIcXgiK;v2REu^2?w&5*(-GHD&0{-7?a6g`3?Q%p zoei32c3$_C7hKVU^Tf6jSsTmSWtC@|0g%K%g&>NY|AkkQ(k z)Ujp<*pQ8y!NGT|dSTiuD1@nlAnG2E?_;{_GYH6 zCaikPeupKg?ide;8y-DH__~R#)>T`baTtfBEe?}EO8Zw;SI&^eB)B-c+kUd6tT|ok zb$i0$1Fs?@>C+0^8`mAU@N9@N0AQwvi#?F9?d(}9yG`n!xd@~lv2%BE__SNvFsn{9Pqx-}M?%5u2$FnF%io73 zkAhzDcOjQUD3(DD@e|gDDJ$e(jf|dK+maYU(nUXR} zV})-Ahl9kR3A5+B*=T7!F8wU5<1Tc-GJ!2+52n>O__v+`;=oy6-1%U}9EZQCjk1Nc z=MgPsKF!V^z<(wR>Fjv{$X-pCmV0+cFLer?4_0ipmnYQ^uW5X@tDhBw^zlcnI|}Y# zq>79tc}ks=3rNfa>ka{VvRIuVGw*10c6H(|M9zqI`LJo&u&L3swR2t!$T;Y*EDa2# zHkVUd&)QXDNeJKRF2Du6-!5uPc-gzWAvVb|W)%pS2QGm=eP)AVb!S8jDk9o(-b!%Y zwMmoS{MfJ7!5&GWg4L;B_aTvz-)%k6*A>~#oDF8oL&hXIsJ7PhENf~_Y;tn7_w+&% zVW8jKRmPUK$JN*(Z;t}(X~>==sbZ~InJl3N+0TlzDG8{Z^X9fk=a-$eByYFv{{*So z;CHurX;i&2yLpQc%$VgsW`bLo-Y-WwpD;voqZ~bOASwp&_uvpbu(fRtM|Ib zuLn?0+=ZUi^BSwzvQp0`R){0nAGvy`Q?Y}DmkCk?0Obz89y0tonUVVH%D;Av*Z2N#wRRU`e9e1H=t1wZ40FL z@RI5o?Hh&8tFuAs4wu$t4Igvrr*c{%W8Gp?0SXBe8~baxb>_^P1uFsF*B*s%n8+31 zc5iK-+YSW-3fn0;-OidTE2p&#CP|?H5W%ze3wA0cy}Cxdbtm(ak|YC}se#a{*7i zWmCDbVq9Iw0$|g?)dKtLROvJC&T^`ac))KiBJ+FXyIsv6w{%@W$bb{zt#sh;2dxVl zr17uLI&_E5KyKU%R_w5Ux3m4LP*mnEcJ&0FcvR40=fU)zZ+l;=G9+_WqLTPvP6R>{ zBe`n-dVG@v!vdLEAT|NK3~nfOm6kEyE?xl^r2@Pw5;!9z3;QIAZ|i4v5+FD3ayx)T zyk@qDxvkbiwewfGrR@dmxuA?8si3!7b9;t}c{Q9Oc^UD-o9;4q1z2^= zuAC~m=+Ig>vyMI&#H>P+Np|{m9iyAuJGn9^3fOiGcn1URcF7Zb|4WK2aXre14ptuq zUE#GA#O7P%*1-8-aSBL1>Ua~=@p^XGLtyAFSQ-Qrtp5XIw*&SG1 z?Ocv}-FN;+(B>w5!2fO=omEu^HDD@ontv}~hI=PkR&UsNM=7ApBLSialYdc2{M^s*e+X^#fBh$SWf@jPV( z+)~b|U9uW1Tme?3gVC(kfh5UQx7N&^PCmYXvk*LuYBi+SJjOL)DG10LY2(a9j;L$t zTbq;-f;D08ZXh56jID3eW=kwN^}jpSkOBZ26`@5$67Xe!xMXzK3ekOf zZvn7XBFC6?Clmx8&FpxDs~_85A06%J>T2iY45~xB+j!Eplv+DC-~k~M_;$~NYoAZA zt6;TlJO}~;5s}}y)dtGSX1|`;-<$P=gU@tlECh5L8q3M;7eRl<0pzq$cm8(pI->JG E0d+*RNdN!< literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/pgray.jpg b/tests/fixtures/codecs/jpeg/pgray.jpg new file mode 100644 index 0000000000000000000000000000000000000000..06b705b4907d980bb7bdc736f498de0cdd8cb299 GIT binary patch literal 1477 zcmX|Bc{J2r7{0$*7zXp3twa-J#vs|Ulk97JQE3wz`&f!XLbjC28d51`DT6plMGIw@ zvSj&WLLY^Q77>!ee3O&j`<{F5xqrOxbD#HlE|1F_0kDmQwFQ7603iMXyg^_JkO;)@ zJFY`;v!T^ClKnMZkdP#l<6hIRN$S{E!4;J1V1AX_rvSmG0&=91()b;g|?$MoBRzR=L3Xmix6)Mlk2 zU~c2Kenk1T<&Ou(UO35`au8#NV{`Xdx<(1zbSN z(8{DJ;^t6j>)Gtox(`|wH!DZQ(*}>ryQtA>TkGbx-E}+845T<1#8*{W>YOsMV@)&l zey)h@q%eqj{#Ejqb3O!hUJbq7V=1>{)#%3Q6rv`9l@`L@*HrF4oY#=H>DCYD+KN3r z=kQv)Y!1lH^|?M6Qhsk+?XbNtus({QxBuPSH#Z`S>1}96&P-@m-mu+G$%v7Hdx4^j z5bokyac1s(D&u^?5Jesf-Oc79i!twyKUO$t6)%{?}>7;O-E|2pAk#>?m$sm7_| zcQ5=EWLyaE+kz*m1D~f@hgy3mzmZBDEbSW?|DohqUs`i5age1SI%~#|PU3X<34Q-s zo?TZTyXdG()j#<<)!~!qu{v4VYhO!N<3&7feg3{TKt-KJ?x9wiyZLuBjB`X|pe352ZgzXq<_f{=PzGL!l8a~3-BvF)B^F%dqK4uSD+FX@uVoWUUjfp#W>D5Sc zUJJ*b+S|@9=%fgD#S6nwvaywAf1GNafmmOh=GL>mQ`|1yp488h2qAxy*f446Fm$ip zKKq9NPVzBvqp{X|wdI<278rG4YacXWEHoB!ty(Y1rHeZ53Lxbj4`#vD;#nEiNcxDrs(jqGqKP?jWMFy=;Pj3$keLsW-Kp+)zLiO~D0a zM>DOo{aW49RMe*RoS9qK(tB#=%)c-%EzW8FgE?nDKR@4x=kW4EK<|n|!XnYTP-yfn zZ>WzC40hy*pML-xel#%X*sQr3(>CFM^EA8`h#XM=h!cMAu3u~<@Ea_(GdS$Rc8<##<5%mI78@jPB0s4pxO zfPT>rd{uSz`I_3gx?e8TH#FGsFEwBchzp9o(0cC&R6>$9n>fzy$5v{%ETh7;>Hfe`c+R-7Gc66(HdXzoA zAZy>CW<;YN0WZdMdV|qqG@8s7Fu$d>t*zZ&W6$a8R`sfSRDDCenxQKLnxVmA?I^f0 zvti6+Fiu;?$HynGPF}k-@SM5{{08P&Z*U!!Ql}ts2|gTH71M6WSy|frzR(7XD6p- zu3w+Ib?esc+rK_|aQDgG#fJ|cK7KL}ZeiisqQPi1Tddz}rlxORzj5pK%*^ba`!jd$ z&)$3dXm0Mer@uXVJiqW{eqrVDv&H4rwdZSVYcF2DeD!L2+FpO-rd@vL&fU9U&cnF} z59jBeK3aS_|8j2W*^+H}$@XGp<@uY}E9);`y?*=V&D+1dd-v}B`}dyThWt8|LZRrA z$*zp)Ejr7XX^cjtP$(o4tFTxs5f@3G*=#GeW!sD2H#asmHaGw47^zUmm2!o`Xf%LN z!)UOd0^rLe{xZq(ip_p*v)_XI|1t7^<_q)i^n`eNLXn8bh|t&&lv38!(JfOL%sP|B zGHRxi$aHcR84#CHl|VdMR$%|A8{`+2*0K-}EIqEUgUFhrQFTdwF< z$iNp?XVP99%cfB>XiPFqBoq`2CB-Yx=U0~&m;bu?@$LA90Te3XMeu zN28UU3T20M0Q_Z+>&;dJoyf`t2mo1JCXwWq6fZ8mp0}+o%x`}D_~*y<4~Ko+;ht`X zy$~og0udP+BJb&vEBZRD#&M%z!ZJi;WHN|!GT|J*4Ez%c_Hg$>91laFkdfhCGI>vDmtxXn8MRKBwPYqhq7eyzNL(N+5egQT zmzUSp7G7^`e%k!}_fK3(%TKY0v$aXbb~;t|;yqJ&4MP1s5`>5=0G#7mihgm}aY#|d zk3&L-S~w?8F+1{1dxJ7a6}Z#s3F^X@%kiO9bA{9qd)6|LACR!E93XDXcA-~kc7~lC z(r6*!{zE3f#q&_rMfUb!_$7lZG9e{Jr(^*B#Tji$dk!BEreY5M9GE)X>g){_5!HgA zNCIBqL)nYf)$BjvP@~hPdIiuGbyKsrf~yxR=vLmB#YI^p#`^J z$xNhYb~O^S0@F<;A|8HUCZMCZ6V1|sDCh0^<_qj_x|+&?x<&KKGx@NHv?0j^B046e zlIB2mscUTvh>26CH$c3ytDDq}u+ufAvXCg0zC|zai5VLuxP&?K(psr(S9vp;D%i&< zE4DCQ;Po6z0N%0oe41}!WQMt~V7FhAoaPdqtLBml&}kXzEkOi~PFNZPM`vRBY<}2&1aDd& z<<2k2OASV$DCJo8F1S;?h!G!2xZG(CfRz#yZI1ZdiyEbC6uMWX#!ym}0CtD(p1!6g zObYr;kK*KsGwCW|4+KZ=Hq{11C8`>w+YZ2#+?s7p?y~kySS+$8#c+tn#Z_r|2pC11 zdunft8LLABSbl%4gG020OFHTcq~U2lTidiSc;MBh{7~p_{4kU6<$WFya`?pNQ9~4d zM|)joqVG?7a!C+0b&}Z%iw&k`GI$Xln(=eH5A21fv)Lz^8RF9F0Qe5BH3OZKXotKpE0Vmu3$rm z(h*g%FSJ6Acgys|CRf69*^{g+rx=`=Q;~qh4P4Fwjztvr(w$+hL-j?$!f@I^OObO# z|F9klaosg}K?lzX0yJa0F(+wa+CkWPNW%&7 LP|-1r5T@YYWX-=X literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/r420.jpg b/tests/fixtures/codecs/jpeg/r420.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d831c18d41b7507e8e304744ab374da4d503ee5d GIT binary patch literal 2395 zcmbV~c|6qn8pnULS%(ZWmI}ufg`|=FaO{SLBKwgnZ8S;@vSux!ju~Sr;@X#N(HQGc zmO>@_GRc-~l_4>h%o*q0*S)XT{p;TQd7kg{&-Z!0uh0ASeb{5{X+X%z9AgfEKmY*Z z1i+>PCIAEs-cOF8oP_bfU{ENGkDHr|2hInF^YiiZ3kV7e2?!zt`T2!Jg%Bc06bc1D zASNz~6cApd8v+W-U)pbGp70m%Yj1PFovu{!{1j!ziq zF9H7)2+Z-w#m&RZ$Ioe?2mxRa1OkRa_FZ$jBRTf~6af>KQ8(feIqS(S8-P3+la|XP zXZ-91%C4UwkM_D5%gZM!CN6PM;fSKr(PJ8?G_|yKbWKdn%q=W2R`%x{9G#q9T)llR zUb=kcs&8NrJ~$-wR#;qoLgJmfNy!9aIw^zv@X_PE{DQ)w;*!#`n%d`-I%<7G2vd!Gvg4&fXK0t%B+=MpwL%k3E;B6~812Wgy^`|Jg;9NLb7^19j2Cn~Qoqp-G* z_7~ZI2NwH(k^Kwo-&~Ub6o9fP05}B1`9cT+Fa)-f55%s@XvOTPhn6bAA7o!Nji>C*JwlS-}RFje8|;>bokHGncoXH2G~yzq{ojF_-J_ z8|bmQ!Up8#7Yzj2z~F&_=NFiIY~Zw^)h>9d?Xlj;k|7mqk=xKE;?77KLp1FwlxQ1y z5w2buLcsJpoP!fE`hYS+zb{oG$&SPusL(=TJs7UZL69{(zn%(L&XIb-2r2$%Xw@G# zz54USPvzyz@avEaK7FT|^^R#!=?fwoc;L86oaux6k^?5j{Ti{8LyyLxV$byIxNMM` zHh?0dssrtRtka=b_xYTn__qO^0<9`{ch99uCqe#+l|3dTg}fL+)f1J#kQ_U`$9Kf-)9 z{r1R6uS4T##XuJ(xjeb@Q@SvkRaQtl3vZZ@t22)85l`*k9r|K*1So`EI1^hTk@^z4=sxs8h=QBZ7i9ns!)^$7&g)lx^Bu>SFZK z`7CtyE1kCC46d5wQVjLWf=|{Umgb&gv+yn~niWlt9(CCBYMGjrW|1oR_vmb3F-f`Y z`P2IO`jG{&>78~m_*X}atdE7=q-nlrxTWT@s)_SY3*a_FS z$$hu>H0&A-Z;jwRpS79pVcxVgIBK%m!o6o)9o^QtA>xh?{k8S$A;x!;HGCo|vI+zH z+2Q4!yVuuuLk&c6WRjg zeZ%sDmXcWy+V!c2VtUFv*Ul;0_?Ht>@@DC0;)1b?d86<5Y`Q!HP|8X#Gq2-BCVfZC zTq$&Wc0XgKNkV3jf<3rmS=X9j%JWgzMfLTdjaY9|rO~0^Qaw!$Hj0Y*e1*kk;WQ_M zBn|D+)_ybfstAkmh1=iOtgZ{6fO~T}kYsprPnS$xkx*T)-Jlvs^+)KfEsxGr+<#c7 zt1y{0N;dQ+y{EjSXC{#N$)T^6#4bdu(ca}gU6zujV z4!q8FHP-6RsWmr23-c@lyM@pyZ2SZi{F+?9ef)H50^6Xc^t8)%inyhCMLsHfdT3IU zf_)X@*BMBO{E|`Tfy`-AyFnP)l++!-d>))5^f^4qu;o%{O;d>X94oJoa13n=I%Z31 zf7A02=A)I*7}`;}Ip*eW5(&2}9Fo$gAMAOeo{d3yU2^PuD2}r`QFcU7OxQ`TBD8VA zI<~z7ZAv~^R1vg^wrM?nHYHw9&Ofyf((8e~G%G}~)>D60@fLL_C6D0~fDS!BVBvgC zo|K7(J{ky7EKl~d<4gFIHE%P~qa8-t{#`StHjM6pE6^P8_08B5V>Qr99`0^Z&)cfa zMrhT2nDU=$X9HyOik8k-i3J#qUB7V6#LtE*ZofZb12ac0+W0QwQ{0mzs6266tO${A zub#$m)ybmV(y>Lyuz0Z%L>mq6)$`a}uX@*;F0GE5%rnmSowiE0UFGsKs%m1AXC=I~ zn-~I_W<_rZ#}b|63E-(CpCj5OdTUdv-jquWmr918sbiQ%sSnI!wK{cc=-tt!C6@@H z6IhzZNAd0pE)6P3P+bjizF?)-HY9tu$=phSQhT+@+z>vyy&T23b4onid;`;aG2Coj z3s;$)YzQZ}s6`An51UO67p386{rW_(fu5VIOv{U2Pm7vPRwoq3ugf{e$0!*#<4SUG zA1)d8Vf=Vf@ZG40iLJ~Brlwr#@HPLqv}PIf;c(s8@e3g!diJW@z_kt4Xrq4F`z{)| zuz_#EF@>_urU!wD&A_kQt_3RCV#F(uRx zj~krfg@D2dSbTrMhY>;KP$sds_syJ`lA?~qqwpSOyk0n_Tibdo__FDh9=xceLeyn` W_rlQ1OAX|f9?r%c=4@OLd;Cw2GFW~9 literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/r420.ppm b/tests/fixtures/codecs/jpeg/r420.ppm new file mode 100644 index 0000000000000000000000000000000000000000..86af7fd9272b469315011faf621e44ff604c176d GIT binary patch literal 8248 zcmXYybyQUAYy&pg37N#l5g0aPn!Po+*{0^vmS4c@^WsCBHs*)I{ zEJP|#;grTm%Ae@U?{!uBjFeuPDLrQ?{br^7*m~oAyNzvbDmQ(UnnKpsN36RL1DxFr zoY}MP^j@Xf{p%~@lusrp=O?RVW+;7~nqpb-dbR`O|8 z@lfcdlFuC_@B7M5J<8V4*4sQ^&wj1Mc<QprSRnk?>^$VqybyMj0wnR+lSnTT)QyW$4e1&_B0AzpF!5;E)9jL`r}PD3B>F=!ib#lQDGA9Ma2%ys^=E z?Erc1sQJhR*2#t5^M~FHgEa5ZxVl@tey{q4{gAr-kn{1-(@D_E6wQ(}&D<=_%v@+{ zKJ0KQEWQF7e+H6pNj0fqTiiAEh#QcATTmZ`ZbO3ZLjroBZcjBGUO;T$LaYWL>_Mpc zM@`)kP4XlRJEw^Pp(q&yv89@jYEjwrpG4%R9 z^hTuhWRkVc!a4n z&LYjS@FFHw#vm-3<5n$@zguYjWN!I~rSyL+K#BWxgXiiN&t+BaJd`VgaX>UzgyYVT zxKk9*ac$30ea~Sd?gw-3I~I4qj{C}u^U%|y!;91I%e@=mc{AASTBz3*p7+IQud}gU zHF4aE!<@2XoD&(Gl59?Ko=09GC-WrtXeBqXmUE!aJ?@HoY?H^1Yn-r~+`!u$-*%37 z56Ar($M&U%WxuPXxA#7($c=!!oP#e#?o#)=eb9^3d`6i6rA7VQgV*N4He2Aw%%%hD( zkftK=a}fkEoGc3^E{5S(!w}zj>VHOT{3~LeO5Fc#jQe-%!Jq2!zrzl$A`i-N2PLF< zAuWDRJAO((VbmnyGb8>TJE7Mm;iYr@GtYyMd=GT_9qbHH!qOUTbi$jeU1%}vP5PslBa&pMTmT9uekn;3gOVb8^c=&SKNo8u!|6GCn$ z`n4yzb|=_BOR#)%kUem~_T2&7j|bU9@upuA^hXcTCl8V45{X~}K^l)=ibt=+L;pzF z^yeYqpCmx}_}a$IwXIqIs%QS8nYDt-TEJ&X$k{?#)~t5cq+!;mS@sY!tKTa7m0k8T z=jUC zO0tfZWv5i-9yp!1`&{mhOF2-;#^_GOOE>nxkTEZg^4 zmP6T$PdNr7xmpu>q}g1&C>JNoMla;RzUHX?$W{3}5BMh!P_9~2sao4y{g+zxADY$6 z$Ql{8T12iEP^)HiD<=&rMocR|GOPNnt6tex{pM8l(7n3Hqxu1-y2GpLu76cqXmx8; zP2;ZWi+jtekDfhqxa#DQiu}~-!u0Bb^wR~|)!8R2(<&YCmf?{Zpf~R!nb=TF42O2LNsIN-6d?KZ#JmcD_ zjFys&YeiX2*`*Ds)eT8!nh%_9*;RKfvc4tqa#M6eLrlw+n6{?qJ551d*L*u0UAr6X zpS9S(YPRlcWDho)eQwqtZJ|!KV&__s;5CH2MRTc1{cFS4AB`%1H!7_)t_QmQUDx$f zrR&?~t_Afj5wv>_*)@sloS<}1YITn3b$v1J`e5GK%kF$()AiWCtJ9(Dfot~z@2-x3 zt~=ZBUk`6@*wKDvPkVhrPs6@@wMm_4Q@U%9v=^s#Km)n_D+>ugt|43D5(&?_a zv)$1bJ0q{$k8JMX-Rb7tec;>P?)0eB@o|UU(+=BrPuzMttp*>kh8`Gw>eL$PB24rk zW_qB)Ziu8yeX(oXx2~-}I+g$KT({N&3y^*>e1MO7H;wO~B=t>E zdndK~MhyBsne_Hq^u1*FKe6ubcIxYPd)wjp_KyFXo1w2;B3?B{zrMP+w_*3I`aQ2M zB=*-IdRu$+^@;5M(!AcB;{ME&{b?urQp$UiYx7|YI;wSr2a{~x)03q#%E%rfHdsTn$+w`+f z>EHf!8%EbQjQzWL{P%4W%bJsN4hf-ILxACp>yaU0(_~5677w#C9LY&AyBp zjE>PKCP>p$M8Px>oFYmm@$(ayl?nK_3Dw`HHvF7gkDvXM!2g}hU!e)-^@L&rk;qse zHWf(C`3sEMCHCyH)!dRDU+%;Q-2}59;79J#WA5TDzr~iYmBy&$E0GHqc?*|$i%q!csuIp6MH_@|?Ow&MLn z$@Ea>?B{IZmrUW8WZ|b2>Bkc*Lk$bPw-?@aEe&*k9d2J5s~3$P`~Gd0aM5n|o7wCi z27(_({6CC^-h^Bb8Q7%#aSMG|oiYqqRhjqi zCkS*f0v&?LkT|PHn6ZUUM^aYm$kMlD;e@VWLZ3gZD;#tmd6E0*R=l6XZ6;w*N9~=K z+6O&Yzc!*zOaB$wYuxPAh{uDD7X6^OCX4Q7{EeY*)D1|>%0rFfzMhvS=R%<@R9R|t|}B7dGLl#+!)jAYJc z{8LG1XO64;8(o?N3lpK?5{t*r>Mq}sDSOFIOiLs#dkSGul z#A37r)R>nrCdUi9y0hFkuXOaq7(5?E0P!Rd1|>upO+h1;sEzZOFEZr90z$li1m}_9 z5aZn108b``O2tSyh*}V07DPl5NT25WDzGJDfr3^H{vsDhDX#M}Nug+tKWJu{RY=n3oDgJD6VXZ$(CPBzW zxOpLNS%6s<;w2*L+?>zS;scp@S`N<2K#_v{KWwoEfv8Eqpz-P$oEjRZiNvAM7y?Yw zi%9B0V?+wKQCI;2D@9;sShQH#;)2D%ZmbxCkYF$}JXVB33ysz0Lh;|~F!S#a5)o1+ z)|CI}_QXtX=bLobuopTOAetgXQYBcL0E3yu7))yNmT2`-Lcat%tB8jL14_`+j}}+| z?vDc{6e&nhSiLMjtq9Re0s=VWzPi{Zmki6KBXaTNf>0zA$rXWt5>c8&ID)A9ON3w8 z7&HO#3%m2bg#5x*WE+l?qOf8mi#kUCUV;dV0tr|t885`41*U5J5d8P^=!IX{D47T; z6(D2+%klBN&X?(~!7p@7Kny{IP+)8EvHu@?fmSae_KR?{0vum}6M|^@dq%_0{sfVf z0*Y}`F=}3fSrp+H1SH9{$Liv31+zptB9lxm3Iz)SIS4MIaS$Y46M;v-@F)ZhgT~-U z2qH$2ZQ^|_W=>(af)=hw1OC^ClEo!f?|zbiNDvUnAdx7*UN2#_%8yiRDl0Q4x$&{Gn#(B zixtSxd^wyiL-8e4kysZL>G5X*mlk@&624F>P&82{lFEhiAh?XhLNHi38jC?O-%=u}|;N(fGbz>5DTfKg{Y5Q_t`1R;h3DwgDb*dgTA^JK|8l0ZZi3CSV_ z_PE2?Kw_ZA+35VsYL&uTWB`8V`!wCUa1$`(CwgOWuiDCu`QVL4I)|l8yUu>p> zBP78*3>3iUg&M*MSN?Qidsn)n$6I|PF$O&Yg~)M)6+BH0GZnxh7O8b0c4!VEmf=7U zH7mu6J~8Xo24a?FXg*(ECdEhv7*K!}h>3iu*W&VRv3O!hKF^<#3Hi&QbaieXBw?5+ zbs7bNq{HDj1PVvMi2}H=1C2i3RVp)J(1(A{&&B;ky>DRVd`M5v~ zO2wSmdk! zvxJ_XgNg;tD?htuiJQZc<~+8c)zQ54TQS%g)*@(8}6`t)}E{5dQ*pm=NGaZ`ihj z&ZdKrzF>>*$B}^d%kI6?o+Fd))58((`>I+WraSQ-Shx*nS-hqiz1L<8;fx31c73?G zFUEBrOz!q+JsYM>Owa|xwD(V}O1{5Il1({%9S->ZIbeClLn^eLnK4-q9{hWH^5@vv zSJCRcWNK+?SUf$rHvMM<`@$*n;+u!B!+09AhMmA9@H&GxxR2*JA$>@a|_90yMLO}3cV#gW{7?UfUw zG0)O6>bcP$FILf10Shx=w-2${JnOc1=TVEOP?k|(AUV)U=R;OcyH$Pf&YlPRZbcb- z+v!1*y|_!+lfOAVdA{!j6(EJUaY8KZ_@`b^9({h^z0@6I9^hbx0Dv~%#`8wy1(q>n z0EqE%rLV`7F)np-pO2?Mwg5KT>cjml3??&s_{pz77C&Zf(RS1_wngXv z$QVFaZd0>ar`Zv3^;vj#rDGli*lek*VMT&Gh^?C~9Oy}H@YOa6bkyBt18u}#RQj%_*IiP2y46^~?_1x2$)cgc$3LCK12B=&ZJK1FW zP|>~agv%BH$x2n%R@LB~e`y{&?oDZ3S$MP?+AxI3$uvElV~|$odz8Bco9-59254j& zhfI|8T#czS1q^vQ?lfR?OU%jPQ}^GOH6LQQJ8UL-s+$%%COqr?Q^TxW?Alij1IOcWqRbmuG*`@Bf5t& zUK|eex7F9&Y07GgDtqK|YjEFF7b?Ns0>&e035vRgc#nlSpYnD_8R3<9I)y?)yK<)dWlBI0X|s|eoPBNgwF{Q#PFm#IqI7q-yHf#;>pRbN1UKgD9B|)8-NUqr zB$;J1!skxB?K|FnV*3GYV6&^baiT%=i=@s%yA-|kTV1t@1%Y7$1uYHM<>e;F3&ZyM z=<6n1_!b%OJw;FXE%v%Amab?@c}Vn&l#BfbJM&BqA9V?%0Ln$q2X6$PYqh)bFyh7u z|4>`CO)LP@5^|}^ytc%uNPCl7KC!CCvaZav+M`?>0%{B(3)CAQ3DzdY}AEY%|< zl54}WvAPpcS?^SsU=pSSXb=G)&dU3gWo`|#D&6pCw#%VZztDX)oNABaYP-@J?y+FB znaTQXK{&=G$DEb&(NCwIhS2OyRbhoe`!Bf{UA3=H*Gcx(fU_YW=m3z4N@}yeQ*KqfOEo}13 z>a1a1s(u;`z?k6G$x14H#|EB6K7X*UKGxJR%7GE2ZIF%IF?R6zlVjI|jU2cv-7uz2 zo?hyggP%)TrwjmXUF6mnC-)lj(|sv7Cd!{Q@2=ozn1<6V5==O~sU4j=uRTe;X`q-X zfb726=tXKy%`osw)eRdZ z)q+s(qM+d8CQ;YJYF`(16!@k166~B*O>%7y4wgJD#YYMgSEIr6(cEz$wOuL zqsXSmx!#FZPSsus1KDjYyDDe^lmtM-D4g@bMdj|<8CK~W4QD$jIm0a`T|4`bgIy*! z&9#35K!wnT;CSi^zg`? z-3(V71Y8SH8mxSfZ<$gTT+7jPx7})z$nc)3yHn;8^WaFi0|XtW&kTTB7Fnm{8RwST z{xazi9`k5Ck8mnz9{mmH%Llqa_eZ}j1 zw_D4Dpz{t`xCI490tlyEPcP&w7VBkj4GaREjIy}VrL43j%f=ek30ES)$!J@CsQ*y$ zEm6v77VZcZ0K#01b3Hw8M-)5{?99_XWQn_;%b(Y~x;yw!uq>nBiE9}@>z>f2JH-1Zpzo^h=@NjZ7Wu_D}_xy#v& z0&Fn^ux*ho4HAlGC$niHN^kcO?M>048``zuR!1^4$qxtmAk<#amD&)Nk>tgRc^={R5_O(M5 z&th5rrkgPF?2rqN`Int5&|%8WTDGeq8S`YqJqXeKU5w3RpSxB(!Dt zWT!J4yFZ3$OGVV0mWvKbrt;ny0^7JAC?BTY1^uRO#)nhPGE*hIK2arrVfs4y`2}io z8ZqBl-GSq3prfIx$b196@l{%TpuUCrI)DzqZrR-)^!@l`&mBELm9Pca@9N&-(9&eo zQqL_c*dAe^wcgWMzul>+$Li)l!L4Iqz7|GmMjFtOgCCo9u4IsQWqED4FjT%uv G>i+{X&9$@u literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/r444.jpg b/tests/fixtures/codecs/jpeg/r444.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cebd15139e8c4c5943153a3a17ebf8e388db667a GIT binary patch literal 3236 zcmb7lcTg-Lj1k4KM`s0JZN9(g905+rqpQQ3rekpbVLDfqxevhhahg8sN>gRN? zQNqF>#{6VvFK>v(CVk00D02Har$|tG9e~C>B zg}&yjrcQp4RHJL=7ZzSvJ2+(F;_IJM&71)s0F*fiz*#^?r?4OZ9iY$D_wMjg5IIk+ zY56Bz8AlJIIK_!&Z~rkGP#Fw6dz5&lEtaq&x@vrA1rT9i*z@k*}{aS^l?y+YoSbrMk#*EILw$1PuE3|)SnHAf&(|az=!TRzq zS2R^hy3G^_?Ht2?jIN$T*`g9_kM!gs*>=#yWI{XOW0LsR@!5hF*s|ocR9>~f$z%_P zd4%xD%O2F1vNG1CWD_SgczwUS9G+@z&zVwW$~ON%p*A|ja?gKceQco{Zw@cTOM@>8 zp|Sua;|Qs7+S6XB$a52_j1wz?Yv7_~2vq`DZHB#d0If=mt;Y-IL)Pgw3kyji(KofXVJ{^xuOkO%%-9x@?YjA-&X? zCWpL;%uj?Q11Y{2UyI`VJ8Vk%-Pmr{}FUqqvT%PNeiYKOE#)YBYhAGEQ#WaY$ zK>LMB>J=-nf3LyuNsdZP5I%=a-x7@bZMwDQ$|K0zwHlumj2zd%ap8dBu7+VvA@i#Mi2T`ExnHER{| zJ}MiJ68YThAK|9$>KMDNeId-zVS&S>mX_CRYr^Fdt0&u>l@&}6u6i_&P81kNMaB2Z zeZ18qDz3{>DJIe0qL)h6mp|>XongbcIYoUrasA(8J5jT&M1O$`gL=hdC5A|)Gb_qV z!QTdAb_u?{%APZxyZNfsR>hq$qecP~=M>mHq%79rS63SZZPOx8X9vW%u3H%3^S`-9 zWhZpbB}Lc<=f9wJiMTacxC@Y7$ji5?r^E&tu!iJ`D{2+`Uf;XJL>&~;x;wMe-$Yl0 zV=l&D(-UbH6zo}rhNttRBsxE0o$O(2TMh>4EiW)>B2mQNP%bkzipZDYjr~o(5I$|j z(x|kwRLkAXpoq?Kdu|8A)e^AVAu&I_fT=pM<6EAOUu z!XoiWH6Onihjo&nk00g5ukSTNXVHA;Q~(ScVwU_xF@Q6I-2&g^nsVZ z)Ns*J@h)v%)07}V)sbjv?fO7(u8e(U+n(G_ymq@>+L-c9!}lYS@Y#DZP0sI%a9AgH zihiXbTFN9&Zihwd(pgKr+P>H*PDaRHaNBahx6v}~znH-Jw#FZJ6qREb4fz1}Go}g9 z!8jWW;rZ=W&RrM@{dK}-`gQKU}mIjSC8W!Kl3Snfyod%p z%J1Fkl)L8{GFFzkH@1$8F}U)ldlEthR5B;siLmg!%OC2#i>m>QkM>nh}DfWZa$n^k!(ix2yP z4C0n&J4{Z0jyG%Y_b~C_+|posGCD@SZ90O!OjXJBGQoO`_ckjhM!NcxOqyO$+rnU? zba4tBUCWF0{L>l(h@qzZ>NiDRp_EgYh{TMc)ZMy?lUKdi-F_whKg+G zJQ2qW>NNrHEsdnCC-Nfi6px8rnRF~nsQQph@?PdZ7k)LVh`DACd-RpCSGqbE-Bhv0xYBs1*csX? z!{;>ca?SA?6&)MMnx!9~i6X+QIZ)7+>??b3j?GMTt}m0|YkjG89j!Uf>AETSB0-3_ zCARR{$yyyy>W9dHt0>R-mj(Es;#<*O%nt)yT8XrLsWFWv3(+#) zUPq%}YVaWwQQYu66Oi?8aoK75hJ^78k={;55}U<>l3<9q*@`*JoK;nvZcAUb8h- TQjIo^<~2?}hnm{#Vov-ATrk8l literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/jpeg/r444.ppm b/tests/fixtures/codecs/jpeg/r444.ppm new file mode 100644 index 0000000000000000000000000000000000000000..84db23e90361c7ae52ec4f06b5e79293e5875aec GIT binary patch literal 8248 zcmeHs_g9nI+V&lK0)h12fFu-=A|_UVGhZKl{1X-q&^Adp*z6 zC{$D!Cn6FxB{C8PFyRcJ+~KV!jACIJ4}&z&vp~&3D0qmjAZQImG=@Wc6jaZE=X2mm z9OBV@c(54mErUOoBW|T2uBXA}bhxky&S${s?Qm=d9Nh&!?L+)<0CIkSeTQMsF~~jz z+s?q|Ut!}#NY8^cHz4H?Nd60!K7fQWh<^-mPhoZ?Op`-o1BA6gP$%$v!B>g!9zZbk zK(+vW7`(>7;~m1~6Cfr40Bdu`e)Yh-_ri{0F{4E65FKM+V>KMCl8@~U!n_K_Hiu&x z1lZacn94cWXK~mk3D~m5nET7Hca~%SOu^k;i@lnTxwsj7F%x?(3v+TO_SkORKlfn| zAHW{?5wrg%?A~LT9jCC8v)HZYF`F-9zqyJ{yMbMG8@uu^%(4fVg=JXL6Kwo5?A(`_ z8MTFUUIOJ!X;{+CfXLIC!M)KZz@ZMl} zqj;W$!qYQ(Y7W1T$L|T`w}{LI^NlDGXdFXJ44^9AlVS9oa! zT=6a5$~(NILhiy6uJ9o*?g@WhB`>CiD`?X;+zLM|T@5k2jXl5R9n1>zV zq2KadKk*zV_y`c#90gxcf_LbsQ7^$TKH5SR=$X+2>}VA?x+hT39vs~iCa8}T$fpY` z<_Mn7i+(&ms$`+y-crGxr0Clz(Kl8L^41G3Z4{i(5S*4o9sir)=+5Y$_Cz1b5y%ck z?K>pcb5xLhLa^RBC!q+&_FhMv- z7wOqTwYR8`FY1{rY!4H)MhF`PqS~3l%DJMa@uDXQ!jdJz!X)9{6{6d#5^k*(Uj0UR zX|w2jrsz!8{Np=?M|X>k>=zyShe&ovxc?{7o@2rtxgyCKVa9pk=1ZdVtD-eGM5}I# zlJ5x_Uy7#H3L_gu5pBZYE@7ZT$XAJcH6pe_NF5RqM}*inBG30C z)Mt^SO#}$>gp2r-yZDWl_%%jsC5g>+v7RGVdy7?m;+`OJTWD(26mdh8SUy8sF<1OF zHuZ5rYUyI}y=CG%E5x@~rCv`}5kM2o5vOo0)S?c#ciue2^ z-u<&UJ6F8zoOsKx;*A$m)31uxTu)8;BQ^Q1cxmyfgoonz$Eow4rOv4mPm_xy8&bnt z#UY(yKgBAZO6)U`$}*%<2F3VcF=kBc`99U{ORD2UDu86dQSu2X8AnS-F;Xi|Vx~&8 zOld!RyOJmEo+NDxk+w{cHbhC~F_OwTl4r5fa-pPjk>q}&^iITl&wP+Yj&Eeo!XO`9ZSpkaYLY((IGcZD%B#&Pg}@CRu-3npz-Tc~iRl zu5@XkL{uV)e<+D9m(Hq?POXtdG)N;_Bq1G=fF3DNCG}BD*?K8uP(m1%;zlJN<5IVe zQircnfE=5X?2CKOJ9N$%Mm9>24bfzJmTZ76>*vW7lX5yjWUW(jnxka(F*#LpbDqb_ zo(gly7UdKs=GnYTekAIu>R=itX=nD;W&=L0TZWe#xG24}uFo_&WpGlo4qLe90&Pw7~> zYF4hsH&+pG>Q&IGmeAaW$lRKkQ!i$pd=i`cWPWauDEIE-lXsUNzq9)IpBqjVr01U7 z^z)hTPF>1Aek$YCKX;!xa^ROA4j-2tIriO;r?U^`?mTjK-LX>{r%z>GI=$xV$&CeP z67C#da_@A~-Q3vXQ;W+_#nzr)T=C2F+B0)nPeirL$OsAWVLPTX)l^MO)Bf-7xxD|Py`ouOet=kQrsF@+%&zoZborcY|$fO>D@)8 zMN3P{mOr?cTzEgF=x%D+g|z3l(o25c`sDD=ho^S@bzD+*aDVCk-){Z=SmD+a#hXu; zrk^d@_FM6{mx|Y4Df~9SbU|ThYEf}QNnzx}vZ=*og0hn74duedqUgqAK}+$JS4F`+ zC9HuWj-k-oQjE41(ngE1GfI;W(ra~` zIt8z`W0Jf%q_#e^wkD#sYP$T{teS_h^77c4hoYMMOKSdHUj66Fnro@Gzos>v&a5~i zsr+fL{P^~&3t2DE9;*5Ara_hGJT9lUF6E*BDtNW6l_VU}cu}xhutvx{< zUBQYTuBMk`=;fOfG_yTaURIUIsLJ)N(($7TV94fRop7uXGR(u{wt9X-5uv|#68 z{ubkzY|D}Ftp|1+_sYya$lm;NbmaS^qZ>|GcAX#Eb$N8tRnxAkhHVAb1;wVd53I}n zvMjl8T~s`@?8W%3a_!8TVc)93x%F?TuSNq@qZHi;)no{<4C1YW*l`Qy!;t4E3(973 zu~{5kZ13G{<0#v(r)?NJF+`lOkR}XNn`YA2&X6yy;a?jgzSau9))6+fQ(v>r+SZ@5tvfrh{x{o_E4FoaJ}tZPCFQzpexYsI6Iqu>}L zM7o7UHxU^o0>g}BS_n)NnW-n6DHJ`II_S5WvAjxnI84%x>Vy1`5}YmH=+k#5p6j0W1Ej-jzo26Zfxfub{+jRu|J|8M^R z@&Ba$BW8Q@zp($i+yCawe@XIRN&eeT{>_U2HTXYH5;D!3M)UNcqHx|GG&-9^_vX-D z=`0?dV)f)GSquw>VI`0?OyAEmtcmE`;A13sn(0(CnW)3@H32jYlVb3}8(tGFX1vzQ zGWN4fgXAH@q)s()SY=^wO(dd*#&}JcZ0`riNF6c6#CF#(m9NR;TDsayGrU8;RnV*! zhM~{EwrEMiYQG^p)jYsZ5BVDn7@fiUtx}^knoKJFu;Go?G(2Ev8PfM-XgH2{6pPL$ zQHTse5S_*$lUP_9nM%@nGvE2rx=8L8CQVNy8(5S+8s5qrpwot^G_5zqNT*wRr6gAyP6p7zVse!O%7P zHd>fHJuH=pq3UP79WoHc3@nA-&0zF1>99Jzr$NWojxw!UOP^V<9aAW^%5LMJ(KKYy z4e?kcB9@J(u$T-KgW$`h<9I$)29e3658}NBF^pGi?iiJ>CgC)6&O0h=oNDG$bXXr9 zj;r&=nw)5T48Ap#+CRwF4dIPV49jbxUQaihd1e(&Gd9Yg>ZtB!U!Q)WuZcxakddP_ zjDgIwm&mu&_oKuS6J<^0g?h-Omj$$fhI@N1f;k2$F0j2bcO0cw|?WHD&Xx<0*L z|4uz*Rhx%ZdY#TdCcD$Uy)g_*05_0H_o9<9c>E+f$Adx};84s|ZykkVqR{#|Of`n4 zB;c(igEw=KZNHFE3{>Xsx#kh~F%wSNrzP-*83Aen zagf6>kiE1V{t&^pA5R!!8aoL6BaHXMgkcq1Z=zZ|sb;Iu+oEUo>pTsERE^Q=lO;&6 z#c76UBi0WZQ(wP!cz9T+GWHp@udRcxIZQ4dOJXp|Br+98@S>7^=yWQb>c^xH;7C0b z`UHWlVA9o0qQRH*hREz#{(V%=I44BIzz%Q}CVIDtHPp+|_A!Qral=F2{lf#kiXog; z6KXV)H9Gcy(%)((X$Jz0%5Kx(yMFVaM&CE2)(sDJ^cgz|-WVTZSSW_hU=vs@9F~Ko zl4%rQI+?D-`AtxX1|m&QqYV;iBLNf*iEQO+>3Ac>dw{{Tut*xV=ZJmV*+GLQk6|mv z+|N<<_!vk0jN@#B6|3nt&`~37w#FM{p}1;&usS@ypXfSDp$`(qOr$s6w6<=x>I3eB zl`x>BYRoFKa*(PvvUNJ2F#|O0f@pkyIxwmsw>3yFzfzV-w2-3E>SrZ$|{c7IiRJ)O2au8&FI!=nFoL$4v{k)^3d%C z9#0=n>gDiZi3Hs6&IJgiZF^hYoG!8#IywOW0Znu2KV>(MWT_Ue1e_nx!{I)yelS_x zD15vu9oQj2q=IE@xoxjvRPu7^I!KbBg=?XV*4j0*>!n{e(iI#Lzzy`gNt4H~#H8$C&3Dd z+pJ75i#ywe9apGNm#y{kiGX<5UA}t1%lr-CL4g9yi(9mYk2@NZH)5zP zNZbOpy-nKXub%t0#>@e<{bRKY+Lm3_zo@e%wr6d&gMSPpX1RRY{MZif4zHQS^ThhX zWFeGsTdJqa^Ss(p{_e!(Lg*|=Sb-UrRMm#cZQphK&V{JCPN8wA^G?l8(H(cF%>bTD zH>11=&^4>MFR{IUZVx-eAxsD}7JxpjGY{F+B5G%`fy#xXbZD5>ph{>O-`JD5113#} zm_;tFv)UR3PqZt0CkY@p)-iY{eBG{AE~~X=HKfasWWJXm9^UPK`az<&Of14+9RmeO zCl@I7QC@Yf9$5Zlk;Hk;PH>}vCbiw1P{$H{{z*jSqdAf2Yc~?}3ncFgMlpBJSCF&&G}wO#xv5 z&anA=P>Bu3RQU~L_mT{7Ksv0;bf})%@hq^ZEncxH+tr&!@WesmH2EDy7Y8XO`{BfRL2revR|8 zklLQ_(wvrwNY8Xxl8h|zZz$o^lmt{qL;;!%fivJSx5oBE?VG&~QFDO6Mr_;<#gn=V zLmvL-+{%qWhs}YI>Bt-8){2=`mt7m~bDz6nfDvV1pL7wPKM!duA-B&;a0{O8V3$U3 z(j!Ak^~63kGaMLv_ivARUUzRD6gMc7tDGF&7p#Z$-O#eA@%5H&-THbj3IxwZ2ha9+ zv*E?yH&t&oy_&TYWf$rEWQ1{TeG#EO&$ZUk133QRK!DMWPy6S0cQ3A)w~!o{0#UQz zB(x5$Yu0XfFkR>vE^?oq1b;X;S<(iI=yyHPt{#3aaciN7T4h;V_j$LnZFVbj3QU`h zjb9FyZ=S2>SLu=~zzGOMS2owvnATFnYj2*>XSX|NHw3{O)T??mE99@2bTR^9TCB4m z%B?=O>UZbow(NRWHZna2w(Nv_M^*E*w(*R*^?M;~DzJI(e^4slWVM!XYo?0aP(%oe zb9uk7@1k3SZCmH0SjS~skqcHK%6$9ZY<}D|qZN?$|6wp=Hq?ezKk}8|bJuc1oV|G- zt2QHVKwH9kSh>|1>E`n3VEI7etIyJEnje}T0sf(gj|aQDm%Mls&@?&HfyD#7JLI|b zeaLKoz^q8y?~3KSGI&roxB3pL{c%|1x*Z66GHC<4E2;5Irg~zR+-|(F>40)ZcBj5* zjeo2W%VQIfEPofIgI$14_q|>g<hUXfM9b zPIa+eEeVa!gX-BlL`b3&fNQCsu6bsS-TbGnK!~&dRr~I78p|lJZ2J^5SA#d#P9le@ z+0Cj=J*CsCeZ65(JgnajH#tvFL(7Z6p70pQsjGp>@-Sp{>(|_Gj%dRBxUbvo;O7gb zjQVQk;0;#8!VSRnc1X*DrWxINoXUKLCMpQIC<)T`!!56xis)B&83XHg0#NLy=5W%p zp)%~%`(4!=H$czYhEG2>*!FiZ!+?QCCGUgoE%NK|xI3kt;qMR-06qb(w9d zS_ApWl?MUs>TZ+uT&FiQh14YMc36-GQzPJKR73kLMN@!k)!%_m@Zbi+$o3bvp}Q=g zHEA0xU27M+!!=~(MO4+7?LB0UW6Ua8w-cWE_muLQY&)M#7kkoZkg@`92R0W4wOoNp z;Tl}p7RQ;%4qpzmUW2YOMorjsNZakT_B*JEY`f2`ewk8acTasp4o9W$gf)Ld+YVOV z^?h>By%s#Y;-=!`*F(AB=>tw@tDt^bGQzI4xoOCcTkdx!*8J(wvM?Jahq#8%fx3_m z&9~hT$uAu!;P2yr#pB*dD(e+ z9^9t2R)s&hO;(U;z~rIr> 2) & 1, (bar >> 1) & 1, bar & 1 + r, g, b = 0.1 + 0.8 * r, 0.1 + 0.8 * g, 0.1 + 0.8 * b + else: + n = random.random() + edge = 1.0 if ((x // 3) + (y // 3)) % 2 == 0 else 0.0 + r, g, b = 0.6 * edge + 0.4 * n, 0.5 * n, 0.8 * edge + px8 += [round(v * 255) for v in (r, g, b)] + px16 += [round(v * 65535) for v in (r, g, b)] +with open("src.ppm", "wb") as f: + f.write(b"P6\n%d %d\n255\n" % (W, H)); f.write(bytes(px8)) +with open("src16.ppm", "wb") as f: + f.write(b"P6\n%d %d\n65535\n" % (W, H)) + f.write(b"".join(v.to_bytes(2, "big") for v in px16)) +EOF + +# JPEG: cjpeg encodes, djpeg (accurate integer IDCT, fancy upsampling) provides the reference pixels. +for s in "444:1x1" "422:2x1" "420:2x2" "440:1x2" "411:4x1"; do + name=${s%%:*}; f=${s##*:} + cjpeg -quality 88 -sample "$f" src.ppm > "jpeg/b$name.jpg" + djpeg -ppm "jpeg/b$name.jpg" > "jpeg/b$name.ppm" +done +djpeg -nosmooth -ppm jpeg/b420.jpg > jpeg/b420-nosmooth.ppm +cjpeg -quality 85 -sample 2x2 -progressive src.ppm > jpeg/p420.jpg && djpeg -ppm jpeg/p420.jpg > jpeg/p420.ppm +cjpeg -quality 92 -sample 1x1 -progressive src.ppm > jpeg/p444.jpg && djpeg -ppm jpeg/p444.jpg > jpeg/p444.ppm +cjpeg -quality 90 -sample 2x2 -restart 1 src.ppm > jpeg/r420.jpg && djpeg -ppm jpeg/r420.jpg > jpeg/r420.ppm +cjpeg -quality 90 -sample 1x1 -restart 5B -optimize src.ppm > jpeg/r444.jpg && djpeg -ppm jpeg/r444.jpg > jpeg/r444.ppm +cjpeg -quality 90 -grayscale src.ppm > jpeg/gray.jpg && djpeg -pnm jpeg/gray.jpg > jpeg/gray.pgm +cjpeg -quality 90 -grayscale -progressive src.ppm > jpeg/pgray.jpg && djpeg -pnm jpeg/pgray.jpg > jpeg/pgray.pgm +convert src.ppm -quality 95 -colorspace CMYK jpeg/cmyk.jpg + +# PNG: ImageMagick/libpng writers; pixels compare against src.ppm / src16.ppm. +convert src.ppm -interlace PNG png24:png/adam7.png +convert src16.ppm -define png:bit-depth=16 png48:png/rgb16.png +convert src16.ppm -interlace PNG -define png:bit-depth=16 png48:png/adam7-16.png +convert src.ppm -colorspace Gray -define png:color-type=0 -define png:bit-depth=8 png/gray8.png +convert src.ppm -colorspace Gray -depth 4 -define png:color-type=0 -define png:bit-depth=4 png/gray4.png +convert src.ppm -colorspace Gray -depth 2 -define png:color-type=0 -define png:bit-depth=2 png/gray2.png +convert src.ppm -colorspace Gray -threshold 50% -define png:color-type=0 -define png:bit-depth=1 png/gray1.png +convert src.ppm -colors 16 -transparent "$(convert src.ppm -colors 16 -format '%[pixel:p{0,40}]' info:)" png8:png/palette-trns.png +convert src.ppm -colors 16 -interlace PNG png8:png/palette-adam7.png +convert src.ppm -colors 12 -define png:color-type=3 -define png:bit-depth=4 png/palette4.png +convert src.ppm \( src.ppm -colorspace Gray \) -alpha off -compose CopyOpacity -composite png32:png/rgba.png +convert src.ppm -colorspace Gray \( src.ppm -channel R -separate \) -alpha off -compose CopyOpacity -composite -define png:color-type=4 png/graya.png +for f in gray1 gray2 gray4 gray8 graya palette-trns palette-adam7 palette4 rgba; do convert "png/$f.png" -depth 8 "png/$f.pam"; done + +# TIFF: ImageMagick/libtiff writers in every supported layout and compression. +convert src.ppm -compress LZW -define tiff:predictor=2 tiff/lzw-pred.tif +convert src.ppm -compress RLE tiff/packbits.tif +convert src.ppm -compress None -define tiff:rows-per-strip=7 tiff/none-strips.tif +convert src16.ppm -depth 16 -compress Zip -define tiff:predictor=2 tiff/deflate16-pred.tif +convert src.ppm -compress LZW -define tiff:tile-geometry=16x16 tiff/lzw-tiled.tif +tiffcp -p separate -c zip src.ppm.tmp.tif tiff/planar-zip.tif 2>/dev/null || { convert src.ppm -compress None tiff/_tmp.tif; tiffcp -p separate -c zip tiff/_tmp.tif tiff/planar-zip.tif; rm tiff/_tmp.tif; } +convert src.ppm -compress None tiff/_tmp.tif && tiffcp -c jpeg:90 -r 16 tiff/_tmp.tif tiff/jpeg-ycbcr.tif && tiffcp -c jpeg:r:90 -r 16 tiff/_tmp.tif tiff/jpeg-rgb.tif && rm tiff/_tmp.tif +convert src16.ppm -define quantum:format=floating-point -depth 32 -compress Zip -define tiff:predictor=3 tiff/float32-pred3.tif +convert src.ppm -colorspace Gray -define tiff:photometric=min-is-white -compress None tiff/gray-miniswhite.tif +ls -l jpeg png tiff diff --git a/tests/fixtures/codecs/png/adam7-16.png b/tests/fixtures/codecs/png/adam7-16.png new file mode 100644 index 0000000000000000000000000000000000000000..cf5c5c4ef5bf909c2b9e17410ce13d64fe2b9ff9 GIT binary patch literal 5265 zcmV;C6mIK@P)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv|NsC0|NjYC_uK#g z6dFlHK~#9!?U;8|R%h15e=i+r0wRJURY3(sc|^g64aJTH3)Up|-g^>Fj98+hj^ily z8XGD~3}6>x$-$1OpnxC>DyS$O`Tj^|VkTwcH>2OjTJAsYI_up1?zQi}_dWNyj|QNu z%*hGv-TN~~9atH_TR>y8&Sss>I)FHVIPp?H)^Xyc{!zc#*LoXu0JeLXv=mvp2?G(E zc!v(K^^*#(MJ^v|y-~#WxZ@aj5SNk^s2P2%JU2JZz#wv;s4Sy1>Z^VMfs8yN)~H%GWUy;a*VuK1jNF{TP&V zDINl))+Ga=)4f6QVAjRrJ{;Y&Vp(z_cPIUhT>n>| z_xJv!mrrTUrb7J!5xYq)%b`nQ>NKS;Rc^IGBx7WXHcY%>VxZL51<$-ilG`QN!us8< zS11)dq*k%WcSm-m!gN!sD@t9i+4{N2smz0E(A_BGYo&B-S2^TE#gDD#fLX$;5V+Cr zVtr^iwcAQ4l#8DN6Y&AJO7(BS6&14(4*JEOg-S8D{*bdLs}h))nFWKPZ3RcD+ttSj zaMr043%)(uXTsTHRV1Pptp5VMmimo{h<;9oM1~xgWeeJ!bsQl+vZI?w&&4D6fl(ck zS5TyxF<+$a4c|pzebp`&b{?rXM1&2|x^+ZKedjC|>2qk@T_~C`(^%xd{i;bKwzdvi zVBJ~GRFTLPu6ZJQvkhz@(IoJS$l2v;iimxQYcag2GH#Pddd&fzB6U9TZU!1~Sy@(Q z5CR3$4HrTF41+~bFvBne@~8i*Kix0{@@M=RzTqM$m|+kC`O|+o`y+GF8ww$BC@=b_ z!i-<>f202n|LyM@?{Egb59{SL^54h8M0!6Odmp|TWHDVN($jU0h{b$sCrH!{JTG$fpno+HJzM=PklePnwMb-)o3}{a z5x!cG^?YcUNci9Fn~O9&-`WS#I}R8qQkp+^nn>-d4Hv-fT9#8pHf+$<73tDp$X&>7 zF~Lj(7hjJ6XmYH>UWnP-FhRs?pr1E13~j9i-|uN0B*Jj!f%(qLW{{TH|GJ3dkXljD zIHg?`*goB4wTR6m`^(U^(nq)9di8c0A_FE&5ojLSWjI_iYPn3LZg-yy@XT%I38@YG zel9Y2){M2_)3Mz~$k{M@fr#-GvlXB}&M*MBR5t7{(#`*qK45m$G8XPO?D>UAzu^-B zozsr>M~Xb0n7R;#rWjZ&b=1l!PbAm)SsPFXE-zB*LFk}XBH0F+8^Aeu?{lSYd3Eg| zLKZV2Xl%npN*$b5xJtxbzhXFyH>!F?spc;i7>RU`A9e&<7GGVh)V!F~JP~|34<5ba z-IaQ}efVXO7vmfaVYHWCh*CTDo0^E&T01_6hV9RID0S}R_@*L#Jjj5_=DK&HO zJ|7XSGXJtF;C{8SE~LJ=Gag>2l?H=WW9{$3+S9HCVtv0|1ZiI;)_~xxlNUqvr!_`G zO3#E^;LzUH2I4#XumLW9bG$no2o0SN{mdq;gqzi58#v6a6$;r_S?i$vw%|BuuIc;* zoURo<8B8l#tc6pC2aUk+s8Kpx3O&;b2F#jz3%tg)r~rmbjGjQt(C%8`HmtrMXmr{@ zar7@<^1oC6;)VRq>Oc1IW32-&EB~*D#M?p#YLrLQVYNRO2xra_Zs9VWra=z4oa z^u`$&f|a%H0Eqp_J6fbkUWZ($9$s@0q`LQ=A>w;2;4A36VS)}EwQ@-mF}60dgU%s? zv*3rl&HpCSW^Atz@ZBHK7qsfnYn}>av&#CyV~>n{xH{(h^N?nhlmyjYIOl-wUA;!4wQvSBQqEVVO42 zcx1aT!MLYcZO~6NSONMo4THeyrELQ^?z?Xhv>Vi~5%^E(QxRS_d3_PIb9DB>i6vom z;r_Ebqd`+Q%XbHyZ|_r8L^D|HD6~ksyk4oHrYE|KnBTNAf*o_ZCMq@4?`Ag>QL@XpwnK zR9f$^}XTcrmgK{ZB) zL7P3jZb0}jdyPmvW8cf*vCGFCN~~sA6=|&NuLmF9pS=!FRP)#_;#$e`Hh9hU>jzq0 zTYhW~2G0$%p;lmnVc?P1Sb?6U{@=l7y!~RxIGHjIuI`Dw0p{DS1gdU!Y!BzVM-PXR z!^N9mSIElIaMI&IAyhwAa{?HRFl`M%38Oo~l^rq5pqt%L7kDr%`6N6i+YerydtLy# z#`;~M>OjXlD4dWV2N%CO?gm$;pACYd5rtY%Qlq3UI4`f$0CbGcE&oobwWl!=v2c98 z9OhT*W~$V&oQ$?2#%;~kK##kRE+`do+^MO^Gw-M0!r-z3Po-8q%^M}6Gd0}}W^Jtf zccqeSyc|UK<}G;%pPTiuP-_0u(|bg`tKQoNpA0Qsuhh34obQU9xfLD-{bRK+Ds^RR zWls^EidvS?_lKNPrLLT5JyOJaYxM>&^|MABlv+LSP@+h2SVUi-?8IjWL>!OSc7Z|h z(=WpMyE;}PHDf)efn$E{sjxPkfg;YO?xkS7*X$;Q-LzdQ($jHdEpTt&s2^Oc)O4N5 zK)0#kP@_}b&9MHkc8W+3$KjcvQ(ITTW{rWih;5)l2K3jStPK&fof1V_cyuX*fRBQs zAmW;Hdy&pV21kP5_50Wp9^Oj*8oaLfeF^4YTJ3~WXAb3pxsBCeNbh%V0-Oy#QXih~&a?!J zDC=7ApftG|=rz{=9_l}BJ_2%d9>>Dt1{r|HL2Cp!jdM4I=Ubj$0JAX`dSJ89{ubQu zKVJnb23hBW`<_OtA-6})BhY|FKv|hi8z?!Z(*{bSb=pG7G2J#$eC(%w+n>+=qW?$y zUo-!q(DqmTpB1A23}5%3etyaSNulk(C>(o3;n)11-2RIHTg*4E_unY|4!>M}zLZ~- z%TL_$i*mVlQ-1Mbn7mhf7$)x(AD-^_ia*?={5|~k4&(2$e{bjUKU4mrJ<$JD|7|?K zjdJKE(ZA@geT_iVtzWSA2;3y+RWi95}X44aDg@&J2s^zBcdQd#R& zQ2XT(H>IAB%U%ka&8d2@YoWy`5zV2~#Zaed!|!0gp_dLy6?M`Ig2W0o0uci$Hxx0` zHIIR#1qN+kcC5`*rEI_Sc>uXDp4EVq!6o-a((fm_!+@=N3t;0Ne>bJBjfq_bo-gyC z!z=4aW+Ji9-?{@Uic(>WpFwq{vf4g=1m}83y2I)!#h;64&v;fJI@cYX0sSYxG*#+Y z=PeH4zqb<39BIWueTy$>{A0*rQ$!0?GG=Fo|{4G+Bw@rk|PrCL+;RL zEnultJ#D4pd{2ac$F0U*5H->~M&z`1cpm7~)ja^C&)DZGHS@{dUEuOJ4_}y3^`^5( z#lDs1Lt4VU8W5`a#m#iTA~U>R;b5FUl4-G&SGqvyir<%`0>wP}4L$X%1u z9QFsU849Vocl@E#lR+8KF0s!FFw&TwhVbp1JAv^c(=p&atx*riwSJZaJI*aDgtLD; z+!UPGxHp5`fzKL25ry+$(3a`#;qKD-957pMIT^0+Iu{59mU-52XV_Js%&P1T+_`r( z2u$oN4g>pJHJ5{5dY~O>$LV|qSL?>kf~v!uT0r*v%rq#y@VW^c?z_1jXyV%Yg^I*o zKcx@0OC0M$uO(Ugm9qcNZ6_oJUuytswv{dwvAgY35eg6HC&A*cJY1D3_ANXQmG|29 zg1=b4v=PxO(Vq?GhpkdU`Je8kRMGr`bZ9-XS0`v=zS>%($?bsUQ1ETucBrLy*k7qY z#JKHHP5lj-5sdhJ!l7}S@pzWi5 z9y+f{Emq25quW=I_4xxw2;Hj*61n_K?EBV!p%OfWT8%DSta6J%UUZVeA64p=6V z7J7F+=vx~m!SEJbQc8D~egQlk{%{@)zj;PPy7w6t2F1?`_d(}?)OAW}ch+$LlZc9G zFyQu)iXv?f1SP_yA!iDqr^@tGs?v%o)1cm`P5Z+q*~ha)G@VigR{=v~qi%3?(DqmG zq|We0B3U&b90bd*Rh+=>Z1`cN498bk3R=~*cR<4S&dWq@n#oGY3{5)&V>=maRO)%3 zr{myJOj;gnw$M)y>1aCODx5nP6$!iZdNfcfD(ahBpcSTV1K|<&pNOQ`CuD%dMeDh+ z)vDuKr3$y@3ly%+I|&O-Gp~!-WxLb{tsiveLW{sl50o;WRQVDd`)H3ZB!AU=gh-l4 zQX$wsbln2MJzuygmDKH;3p|RrzYTKdOb8YUb6U3#oCDompkMQxuazq9TtL9x+&+NEaLSLsK2SXKIop)D}>1LJC{J##q?%iw8m^M z+}srB4?FYzG6~LhJbV{&ujhn7iFa{pFl%I~2l|^01EBhX8V}&%mXrXvp?m%u_-p#i z2iu2^Ti})Xi(X)~)}#eI?2+;aYKM9E10u?{LFKrresKARv!6o2;=KKEBmBZ9FwQVb z1|w6`Yv2>xE+1YemUaj0W7YS8W`SlG=ocGCLekdjiy`M+)=bzPyeb^dG&?L%H^XNT zbgDPF31|*?ac~l`2(-=s{rLt?uqLfd1J3EjjCp*BxhnZVMN)t*< zpkeh^L!qmCTE0@Pb$gzJJnNV1VS9i{f01tsw@ruaIhlzte6QAOrE1slng&+esv5y( z2a^YgWO=8@faQ@YLtu6@TO+0P=If_{{$C8I!1m)N`$e91$=nJT21QMSgSP$cl{#M( zRRq=YonOL&6A$Z()cm;KF*tuMS`Wtb*7Hz`3q(WSUtjvbg9!tdilpqneH$LC004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv0RI600RN!9r;`8x z3S~(|K~!ko?U#9QRn;BGKlkP4<-P2C$PEcufFwKuNjN~*0*I0Z1VoWdKyWFd7U^PJ zwbgF6)9GSs?INxyL8X9@uo+g9fT8(8Si~p+LU`nbuw)^D_wruyUjJyd+QJk%%}nj^ zoilfS_j|wdo$s7`?(dwdfiIPl|2lM@=jt#F!!R6%!!R5UhhaDjhr?kw91auL!pabN z5iyc^BS@+zNJ0u17R!z-(W2wYD`0(sWNlTsV_6X>6KfPcv_Z)0UlK$DuUdpA%BqNuh6L`g6#!pA1&=*0=^^a?(y#_SHFaQt$ zQJ>YK)Kz)YjroK2s#)H>M?F?0896*e*|m<*lQ~$y$)g-ULYIf`E+#J^G=iW#=Ht9>w;7@{*qnzm2w~ zvN}dm2hjR8S)V9=Iwm8T@EF3Q`0y_b9*N5dkeC!jN%nN|QxT;-_mBAzFmBgxW;T3=B`ku^QO6L>uZf`MCSgy%? z8Dh3@Y`T;yNzR~cso3X>Z5SGTeHNTnTvl8boS)WC3$Cm2|604OIKQa>M}1@O{zma- zcK>Xh{|)lFQeBn*bp3ykzlQjR8`2G-XWg~ZOi3BQyf*bvxp=)itg9Vaa{3s{$Eg?G zl9|grZR(C936EiJtEwC+&dUrfQy)*0+Cw}ZskYmsvXr0nRcj3~k{PsBJ$+I-F0o;r zS{Wwv&0_QIqwmg<#(KUQpf;yUM=R=}YFHr6O{A?+ zA5RrvmQw3G#TL%81eO1++_{+X2h|Tw3oz)Yy0BQnt@*^&hJzKCJ=bmqn*pIpz`lNHTimIKgf0;SU_^68HOj?>KoJ;-` z%8Ch%;QjSj0y$8|{Kv^1OJFd!+(~*4nvTc%=?DGaz3TMssnw#>ujj09rv5)jeLbD_ z-?dq;-f4TV5#F@^zp&=*C<(CAZ!r7E%fR7SgSogw;(D{_3Em$f{$`T;Q4}V3J;bO< z>>4a)3o!79zd z8JCl?5*kjh@Cl;g@p`E&LYJONuCdO8)U+$C$orO+Snkm*G?vGU)8>Gp~q*zs)Bt|krcB`FP64i?lAE%)w7La8^+VwsxDskZb5(Mlnl72d|rNaNoJuqPxUFeS5vhgP?{-^ znpK^f`nfXuqPoz?bL}$jV>LF3Zyl2P>8kl0fAY$(a^=n7z%4SSN)71GeZ_K{u7U?) znsy(SKr(X4%EN4-R}zi&9NI&8Gzlr}+lI%@+t0J>U6T3}9LCItsjgt!12ojp*39Kg z_?t;c!R@4K2L~(gbkgM^&4y+T=0zkThPUoeODZHNlo@B$?_AP$k>%smVC*A|)1}j;)8$W>jz|Cd z?dSQ=$m`T!5C0F_Yx`f7@3AecN6~}(V-M%PIo~&PUr+8Y=Q{bP!{z58*Pzw)i@$gn z{dan~0ddd%!uK3*=DwNxX72wzd|7jA?`24O4p-WF(5pIHNzdWU5II;ubUc|Q>Xzxa z-E1EyE$7&`jjxBO#J=oY$KE_SeGHGAMV;y^bJ?|yqHqa|Bxekjonx8inj@3%R5l<+8yRN}fq?ICu^5hL)*L7ZYZ1>+fY$A+9TAZdB7B zz--~^lM)n)C6LtBDm@2pH`@kCcQ+;z)9O{949+*OT$6))xX{QqLR4HLjymiM@2ma)(bS*c{M;L&!@7KckWW9?_e@f+(+tai0Z|gla$Lz zr<0$amBhaI>5M&~B4XLTnz~tHKTe-?=3P>?hdFzi_GPkeIcWo#+p0WnvhpZSk}XAK z3}M1yWu(w@o*&u82mWT(%~3T~*iTS5TLOcqET!NRWpa12=}kOtYW8!f1=&fbi?}2{ zsph@6Xm4fA?ZhUKKNZ_>LL;cy#BDQavSSXQu^yj~+Q^nO=T)#44$cza}7kr@sy#=0R&ii zGenx3s4Qi}JXKjr?=+r0EBywsZyS#WD110CW1lbepWryfQi~chh3YcCe?mqU(sqHL i+f>nW^v`C8P5ugu)aBnNA2VkF000018ZDist};dTFmfT<!zW(zfMEH+YVE6*QTx?3A#;BoA=kvzPV}JG`)=b>0|7h!}c-t&)v`+(p8*DAQFfK z{(AzSnN#n%GXpOJ=hnWAd$>dbkw7HyhZD&C0p{>UkCHQS@p{fQuAX^4=U5wmCz1A= znMB%=HYQ+@_>q`EsI8YtJ?B_^&F?YNUMFpOU)(_mE<(_j5yZ8vdy60;2x=dxHSH)m z5i%m=T%k>vGgF9$Xhj?s)LJCq0*1o`18PrG&*U3J(-xjZGj+{t%t6e;T8MH(HU!fO zIfv(F5x*=UVS!M%l9f#HJ@52|Ew@H4tx*Ync7cY7khu$hvq(!4&39{;V?figj{&LW aqo)u;Eq@A*G`T7l#-~h{TdmTy5WWClUpy87 literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/gray1.png b/tests/fixtures/codecs/png/gray1.png new file mode 100644 index 0000000000000000000000000000000000000000..c60c472319a0df9e1f5ee39946efe23814121249 GIT binary patch literal 241 zcmeAS@N?(olHy`uVBq!ia0vp^wm_`Q2qYLx&&S;dQcOwS?k)_Bce{j_0D0^sp1!W^ zueg{v70h=={qO+_P4{$h43W5ebizj7LkkGVV%8tB$ zW7)-(Qne25*LH?SOsL(e{Ai`>u8*ujN-{nsRbCG{_6mGDc1CYm+56?OQDNfwYXrSD o{F{oC{#s3TIqy`zRYd#Vjn5tT?_8P~3Unfar>mdKI;Vst00*X9b^rhX literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/gray2.pam b/tests/fixtures/codecs/png/gray2.pam new file mode 100644 index 0000000000000000000000000000000000000000..e5ea0dd99ef9ab847e799bcb2c83b696cd33e717 GIT binary patch literal 8296 zcmeH~TWVWD5JdBRSD`I9iJWf-3CrLFVdOlvm{n$y6CH{kS?Hn%1m=E>tE;Q3$9-jt zwx6c&PpjQ#aep^$)=!U{-QweNTCKN@`Y?TY`0?%GdGUU^oOZ9<=iSfkdhzo3d0Ky6 zZB{SSyYY+-{68Cbo%3Aq*P1i-T&>qWH)#0B2F3=?*uby-b4JE&>we}1e$JYGfq5fh zY~WTK@W14VVAj1(%tUs*35|;5Df%0!q7?EU5;Nn*K_SQQvn>5Tw45l!b&hO)tO_K_N>w zLzt3GFK&#n=!*tH$`GVXrk_=e3Iypjvw+liNfQn-lFh5KU`qi?%LaHz%S?G&c=K!; zyI{J#7pCx%y(_0MqKOM>Sz^)K1st&}=--fGIA?BFj=u^UCKqNV=zM zNO&vUK?usJOIglMvA1#@7Rt9=YKT%SK#<*J;Eyn+g`RL*1#s2=0(cc8v!q*+ONeFh z$~yu%K42QIZ(s1&Rl(tO3QgZAjK$8q< HFm!(d*D$GY literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/gray2.png b/tests/fixtures/codecs/png/gray2.png new file mode 100644 index 0000000000000000000000000000000000000000..2b998fd73a0280691302c5577c77306bf73b3638 GIT binary patch literal 308 zcmV-40n7f0P)|P(_ z6gkZvC+sPszbq`<1yW`(SbmH=G6w#nw)f_<_Wcwg`%T3DEBLy-!2O{I_`JV#!~I>q z0hg-yuI=L=0u_W$X^bY*lo-xX9Tz}K5?wJg^k7QtqyE}L&LdaK3SX!e3AM16E;-Re4}E88sFkOJ8_Yn{<`jv5MQIHv7z=?3+(h=XNMr`vUh zMC;wPyVZErjI8LHuBn4^0k5}kQF%7R5k$0EX#`XIR^tzc)4v*0_&gf`0000*5XE7wxl0E^I!GKPYX=f615O|qa{e@s7Sw`UNDFDfEx3jBl8^5v-`IR4 z#Yf6J&SEn6%sFS~UOzap?tWVR{`&g<_VUN?R<}2=U)|nc{&2OrzPSUvSpD+ykKbOt zx%~d>YIXna?#=z5cQ==BU;Vtg`Stqt`t9nQ=ZAP3xK`glM*VX?e@z|3PP|9%~@@%)jTKa%-Zv4NaFlJiHh z@kz{&i#`%^zdQ2};fsq4h3A$1#-SQ0{4T{mIU#;Z#P9bJK>uc|3)dC8@Qysy$dktf zFrBS~(Yu7Jekth#|xsFrIl5W0Kp-YImAam@S#h`V;kR)zhy%$SzsQ6qg3MveLLd}lqAn0K z6L_-}R4x(|!PN-y5r7a!87-z74*VPe3O@PwuqO6I83J33c@xcIMZ!w%RdLkFt(2r$ z16ME+Xk`TsvNdG>Q~&X=uV}yqA#??Zu%081LaxARA1x}jaM_WhS?yyG1m1PVJHQcy z7H0)owyZeh6Aee;XengTyCEP0+b2WawO|Safy`W}<4+#{n{+#b_G|%e7KU^+5=h&2 z5p`3VTTLsp1WDJ2=sM<~Rs4_^BjG$$jyPHnS=}q)XsKnmwX;eH6d|b`ZKw-WPYbR; zDhRF2&>Fo@wh-E~Lg33BserNt z5a2B=GqE;&tOPMJ6^Y{WYqo|g_~;S}63&=vDqYCLT7L-!VL}8|2-(6q2cdHFkUqHL&iw$N_~PN=em-B0zaBj9 zVSd*6g%*!|UVQcQ`v3VqKNp=`J_nVoY)w^0inYu@OUzz~oI9oRtk#FUI(Oxu>w=)s ziqt2^r^F;1u?6Dj1Z}rU3h;D9ORi+hs5W94Royb_qq8V)r6%XPtONv*GdHQYjQOEl z)=CGs5!+S{TJ)QCt%4$~W&*igVRG85^)|`pBSy0(H<_Job!WH|;_=%P1*+DOx~Zqb zr8IMG#@v-du`cq-=1{>#H7u?HTTtuDT3a;FEwYCZrb8m9BQaXMOh^PHKut)dMXod0 zC*jNx-Y!=$4fV zo>dc)WlY%D<=s^-Rosh_Y<=SjV2wnaWDucCR!79)AcSk1m05uQDCPMCVg(SwRy=ed zvBg5T6>m`Kjdmh~R2!x1x*4n}&>JLs^;9 zXVqNIn$fJTqYExp-i?e3_5F6R594g$!=SV`Wu*iy4Sts&dgPJrinyEGf6`zjhLvBhRBGB z7?Ds!NFqXsh?t3pn2^XH;pKVO+Uv9KImPm$b>Banb-Nr$t_7W~O>^63)>?0E zX>XZZyDBhpjKvYZU{6tH&2-|1!?kL zjx>1-X_Xgg@)pu6FVZS+l@#xdf#(ILPM!Mvz)gV{1g1@!_QJsQ>CcvY4Tofw4-OjGdjGFA2;I%$ql_D{y<@j==o+^Y08SSg_!wftLjq zE?oHX0HKAq$ZV*zkXCt-*7G7wUZhoCq=k3UqD8L=yfUzO@#0qnUL9DnWXWp+uMI3+ zy7aEV-GODxmR*6A+$t%#RnjUi(kd^~KOFc-VB5BB9}RpguzmaXj|V;x*s){BCj(ayi?Jaoxo8V%@)pu6FVZS6(&YVA z;Gw{$13P!_{7m4pfnB?HeJ-$j_wLUJz7Y6gV9%aC|C`vtTS%+CNRt<7mA8=M-Me@1 zmjYi7?Ay2RD}k>D_V3^SwZPW{-v}HyaNwJPg9i`d#n_OP+$t%#g%@d+7ipCjX_dE- zCNEO>R^ZT~L*EX3Cvf=i;qL~%7dUd{$oB(32>dW`^ytxJ$BuPlq_xUOD^hd~8I!ay zCh314g4%{^5n^%2YwMab?VeF1HTH;T6l|6GOJ39%v4%P zleds2Zy`ZZ>06FzUeiD z(^L=L(h&K*rT#U)gmin&Y}db%P>=e6bEIL+2J2%s(lBO&^#SKdw}A6)eZV2(7bm&myY%BlN4;V0j zxl5ye?HL{%26i$h*3mG+JP-z7I-eKfVaqTkd-duiNJ(Q&nZx>E!TKh~LX<{^1cw1B zJCN5ZGd`6T4ywdT2)COeGi@?_`0zo42B8y%c=$X$GCgxEQ~JI%m_<@}lOm;hUw7CSJ+ z1jbV_pHgwA8&9m3;6!oNR6%TdiH9RXWtAwwvwD2WgXI?Dl?^sbG73h|NUWG;SjLQ# zkln@65{Zvgs(0_+R@s~`5o%5@ruytW$qs5~rV&+;XW4cxyyceJTsBzB=^v^)B0H0>4|S#%6{ob@ z#|Y2NA6go((#s6zUav|H-Vq~4@XCmFh;)l1Beyam35X;-OH4B18b;3jnjvp;A|66) zD{O_3b}?AuWZ6eYiCk>zu3e>3r`c17OO%B3UA?NWh5C>X6GSL@jhc0|zmfEBvD=nv z+uF@E2ThiApw1M4gXuRH(^SOfGAwW6ltZshx8?GNipC` zEcw!96Y;otoGI$&b)x_(7NS#d_F;zxql^#Rw&XH=@ml0e(RRWQC=;$A*lWk@7mJsZu0gWUG z-T}0&kZeV=|k3*Oa(QVlsek3T$j95 zyJZO!8;~zWf+3SMbL?Z4W1^)sl?N!L8cz&PgmbM%Ufon4OgfolNkDB?l3JU`*|Wn% z=jT%iR3OvD?CH) zVJkCDlU`zdiqwcz_Aw%R?s*YfBE6EPhmFX&U{p}%J!|CCPr$0LlkvJR<9FJB=h@k` zn^0ZyHgq${m2=^MOC9JU?JcXiMF2u|;Q;N4fYB3~ET$HA0vnKWPi9Zb~1)9_R{^;Wsku}A_fc-38&4BA%yrJWG-?UOf^ vCy|C!Vr!L{Qg;+-9vQNlm%MJ2L(OAD6(q{{7BMK9MCpgzS#?xF?X3D2q#Nl# literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/gray8.png b/tests/fixtures/codecs/png/gray8.png new file mode 100644 index 0000000000000000000000000000000000000000..45b3a890e8e7bd136dcf47c576045914041c7762 GIT binary patch literal 1205 zcmV;m1WNmfP)6+R`-K<@7(u!8G ze#=!5K?N%+a8bBkKKG+-S`8}A{`&rS-t(Muo^#Ioya(g}AP9gU@B&^P?+*Y7!i<;d zSJSSO60d_WBhlxUWpZaknDFX~RN zL%U%Q&y%b_v1>`x4}gi(ulG}#Np~m#!1UMqp-H*6kLNq62zVCE=lRmJ#ClFI13UPo zosst?r%1=zgt<`4P}ddYCq47I55Su~22^~#Um|5p;_)4J594*pL7`@^M8 zALjWeXbOh&vYwp%Or~5@j-(-LO;ElbPYD#gy{x@gn|TIb+vfgWusGt%nN*}5yDEpv z1-!`&a;0o&0*~_JzHW|PRN)A)!}>}09slU9wFYn&7PE zX)E_nvGeP7Gj`s#q$LefgdtJBq6C;i2%{sG^_1xScx;~qJNa)YZC zn(9}wte?haG45yKCyy&R`ksVQ9G&5%ID&QNCMyBb$nsZd1Q87y_stW z>+0Ine`I?209i8b_!2SPf!4>wmW_Et%W&eXc@WcR2b~$(CF=HsTP}(JY*HNcvpTVA zrJ!_pDolMtj}u&fiM8&=3F=aRLs@Lv6@AZz_El#`%yPzvQ4TSC z>Qh)xG`%IAF_q`|)+5&nwQx!{bNn|8O;!~EzsVx5_}&q<)!qfdnHy5H=KA-y*eSpi zTohooaX!7KiihrK;0xcDv3*3tEwqFbaVR;$=3dL0$>8arbx&MTGqS>8 zo7>9o)9{*2uI@aE51>7b7oJJ$&<#Xc+P}?l>jyvznrpK+u+p!EYM@V~os*l3jn>Qu zM}3scW9?i4k}>bJK&i`EYSy5TC^Z{wEGXxfs1mVL^mc_OT*m2gHT8`P@B;ULE1AjE T$j@|}00000NkvXXu0mjfZC+C* literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/graya.pam b/tests/fixtures/codecs/png/graya.pam new file mode 100644 index 0000000000000000000000000000000000000000..d12dfabe0201391ff1890b00d4a1f7d14b24485b GIT binary patch literal 5563 zcmeHI{aX@d8>ME+G%6~rut+gT@dE`BKTttYK=A_w6+cixQ8CG~q9O~86%`eIP?4fV zMMg!5rj`~nsjw)uu{A0xmt)IKx4AdB#+tAGw)Qu4&Tr3kJ=b}j`<(l})A4TEG%}Ow z6&B(~O`uVzOs`O!8#y6;`UvBeLdwY^(Y-J@oEwvsPG_>y6TB!HBz9&ziJnkMqNh_y zZV9PmDmlY#5nz$aV&D?c5-HnukjK2h*wKiOA#`p9I05NT%+<;`)T~NC>=`gZwTlN=ngannu5$|3wkiv z8f*)(V}>yf>?n3TbRu*T=M0-#1z6?c1@s1agW(V#s1Iy4d^Hk*LZFe@HTX3IU!pJB zkLpK9G5lHn>;O(6H;^AB2oj=e(4t^*h$KXckzwRmMW`}Vg;R%V!nAlDULS4}DESCYCwNk~NrZ&9UX!*~7Vx+|j)8yovnD0%yTgB7ovT z0a8IUFb$FfO@bxElaX{(3OWUwicce?5!1=(R0f^F$Y5o%GdWBylg|>cgjqG&qHJ-F zge_&ua^<;-JY~KrUtORn&~kKz`a(ldXHj>tk!#|bc^2MaiM7;LYUdC09c82Cai$R`$%3#c4Ahf&BXWEXLYxy5|0 zfGgzHl!!{ir4qiBFDsLmDaw`QstUD0BhXgrD)nm(Rh?DcLgPBqI&-z9dT_mUy={ZN zX1K<&adhMOrio3Ho1LPmB0!N#F^~)5f_abx9)c>qYCu8zdW~HL{KJjfzdmO{&dmkw&E5qT8b1YS`Afty^pq zo3@*4EwzI?tUGKw?K_7hj=Ish@%oAS$z4wAR24wzvJSWoR1L0%tcPxZZGhJxYfu}} zo3NYkn+cnVBJvjM7W!7kR@OGQm?P$H=WiF(3U}1(5bYF8Bob+ztWI99s8{Y%N!3!# z7uqj$yY;&bdpc#^GUHy;KJz}y{=xlLxlL|AFnrK)aP-jlp$Wz0VdvqgZ2+;07`Po& z3$BIifbN9tgiDYTR2{kwTaVvG*hQ3*rPMFzyBWJ#d)P9LjJub=SFlgGuV%kUE|yCU zNDs&k$`2|IDHSS(`mpAR_K5DN{;1(tr?OjVJZ?H}K4CdIc+#q}sqCkQ8ypRzjpL0I z>d7W&)6^b-%tZ#=3)%KH)jq68iX9S5I)oP?f)so*N)DO3Zx0o#agB&dl^ zEb%uS0qv2}!X9Z`4=W5Q2&Wp8@3(^a+7I}-}qEe^QsV`|RX)o)p=&u;` zo%-&p#%rc)=2lDVpuyT^YqPfxw>z$nULWt6=$!0yc1@iDXk0YFv!Ju!bCC1U^Dr%3 zi@bnpLAPKp;x7_(L>>7O^)mf3;|l8vThF=5y~@8PxF&3^F^CM}Hc6YbU3Oi5UD2WJ zP<5)iG+o*ox*PhNhVIVp?jB>0>6ZDn<@TV_YP5Z6?;Y-S+!?(y-Z#-VX>#73x(c}J zat(M5)Cz8e7@%#iHh4R-9d#Yuf$hL|61s?8r-yrse@k#%Xsj`c zz7+RLdZl+{cjSGFKBY-@SAAD=PkT>yUvD;;JNvu)jSox@%?~Y>L5uZ~?Xmsw@PK1r zbZ~rVVrcS-^T|{LcnfqJd>dkfehK>$-iz!--9h(Z`|u`$iFlWMk9v=OpK+gM zX7_XYxexdc1P_Il8jI+W_>ttXbU-#BA5;t~hg3uACz`LcU+JuRtKsX;Z@RxRJ~cfx ze`~P~+N{rP&+N~KUpQWj+Q;n^FDG9)Urm_-{Vx5$2cU=GhY$Q{6t!^--a{SD_E?o<9#!MDP1Yiy!t;%AcQ(&w@l@)rub@}=sf`jzIj z_O)(UKWzA}^G){~YT#Fj13U0n%yKLoD1{1H|i9N_Be_IaU6J{GNA zwltAgSzK++?^S=8Gp8uW3l`f#IM3+H&s?&I6eW6=W2_pQJB_7~?Jo=OX55G)V1v9@ z$wqg)PBIXqqQZFWx;JSZ>JOlKXn$4;@gn~rR-H^{r4l2LOk~{H@p{8Iq$n(!lcjoJ z(!b3%UHE2LRCie#muSHT+fkDiW6vOHaTxE8p#T%VXy< z0(|rDM4l5p3u|_DT?$zQX7%8j(5i(C+}(T;n8w2s8^2w+UZnwOEEnVC$zR`EFd)@RdLwUXYJN?FUr1f6`}^iRWIzKCTW%a{5WXx6O8zqdRW3{(^b2XNW)G0N5CHZPdx@;Cy$jbn<@@(b3i#-d3C<-0=D z@jt?`gs>=FNJG)R_{#u5ZpPw8CH;~&!Y2stNL)^2HDQ z0!$z|ruY8N0pWbHANiWF* zFWmXv))%oYyxc0@GLOpQ{5$-IP5;bPFgT#%F{>xx%4#o0(yZCSCq?%{8W8YAVnk@z z>81~|w^clMcbF$uz5B+?Zqe}2LKF?t)ZrHn(2Or=Czv!c0k9Qw z=0u)7FrL;?Q8=9|&+4Uk^`&G<^118nq;^ zq<{U_XjOo3d0{^D(65buCmZIugBM2Ow!c!nm%O3HWu;=#RYO?yp106tWgKc8qbpjQ z+(sd#Qs%i&C-HH$HMe*9QgSq47Nd)2Zg5iLc)7S>T5FP_!I?&dubMr(%p!hSXj%zP zCYN(&JY{vG{ZkS>mh2s^A1Sjeg;eo;yyRoFR_ZlYsyD2%xXePnOudHoPbOCu6I=3n zDOam_3+B(A6V{y9t9-}Hts7~cI{7C84q04Lxa)gN<2E~L&CGw}bZAvt$C}lZ#q&Xp z&P09ot$b!aGdLi$sidE6EaP}A@kJc_AEvROFF!LY)x`y)4r@OC$4V%ZUYgJ9Nxk0S zOo(0SnNG{Nk$Qc`)3O2zN%cOYf!2x(Udyd4&iyjEZKh+&3zsa;&8Q!dkL~`E9E0#) z?VWRb&)e`b9!pp$E0%|y#xzz9A-shpyxgXLQraUlZf@b&G-~mES}VsiGm)9}gTHLE z6V7w8rgust+gLx6aAn1E&*k8SM}M!jGH(X>R+mPE(pvZZwB^ORQg=68@cyxbzZ{>$ zs=Z*Kd6318e^*;i{^^G-&cOuH+jswX>b<*rd~`xA|2~Z#c$PoUxde! Rx;Ha-OY_nG`OJbl{|6_1{xJXm literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/graya.png b/tests/fixtures/codecs/png/graya.png new file mode 100644 index 0000000000000000000000000000000000000000..273e65c7e79aa465d4fc340ec8dc5da21bf4b895 GIT binary patch literal 2152 zcmV-u2$%PXP)oxQYc-O;sbi=tq?aMP8W z282W)atRO!0YV75-!JDJvwzrDJ6jd8vwwJheDgf>e((F7^S#dt(f|MkVG#e_c@M%b zvHzka{w=~UWgk$#RDr*z%ThfY3jhEJfcKoh1K1DUSbjYSEJ;7g)#ajxeH3#|vxQ~&)m;G1?JRpAncu*Ds z{%^4=y(+yby(+yby(;|}0amwKZF1QmaY3%tMtobA-8X<88lAvFyRJ$yziFBHZFXjQ z3jPg?wYcaPQ9r3}S0o?AFnV0f(dITu=9=Sr1D$rH005}upWm7_x;>5qPM6L3YM;-i zRQvvnAVNO(;O#rx%U&a=CTFCYU&u&RshM9B2xiO9W+)t9FApJW^ZkK>yr1ns(Xx#r z<7LGgp4zw;0BDpr3LgIagxg~<9j^sJpU-9|5|TL^*Pgq=<)9cRQI^f;F&V-%DkXtl zw8my195F5igHzLPFAi$I>G3L5Hb-UY^o%5v5$_LpeL13|T1q#Qs8m+HgtGgTSkCA4>aK~Z0Gl3po?sQdGWGoJj(&K`84wutqZz;&T*{fp} ztr;Fye!*oA4D)K(%+zE|VX}~jA(J~zmEy%K|E}Czd`7FA($Bv$IPCTuMYKAXCw#bDC6$Q& zcC{0Rhku120zTnQ8g+U`*aVGDcB{xF4DC=L7=@I^OXXT@ET-zt(Nicoskd1Dfr8wL zsUgk035OdQ&k}Uq3WiWjIT%OHOh-`tY@Q@bAWUB{YqVm)_#}$r;dKQPAvyMGIfgOf zhcu_ogW&1<>o*gIj%`+ZkFsxo$>_OVdjY$fn#||T&3EB7 zT3sBqZVQ`fSoq_N#X36S{8N6;$#d_{3~3@G{0IB*#1c#Ec-)q@$RjRyAjo(x7}Cv- z?GJ`3HwRz!`U8RV%P`JlhF?d}2>jezllqh-_J_}u0pN+EDgBOe!*da^MvHz*h{oYa zZ$q-|MGJx$7d6_s`QCm~tlL|>HkngX5eU$z+spicYn}UcU%8sXrBZ4e@+4V;V8~!B z$i3KNu{vG3;{2TFw##x}tOH~SJ3Qn}GlipOw0Eh**?+gz2-riYGr%5G7Q?4kMI55nJcY6}( zi3}DqCT4cNci_e?t36B5KjiUn*?2sWXflJls-mMC8V{Nm%#65?Gozz$&>N%b5u-`7 z-{vry3XWA*boQ{$Txx}&Z5OpVdR*K|e;^oSeUO|4<4$der(VAHd)@RbKl#QBqZ9KB ze{p|RFW`6XK@h2A+r@?^iLiE463b?%zYl~X@X7Uqqx#uD=m><)p87Jlqub-Sn4o8yAKASfbY_7ATZ8m4E$Z)fOuGT9?H} zij~VCxeS8zb9rI`pF|p))X$!~;`ZY4c@i#Xy*x*Rp!JPE-IYMs>Q0>HB}p>lX%1&% z0*1A;pE#Sw6ASO&z1WhTLM6*(W-A`DaH-<#vIgTYTk4rfgz>w|`-t;H9%0bvA9`p9bMC297TK7I1s zr?#_~sAT--05GJ1U(e0*`bftc8fnyD_aCdx5`+(jkov~#BQW&R^B?jHrBsUJrC_jX z%h^(mR+bIDhNAkpjLS62^xV$oe|*VgSl%s^hQs!~xR~Nai`mLIjf`^=fSnLeQ}j7q z7$(XH1Y0|ruB+5;&$@zhmt1agEDWpE#F%HcMnz_eZuHvhMTMp7o7*R+<Zgj*kyskEZV?v&r#jXZxamo$Q^gUKiUt{i}aw99GW^vwvnB?kaX} zy524BHuid%`@D9ZtIy^?$Lw&#XN63z& z?)*lDvr6WUC+#@8|KQ$@RsD-eyZL*wtz{Rier(hJc=WTaWg#zrUAA>&X29gEHf?5* zA$I%b?Nfscuibts`IxIs`(cB$?<_LBcJ+tZzOzX6$Z3byuKqTw-@UZeJKGMg-Tq+? zf0EUwGJGV%N0OfrHr3~GSHC3RAD&ZxzMk^~`0CBZ<0l)m{5xP}@2?^)1Q0pzzirs6 zqE!WfqLo&1^a0V?L8w5afl!q*1Q0xK}0})iHm0%EQ3XN0>y}srOIn70)%4HJ(TAT@Q9{eS+f>_x4 zO2$)#A*Zb2gB#BnaR>)o6+%w+WREb2NocVueQ4z%)WjNTKs`N3WK3eI+YGyz<6o?Y=AZ%hThY|WfGmk=OBDtDw zQE{r!0O0XqkBSwJG@PNyk;Y!cL4Y9AL=ZyIfz@oR-K~RYx0n|j5<{;9v)fprSb0ZMQp*apK2$ts1bY_JkEvhnr zZwTMJU?KuXBo6|I!m7Hgh~xAD$t*{!Rp?#70iiijT7)o}P6jvmfeXN4fr zY*}#-DSZSvHDU6A=*emf5eOoHl!mPAH7VzU$SJ3Q$N_|)N*|pCgK%ZdGfM(^X8A1O za&Xq1O94W&v@()f39K3CELDP>>hCRBX+^Y!1|K0Hr#jP8Xv5JN4tzmWn%hPQ7$KlS o)(BN;m5>lXGy$}QDFK{Qol74OVt6(1T!g)M5rGzG5mq>V0g0Egl>h($ literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/palette-adam7.png b/tests/fixtures/codecs/png/palette-adam7.png new file mode 100644 index 0000000000000000000000000000000000000000..6f333e4d668dd0806192f3cffba081a3785f442e GIT binary patch literal 920 zcmV;J184k+P)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw0000mP)t-sFf7i1Hh|77Fi5ku zwzEhZ<>ch$8xs@_8s-|?Bi-KP-mDkQ=V8n^MgSx(08?lH?4yUX00007bV*G`2kHs} z2_QHr<>lP~00QJmL_t(Y$L*Hua;q>5gbg9MihOzhw>{qqOleBm&h%GjjwhwWlGc*E zUMHoLrfHt%biXl{Wl1@`-Dg`L?=SAnODmpoFRhna(>aQmWxa^XUbM-fm;f z$b8RXBynEyIfWm6caMymjObZTZgisQ8HUuV>oDn_3wA_SbU4A2H4WC)uM*~4NsK*jub`u9h*5JOPh2LOyBNToUM6{NuFr92!2`Hgu zuTdli0>9qVi!ps1^Y!>~^d-XgfnTkko{9cpNYP%5lfb=*me=#a(kZx*ze|i|c@AFB z<3scn!0XU)1P7UiMDC;>#2)0{`8`x~9E1PSe<|A07PP=P!iWlb!3~8&r=LAa12y`u?$p%px>1H(KwB=aZ~LChmFT$}hLEXMVSGBJnR zaW`(z;At`WcBF=zF)-v0UW*iy9w-jNMgGc@8x--;d(={tO86W($5X(b$n7YuA&;Op z<{Hfq7z1Fw;@Yo3a;{5wClESkas uQE0TOZP`}bEh-`urKee0DfX=~wfqCVNJt06vqhT#0000^^-z+MkxAV)9~Kjt`2>jnk^DINUj`R*ln*&8n;D$}hUB z`lYWczv%w$p5wW-bq@cE=eGQ|{hZ@7Y5V$b^xU?`RPRrCE{~2YBKKXemhM@Hr#$YD zkILHLyyzERj96=WjfeG%^SN-}E^_o7_wV95cMiYXZ|aLPO|iD`&o9=i7&*^iT|D2M zKj*aJ6JJp$`i$3go>Sc2+RE;xp7*Qf=xNz?>TTJ*JKi+w4IQsn$;dQRV)o<$A z{#AV1lk?LAtMk+Zcki2I_rFeV;%gD7iMJ-4roQzC-|MD%k&o-tZr`~zSQNQ;kch2) zTdV3~*;(cOJ0te_-j}K_mU%q;dREoNBEQt4zua}5U+~`Z{JUO!rn&37XAIsy=d15o zoJZZ~8od8(&;Op~zQYmgzt2~H!~5T`{x^)zK<>9XV*T&-)%TPBzpDSQ>i?hT-@E&F zlKsM%wcBK0i#C^^-?YUxu-q$p$|q~ea}LF&ZY;RJcq1XcTe@f@h;AMxnyvInLYg!E?XQ)rsFE#iCxEjbv$Nkl! zM_dowJ16Rhliihi)aM=@GCX^jOOJeexEFU9YT)*WJ6Bz@e#j{gT|zIBFHR5Py!4rX z6W}?0YH^>)kGNjQ;O>O39#TFv0z93qUhI+24(gNP#u?T;_mmH=mRvHJ{cF)oMiwWl!whkH@Q%Lo)gjYkaBrU&eUYyY*)vr~Z)i{h2V*XLwaH-2Aji4x7(Jln zKGdCy4!VSVcYvSnEmz!rwc~#1L_Re_eX=@a_ja!S!O;;%gPPjvI2+s^XF3;L9cIRJ z0jD?ixDzwr8qTK2xn%hEL>>9=%53WNgQ+hLUmQ#vKEVuevNOfqNqz9Rk9_si@;shhWEY|e%nJ%%&%pq^Z^TGZS}9c%EM z?>Ugc#GOeG{b*5x=UgxXy~uYieEO}S<7~00MJ;MkQ;Qt6)Nw}i1{YjyYGU-sr4G-z YsXjP6dq&jbS#a-ph|?42ij(300A&$(B>(^b literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/palette-trns.png b/tests/fixtures/codecs/png/palette-trns.png new file mode 100644 index 0000000000000000000000000000000000000000..93807bb3eccc19b55229cd8ac5ef530991d47de3 GIT binary patch literal 727 zcmV;|0x127P)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw0000mP)t-s6BG?FEY5&7fX*y1 zNVB%Kvq&4|icJdkkCX<-hmt_yVjo$}fqfhtI%W@z6 zh2To}a$~mIx-+kBE7iIeqiuz~wLQ=e^aK6JX!mK6K0M9Fbc>qsRJwav@NPDTN9LR! z{hEdNsF>z+(l@{nc+armZeRPk8hj820>~OJD#k;03*#^a2x~-G49KMmlF*m2nnPfl>IWV^hmJpgfn9zAMYGNK!{pX=# zVGxMnuvVoH76Pdt9?2e%n1uw>a!2_Kq}anuq9asRvPU2vY=-XEg=ivbL!jqk2`*RA zr+%uOUKqZX)L@2eR%z0VZ`meE+%knzcJ?wra4!tfIt45tx5}QJmP~+dwnGffqw4I8RP6T}oKlxy>IVT12 zUZjN!ht1yWuC?~M$0R~G&u1S_m)rIH+0kshIz3r$=T8^2_Y`Qyc6 zwtcrb+kV=t=I19bXR9~M_40gncyKlFe7%3615G_w2Zx*<5g%9wW{$kZ6TIcIYhe36 z_Q1RC<+-jQO_RLF?l+Et3`x6F%PUmekbpGSI}zJ|h#LO?#6G&XthZPDosV**FiA*# z`(=;%>+_!rAM3FCFHaNrCe`J|Q9YprO!6TA(8PAErpXZ71|K-ac9f=u(NKiGJ{sPS zk~Ss@*&xGnHV*M0rMaWA>$~R_nu{7`tc%9&6C2x6qE?e}qw2QPzk9+eX=Jb_pJ}T3PWcrZY!e0{q{K6kG z_yK(JYL5!Se+Sh3Br-w}fy3WD7zN=ls?y34ni6R7Q3Z{s?gEh}qB8_QRDd9ksu%&4 zsI9_85|n^YD=Gv=5pz0bo#qOosy=}F0LHnh=y6VLXpY$)p;iXaDu^2$sR@aduU1un za!`5Oa6r5b189XxXC;7+a?ABM2%svr#D`H1LVaB4 zc2!1_07n8Kecc6OBtXcHmF6z01UU3j8A)>@g+ng~q;WPR6^>RShC~HOuQMEJ;RKR_q0oQ_W>oD-eYGP<;!n1VI=Zj^zn$=a`p2r8>sFD(*4)Xl{o_FBt@~ z$EQKE1;iDqr0Gf3hZ-M~=mP;9L=`nYyz7DvH zsG2K;=F!S^Y9)x^3@Cz?1V9k|W1e-|8c7G)p~n`ji@+IG$=N9c?1iedG8IUy f@K0<&M||K*Go;QSxi^@JL@!MQn(^d#0}y@#qbIXs literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/palette4.png b/tests/fixtures/codecs/png/palette4.png new file mode 100644 index 0000000000000000000000000000000000000000..38f588a61a0963c15cb41235e159b22a200cd486 GIT binary patch literal 691 zcmV;k0!;mhP)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw0000dP)t-sFf7ij7tGEqFfq){ zQ)mF^Va(0UF&P~Q8s-|;B-!5M-Z(}8|Ns9a!|~ey0004EOGiWufwNI#00007bV*G` z2kHs}2_QHr<>lP~00H|+L_t(I%k7cBi`y_1$94U&=N%TpcqtwV-AV(U6R;7+%Ly!m z@zN>t87xH5*d=2GF(Gv6oT&jBQ}oZ>^BqUi>s^*kg?^EY;Pd?S{XP-$OS3D06xW&F zk#hl%OC0Wb`XaxYc=|HO3PRHB>x&%HXZY*s^AUOa>do8V`_CUl?hl_=E8OY()uX;V z@&`TeGdf3x3_NMnU+S2u@!tBXSwvcA9ZYUYEMw=`j(g$ ze9@a$ge8PrbcN`0VFu|3+MVDB;kveM?@yGkYr6!m>rMkNAS@kk`vpN~csZsJQ5i=@ z>~P8%G*b$ZWLpyNI@uUH4IiC*_bro=?J)u?X=QH+zJ^pKRUu|pVAjU;s&kQzD004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv|NsC0|NjYC_uK#g z5^_mIK~#9!?UrX$R%g0~FW{s1-Vp(%gUCh{JA()+iYAH$g|X{sG&+eI)5e%s$F7Mb zMk1DoqCo{kL_|e_*9a;opddv=dT$@d{Fym3b8^aLopm@r4%g3T-}_$Ad#!ivwG{w* zdSn66l_U#*t{bv((3PYd0P>{2&d2@z=|9c?tNgE%e`^@`tNGs>Zu~2G<$v4fpYwlh z829fQlK!FL*ZIG0`>Xtal>CSD{x=Q(NnQp9!SvBf^y%(Z`gHdyGBE7Z-D~vS?p~!& zcdsG?!wLV_OZ@+#?{@bpeY$&lQhr(O>*PDM^|8Lp(w=^sMw$eWSXY}drRr+-IDt)?pl|J3QN}ujtrB8RS z(xC@e-^y%(Z`gHdyeY$&$aY2Nojc&H590$Ig(^I>_B)Ker`h5Q5IiV3I;8vAA(PEYKo5X=j!9Kxt5rjuw-Y$gQCRaOn+<1Q# zoXHCPN|H2QYE6gg1r?vd^?i=PcW z6TX0~th-4t=HsdF!?L4sw_$ATv^KF!o!`%M_wHqqufnKNaFwj4x-3+p!%HttQ zcUuT7@fcEs0N7G=y zEzh~o9nh5n=IV|Uz~GLl0OkEE8^L7FOD)h@Y4A044r#v&#)~b+g4JUC0*DPhYzfca z)gA@qc-4!51MW~fHO~h$QnaUo;z7lQkajqs3|uz)ECHc*OB3ok&21sz&2$GS4J)Vy zr?|m|pt(}V0NQC)gVwgDkHAI4#}918fNV(Wr)2@{fo+4JcH>)fcobNv1hT3Pug#$U zEN3rB|LR5=WL7Jj0o_jxETH6AzBZ%^(_>JQTOffvx>Fg{#~U7oJG(ER0Lyl}UGROw z&yEl_Z^db_o8@u|Dw6IkhsGc3-a`MIF2&HQ)U+A8B08;L;_P`BAmXgyUdT{M+6oSn z+=HQh^+P>qJYTB;@*g^;g5e9(S>Ragag#=9WXJfs((nA?W?lSRZUo>JA2lT?%o~-qzXz`Z}i8keB{w1k~@S zx&S}5=6VBVtObizwqDTq&AX+b5Lh`g8Z6c9GC}0u$^wxx>SrO8hpBFb?&Dqez@_=h zDoJV>QM(fq&MIWXp-o)_giuIVkb`Td&o%h!XNPb}>MU%Z0Ro3Bg$z3Hvl-a*@gW~CV=ipS$6eme~Jo?@)7}PwX0b)!| z3Wd0*5kCpot8f*Lj|t3@q{?xnhv5F8>)mkBTmGdGO6!$OAjBhb1B6d+UM5LN^J6wb z;JGkk_-U5WMInl+pPhl?1JAF+#w!+)l9V$%V>>i!Ht0gv?u~1OD6)E10!@qRN5dXt z$wHDIK2A{q_vb@(;9za1ix9V!;sQYCp*#%!@V#tkAUveU0IOXFF69dJ;(Hbjxg8``XweWp(nDZ z18UQ5`GTwCkOp{i@xgA09`bVlOpRWA4PIsE-G$m!JtIIhO??9lG9MWUUnJ#x35`{? znV=+;TR}<9Is)={XAK4qGrvMe-<$XllqSngLihEqC6M*`T?f$LYWxskkfE6pB2rfRY}T*wki&_CZ<1!7%}#KEjb#zUbouXYxU zY@9S51_$b%0Zl)hsc_|P)K&1X3MvD6P)9zL4Sg8{-7ejiL2-26o$z4pjkPf7 z;fUKHd#rpPOw+8^!P%7k^^iO<_9fILRJ?{v!{p~slT)Dyj+tJc!K=u;_0VM?Hv#$9 z4i}g>Y@RCQ?aZo&sa1;xg2@xBAg~-|rwz?U4Hlqt++ZA}?7y@g-YxIG2Q^U@>5%hF zh9Y$B?Yau_{ZF0)h2yCzYlYDJ(l8PeLX7*N4k+C> z$5)8wiywUfs;ksAVVj5RdP#bc{@_#4{848IT(CED7sAG4z%@wzJk|ydZySA1lA0Xq zYoX(ITLWyWDp@Q<=fIAOP$JL&1U|6UI4en=O&zNs;KcL?u=Gu8i4bi&nmwSszO@Rj zy#9TmBq{aCZb8*Iquu@n6!=Gksm84>&yZ{K!4-bW~W#^TJP|j9ShJwRSzJOg3gW@Gg{Tr6of!w0A7%E%K)5by$|j|Lyv&d+QFgFk=-5uc=CR@OpmH4XE?30^X{Y27~<5&N*P6HozB(qw+G~ zjecdG8$fj2YJfhns&Jx#L>atku2!K;4H2SWbB ztYmndU8oERm!iXA$fnFqMNx<*CmSAwLCe9$8(?+V{tHlcS6v5Mb94qn zl}mXG$d-JqxLA_Zwdz74;X#%IRJ$%YCPd}H*Uex!#jF&Z?!?tdl6siNc~G=bl0kd@ z$2CIa=7@dp_GoD;1onUSlO#3F>>djhcavM;WRli1Atvg~&4&Ba5}n{rt^IFGQexs+ zXHZ_2 zUVyG7=}$BXhot$({h;WZu%$wjy5kA`-i*qEId2<(l%x+rV-7>bv+59NYH^z*M66v} z5!eTJIDpfZI1NdXhnUzxv}x-`NdIJbo)8HuPt5?Ql)?4judcpBk}LyqK7hK=<}q+~ zkU@hG9P1elvKudA;9%*jIg*q+Uz~$7S*s(wDh$dMLVcvBDLj~*s0HIU>z|S&+5M;2 zwn6KmCOKFn+B(Cz9}kv+o|EBBP+X(*F<1vWJ_FmE&S#;qvi2O@?YUY4XtM|OZyMWx zT&HF&sC=Ym0E){M62U;h@psxz`r>b|sQ{D7w;Mm~h1ZD$lRzXST1#eIb)zE_G zA@xdd|Mm3;plqe`2Bhs{-M}PUc?-xl$~)kv{9OwmQ%`XQjBB3}4>QiJ$bs^(jAx*8 z&foxCZaPs2Z_Eap!r1I-UqkDUO-rETY}*qEYgsW6;+LKbhl>8S?I4?~avCaQ%PgRz zxg!h$?}qun+oZDP;E?XN5wu3>szb|~rf6^)`GgQAo(HUkvBl#-!rP~ix0j~u!V>?JoqJ4o*cyx9Bn zDwM_*%!8|we_Q}9M;lW?IaB2wxP9$=8myMv1;EgkfjQtZ)#o+He~@p1c%SH0nEuJ~ z=U{xy;tmukJWGXhuMW%v>q-ZEaGoNa1pU1xtvyi{cqWd1(c54s}c zAHx-+D0Ao@(Y+n~ue?7WbQcojiW0ohF3ti=H@i0QA2clq%%|C&0onIv zvIrq8eLj2*9bdJVf%Emt<&xA8RAUbzxsjTXWm|Dmi1_EH2EqxG_uC-YzM!8Z@l{JH z$YU=hz_ywyA0g^mV@E@HxP2$Ays1+!NuvrTPlefO2YsR5W5sYG;=)tz+uN8e<759-kA&szFb)Z_9-#_C28;ke=E@Y+-NnbvH{=fq}+B@T~H4g*_n;tA&tf|MCXPTw*lg)S}2PNz(H- zZh+FwFUlY>pi5hbVdV`CV7$&^5`0n7uS}A>hK}k7C#Y>NGrw68XEgBA*=GsMIw%j@ZNk_1!M7#=s>hV;f%aLw#}Hli=NC{nyfOof^v#XopqJpzWJxM+jOu zdmFsxytElcMun)uMXw__VMNBn8}N8fS~C=?=j;Tf4YDv86gT2H#7+O967rq1FGEk@ zyXTNL^;$Xj*#)12e(xM_f}NUkFcf$^?f|t18i~-PR+j+@mZwS}G-P2UxHb*>8GN$* zW$@Fc{XfE^y43UFHpw>v6i3XR_z?^~I!Y0;kEAKUE%l26IybaGhueN}+rdoHMg|q@ zi)VnIjj;n%)Rk0$ukE-B&<@Z)2(5dXT7VrrAHb}XRdvuB)f^1FCe!}%!Q_{4a*@u@uU-!Ru-Is!u>hz(0R4P4%&CM#evyL>m6XQ+*BDd#^20` zM(^4b=+5ib1;^WiRzt_(wiLMi$G9v=&b%-Z9^Xpygyu;N5#XccKN&9jozQ^B*t%Ju z?X3Stklj;Gfb0*_GC<2*=M@Bvn==DcUaB1c*HE8Q$WTw(3H2XT1%t2AxO^D(c}NkY zoVd6Zibv&52JaVR_Ccz_SR%7y;Wmfx}$`oDE{0EdO{BOv#BrX&0Xq!}4WW)!N% P00000NkvXXu0mjfUO7eo literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/rgba.pam b/tests/fixtures/codecs/png/rgba.pam new file mode 100644 index 0000000000000000000000000000000000000000..9b59332ca039028d22063f79ab9bf6b130413a95 GIT binary patch literal 11047 zcmeHMf0$Bry8l+RkwqI6)l5Z7M2Q(H>QQG@R8)@6sHmuP6crVf0yR=9Do;hbR8(|! zsi^1&5fv2`)uEb-YNqW}--?ReVu`ldAM7r>%=BBkNf2oH%>>1m{wAxpV!*nX@K1mab85&79D`Xw!y8eG_NQ znl)j)drjYZ&zhwZ*DhbYby43M=b{NqS2>)HwG#-Dbt*D`nwpHArXi!JYsrXSPulu! z(mKOHhR-yT=9y+vKg&XDXIV+L%SLE7L!|CrGI+L~RL*vgfpeUsd~P2po$De+gPRl# z9+E%LOR^JvBs0-Z(vt!tH7P`r#xO~oA0hGcqao)9!r6^Ek)v*QX>6R%EWo`0C7yM5c||2(sPMK7%L?WmA9b%up4U6;MB)7wXM+C`%}&7v`#dhxhUwM5pD zCB!6OtTK&HRh!19YD}Y-XiXzly{T>OHnpZ1OvBTRrsj0BsXpCes?D&Psy3U6+8C2G zv)42@%WkU7a+n5YJ5A-;eWnuQG8N~zO@%ogQ+}@3l%4A{W#;)!>3IQDswZSh_J&P~ z-iRqaKWd82=S}>Am?^q2Zi*~Sn8Nm?DP&KX0*lfn|Kg0vw>WF^F3FobOA02pqiAw1 zEt&e4mQBuO1186^ipjow$kgMMOpKG7Y;4tJWostOin__XvS~7|95xyHTBfePwn^VV zV$!Y}HEC9jnbfPtO{&$hiL4=vJWs`p&r>sFJsM`TSIdm_>Y4WZZl*Qgzzi=iGR=i% zroPa^)a+KKYPT_T5yMD}dYQq+cBZn#!3->MGG#{}Q*yYN;!-zLSmt5!%e+i>xsS;> z{Y=^!U{Y*|NwQ%ku_D66S45fEN}l2SVobCz&P4hXOt?SEgjS`P!0I&PU!7rmYqE^j zm1jJz0^?p=WL#@YO#iwv<6JkuIM!DfyL*V~aZ3!dfikuYRmQrp##lDi8S|zlWAqF& z22YFWy0p#cxe-RojWU|eV~l$9IHTGkGsH_+dAW)mU#@1yoEmo2sbxo4J=;#jw(B&?@r_Y7wuxtXPmGOv;%wy71RK6I$%eQT8`zv? z{hKqaZ%dZ-ZppJAZ-I4ti>zyFiS6H3W}VvxSjYAXYu`S^_V^^0*+E&`jw);2Sz|3b z>#TWKlQsH>S%bgDcI|Gn`rRX}cF!oQ**nIn_l~owfXtEr;pBBHZhXC(8*^*8QMZ;G z*`Vjz8@jpHMgupz$;dS~nYp^h!qq%hu6n7Bqa4FYTrW4c+0IoqJGg-@POj|j<4Rr^ zSKR963R^u~ew&xeZufDS?S3xp3vel4h)eDWbBUc1F1|C$#dh%=?~id&f1Hc#PH^Gf zNiMV}#Rc}HIse`a=L=*xZy?WkE-P^E%Zi-q@)Fm7d6{zt2RKKl!r4PZT+cpQb=(>T=L| z%|Or*tpx4SpgVyV7LCf{^p!sk!XgoX|H1Mrp*A4BU{)UmD_Quhm z=Ekw0`lj)qDkcX>jPP58RaI{WoQJUo6XeZ_e|c zn+v@A2SwiXgA(8W!!qxT5Acq7g}2`_#P{4H@yxB1x7}9dt+&;9OQO!36HVTD`!H{~ zqs4dK(dPAcj_}$$M|n+hj8`YedDUGqPXr>!QI#+rRSRR+YJ}12w8F@BdZB%Nx6nFl z5QYyMg(hzn>bym$-Cz}}H`oMvBO^#R^$LSG*@a5XAq>QvLiy%Cp>(rLDE`1L6n^Lt z@;~$n*|<;0+~OC~w*-XLtsxP!`BTBqzsJx$(FYh+8c~3Z(xHpoE-y6-v(tM7; zFP4km7tclRPvpY)Cv%|(Qn^4To%3fhIp2fXocE!8&htV1IUgCw zIkJ_U{n4RZ&!bX~$2GiQ8!IA?ggmFs$4 z)%$HCeSi_A2YSW9j9sie=nw}Ubc*GN`oz*hF0uHqTP!@{5%Z6D#cb9mX0m=U{b)c; zJsJ{|xv-dcEF#7qi;A&4FY=Ga#OUL3G4e!03_p<+Lr{gwU&x5Qr?R5=sl4cU zx*)orE{d*aN@9PpEINw=qT|_$Xn%G{?0HTSndhl!d%h}KOEu9_s*C0qnxgT=VbSnn zOYC~7E$Uwy5w+r|s40($>hid#dRZ39%S4hNQAy)jwKSI1NTZKxrIDOoYUjG8)?)@~ zIB%4id9zf1+#=N;w@TF~Y!ZEvk)$VkrNM$-suUd3z*A1C{B)mGdfFuwpK(itXFO8A z=#{e1`lQUWekuK2KuSFql9JDdr9>$r#Y<5s_5v^QFT|wii*YIPQbG#9l$1hZN(zW+ z$zRS$zH(ObzMPjluM{NrD@DomYDwyUwJbRY1|-L870LeEkks?KBr$JL$@WH7vQ}!6 zrBav7Z#E_4o5Paft(MgFc3aZFJtAobM~Y|cB#A3dcn{be!_cz#l7xZf={TL7w{X*`LuZb+br;^9tQ_ExTYvj=nwDQOY zdbv%z?Y|z9dwwm+ z%x|b{`%P80wraAaRhP}bZOX>q4aLnRL4U z&sS@5clUQ(t?sA0zx8Sjbhp0!YIS!n{qC!^zSaFLSF8K;)^}d5Z+-orEq_L z#Vo$PU%dC-{bC;9(l73RXTO-ox4(||{7n=14qhL{`5Sb7l-vJP-$(WQO&)&K!~Vg? zkNWmEWcAUk`tK9?rgZwpdq=bCf9;`1_ptww(MR+7Xg>e{{l<88GF|_~Y1H0WN3TBN zM51OKr1t_Vnf%ZRboPgf=-$lnbmqkjnU42PJef=wnoYNM_R>WDR6766b4Ztc4OzbZ zYI0d^1wHVVjc)$iwKQ}5_sH>^f@Hhl0y60d9bNd?_v!qXFQjYN?ID|WXOh!uj3%yaifUf!5b@aiLzfUw%W)W-ucCz6~rKb-TP(SK-xXH>@ z%Ds8Y_eS?q0cYc^pY_o&YOyNM*l-!y`q!&y`n_Jdv+1T$)Z_G!)r;2=_CF8PhtacW zqN^{QPNv|zV~-=pNj-E&K~EQ>KYV_bk8ISON=_+Fq$}T=K{t=?qk?(@Iq{OY#5QLc zS@6#X=#M&kXyTtj^saNxC+As|S}(YSOve53Yv}#JL3ai@{VW4H8`t|v{XbnvuXxc& z`^hon81!bg63b^!y6@kW&;Mc*y>8ZGGH>B(vTW%F(g)1`5~iu&@1Q@#Y+QbF=|wZh z#cwOPr)LvVU3+nK^v{VX`ODxsNK(clUL7H5@O8P z{J~FeMPEzSlNDR8B)iw_B%anb8hd{}-SyO&)Ujq4@u0r7%AEg0;XN?Ntf7Y$o5@=3 z8RRs~3b+Cn)QuUe-%GZj_b=DeYfv}1q0y4>A9E}@7Uw{Vn9tS-*$eG?_7NZW_w3np z`3n(7IduEeN)O-_>Id(@{a z<8h^jlNJ3;okM1TqtN=pCsGD_#O%2%$gWdQC%Rv9l*jDgEtei3J9k7$5O`wlm_Kw6 ztdDRIGXzJ#b>Ka5GBE+4W0iTMC(Hsf0haKynTyE0hZUWGZ@*W3XUDZ9bdrXg3|_-e zey8Z`B_mx0%%;pH)6hF~4J?4Q_aNB=uK};YALtTV#b?nMdWRN|@M~j`Y&${mk4+)6 z{oQ$V2kQJpscY*YvKP;Ur+^R78|Vt)09`%!Jvs}#g_oUoAu+=9zzeF(9^8Zu(I0e+ zzrR*|5?=fCS=2F2!2;Ym=@fD@>W1Hbu#oP?yx4G? zPhh@c3t0<%aUYoqd@v8_2+#hl;*nphrU%gjGUkX!<7~_V838{*F5$edHqa>Q#b59Q z+6Er)_0XNjuYb9M{`mARa>mZ<$UblbdO*IRXXpzaigSvJ2mMv?bNoei9+?w79{R=S z!5`=noB<|(QO<@Y;rm2+%~(k0ygQfrUN%$L~$--r-e$QJ#q&@C?ilv&VjgGqWetd6*kC1s_4JeacJ*6`#lT(GnUkPa_uN6k-Ox zFP%?U{fD9@)CFFFbMTU9&!JAdhkXQEf$p{|y(7Dk?a&SK5;%d==m|3g2B;nWgRDa4 zLZ>(fo&gO*8^2I?HOviK!k&cv2iXIkflnegu*bj;F+=bYHG=2x68Iy|gNLA}zweOK zDTiF1-%lLJDA@##fQQ(Ra0X@pPr!WOE4YvP;epu6;1S?Bau4|e5Aq%&dyeRIK=D@i zFf@djLyyoHzK8u2UJovU$ImO;eomPoc1Pfhe4&aC!6V$qK8EvgAD)8zM@HieV0!!s z61^e#irO zC;S0k35;+-2gn8B2%cl^=n=jIedGK=#lOLOUft1C629Hx)dA_mPYNr%qFT17PRC+%ae5=>i3B z`12$so1tlN=aC6?4(f*=K*#V&^ZlPlBJo2=8G> z1pdfF%mVvA&IdlYkKar1Gx!7Q0tYcS>>cnK?EcUn_yBG}o4^a)$1Gk~Fo4%!KldLd W2f!g%g8u>&w_-T} literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/png/rgba.png b/tests/fixtures/codecs/png/rgba.png new file mode 100644 index 0000000000000000000000000000000000000000..2cf5a36fa2ff43ec5c4d66b2ce202ffe55e3d1b0 GIT binary patch literal 3575 zcmV004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv0RI600RN!9r;`8x z00(qQO+^Rl3IYirI4R}j-2ea$ZAnByRA}Dqm3dU0WtPT&RaCJrMM1F?`&#Vl2O(tN zC0l1Pn;lK2ZCgie+wPe&)5ku2rl+0b%%pp?kB-`Ew=tS%Od^R%BxEs=kU#<-5Fl&; z!cKsqpn#&N<*P7%sC`<;$=G(H_DP<{w3p}5m|K~jacl|%r{9o~x*Z;is^Yztu0Wv;;>PhQ%|8iQ6McUk=TEz6P*o1 z=;s!&$aRS!c%(>(~@KYX^?ARBsW5u;Pnij2N#q1R<$S+_KfXW}WN`qRVM6qWVzc-CDG1SAr z{+D=5CP!|b!aSzO;O>oQXbchg_p$J!xA`D6nh1x4BRG=KwAo}wCJ-ACLQrff2`Yco z8ZCjjOPDjJ$Iw(o{cseUo56{Y64Sr2^B^?hNYWW)ze02Vm7J% zS^_Oon9U~4Njapieu#~l5Q3bPC`O0SUn!$fq3>rfDv{XBXDAb8)O)K@^|aAd7J#{@ zoi4i-o0}i*=Z|wHB#Q7ikMQE=C)pXDMBLy-&QFdp9+gO}d6Fr~j(ydGY}nyPcGVd! z#HNvGtY&oFfYENl<`;xUmr3&JgB;)gF{T~=#AA(>)J+$D{W)1;pBMBRKV3e)c%G!`cw^q>9 zUqsB9OU{7+ammFZN@OzFyg7hoDbBrY6O-glIIY>qrUy+z`NxMSTDFfL2_IgiTZv9+Z$-nWs=-+l~&1)U7QX9PTyb%6!!`;e@Q*&W5pJ3}Pu2S1wQ$5JFJR zIW8ahBl~YUxET>obYudt16}l9I!#%|9C8#&lmVdxzyA_%l@wBJ7(`!nmU6=&dR->T z-K|`g>_~RoC*ySO3XSU@VVfp|pwMW-O%qJ|s8N+3;iN-CG7O?`tmKL$;V9Zmq3lg( zF-PT(uZK5YKbjG0)AAAOE>Kk%BChCcrrlSAdU=y@C@385U=IU5-xq&n7((AxPxHUU z2@~o0WFLB!cX}QWf7MdURcBXRb|nkb4VS3#^uhaJptvMFj;NBu6u&lKaGf+VVV%bE zuf3wiX2IIqM%PpBLaWV!b=f9XJz6GOr%jkGW~Ptt6ylu}IOzu%`dO{0knBiGXOuq= z5c;}XxgHir9ROP5Kq&4TqtH+>m%$vL^7qlO{$6Jw00 zCkqN{k38aZ7RJ2~9sk)R3HxJyJMC!X*=xDt{Q~z~( zPVD7y?h@uWBqS#VPTB}UyIN?!dYM|Ip3!q3a@y4$H)j`|)AJEhW|8s1@7ddNl~w>< zCdmyI)HGI6S5ro1!FJZG1MyFtP1aB!HfIv63tP!33Dbnbc?r3Ag}$<>fP67}GPV%OvIMC2CC*Ooqe|p>#&+>5Z3ufFaqMoosURz`bZMh5ARu z-{|`p^b10hcvSeUt2=ITC*;j*#D8oOsUPZP;3+qu)i}cFP%i^-x`?@}9%RF%Q=ET) zqo6(YKF8#8TL~oxEF1FRvJlI43cGD#ef+=>5Q^)n-JMtMO|+P-JM&-U%GqXe(4nFSF{R+ii(q*o0`O= zjU?>gE4=NaMkRMb9-2U8WCAf0V~k%Y;w*qlgW6`m>g@5xsWZ_u6fr6BYV2_o~Wm{N1+{a){DmqUeyv>uC zbeSZJB~+~5!TpaP;HBkTSmWb|Z`m=!Up!ni^+P>5MXU7MY>ZMC2`Jeo_wUk{zjNFNZfh&O;h4ft}5?9eA0y z!(xd{%qCSGfdBX?#=ua59THOMhnza_GJ7Huh)KvI^`-;I$@lm$Dv3BBKUCQZnQa(E zuW&{wmQe1HkUrYOp_>wpB^z1ktwxoSONL<({js+=SY1lRP!9vc8akNEgTH+><|L@eG&L2x9Yvc3n!Ux!2!Zna=dIwt&fd=%sA9o+xi zpr}2uk0XoLbKlA~;m8ckNH*;MF(QVK4KorJOXO2-LhHOWEIsrJZ;w79K7VXC2YmeS zeRZzj4A4@;)t}XhisW3<%_hvdmkHiQdnxqQ;8(j;d}9BL?AB$F^gBVAvD>g0y~78u z&4}r81x{Ok%-_Wv5}wPN&n%Tc>Yc^nnAL)H`4-kJZ4?f+*VCMqkMMN0D3|Qm`#R`8 zzEg--X;AmI(_O3+*T4N6UJD2z=wBj)k*s;-&Hy`3h-32FGAhf9DQ&n!&AintWrmr_ zF~(H;|QZ80}Oep@ZR@dygoXN!9SRQ z>T_ID`J+zDCwu45d0aohP;VQZhhF8K2pusoDd-w1sL^N%l*y2d++cXx#MFHcux`U+ zY@fe|WreTv?%b6ut}mzhdL!4Ilql2ZAROJzfopX%-Mq=oij$nnFJNJWj+m$<;@awI zc6G;X(#S;dyL`CrhipyGAw6di`TJjDcWoJ!sk6wG&t1jh%=yf!FQ>ZXFvV62)^kTW z9TZN;jc)o?{-_6g7?`z`xn3%K%#%#b%rLX{C;VXAgxNU4XnZ3002ovPDHLkV1mZH@Y?_Y literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/src.ppm b/tests/fixtures/codecs/src.ppm new file mode 100644 index 0000000000000000000000000000000000000000..d0c8f4589af79e621b20f7725d3f6843a4a76a98 GIT binary patch literal 8248 zcmeHJ@4GT(o&Tz+_ydzMv~yHc8Zj|N#m7m{QAsHoJ4Zz$rBPH=Dr)ElDkYWkf)~8t z1=m~`FW915c9x1QDypHPmaTJko9eEpW%r7msMuO6YN(}+eo)PR=6d#p*LM659xgl= z-p}0k{r!G^edpdA&%E)vOK&)K=Jm&pok?W7Xyc}}hgM!%`e?CDb3e@jG!4=uMB^}x zBE$qTcIhBW!x#?cr8lZt3F|+uYpG%>vvs$W21rILwVA91}QWmph1Z!x%S+bNxN8 zm*Bcdu9M>0X|9#wnpv)q1TzJfdCR}jJ1!kOo&TTC?-;(pLIM14MZ#b9D z5%IQ*-?;g;hhKU5rH@~1^K(Bx3-Hq*KMC>UFh7d$OyG@O{vgT^WBee__xJc-g6}5z zPKs}*`BsK+X8A^rujlz%fv*<%N{KHkyi(>%6~0*I3pGAp=W`7{+vGDXKHcV19X{FR z6Fq*v&&LORY{*9s`5l877#|t&;V~bY@WCk`nDPEOzqR0fOWwQUJ!{^*;axUQB-k!t z;}+H)VdWK;K4Gyf%>BYFAWVb8BqWT(!YCpzK`?fOgQzf!34^%M-xGQXp_>#sDWRPf zS{b346&g9Ao)>Bbp;{CwC84YcN?9mXgkn`F)P#Ip$Tfs)Q^>T0bX!Pugk)Dp^o0Gs z5FZG!p%6V3b_@YGMMgq+EQBUPa4H05f`2Y-Ed<|E@U8^UT5xX!mn{&9woBZ&#kEIV zdBvqqTx^STzc>qs)1WvBiQ}+1iik`Qja~5|Dh^}fATIXz#9l(|CdE!lY^TLmMr>xq zMoz5f#acnE7R5?QEGwc?7E2YeSQQI3F<%#R4KdpkGc7UQ7E>KD*%cE#albFd2V!g} zMi0duLll@88HwSs7@CN|sTi1v{<*ld5PeJ0yAnNX(Y+B}wn!w|E@|VI)*fl)m6kqf zu`SL0(kviNgVH1l1uxYXa1dI_nUlsYM?ot9b|shO1;IjNqP zY6YoUlqw~utVl{(DpjOnRVvh^d|k>lq-;~lw4`)fN_C`US4#Ax{k{|*NU@<5J(P9~ zNnlcBB!$OPXd(rtQeY#+Gytc)TG6BJ`tIfyF5m@UpJBP^v|xQc}u_ zg8xbtrC3!8H6>qHat$ThR5C3k-BwZ^CD~OHJ!QYI#0N@js6-Ey9YYbA5*aDsu@agn z!Ko6MDgL>#wNQLZ#k*2GYsI}$T(&}_+AekDR@WYNjVt zD55e!HFnj5s5*?PgSgt?Q+o-un^Zd~wVhU58MT>J8#%R}S8D~eT2w0~wXCR0SuIu6 zVpT2F)O=mdHPmcV&9u~XTTOM;WLHh})cw91AE>dR8a-5Z3{_xiWTb}2YG|Scr)prP z`seD_LiH_G?@INoRrf}9*(#A{yR?m4TYI#XS6lkD#kMy0YqNkh4Qi8+HV$i}h{goX z*wqfA+AyXK;#z-C>m{^qQtPC&c3Nv?v}RUo5>?a^0Wed*H|+xpzE&jR{1s82%rIINE%IumqbS3ijA z!-{~wm(aUOy_3@0X}y)vn_0b))9ZP?R?w?Oy;9Q4imsIPQbjLT^+HY0*Y#XO z&o=c;OHa4;R7X#C^+ZqK@9Xh_9vkY>Lw(241*S(vdU&jdCVFtH2WGl|u5T@L-%|Ik zbkACMZ*-Tf6B)M4*tm_g$5?rdrO#Mw8*{%g3mDU&F$o#turZ1lOfZaH;~;7bW5ytE z^!JQj!ssTAPReMfjaJ5JW{pP9sOODZ!KfCEO35fIhEg_46{A=+3N<5NH*yUl+cYvQ zBi%Mq9V6K_5iY-mIejUB@fm=PHn;js~#7{RF#m>K@Lv9&OKOT)V|JZrrU`~VPBxH`m<|tw^!8CTwgQz)-nS;35-!pp& zvzs(KDYKn6TN$&NH5)mzo;Pa+vsyGOC9|xUO4%$`%wp9n)XaR{%r(qx)6BHYblXgI z%w*S0^vwOf86TLjp&30icMMZtW@KcB$7X0^2B&6VX8Pym*245HP4CL|tWEdEblE16 zWxK46+gf|9mDgJOti`r9_gk}oH4R#mkTnilqlm=>%hYSF5ctg>P$Wvf)NidCynv+{K-*RZlpE7P*lZ7bEWl3gp& zv-bN|d|<_fR`k%?F)V>uk&zW1TcL>+oLYgI<)2$y3(L2(yerGIw%i-bWm|Xwv|aYb zZLdA{%4;uu_F~(f`|Vl4o(Ann$R3C7QN(6~ZS2|yQF|D(2XVWzO$*!H~+53Gv zKCoj$J9=pE7`DLd$jAx^D_K|NKT04dCGX+&l4hXym7QYoPYT1&krd#v);to z=duefqUgQ!*t=+a7yELA{rTPO)YIrenf#a2M>zKPFJhm&g5Cc{;x3?_yXZd>Y#3(W zc{MxDP5An@=?4$6e-_y1U&eM{L)Y9)mjr3?B>Pc{^)6vMBHefgrQSwAewgW(vp>Iw zo&6%Z>KN@mMjt(oedAWAo>-FZevEDwY4tYe5N!PSJ%)?IH`D9hOn-PM``Rv>CY|fz zDZ2fB`pa`p**edzxQ?**1Ef`S0YUFFu?Lbw}ZCtLh}0Pi&wD^oX#4=UUVLv z>2a=m|0zyA-@Dsc*}jxs`f~cmYaH-@{TBA*b9C(vU3V+B&SHP(VPAYXyD&h>9G&Z< z_npH2_%8PCJDgp@tLT(d2)_X%8o4t?7hdKti{5{hVc(9idmg7ih`{DA-@yL-UiNF5 z-S-9paj!|!Cog8-x}AOLYIcf?@V%I)PhZCFe2_BFI{5sd$o}$Pr&H8<{zY`b#q{wl z*4<{4d)Y$;hlT5Iq3_?%evxIU@Q&Bg!%xw@Ptg2P_VruXKU~1>ebTx2zAXLe-45&k z1X{Z5A@ZJ2Xb=bkF;s#UUi&6O@!x-~Qwd1%c;i{D)B|QA zo*zHNzI!LTEJPsjraS59PcZEqXJzYBf*9_}5Pb37IQ!{i&f!=V0YmZ)P9%va`>nt6$-G3WER88ID!~j`R*X_r>&|lG7|q z^!m5c<0S`MAOn1$d;or&VzdluAQ)hN>6H#{C!b6x4~?K501I#4@JjlS+u`)*PqN3~ zO=o!s3W0Zi_Bi`&fC0vL4hAQ%~1l3dC3)yZNUhOI;2CTs1r)Y-=93}1j5H& z!mhoAK;l{FIF%q1zHyt=BRqooQ3I&QF08~~Pp?eSS8j0r7v-UT)V7y)ScaHUGb9HY zz}>JpQ0-sN!aEM0U0s#d;3?JWSDDrPka=d)TS#)KD zT&Fr#LXM#?$O)me|0sbP5cHe3F;ob7Jn>!vbWn?VA9J1N7!V}F0zXN!U%ru@!#M)O z;maKR#T%Rmf&%fts~;ff1pa!zi=E?joDO!DZ*~NRz2NRu5770u63Sa-*?&FaXcd7B z6M;~i43WFfaA3ddVFJ!rLHq(Y^a9o4@SkSb_wI2@LX;hk4jh6;5KZt75)XTS@H$7U z_zQL*a$xnf9VZX}=N;_DTlBP_r(LH1#eA;B(vnG+6Z4PfF2vi*0@IFQ1as08^5VD0Ce zP({{3=dc?l3nC5}f>~4r526xy4dNMI%MeGn7m)?%)=x253@nQeIlG`ST#d}R{XQqY zu=4w7ocx5rQHek3q#U68%w>+_FoWPw+zvT?)aUg0&{Gt-%`xC_pJFHpN1NB ztiV3Ve?&L70NztiC(J~wKo2Me3Q~bDVQKK!(kNMHfn0WshPDWZUXy3WD;c$9&@^Dc143XlOB$lhD`o!q$W zN@tXVtiL_eu^YSqRm0sV2|PN%@*al^1U}*j;dbWPPKy|y|4F{6O+a25u-T@sJF`9utvJ{Qr{Rig&H>}_t z58i|?a3d&2r%E?=9Kq9LfL`-U*MN40a$qkc)}% Ezw9-zuC5|)R-1(ngU z-%$hvglSQNf(W)EAR?eXa7A&%5gQN@P{9V3K~Thgzvoa>^;TK)Q>uP{qE&&i+S|83 z_nhzfJkZYoElO*b+&(8t%gM>ki4yq7_p22MadUT#SsZ-6%ggCLPb(Ijuhh$t4;#f>}wh&TwC>P@W<#~IAIM_2E zEAR6Qu=4KRy|MD^<$a|PJF*61<*k>Cv2s<_h*d&tDjSWJH>Qrm%4<)RVdYh;refu% zil<)|;>noVSb2pk$I8o>SMC<#fr0>54&YZIDt9l(%H`!Nu=4EeCu4+|e)%b^Jhf^S zRxT@BdrF9LsT;BK=+m39@`zPcSh=`(D^?y@cSn{GeLr{|EB9W$8!HzS?DK`l7YDI& z-tPCYa))w>m9w*tVdab~$A<{fy6Oa0ZeDf@E2pNOO%WpT^aZROx9TERu3vl^E7z@i z6)V^J;QBlvYAnBrm8%u_SegD&bfT^3L|f5`wxSblMJL*dPP7%BXe&C=R&=7R=tNu5 ziMFB>ZAB;AicYi@ooFjM(N=V#t>{Es(TTRA6KzE&+KNuJ6`g1+I?+~iqOIseThWQO zq7!XJC)$cmv=yCbD>~6ubfT^3L|f5`wxSblMJL*dPP7%BXe&C=R&=7R=tNu5iMFB> zZAB;AicYi@ooFjM(N=V#t>{Es(TTRA6KzE&+KNuJ6`g1+I?+~iqOIseThWQOq7!XJ zC)%n-v{j2}s}|8#EuyVjL|e6pwrUY=)gs!eMYL6mXsZ^{RxP5fT0~p5h_-4GZPg;$ zsztO_i)gDB(N-;@ty)A|wTQNA5pC5X+NwpgRf}k=7SUEMqODp)TeXO`Y7uSKBHF4& zv{j2}s}|8#EuyVjL|e6pwrUY=)gs!eMYL6mXsZ^{RxP5fT0~p5h_-4GZPg;$sztO_ zi)gDB(N-;@ty)A|wTQNA5pC5X+NwpgRf}k=7SUEMqODp)TXTuF<`QkqCEA)xv^AG# zYcA2&T%xVHL|b!-w&oIT%_Z8JOSCnYXlpLf)?A{kxkOuYiMHkvZOtXxnoG1bmuPD) z(bim|t+_;7bBVU*5^c>T+L}wWHJ4~>F45LpqOG|^TXTuF<`QkqCEA)xv^AG#YcA2& zT%xVHL|b!-w&oIT%_Z8JOSCnYXlpLf)?A{kxkOuYiMHkvZOtXxnoG1bmuPD)(bim| zt+_;7bBVU*5^c>T+L}wWHJ51XD$&+eqOGe$TUUv;t`cosCEB`5v~`te>nhRKRidq{ zL|a#hwyqLwT_xJOO0;#AXzMD`)>Wddt3+E@iMFm1ZCxeWx=OTlm1yfK(biR>t*b;^ zSBbW+5^Y^2+PX@#b(LuAD$&+eqOGe$TUUv;t`cosCEB`5v~`te>nhRKRidq{L|a#h zwyqLwT_xJOO0;#AXzMD`)>Wddt3+E@iMFm1ZCxeWx=OTlm1yfK(biR>t*b;^SBbW+ z5^cjI+J;HA4U=daCeb!bqHUN&+c1f?VG?b_B-(~av<;JJ8z#{T+NMLa zO^0Zk4$(FpqHQ`v+jNMw=@4zxA=;)xv`vR-n-0-79inYIMB8+Tw&@UU(;?cXL$pnY zXqyhvHXWjEIz-!ah_>kvZPOvzrbDz%hiID)(Ka2TZ8}8TbcnX;5N*>T+NMLaO^0Zk z4$(FpqHQ`v+jNMw=@4zxA=;)xv`vR-n-0-79inYIMB8+Tw&@UU(;?cXL$pnYXqyhv zHXWjEIz-!ah_>kvZPOvzrbDy?Y=8kazyKRyfDJIf1{h!i46p$P*Z>1;fB`nZ02^R{ z4KTn47+?boumJ|x00V4*0XDz@8(@G9Fu(>FU;_-W0S4Fr18jf+HoyQIV1NxUzy?T^ z1K9KJUx{{r4KTn47+?boumJ|x00V4*0XDz@8(@G9Fu(>FU;_-W0S4Fr18jf+HoyQI zV1NxUzy=s#0}QYM1_aR#umJ|x00V4*0XDz@8(@G9Fd&F_fM5%Y4bWl(wAcVGHb9FF z&|(9$*Z?gyK#L8~Vgt0;04+8^iw)3X1GLxxEjB=l4bWl(wAcVGHb9FF&|(9$*Z?gy zK#L8~Vgt0;04+8^iw)3X1GLxxEjB=l4bWl(wAcVGHb9FF&|(9$*Z?gyK#L8~Vgt0; z04+8^iw)3X1GLxxEuCuHVgt0;04+8^iw)3X1GLxxEjB=l4bWl(wAcVGHb9FF&|(9$ z*#K=eK${KFW&^a@0Btrvn+?!r1GL!yZ8kug4bWx-wAlb{Hb9#V&}IX)*#K=eK${KF zW&^a@0Btrvn+?!r1GL!yZ8kug4bWx-wAlb{Hb9#V&}IX)*#K>elEh{MwAlb{Hb9#V z&}IX)*#K=eK-;1uvDpA^Hb9#V&}IX)*#K=eK-;1uvDpA^Hb9#V&}IX)*#K=eK${KF zwkSz#Hb9#V&}IX)*#I3jK!**`VFPs7039|!$EDnMT*_^S4bWi&bl3nLHb93B&|w2~ zT*_^S4bWi&bl3nLHb93B&|w2~T*__7rQCMd039|!hYiqS19aE`9X3G6rQCMd039|! zhYiqS19aE`9X3FR4bWi&bl3nLHb93B&|w2~*Z>_iK!**`VFPs7039|!hYiqS19aE` z9X3FR4bWi&bl3nLHb93B&|w2~*Z>_iK!**`VFL`RG$n&;l-s^f zzU}+u+rCe}?fc~0zE8gG`{dicPr2>;; zlq9}SzU}+u+rCe}?fc~0zE8gG`;^P^#E2T1N43JZQrLU>HFl{zE8gG`{dic zPrmK@hg z-zNj~ee!MJC*Ssc@@?OzDe3#<+rCe}eVZ@+DPY{{JOB4W8T~(h_UE6yj#i{=|Lo5@ zS@%Ety_2>7?6tRdOjrN$zjx01&vU+g<(*KuOZ)fdaVPxl>}>ARzDxUdR{Xzz{&9-X z6~AZs$N%MSZU3J9UE04-vD@|a$3O2R(QcE!OZzTu%BlaJM0ZkC|9zGJevdz{>i<;g z?O*@=&%3q#`*XcZ`~Ozr-P-=Wquf~!-^tZ?Y2T&&XVUv_Zr{!A|C`dk|NY%0xtk>a z|B~d*cUsMsa&yht{!*UoK6s#%)u%-k;(fI<1OzyB$i0UnB{2)YRQO#$CI8;{~D&^&ZDW6KYsj$uoDI1(@{6BbOG=D&UAxdj5 z=qJP{+x62@zSA-5T`6xpx$v5l)eeRKB*d_9%(Hk`^u=b15HF5V@Mp@;Z?02M%3W<+ zER=GvHF+N14gE_)ys4V^c+o5&-0*?#OSx}%<`yZBy;9g%%82PTB87;Euf75AnKq0c zEyNf13~MOmp>f)7taGrXCS~4FMOX2r>g3!|A)36}d<@>+{bAx(DZgwpV!o8GK9kf{ z%G{6jhlI#^zh@`B4~s_?;#{B6B~rd#U&Y_L-nzbMo|Ls3)=9*>uE%m76yo0HV=oG^ zxmD~ODUWRF`ZV~g4G)*Hz%0favi*um@g{8U%lZhsHQep~I@rmZEn7)>=E!jTUBIXF z`r;Y$N{e!_tJiZU3NbWn+5mI5iBft8rnHyR*{kAj%~~vNSBkfE=NCUML}>reukfz%nY=hDtB%%R2A(Tx-@-bP z)mLCwRpam$aCEnr$Ax(H-$}1Zxqm}el$1YyGUHJxYve}_5F*|0v_y!GJqz(x@4su$ zRB*4wlW}%G)}6jm%Err@{sROa&S{CaNcX0HhijV7OqcTJmI@Hq936`)QffB9`VIFd zZpY8_^nUb_9$jOlJpNsu$x`lInz9jZ4^I=I-TFe#bEveBG7E(G=gQuTu};B}B~ndhZIcXIk3BQm(rhfjU{W zUeu7X&Z1b#K~lsQmOgyQKX7;rptjoVa}n>Ll~^yyt~z_gELa`@C^N)Nj~TOf=4Y&$cvFR6^qv zoYasrQyXDF%j@AS=`}xvqAz~=WdYXtaC^^nxL25h)9n|x zb;F5>=}V>TRWt(kir<@ZANKs$4A7|BSs(Pid4AkcDL+arXd`9+cgMdWM9Mp@vxI2y zuf`zx-K&$nkn*=Vi^1yqZ%ptU^w^|yAqLCI`-JFopk${IuN+H^kn-s29zCRdD>NOo z6nZ1f!A?$wp}QNeZHm3^Y?^}g3oj10(dj={%s~CfPThp~c}4m6SpU#s^w-Vt6M-2HzVcSKd>C8B3v-W!)8<<^Jd(HAEI{lAoQRJ++-&T)1t%j~y(FJF{<;w=RX28*j==9X+ z)_)UXP)Hf_>Qyu*`mF&EX9x2I@}5I<$j zej8VA$@!O**R8oo(d?3Z4M{$?AQqXnrYC5uSr$4`%6F?e4wdqy5e@H04^9%;)xhIr zeL!GSgE~SSuHSi$lwY}{{wd|hfA5tmWlCwQH?cy!9>}qdXL_Mlzx`&ycvNzE^i#Oz z=U#6}88<5llcKTF6#3l0-nbJ&eDHKWGUuO7dR>t6>uIIEu=D%pNYuvoj`$8l*IoT4 z;hK_s2h~-x`{U^M<->6<8G|}qz@DEi=pjVgt6gw9zl6?5)qR;YB7hz=?$5%hRm@+7 zYJVyP%schzwGP*`oxfMgD{H4c2ugNctX6AIohNax!j3C3r=~}O)vH~aU~+9}5IIW9 z(=Cd(qe2QN49DB6?yO@%)HxP=2;brGjLk^hoFTa5i(Qm^r5rhFrVwI$Y~^RD+l7r2 zP~nd(xP*i$&H4qIzqo4&D*W2wol+Keor<1{d88iBqD|WlorO3$vAd5>ADo87d)bbw zEoJh$mbi=l<0$kwd4k@oNI=vXS{n%SX9&XgZpPewij!_H(*hLOhpI zBM*0(zZetk;@}BLzwv>EW06t2qo)Xwkd^Wqz8&&HcwOXS$$0R5ttb__5nT|28cXY< z)k3EXnX_34Z{FljkiGR%;_-CnW1C1>k~H@POsMI4B<9Pm5%~SacWTZ?S}v+S8YiL* z#~suDssTausgd^xF}A^c5cvFW19Q-i+saTU8{0(T^oPA{K7;xDaShb=@DbDTbnnOH z*2l9CNt=QS$tyg9d!3uN7Q3CEinEB$i+L0|_IS@(n7m<4aBB9^+M!b3&cJo=L|_kF zd&Hpvcdck~MarbS7EzeChe|uZ6Sg-)*2$y!=$b7bH8_MGOldP!%8-+xgOSP4C!>Z# ztdQ%N-BqKH=3b%u%AT~&AU{aP80_#}Q40V`UD;J#=lUlDe>iLCEb&&~=r@SiVuk|YvFa_EzT#Wn)FO0ym z*GMW7V%*uv)k5s*(_%dmyK%aWx%Qf93PY&Z7G2qPb?5zfuFCw8_@+^M+?(*a-uXDk z)d>O#vvX4lb`{yK<{}XIHoGZ(J0~2ru;%MfB=Z|@H~&G(?e{0*Nnum}MxVCriC*sO zj>WD{ULMj~%Ci@Z=h3HY?|%q){Hh)3rA%yvX)@u{#Wi7fU&p2*TizbET}pS}pkf%{ z!f>2I@$#t`(TT;g((v7>PY3js^4wdaFH8B|p-CWFyPz)Ug}=u;?AEV9x3dPw<9K!Kpnnd>?k(EOCaE&mIm#7DaEUi#k`o&%j-x z-ik(-UCEsKD=Or0FEBju<$#e=<|hw;)!egV7+fMNzUu~jI?+F}PRu z()?09`_TdvL!_l8A37l{f~1Yvcna8$z*fJr$NgaoI`q{hveg>tfgD^*`Ux~bgjEYmf zK<nbjlay|HA1{2<DM#*If9< zV__MH;1Ype%No)3dm-N2-w6!gc%b^4236IE%F7+F?w$^rjur5kEv=KXzDjI3`Zrsh`5YKU1H;d_P*gA3eA{31kwq z)G$o9OWh|S`J)57>`+oiYbg;OFn=V^VbN zQg|`mLH-NGlG#m$kHeO@j>KHstyqFQ!#Nx^yH8&&8>Nj~7_pP0x;1kx6-rs`2=QE!~ZX6tg3^{PR zJs2Li+5Q)pQen?VQZ`@NwhPQ{V;asP!l?cuQn6Z7SfnwmAt%p4UdEV&^-el8{j?uVkas(_ieQU}|rxh!^7fz;Viz_Q7LPtMPEaQei(ZI)xN05DSQH*IjkQ#B4qwwka$Z+l}g#8XwXS~{u)qv z9=-EP?jxA~O5sX;X517WgW0`v0=8Ez%-`7A{4Ab&XAD-@F)ld| zr{8iQp10Q{Bc=&av$FO`OquqPA(*H4_Dsgk^&-&TKeQb(p~3ma>xAgCqVE;VL?vVx zR$I^<=k@-(xi{eCM=IXJu0jSa#fdDLnS|-^QfKu0_J1^q#;Ki8T90e4S6q{_cgvAk zLL^nR7y!;=eoU*RM|Xq2%K|G&H*XohbN<+3x*cohyCxFhrPY>abk5mUBhal zF*iG;-Ge@g$w89ebADKf5cPV;8A4p@PzJ*1^%7Lt2YvHV!}Y7hqn^hPScu$6y3_(T z=sh_Zd)S_r_?VRVxIbLVd%q~fvoy(W_BKwoV!>zF&**M*G3DQDh$?!eyz$dgw%(aj ziv1)PBhO1)ESQPu^R%)TWWLJ6ezr|Y=z$!2d*L=@)N%z?9o|3UANX{+zdEvI|Cub@ z<(f4MJu|E(q4q`dK4Ir1>&_14&-;y1)ejX7QpCKtlTJd9a$s#<+G z%1D-av<|H_*Kifuc8MJ zHhK-80sCg4a<0vug=zlmj<7T6ud4P>;m=Z1CZYTKEv4@hS8E;K9^RN%ZJw0Rh15Wb zUjJzBA)MpDWH9gh;FuSL7!@`<44;t)rj?6YH_XH23KDNi7&#u;x4 z@n%R%)cI>4H|>q5`&BH&8I_LR1@ruDE}kp@(!l1h^vwBtu%G&22{_FaiC5rbn>*vP zQt8hX<@mX^0-X1!w_AWZ@0W~TIJCY)4GGZQS|eQ}=N$p$g z$TPKu!$xX$JBsw!I`RajQb{Kb&-M32RN%qhIR+>_*uMZ38N~ezP_3@LIjWbKl`iRO$Kj5^#9gk3-JH4NXGk#3dz7Lc;8b#mVB& zTiQtZ$wx()LA$H9!l|`9;y9gqLtUeGj7bmi;)mI=ncPOew zxz=z8{PxKfKj9iPJ`!#gIT1xz76KDsUTGbdibp0fpJ`l!LPVI64`v@Yn} OkSQU!S5~$!<^KW#lq8G* literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/deflate16-pred.tif b/tests/fixtures/codecs/tiff/deflate16-pred.tif new file mode 100644 index 0000000000000000000000000000000000000000..03855b817fd631434a72df6d1fd6b4a35084ed87 GIT binary patch literal 5288 zcmb`L=Q|w0+QwNmM0650dM6~TE?A;>i4v^d*T(9-Bx>}|M(;tC=xq~8^wmprB19K! zSLblvd^mr=J9Eu-|DJoExo19)swyuQoDvJmXKv5L*8sUQ*CpyS+LAI}JYGJE;+qiT z(ql<2NMy03|N29W>+{oux?w#9B?l&rEWHG^J{`3b);Kl46y$HXXBWEK&1mP?v+LUL z#C*{2)z#8PYw%3q;*6&Z4QpYOm_JWpYI2Bgpr#|*ii6!^;PiM-VNq5IQVGU z^kx}-c{90pQ*sl$=gay+RCw+~B*xPEPP}qIJlsPn&d=(;_u4Gz98$a!#%7H>(G0Ts zEG3N1L{qdFeea3EdoM0dg!t{DOsu@9vHfqjnOw^4l$7AKyMXp;&G%mR1%Y}yn>Uj+ zH{x!~6M&1G^2>((Zu8ba^!xfSY9G4>zmG%g zcc256ZP>|KGzwi@NZ*-EG5Y%Wh6{?-T9ohuw;ZuhMkT<9H{`dP#PNs3B`$=lbOxSP+k>px&&z$ z>_VL+lS0Q!6anhvrZ!;^l1_o>Fd47q^@Zh8vb>$VY9CN4V^d%rwB`HRKY&Kk$t>4S!aiV3^;?&fBn z*9FEX$M6H3(`G{50K`luHk`Vnd-8~AmF-3`PuLAk~B)z!`B4iX(0GmmssQa_c(E8ZlA(*N4?x-MsI$oYy zaYr^|R_l7egq_kn9h6D%V49?i_CAv1eBHq0acvyUT+=B(ky2#Brw7w(m#JG~EBX3j z-60OYCMlV}DEo>A#M)fyRQp71dLqLY2!!zbyFoZW5)0Rk_O0e1i@yOiG(HE=Ba+h* zg%^PSM_!^u(djZ8v25oZhZOf*Qj*1%yp7a>)}sf1w$tI%I_@&Itk_HGJ5=Pu3>KTw zGA0csnqZNwP#%y_o4D1BrPE63-_rH!-T|^Rzv`IUvKP@G5lr{%8DDrvoI%CMj%2i^ z;OfJ^wKThax)|Jmhmd5B+6lV~F%ajY#^xyAmN7ykx~iu(p^2mjvG*5JCU?&Tjf!?$ z$-R8wVcQ0qB0%m$2zs*2y_Tgndk0zkC{%keA{LTI7srGK`3iAKy~(W{sFm-Y`Di7i zurUyeD^@?aDhSfljEe)QEv2}@u0ba=OQ2XM<(CwJjrOeoK3D%pv-Yy73a6WX&pp#sJm-d{-zVCq$DV095@bNu}xlP&>8%#qE=@Qb^a(Zu$Aw&k4L zLw42Z4e_RONnrjxh|;QCRHec&C!xz}!`19gM3<+|)8Qxp3Gz3yWca;EZW^w5@f;at zu(d1`AItVhizv1!**e$SC2912@+esb+Pr+D^)wc-QR4FcF%ff-FbP8oMactMs@H(X zgf8s>O{#`3>gr%c^L;HYJqMj1pa-9;mJqF4mcqGzuSG7o)JdI)0fVa|-d{e-s^LUe zCYY@7_xodj(Dcd2F4I{YnDJSiF(0T~MH0?&*(S4c>q_lFj75|e)d{}3z?#(tu}f_o zTl#ie2bbN4BJLtUwaR!%@~4qW4G!LB2{{HMlGYT#Cz}1$Ck zX1R!~L(#Z_;qHw4jE7sHy*Cp`-jV{NP{HI#^38_wV_^OhZLU*lVt$h=hR;#zOG#f- z-Nd)tgC6&95OF%VKFf6I4Bv1L4NN8cVjL|dE4~;U`v&`&{5f0c!O`Gr@wVf+53^N5 z#*I2+-cy7mg|Qc0(~7}_WaDBgHF&pf`TR`8~GY=nGg^l`u(Fx@Kbdg^f_++nSAseVLS5ot;^lsnlIK z6T$j{SZ>9Vlf#cZUz+Jr7$tu7APiw?2TSpTc~-oH7gpMGuD7tDtm)g zF8n@L^j8B|wriZ3pW)7WsRRiHTt>C_02vpT4Ty$#j7d!cDmGaZcQ@W$9OKY;|E9P>tsq=BW7BkEyFSNNVFlXRank1kGh0;tK}lCgYxVYsOt<7lqX2Z2!9hp zqCXbg`lBNk^a`_aOg+1ws%u407r!h0$Um^p2M6%fa%Jo^RgsWoNB&x-z~zE?LlBHCpw$N}*Z9=WnKM(UXp}mqWrtLK zvi~P;Z+CtzK^eW0iK9EDIs=Qnd0{%-ZU3AvAQSPv+n{LEe|dXFDs7&I1_oh`0l-XR z#1Jr&bc=MH`J7iPT$_6n3nAg!e`Sy-0gaHym9CX<+tQV2eeP9hu03et%pWI68GbFn zO9^+Zcnkcgc46)PvIaIyW^}?z>M*CZ=zi+&`y7hrJ~{jSDPmR-RWK!lPasR4X_F+A z>$@XmJ7w}GYqLyqTqtA4U?E>{%R>JTj3mO<@az* zXcC?DADR3(`WE-kW_IMR+1pU zg_7T$2;??FzJ0fL=fLQc>WLuyV6f{NOH#j;dA94wa2LPHnJ$ba%eJT>h)?}wL}7{h z??`Wa--h*h53OC8BdNm6&y4{rJ zy^Z^l9mvR2_?NbnWaD)UV3DvoFy=iS?`oLp-Y!ho986PB^5>Ab4`dIIY_60Y!Bfxq zY#ppMT*)gB7S&7t6OgP-xSd*@Yw4rRN_eVqu1mBq7qN(Z>+X~eHV1-oeKI1s@E`LG z4=-ck9cGI|W%bItmN<4-zU7=U%uo<9?K7-3(4UZgbUm#4^kaywrg?+DUeodX5%>B= zWx(!C65CGq8`zg zYLuI!%>FQ}H-VBebjUV`r-hb1yC<#2b4=mGY!2~pLCQPkeBCXloK*-Nt=4;5qds6f ziR9nC2iFGYC<(7tlU_hh8cW@y1~0~!7^)MhDGi6Yj`c6ll#s7V6XMOhjuBevJ9s?@ zrGA;y#4dWd!d_3Cq;XA}w_+oOHX~+Owe!Q0gp+$}A6+;h#%XXgYClaW57q4cV30ww ztt}MHhT5(6rMMSi)(MBqFYr2o^x}jQ;j0z|jHYuNAs!k0=zCek>y^FtL(u~y1a!1& zUe@|VM6j_Doz~9hhJu>H_Z+9cV8h<)lH%v~(wVOCtD0<-pS^K*WSOnG#Otqa9W(*2 zksS_D@!CKioqW;uM6Ckmc4CrhJm08?5b*qwcQY$PN5FUj4)96U_*>soegZM>MX&EZ zA%Xk)*?!Y44hu{vurrLYJFK!AmUj8v`^<~ll&zYOq;;thrzy2ME3PAn+c3U4k-9DZ z?atl}rLT3-TN-GPzcHF{j9GTy3|9;``r*6lBsRy2Aa#zO%1o&^LhL?AvMioLegKW>Kf?jn{NFQt6gkChl=gimZ&g-d1$4w#WeR6U`&4ewaPR*9* zi(GjRegzEKdwW>rTVOAB83*Z@gM}Ksu~W{nsz>{?7YOZW8H8! zqzj;eOEMhPjx4(sM=BcY*TTo2MlnZ$D~pZDUtCg^13}jUprQI!fI9JV6#L=nj^F7~ zWy%1QB(UcR@hO{B;2r^ZXmS>Dw1@jH}KO{KFV!cp*b`fHF*3zcm=h=!R8qEsA zZXS>bW^87@Ktn;4^(jfelBE~)=Q`>%XH2xLlr=+}(%`|>@$y9INn=;sg>rmHlKx*z}{Snn}7swgHq4QyS!7@HY8nDrB|)@qH3PonSkjgYIkZ z@|k_MAG(viLvdu#${9HnN zh${OtUOA;sQij!o0IA3Abc_(<9Z#}lw5ikMCq>&)334~_S^&9V%$OziX7(pfMCbFO z?}r(}FMAV#@w4~eMu>MyN9G)?gm`!eI!irxI9CqA#_2R{VxZ3aFpLB3f2BaqfclFj z(7x93BKSnXCktL~$WSXlVUJ6NjvKKF7}Uto^Q~ST##~GAt}?94u@sEG(JZh5e5OZW(aPIJas=g@uLl&nLXC@&7U4mWlrH z-Fb3s-2dj>^-%nePyLVYvS|MCT|Vu<{?yx_L5Bb7=egy(?AzC1$^7&0YFTW&|N5D? z?~%J@{9DiAmhT4Hf9Ja$-CGX9>Oq&^nSkLTjXTBuKMle9R|68hqVIe%AYJ~Q0{9|{ JZsjr7e*h*c3?u*m literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/float32-pred3.tif b/tests/fixtures/codecs/tiff/float32-pred3.tif new file mode 100644 index 0000000000000000000000000000000000000000..85ab48d6bcb373a0f926caa32f7dacfc74de353c GIT binary patch literal 8876 zcmc(lbyHl=)3-@NAOQlwAy{yCmmtC2T>=Dm7FZktB*AsjWpN9O%ihKbA`Y|rW<5bV5@V%KQppmgs z7Eni{bvn&5)unK|{Noq|(S?HPP4u@n@Qz1zs!q_V*k}9)H-E0T@Y{-&LO4}h=)=6N z*a^WbfCODDzzn3UG@-glX;wtg|BLqByKn(^*mGHrHoj@LN*0>? z29zE#`8BVtIylOmD?e2@SCY)|&5@2h_es7vC0mHy9nl<5<-^LX!vf!&!?WLSsu#Y} z3;*8TS2G48n0qX<3+7d-5#&*-@#n03;H`Y{+%WTY+c0a4^@{t}-3MRm?gLUTy^3J_ zJL%itT)EWfT=@_md)OL#Xd4MS^o#`AOH(fRQ!cm@(JrJucl=1Zr${?qdx+f^D~O%r zb9Ua!!)d-b;PYtYzZ{3pwfI4wL-qVu%j$CqiRX;Y!pMA1tG|0h&2N*B`ddlu^mO~a zO5F@l@)9=zw)%Sz%X}5Cid#vWfYVH*oc&)&>(^HKUABd2u0cJnBRBhP8TT1TPn%Eg zg}mVhJ&3iQ3hu*SFdRUjj(<_?%o?+FC>Jilv4=lRBkg8vrD}-6xGN3I2$*-MU{;NbNs5AK#@%8z4V@chk+?ZnWKT9=Btz*6dNA zaRHL&xg|?l7nmVGGDhChQ+IM zCQH396n~Y^PL11Gm7T$FGGK+D9}%+IOdyA5>L=Zhn{}kIzF1fF@~+Rclc8O?9FRN? zM_}FDFk?(V$+dbhVoCRqlZ?vlV0z1BAe{B1n5rv=uq{>BRPTL1`8-{};3*C=C!4}z zElIRDQ$`U}6c;_6n3Ym^>gP2Q_+@Tkrj1R8Yrc8R#{-&f zT~rKL)QiUY33cWnYBxS#VQelKt5ROi>q}RG4sm`j?YdY=RpFYQDRlB&2lBGQ)ybc# zv=v@@Q*(YHwIYB!CuPNm#E2nYIE5c0GhX%L zZt+*?w8R-@#}mrjs7|+1ei2e!Bxh-*pNq`xDe&P^zqm~qGk8pnK_qpg zX*5gD?Yy}#Gzg6Kz1su1b|I^&yR!sWV0x|-oVgIN8SR~6ls@zxP5`vE?GCSJmBD6; zeYjG51CqSDl?2Kz^gaNI@WO+WZY?ZY@73mSV|{XRJgCy6*0CNPq4Fhsm2#dFNgSbT z^rnwmYS|~Vxj4P|#3Og?*?)#^HS8nZFab`x1Ypv@k4x>jJ}4S{dC-eL}=$@blR@v?H9mDRGjl`{Cw3#3TA^rml$k+NTOFmBTo-8<0c#d^a;fyGjjV_ z3s#pZCqZrK_muu}dYUwSCt4!QpiHIpX+^1eC_N3|;nuBHmeipnXzH`#q4;LV=Vfm2 z+_=07C&uoIr4u(U7tEV%^NeDOC6u&8*Vo`Z@`M{|6!z4eqz+dOpBA5R#J;xYvOWx8 zHp9DFjp=i@YqOwJG}N*Qz&tGaUiGzaz`__jU$14~w(uhXSbd?MQLzoAksS{F>1F=< zaA@*d08F={JvUJ_jdzGdL&dtZD%WyVpn=O_3>&~5pb67$NUUvWG8C^=@}3GRsur`c zlpv{{(w^DcT;cSb%BfEaHm$DDf3kv(Ly4g`QJS7Yr0=ut3%) ztgO9=Ewim0Y4I1=Tp5m*%$fZJ+D2G?ly2}-T}z3=yG0dj_%yB1k?%jt-TFn z9V?RH;hx~^vlNcI^9nP~s`YtdX#}!uM`@U2vzw!p*%`~n5`dLd>B_bkivnk>14!#l zby(OZ2*CN91?=WXb2p~txI|{tl8ls#$>81}cFtoO-LARH_~tukEeH7}il*H(6ha}4 zYJ=XDyrH#~67(6JubZ%n>f|rc6wmq{CLUnfe2Sw2P*w`@-9@A?9> znb78u^L10*Hy;IqHm-7+QW(W`{!opix80WU?@*EuAzL)TbcG+V-H*#z6ggbBcMEpY zDQO=hTE%kR5?TBQ61H5EDUuS|&&h~k6W$J%@8NMmPnyeqso$}7%U^FBURNae&;*eX z$v|l5qBo#qwnj0A7RFC+;{+!v<6Gc9r!TG^x?aE$r2r-2XD$Nf;k^;~*gy_DEObHK za9p~ZWM;gQxLy=784ZC>&aw1|Y=TeUHYuy+RKR%U0`JJh?=y+$89nf*g^*UlH}k@< zZ)1~(mfutR;)nHZuq$8@(vD=JLDcEUo(XA>=E6D`4iIa_A5?Q~H2GU+tB_gh4C_}XWck+#V{SAV)ZqZ) z0UBdr8BcRuMT-i*pk$T`O*7dBfCC3J&)GWNSYvYG@mXpu7Sq?umqj^UIV&3*(dB70 z8&jYkZ1N^FuRSfn^OR%I$#V;f4PG(4r8%E+Qd(2$@6h`E7%KMAkhPL)SB)i-ZT3C{( zRkU=3E2iFfOp2AEjmm3f>@sOsdm+Bj=a7@AS+wL6F$@fZxHN8V zU$R(_e>JSu26QOd7_2(mi%t2M1-lI=V_cBureH}?BlS`n1ivB30NMBnf+Ye=w?Oe^#4#iV0iykt@lly z8@_p&M9aH8zii^r1KBgGt#ENjn3-Hi9bK&ND*{mA0mjA##_7F8wXT>S52s{aT6-Mk zb$7^IfENs_QswOjaV2&}-cWtV_p_1ms{Q+7_kiddzx77_F`Y`6Tn0m!-^(!w$?o$( z58KzOQIh#2fA&W;YM?md_I8Y3=5mUt9uu$r+qJx0BkDPccW-G$QdSyJ_3V!tQzh`- za`WM;^9iUs-Cq|1(`TkKOzS7GdYl7~@px)``V6=)Or0qDmOuX%R#NWZ)|#4(YE(Es z3LIhaOOx5RfNE{j_J8zm7zKX18emT@Oeu2`%oynT{_VvJZqKS|+8Lc#8@YE=uw07) z+jrt5kZ8r#cW@0g>+BBQa9eK3C7Qxi##{pOCnV?~nL^}1QR;$tRRu9LhS#s7&RHRY z(GcFV_T`|3;mdH3%5a0Yni#{*^X6AuoB${rCjV$4_eBgF<1@{GBh&9%4CV&;BTD{{ z9LGeu`k%s4`I_Vz2B=){n_FUMia%Q5?+44d^ST@x3eU3W^Q>tn7_!R!G+1`AxB*>&(CBTf`=sDwY zCS>&BH8P?$bIXbW(+BzOh2{k7tVPyUH`6ZI#mn%)hP$NBT4}Y?D`mLb=(!U z#N`dEY672FcMeqxdZV}T1t%hY*}h0W&vmXe66JC7CS1Wf^*E_!0^M}4*)KR|_6*oN zLUE~aSk;$P3ufZ954#-1mRf+tf8>PEv8KYd4e^}`c!QGJBFV?1a8Tv(@gMOJ>L3By`l zC3Wz6%TKt-VC=*TJ77prUVVyOwGto1t|L*G7X*yN3C6vOkb)n=q1FUQrbj0Bk z%~o48dnej%@-A+XF@nm{7jV3(?05Jh#`F54lQlOn5n$gqlqE~yU)R526wy_q(Ub1c z2YL6-8JnuF)bl1vySRj;(Ox8rY&S!tOAAHqgTO^!)&P+MewDuRMrbBO!DDt*Ub~M97EBGLG*nP1>Hc5l&F?7MZE5JmE#6>m@RnZs0SU!-lx*4lpgLINwCppt=-j1BMCPzeAV~NvNo(P#GR#bAft`hE zdc+`CJ5f+zN@qTTiDDU|RpbQB@=pOc5IeVVMPh3+8y^a~5@l~9jdiB`Q-`#rE!td z177gmnOUh`5wOMq8bkxQanV%2a}ZuxKq)0DugL3&wuzi~$3Uq)-m~#m(17XnX=v;7 zsg}Sc)VcG>Zj{h`zRb>uYv1)Ta2M$vIzkZ@4+E4zUb-Yjg@)OMCHgsOq6X)umKB2B4=;?|eNo-v@O zx)n8E+lvnqP2}=l-<;gKyX?Gx-1E|l^ci|#Ek=hk=ViMjbDL~Xc#72}cHi)c2|N&& zq7qJgIU0@BV)odv?VAkj2Wb81XZ;!Lo@PNaF6q)e*u$%Rv{{rCGa-~qo1Qmem+!H= zwU%E-SSClgbp80@g-E|SuGN-Lfp%`1DjHGS)Y4h_$bKW^m&@3|BNyPi*7U>~zpnl# zl@!{gIC?#qX{4KBW?<)Oznt|OOhb#xrAU9GPIFEf{-`@X^9jA`uO`y$G|5gxKy)>| z;;kc7tVXLk%x$Ta`mpZ7WNaqpX?x(h5)&)K$PQ-?u6=L_3;E!??Nkj(0|jdqXGv4N zav)&>cD$t*;Ez7kK%&6pyB?;qXhrWPwMblGr|1va3{ z;P$vTrQmSY(_)PArj+%^9NE+Ws#NDa+AJ3grGu|}@|V+|3aO)63Uu{7c|v;cRFuE8 zU!v2$dj5EcMeLUv+^{0F*{!{%rR1E#l1Gc-Kc+21m|U>q1b|7zuZemcLnw$C>d94=p$RaBwMp{;=GS_Rv@dSm@E<{Yx34y()4Hh zJb#e_cjR)vno9~<8;{IzzMx#xhM#sr2`4skt1Ef}`bSCkJ-;z*7&Y=1w zqvdR-hZh?VsX(GaAJGNtkBjIWdql7AffMEgFD4%XxkAc*!Bdi`ewxGrT}}QfZVnot zn}Oh5b3GD=SZ^Yqq}`C4RaX1%h{YrrV_Gp~S$}E@p4+Sbhj1X;x55q@RlO}?B<+|YRqb;018h3{bf zBQKN^Xf5lhWxTK&E||;An1Q=MeWf&B)%@nqu*r}jMA{A>lq|ROFvH33#%X%%ZS_+( z^|}Ns3%_H770k%#evqD)tdW-0E06rmdUugZ6Rdn%+01nyu&`2q3K)UkBJJwa#BE_~ zB&u-90bMP&7=VVL>ICNnkJ|_k@}=mxovoJKkU-oYMUc$R`H zC0~;GL}}bU$lxgy&TDRec@ID>5tM1ImN+xbPAa|;W$x-j%?nfkvzlB;&H3VWV)F#7 z;4vC@JBh@TlZ9~h#N?+0ur)Uj6Dkx*RHVu@aHftYq!Fq5&Z#qyj*Yt!Bhsf%?<3Lh z$PDU@1o#NqC-`4(HsvOiW*-WAIPA!~m%P%rDDP_4Z9$j0W4O<&;0FzZ77&NsgiAKWhn{HD2%gSoxW{qgS)pAv2 zd!gY|jL5eBlEsrzsn*UWvgchaM^#HeAr#7p2o)KbeQmeY;V$T5o#g;Mcdt4@y;;5D z6F6BaihI!cj!_;J`+&43Ncuyb3Y#dsL3tqPY=CubHcm`=zgDl({bWsv-vPDx=LuM> z;fDK=M{Sc?+5hLX!@V6t!V(2IKo$ulT}O3H4hq}#JMSp&F>bAAsoZ;(|9?w z(!ZY^dl!GOxGax{<8@J}1Fb*q&?>F&A9~LyX#-`^AH-_y__Dd*vu^3ZMUJFOHknqM zqWx0KgDUA!zfC_iui(CW72>v26UkwQi{7Q6OC=>5OGHS7vo8~7Ic{B$d>o+GH;Esg zmF2Mh(z*!@Mf;_xc&#i7>Iay%XlS<=G>wbpcBBF;34%nt9mF zBp%1O^;Wk!&GSJ3zZ>PS=}%Qcd-|R#KJ+LqgIqywW71`wBg=?CP?xsf@oj6~*fBkz zMQh>BqFq)A{pUL?bP?IYf<4a<70k%*+B^L20+3665GI+i+jb78rqy~ ziY9~MX4jy|qhNPQn{M{PS}s?;@kQ>CyB|KY$}4{+n646W=#S`v8l6_vb-l|1iClGP zaOcN>LOTNeXC}+u8R?F46-nj(0sQ;s_K>S27njmWdm?w7#Dh4_k@N2T!C7*9UGbgs z`>&zJ<_z{J;ll}o+vf_TBLV{=)T5=G13%@jSlJJdX!N%VS$CC_?R<3^MkpDhYyA@! z+_yZ0uB7FOXvYCW%!z%DttI{kd0+Dgb0`-4oWC5@!{3hckYb;crf8PF8&tM zw)9ql6&GX3aunh0WkQt+1R~c|a;-%C(?iNH*P~$U0YOnYM2V8^!o)Zp&`)@b7Bzy8 z+Qd!P9`7IrWOMA?fY3zE_d-4@bupao(#)Ub7Bzn~+GQON9+S2zy)Z5Q&9nwpCnMG;3 z^oz`68BR{annMoko-Fv;KQs|&0yeOf{czQ4LBgFpfL9LotxG+@X zl%;ua_B_RhEArkT&LEdh@mz^uzPIIJ)aJ16IG1R^8IqUxT9@&VoAKI~XxD;4g!cT% zm7h*@rSj1&X%iNY4fI)7&ye=!0r>xl$CMxb01)V1FiU($9Zbr5OtIQJY?3{5!FIar zq?Kr>8IOWQYqf+?Opt+CJ9`Q3_}a!w!Xg90G;uC5wfnxaeBB_} z(iU0VAmCGitd=+$=65q*VU&B|wnkt!c5T$YQD^OXB0ckpCp4XN76P1tp%Eyi4YfEAP0k%3Bn1f~soY2JFg@FsE4;2P>W(2deH#c4o{7#X9wZ|Fd zA2?$M()>|gig22GcRmzFV1T&NLc9>}@6KIDh(7ZtiK@7K>M3fZ?$_%AK6aFWf%eg$ zMP}M1?L&>e5k2r8xs}b;MW|{xJXh&RNGN zCZW!2#a>AWnyNt($5?cMU8g(?G2OOTCV)NSGRK2kY4F{8%%@uH1k`iuq)rfgJ(Qw* zC|fMTn_=SSg z^mTVK%ub&h#>ji#+eojY^L*E{fKvORaXIb8sOa>Uf#=Pk531FB-d}8+PpWOgT7$jr zKIZdq`AQMgffn^4muk#Qr?B;=g2&uMp5Yh@?n3Sx$?9{gBOG-g*^Jz!{|n#J-C+c5 z1cVo_5MCf4Abfi6Fa9y}GrxT1SI<_40s-OGKmVKOG15PN`OGN)`0skm7l{AG`K!VD zA3yFt{u>MLAODSy|4*;^{BH;G|LEzT`ETs!Y7jpC&syOZumAHyp6d~LW~66@-7~8{ zYyQSodS;CmsQKfbf6)$G++m@A`os)yh&Bf!l@7O^gz^~Qz3XnAu{nHa0djHMg|bY^`>?!{Kzf+S+2dy4yL6)e2biI&&h-?e=)Q zKA*q6y`y8#-o5+w?cd+o)fLONf}C?T7h`_FfJ0bk*MS4w-93T8!GpbheGfj^KQIss z4h{|Z{GfJQbph1_R4-8dKn)HZI&}E(@W{yM=-81Xq0rIs@rj9J$0nzc+P`c7FyMxV z0UHAhIKZZ+r)Oqoj~}0#I}r}g&o3-4Mj}g5B!{r|+$3-_z#;4eU<<1(y1e|*Lk~al z$fJ)w_SoZ3Jn`gHPn|q@YGpNtuvl(sDH;U~xHSgcsZ%Q}r_Y>u`suUh&YeI1%!Lcj zKKtDB&%f{ja7ga)+qsp~rvW<)*fW3uck$wjFJ5}-rI%lM<<(bTd+qhhm*05f&9~kH z>KsrP?pA=^R&T%k&O7g3x$@ro?|<;YhaY|P@yDNh^6Ay9*VbwXdmY4(8es2Uc@MY` zfkW7*SFc^We*MO0pWVFq`4?Y&`Q=w%fBnrj-+ueu_y5gZyME&aV8DF^9AMx7@WYQk z{`B+Dzx;CR)~~<)_WK`y{Q2i!e`m*z6uXtRyA->s*wwDx&Dh;qyL)dYk?wt9m+pN@ zYX8q4MlG)!Q$d1VbSfsv8e(UO-5sV#LKA_@)|k@xUG?6?#LR<@S^<`@Dr+NP`8sfqVBQHf$E93Ax~ zSJSaHU`R!OFw?58R)E z8`SvY6Y+uG0D(!jv1c;;E^1523*p7{V*XavJSW7osbw>EG^)J0hFg$tCF`u4PV~8?R2P*g~)B&&9NHZO_{W;3IG45 zjkcPsb4bE88SL>iC>kBEG-EI{EF|u%8!6Aw;b6#1^xL9J#zuy^S!NL_Y9|70D}iSW zR^f86(;ciB`DAYfGBc~q# literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/jpeg-rgb.tif b/tests/fixtures/codecs/tiff/jpeg-rgb.tif new file mode 100644 index 0000000000000000000000000000000000000000..36dc1b3a58501c88c851630842525badccd1464e GIT binary patch literal 4768 zcmbVQ2{={V*Wc#hlFUTiH-rocp-k6XQBo<1q}+r|ndjo(k})KdvC^A4NxC7!>&7)? zEab`+y4O_3i(HpGod5BDeb4{@e9!Ye&-Z-$oU_+&ue0{r>#Vc(Ui%zNOEqw9Cjih_ z=mQYt2RnfYmyIYmAqtL)0*C~JxNN`)a1;O(VD?ixsPZ4nG#rn1_TCkAkgI98F_{oGVdhA7DSOVu|IntFrhc~ zOqp%Cju*o6ApcwCsTpIAro88eL; ztq|yNDk^~Mihp+=L$gg&usWu@YcqwLT>X%YE^|yy!~{14ew2svK|s(^i*1DNMd6SJ`Ue%GMi^<~OjkqFdPb5X2?@&8&kR>|b}z&qj(v;6=rEBy;~wJbm%Piqz8( zQwSU&d7{RWbJs<7(DNR_*TiOf5}HVQ2lV?TLYGq&)PXhScgq_Je>+`&tp z7_HAC>Wn%&#BIkjX9e7HE%sg%y_k4I=?<96aH{%_m-=xlv%uZiv%+)3e#53viuPvA zVzpOs=gWlW)7j~OEB%c9mnQBXhWbxKu-H;hqP|p>@rJa$fp&+4cBw|+!b!pBoR-Ew zU8Ef&IvhM^N@FjZfAP7gc|Bt3Kyh`NLYy8?&R9ZADM+^lf?Mi@CjJ!(xyW8F+f>&4 z5k7YJ735Q@HT!<;9W1rzEd(a3*OvaGTvbGWx%OsY-BI%td+B2IIB|fyFVj;d*4Es{ zN?Qr=DQ&yp$F4$Hk^T~DDTYH}+(sP-hgsMlYPPzB#X_%C3LEYznmlt|Q-wf^A~wAI=DT_`_~T_t zL}=L!QUXF=t?IBmu=e_uqP9gciZp3G6@|Eaf~ngC$D>IFYIzOfYOJdBQo0PWCE?3TUcEtQ2y z2&f>acy{|!EeM>VR2s1g@KfVWs@Sg;FR?$Bsu|jh6WGqbBhNvg%Fz}A1D4(!fq4G; zm3&$N1TtdjXb8BR&4NHtzY_lnTYB`bz0)7zK@~f*HvZkwQF>|F;v5N!vZ%L^OF9x<8Wgni^}WLAmd5fb_X8tH9^(Qm*}r&dS9wfu*RJYCFj zY6I#bIq})Yj;Sh`v`Xm7JIM|ezo~D!YB;-)*>)Uv$o!&}{)ajf$Iw5|fBa)gNFGD@ ziK5S*Nd!{NvX4(_eJn03O)7A*+X0b+zmY9w3oh_wp2OboMfr+EOX1$>gwsa*&h@xh zsTW_9+&ytul<`94(_eCDW$s`VFcNeO1jy}W)XGVbgbE1Yn&k2KZ`RB^60d9;>?>k* zNoC#jF`x$FlBe7Un-Gx#E5k7;FOk@Ki;Cx#-eomq?iESS0Yb?)pTF1AAb3CH9PKfi z8+YX4Ubzz1mQR``pJ=td=Vb7?(S#BavKxJgI#b~1;&G__>$v;v2*uNWG1sIH3;FLL z&Q9ONyo|)qJIKNptX5Q-=Y7z<^b|@Z!VC3vOKYSU={4aKSk9n4vvF-xnFwJtO`=|s z{1&CD3_I)HCN&LvQ$MU8a@relh*3&xeq3bN>2W6@+fDWiL48Sg^I((A(CM&My+>7T z&Z=>9mS*OO-4b$1*IfJ+O?1ccS}1o2#FN;0D{0l;Ng`UO=q{C{aeB>UUor%45d8c< z>G}xQ`;_|}Y2Dj7^5Mvp!A4dYM(QV(H@aeJ6| z|B-9F(k2JJNANCDL1*dC3=6tko2km*_fCCwG3Xjj{o^60k8*-=SteuY?|QL`U@_Ar zRt?Gn1;XcPdxxrfMbM1U#}vnMM@{9)g)mW8u}9^_sjHPTt}Ud#!0%kR=)k%kA%4ji z(a(+8;&5e#ZMd;@*=WU3QR>%OKSTWp(UbnM9Lg#mG}FOh!hTdq7ODo_%rLOcYfD!= zm|V*K*kn}OIsIHFKD{@Yqm$cU?2r7%Sl4Yoz*9|Y^ftLKe$r87;i?^lNTaD^4UcRb zCE6#*1)uIR_4sz}$;x1w4c(eD5!2}N$~)IC<5gkqgG2>FspB`ozH+mL0afJR7sq;R zM6wQ#F6rv9zoPj$+uc@@LsOKz)rzK5h8h-ceqRi~yIX|YHLP+_iwpA^1LzqPq@)K% zei#DpLePk@s3iMZ#_m@1jl9Uj+MxEA5ICeG^q2GM`jq>>S2N-NJ+K_FBpfFPT2<@hD9;|txfei_R?)9fyy##TvjF88ysRVN4qoH6PpJOoPC$e7dI=3Qqko7v$k+ zVO92GwXlzIek3>-Jk0uLRHbbC)VJO)zbvPynyRr&L3LH-PI;ug8O4Gl*~8b4tl3g} zA-IC|TnDW-@ZD3tjBKK7uiNWh=xC_G%ANU!>y$gW@7n8rx5otu3b7i=Cp!<@xv-C- z*Y`o7MH>P);n^DwS52lvv{ZF=zAmeb=?H-cymxt90jaa%4B2Bn$;9`@ed}le&uL5Y z4?>kAu~xgG6>GV@225SQv>9y6{s*XcO`X%IEPU5Q!$KPNqt)`$ zk@N+OSU#b@n>_C)c8sEWy6iSz2O>#9Brd1$p=QSEx7uR9N0SoI+oE{|68(d(Q^)#J zB-#hMxTCu~mNcj82ZSu7(jCrQy>!mCjf`>L^F{6okY7Z-#p3XkG}ze;wzx`n(|W-G~jF%&Aa=p@r`4!&aw11iBNHnp z;n0hMfI$2xoZPYG!bS+_vPDk^vGQnmJ?7tRyI#C^5*(xcORZ1vq$wP(THNbaSaY#x z!l(OM6}gI&FP^*G+KUlp;#GPl>d&*&O`V6{_fz&q@;SSeehUvf6*ffKaqUYm@lpC6 zsrP0gV-LHB!R|XQ(*+C_wm6cWiQOJvXr7hGPJzvs&8MO04p;)KXeOeDjWNa>h2_8- z4dmv;nlFZNnTm`v7G+%ZK;xED3l8K^mz@S?ht{nSMu{A`>zYM%mIDs5GYR*6cCHf9 z8jF2>mkb<*ALJD=ZSo19Jv-e4By=rl41rw=Z92D)w&!zM=7|5`1E_}b&A6`JF z-TnTF6yJix)ucGnQ1_l`4onfND}^@)P^4v1-yAoFmG=A7dMRb3bT#&TNzdq8X~Jyl zjm z{kG}LxhrNF4Km7V7YqGejT&FY2?=H}uPn_*?uX-|gQAp1IN|qY31RLCZLO-tsBr21*VVmtd!zSv*95-5{L5M*()6>jEaM#g7%jB_ zm1zexsIC4=F0q=7H$1_(O3@tDz5QwX)HnK5Cj|Fe$1$vOy=A9JjbAHLIV@%O^ zxmx@^>1v3JwbEi1jso@WynWwhLLZ4EdtUD`kDAXH>nx(<(E2kJxiPUe=iKn=(@rl^ z4`p>p@3`cu9V*M{YJTeYlv={HM^c+0Py>H6V#&u@C2YwFCXP*Dph(R8y3}`z44x8Z zWJKL+UEj=DVp;g?)z79}9uU|Stp08Qqe?Fhzea34UX`QNP`l>(=Z==p1Cj4*56Wd* z@LHU;X_>j5hM}1{PNkfRxZ4^Z@IJ6DCkZ_F0sr5(@(U?RM_Ew) z+L3&b>Vu1}NRddFVka;AdaEl(9=q1YO%o8wn|T`!q_=Mry^j{gaY+`GK7RB0*W&eK zdPBsb-K5dJ)tk9}G72};WX>ts3Ob-u1II-0%vv#F}rxHfenDH!*Pj%|@n z8=>F&*5mSQfbT+`(i7o9^7X_&F=l6{vmX!Wsrw1jgU-IMey66#KUo*yknWfxyZHUl z=G(4RJg*J!kQv|gvmSIgD#MIb*tC~C-kII_ zQFf2t*vROCpE;u&5q%Dc&6zv6E58F z$-~dX!_Cbj$j8UaFC-`=gb+j^gm;MT6y71a1A*8nwNq4FLQ+yvNJLsjN1 z1xVN&9*%#?KO@2w2PdqHmycgS5CIER@7(qn7biE@ws!b#6nr0Wi}Hx=)&7%L{Jb-t zLV$$M-L${>6^~XmOWO2Pm2|HMMhgf^Nz2IY+NZ3dx?k;(p1#51BZkM0n_HYXX?f~` z?L|BLOAeP^T-|QCdw6;U1&4%&g-6`F7ZV#7pOAPzJ>${i%&hF3+!qCfMa3nhWiQ|2 z-c{GszOSoqA+)x&cYN&Z8W{XCL>&G)LLyTpr>19SfBc+VSzY_JPTQbwZb2i!VAu2Q r=iyY37lg?lAa?#dOz!}~dg(v>-k#Ijl;gkX9q_x&ncA|x&ENSiiOmUJ literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/jpeg-ycbcr.tif b/tests/fixtures/codecs/tiff/jpeg-ycbcr.tif new file mode 100644 index 0000000000000000000000000000000000000000..389a331f208c67f800ca4cc43c418df94b5e1f1d GIT binary patch literal 2800 zcmbVNXIK;28lE%~ARvK+VnJ!521Nveijt)W1`MnqeOaW~z@Q)jqzIy*BIuGBqJpsW zB26%a8c>Q-6zL@*O{7_ZA_PHlCoK2w{iL?W-M*@JL zPf!bBP=FM02nJCGpcn`Y0}%`WXcz<>z%T$2Sd3nGwVLSj-8N=3GU)QyTw#_{7iYt5 zjvlW_0F=FC3jjIC*DrZ|>TFij^&buS0)St!lHFR?Sb$HMUU*pPwYd4!B^QOU6mQRq zF7q=2KxKSVUs3>cuIqSmg0Ck4juOq5phL9}^!8+TX_(7|!>8!qd*XPqacALl%g~c( zt(*WFsomx{nnpSZ;CTnzV%2V1F+?w_RkN1wbQdRMm^!W>_XgvW6`%3~vOW>b+OH0O z{;~T9emWueJS<-9pxwxq`e8`UQ@Q}SV>?eDX+wK5eFplyD#(Lf_xs^;kM&ALEU*L% zK%G}uukF2~!6xg#lQDJqPaPCBPGQQ@ibLc6NY#gC)}(+K=41#R`E=;J>vtReisW+5 zG$>xbcf_XZHZG*pz1;xblOBe;E9s8oTevptt0IpZO4B$~x{I50#yQGmcr$;Zp#N_? z^ySY5^CjF7(_3~9r5!bo)pZx7ex&YW+O##QgW|JT_1J-d~B4Xl$GOB0d&R)Vv}IUklgnGG+05IbN^!E=v4pm@{C ziG3d=cUfq~ZYLzTh!3g`aQ#@99g~Bn1i-8Spa=kGyT#~%*|z1I`db7*QRwrPTb^IH z@}CdC+}hJ(Q_-8>(MXEUi!OL~S6X{HH-mEwT|O33cJQ}#Mx(@Nj(o4i`Gfo2vq}2w z+_Ow+hyGiny5`D_-U>efYWC10uX-9UcrDWFs`iG++Qr=7Dk*6}up+xW(2Vb8EplG6 zC&RXnCu%1>-(TAuFH#(xLt=lJ@JQ?=bDWbcCSC=FEr)T#dTmzRs)vR*FEjGRSGWRT z@+Q9a$)mFIvYrX3@%1_;^pGt{*~7_d)7^JP3JS4}b}A}w>~faX_-P~OMFZ376!G1x z8|UW4b9O03&ob_5-xxO}gxiPIe%mAxbkT)OKiocCwXn{{_m!XLmxjslr5w{irPaaUhQ1cl<~6Zt3eoSnH&{8XJX7I)$>^{kI~ z6Rp-q)iWr~Zz_8EPTfKFhAYjvuCvG0Exhw+F{z{6pRf9p)l++4uUIs?`rz=}o+X^8 z$P9Y+<~p*t)_?Yy#DD&{c{7y?N}Vk7`k5o8HSxx%w+9?{zUZ`&Yq?oqu;HgzSEKb6 zvT`0D5fONX{pm>6kGqbB^F0yy~=UJ`0vm5!g@zPmI)F4x=ksL^tW zzMy_a^>Wg1*C2sKejeb}aFG@IAwJgyn_Q`Rfz~s>=|BhRedidh&E{derHEQhoZ2m!eKtXY)g?BofZ;lx^ERd5YEU z+^v#w(snBOffWuEjCe~G&u zlgjh((GL8z!_@wqDkDJ~e!n9?JulkTN-XkS;<&{?^S&U);xB~ck|3@NC7saU;u*gp zw_MK2zPB{b{?$@*G(@-b&5-v{od95(lH1zb2n?@22%~wJcrGq zEkBER85CCXnWGBs`zm=735PRVX*;6quhF1GTi=J&DYTTt6t?Cmbmwde{<)NAd|9hw zoUGe$pqSefmXm#o7C1oWxV)8bI^j^RfrXS7)5p_iS}X&SmMTrmBv>V9D@};#(Z%V@ zyz6`AgH7g0EhmEyf6=8BBt;X^%xcY$?yBy?gWZ{N)KRZC8S+Kf`Oo|#C*2-pR_-Z^ z%((VN#YXkYHewYeJ0*N$cDD!b+r#v)2AOt zK09@so7)*?(5`&jL5C95@yY*6hO)ge#_WyRZu9skS-Tb4SP~iwa1iWH>JiPn!Vl!` z$e6fWTRaql@bxjqv|{=${hvi)kYE~_+MfQVM-tnWK+kGv9h2LpzTfnIa5J8&7ffo} zXTIQn+W1T}Rd$ow<j_}J^j~<~8Wyf4yN0DeEC*sCw;QbA_?PN>of7EMQ3qUl|MvhY2Nu)uG^h0FFUOD`^>s$Q*M;D*IsfT!~9TsTe+finD6x zscO6VMu>{Z%E>FNSKF$-ZTk+Ly#(ET`wtiyA2u;PLNc>HZewd_@8Ia}aq`sZGiN<7 z`ceG@0xtz!y%rgD{l?8`8vQOKo_X*7gVeP2jLfX;oZRA)C#+I-S$V~?y84F3=P#O? zJ370%dwTo&2S!H6-i^PXn4FrP{qlA0+x!B5@w?C$1njPV#=rH20ewN?a2OmZ^aX(i zfENq{M<{8DNE;kOy86f{@414)8pfqOek!V>ZNJ6s_KlW%?hopI{SOZBK|LD z|1$QcuYTS2zYEPk@z=q21-1Z@GsnOj4%B_iUgcl59u;QDA2}RY8$<6r`zGY2{sGLn Bfjj^J literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/lzw-pred.tif b/tests/fixtures/codecs/tiff/lzw-pred.tif new file mode 100644 index 0000000000000000000000000000000000000000..5825b3017b12ee3bd1114a5bfd888a8d91f5b1e4 GIT binary patch literal 3670 zcmYk8dss~C7suD0nf6RIP1EQ$(==@fNhOs;E>lXmR!Zc$C)7kyL?PMJUAoET3~|mB zl8{Lk9g!Kg=vSI9(m|a)LXj9sEiK2-`SxNG zvH9q`thCW~x!t9#%ai3zZ#lf`Ifpk&L!(0`{b<}P0E2;!y=Uv2w_bc2oxuAsB1yiz zYKv)Tb=%iinOa0pmb_~?P_zD>anubLmmMvlsh_f!2aP>h*&Meb@%T1}^Tm;Id!px4 zH=SyW_*8gm?PLGkXVLDaG04^RHQgI4c3b{>VVk^k`|diy(J|Z`uiw{HSJAELyZSe5 z3C&rbVR+)>+PXDU1b;t8!KSX~xBZnyMVjriZeCt-@Zu|XhoFu>2%T}SzR!^x!_bWP zFF0?eUmki)zqPH7TrC{z{n%U^6K7vFQ@-JX-klukvBArzw+nl2%nRF_-mM$mzWKC# z5BNNfM6R0r-l~rv3a8Wv+Pn{Mt#5e+W}8^l)1!8e^?7$Ex&Lm(=~io}hu4XrMUfBw zp4eEx_h;38%(ig8S220le;4*UO`9$Y%6>WH;o$?vXSR$vFXj2W^dlZE?M)&edU^owF+fo{Z>JuKQ!;WyacP9X@C0{1HFCVe_+^oEx!gjMHw$tzO~N?$sSP z?Q`Ul$JMVB*FJvqG8x~Qb30LOI<0qa_loa7l3L87)$!`i9>d_?_;Qc*r?p9AlEQ-B zsCm6ohoFMiixBin-rYNk0)$A$DVCaA}Y!!6JGfj}1nwhx*teF)}v72so8BKnp@fYb@bgfYbH zkCLby#*j0l+Y2A4904sc385zokpjW-j2Q|LWMqP8s;KBiJV8Iu1zgcr>0SYWoY??0 zzhItKgbIw(>gqp69tX&^2iR@HqpF?2NQZ#hP_Bf%;;}i2EVV_60CTX+5W*VTE75ji zuEaeI1PxMf{!Llbp8!^D2$YnB7XXE5VTPtBvx~uMZAF4UioXv(ZL_vo#WR3@8=!ny zFqgESU0Fz920iiBXsumN_0ZJK)=-v;dAX17N|C2|;1Ots&uf4ZA6W^ps!Jro) z#L_>+6mS+$R25vwO1BveU3|>_i$DQe&c(XIeEduj)@2PymV*Ms;G}NMYlyN_RIx2m zmkH?jgh5NW1q}m_oRyC)e4YNBGR~Oi13+0 z2nmm9D(pVI3f0 ztgllOUFiy}-HS2!;>z3Ry(e!{KIa~86x-X}hK?OJ00sg^4~7nYkkTc#U^z$|XRtE_ zl>l&V4~Khb09A7Ko4u1+F%|mU2J(A)v5IGC)IGURbX$i( zrhu!)G6+b`kMsf<+IJ)~oaK29=uD1rkvq>|Y!)EIETEKmX9q_6@rCozlrymelIuvo zQLA}V&jXw=2Usg0RO_-7VB{qS6D%Oy$Bu9l!d@z-+MIpWy)UC{&!vhbp9lmiOBZWD zQ57GMNg?;xSJJ(0rxBspV2@usulFS$4r`=7G+O!4f<_est#$>Qv5wM#NNIvV?eRZq?rUM~%O!I?;8q)mQ z)h0(Bmp&^}#ZD%`Ej<&?HmQKBlKvq~JXLtBBXA~}r>}m|3Y7a(QiS)ktEti$gYju9 zF!xb4A(%s<3sLTY$m*on_RK8IwCU+`L6l6$qm)zJz zS-AUK{vbm?#WTQ02<+?DjM!|&F*5?1i$!?+ixU*4K7^tkt!TqR|S+)cfN&n07mI@S1KgH!qxVsPv>op zB*BXkAl854evvb>(t)XzyC`T2w|)@y0GLxX0cO7q>)Zmw*-&zJCQx6QXY%V7642YB zuGOI~A&tCBf!WIpH;i9BS4W0d+ZgZ6#etum&}5bJ7GR}V0CHFUGzCj##F{A-1y+2psvB*mFaAivA*#7spC2mrSdL3-!06DjUE0n==5mA*!a6lzq3#t8Q*M_Btq$Wj9kNXIQ zTAoVc5wAK7#%2!XmR-StuIs)H2XxWm3!c)?dbBw53sop?ApljR1Ede=)gOMl(p2dO zNGDS*efR3yHgcKiqK+F`*LdU!Za%;4U_XM11$2M9=d9Sp3vV>aO|X*sfsgO(-Kc{J z+ZuXwg<>m4ST_M|rK;c7xLOEw^+}YlrYOMdpwxma=SuD!!spQXj*K`Q>r%dAAyShT zIW3|<-;=BuVBE%MadS*{&?^klnUdENuD-41O8&x@YPXFw`k0va<}H77k_9Q}62^BW z`4=Gf+Qc`_eNE@!FFs?=_OfgD-|bQ~%r7`#ztmwPfZS3hR^xC^0VadHij={e%Ni8K zEe6_3%T1Kh*K!-yYrzYdm@)azh4d1Wv9|e>&`a!f^^zmpoO(bqO-qhN%C_bey-8HM z!=ch=>;RSI*;fEs=`xdrU9U*6^t}Iz=R5RJ8Go!C5N{;Mz8IJ4lc4iHm!Y_9YL~=% zU~hS^qlL8$C31TM%dv;%=HyOu+lL=YZ{33>pw2YS3Zq?GcYShcyh@L%y8}^D_;!BI zM9l@I(x~V}&m>c>uM;Ie!EbQWdvImf)~EvfjImn!Ufu>kBDnZV(aB-t5;{nBDGDrv zVqL`@&}(eMlDP%WSS)LdBCD<}mw}f6beb!rd_D4GFv?BrYvU8wxLH{D<`5lUO+(;kJ$ZR6p1dDFVu44ppEGwU*_N4< z@bXjxRRaC|eUpNIOGPJF5^1Yr|{;l z3U!ombd%MaT1+N4IJeb=5H~ZgT#+fv5b2vG`!Ot&cd>u7K@>|j!qjLZiHZLc74_La2ztnUw4gRIV^yB#asGA#?mdNn-Vwura?7Qf>y5qC z+!LSs$Od*MAYuAMB!>hlF~3k#{$rv&aVgmUkfCF9uao11nu%`pvPc&KhDb0hy2d5q zqR%bfWh*x>5&&n49b=8Fb_4>leqeAPL2)(OAVy@(v**STmD3v7? zS4A+lV9&TBDW>f!0T8OTApw}JeUP8*pk<1dsaj>T0H{BG9c_&MWQvyce)8!1MhNYn zJPa*!{?9l0$)mYUfAVO4v!CNV4FLH6H-3_qM{{du1G9hnqwyR>=O2H*c0O~pjA}ho zEstJ|f9|w_KrIt+`%~$tNoj6cJgUgQsy#>ljVXDzK8^b9={(t}QYL5UX$6D-0n-GA A+W-In literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/lzw-tiled.tif b/tests/fixtures/codecs/tiff/lzw-tiled.tif new file mode 100644 index 0000000000000000000000000000000000000000..6a00cd59b70e4d7f2cc02c21ca5d260e0cbb7811 GIT binary patch literal 5064 zcmZuz2~<brQox^8-x%L5Ku7z z)G#_x3yK!4tzim-pi$8xwKd=bKBQ>14_~eSe|gWhR@cA&+;!Lf&R*x-b9VOm_WmLw z7K6kL00%IcWh3t>UrB}91V7Bu=&NoAK0V6A{e3~OPz^`SmRQRAMYHnS)nQg8-9QR| zQ@zyiu%?k)rYkcxi|ZK*090Z;;d0*W{}TF zn)zt{heLiPYadJW@8zXzJ|~c*xhZH{$Ah+Vzf0FWrNdDNl6;xR)}9(kORPRFt|#H9V9@&i z2T|BXmvWqv+>FXYlPi4li-Q(A=s8|UxaJjNTGi`xXNv#Jr*vg^!<~p8jVH%x_}PZ3 zeXk4I)xq?Fs}}nsLKJuFU%$4$T(jb259gk%zbo=-{kj*+it8gg!;iR*jj6K@W(KC~+xa;uiru_KnO4-jJrW`Mgxp|)2j=hs#5l*dtpS{$6@4#wwoluMV zpVUfryALyuMGav_Y&Pxyw5aUB0wDp-r}+_ly-_OKv}Yjm1_51}gi{OdiOL zJZ#Z)Z>oJo66yQouM^U%R=hQJ-g;>){YTdKm*X2dHhdlXV)!28^0ncm*-=hu71EQ! znbFvw9j0-o9(ipj+#b-mYhdE>`uCS^I2N=7*>tM3D3OKqJ?_Kt-^LDMX*xFU4Jh|7 zky!j83l<6KQETVaz_6dy2qX2(i@Q@}I@%+H3`;`mD>|L_FIaRi!bu>BE#BZIo{yv@ z;+@yY^$vG)H?kBF$9orD#N2NNt~sdLO1T=<6}DD&=k%V%+qgf)oetudC5?<-VKlJa znGt^`55(6e*_HGhJ%2p&O8jcyEpZ|MP%&Uexb z2S4Q6@qzP%eT3~O6H>F#J z2Ff9$Zc?sWSs{#f;VEzlikdA~Ji4$>z-w%R| z7^9d?yE_TjnBKN;T_R`R7-4)qPOa@!k>}69dj9;&6g-TtDj#iRT3Hr%PjG#E1WRpY zq4fei!^$8=#enM7yV#@{o2uSsZkk0`ihI>?@~+(4tIJo_-r}2|nVyIXR^DzLDSFEM zoZp~5a|FxM;?Y14VWTx6ikG`_T7Eg$Tku?!YQrsR#Nws+lh0M45JC;R)au17G>T!p z^g&ttEXdCyXb-JU&T5b%hP8a$DNF9EB$OPoN3i5^fLwUFq;GdEC!N`hp&i33jP z=yZI=fxy4S;;i5u_-`z-|He`f%x-ffdwt@3FdR3F2wu3JQyTuba+LSO8qcFc&v3o= zyq)gHZ>3y(H*%-Ix;}W)`^uBE($Ho>+Tp>{l?RtJ^rpvQEv))bu~C9Rl@ksF3oqKt z0D5}@0_B=Ri*k^OY4GZs?z^akJ1Jo5P}lJC4VWI>u6ZW>I-N&LJh`JB^_2~gNqqg0 zei%V9M9SDxE>##%@dYol5YHcYmOWhcd@TRXOJE|A7pFA+!cJjyc!m#=m!8B526>&Q z;laM~+jQRE5L)?w?)K>?)v<8o#?#6Kn;$HFjt)3%NNm@{c^~g}{%y*iw92pUCc8at z_t_$cW`XO7iV|9|p(*Z^#oV9ie~WGKz0snnVMCZZAXE0LeNkX)0F>Ut++a80DRh(- ze2G34Y|C(xZrza6<0#(>_>a3e5P`8vV=09?QIqG!)TBF${HHA?bF5w(Yn zeix^R_W_&XS@^k_=U4?u8v{{XC;r(XHD@9FJ?P&*5O%Nw5WvlDX|_1z`2f2oCG4&a zeo70Ts1K9?(+JSjK*z>Lg+Rl6w#q|J+PDcpzLRVA>^Btvht}ZEAqf7eDHjQ z3Xl1;rRmX-da@ke{S7xw9&1YQFviKblVTY7ts1D!49OP;8ll$<){XFvTq+)I4J4Ho zqT36L#sGxYz&wVijLGM2AXRosnX+8jDB8Ij(`x{@0hG3IuuWN^*i)+l7ehcIQZWRg z0SON6s1{=yA?&Ud!b7sGQ2M}iuyNK{Ov3wN?};6JKA1d56tue6LI^4_+4f7W?UX|l ztcTC`y4%*(&3%Q_?5~3548P1Br`o5>qp7}oNQ?T?Zi4=hF3LK_xxvuvTaPd91N~Wd zqX}*%2Y#)KsNX|b)G%|75>hR1(94^HAX}p?GcRC2YRUcty_73PjWz=ihK z#C)pI$p8l~1I(lyk|fX0xf5U(*1h;fqecCPo!V^*Scjh*RE=KZ=SaRR6$?$AEuIvt zV^9nC95WwGu~%fU)T9oe+~%ZS#x$FDY?S4hD+~ZCIG9ZzZ<$|;V#ePuGT}qWA*zzP z#?NL?>ZWKHey$USj&s43f8o0dlDlLO$8l;tKsXm_5N}&!Hp1zE zmHC>IOFAH-V3XKFFdbMXxWTU?6>$+ZomJDn-NpSO8&(bt^UxU`$9=IZ*^_`Bcp+?swem6>6HQ<92if zkVz`Cd8uN}Qed5%MMRH|n)R3ID9IaPVu|+x!&$IqK#0Dk)Q1n&Ca}0`TK)Ue{ojB~ zSa-xE^7@~^-gE1e8dfg`#vo2|h*PX`!tG3i&?Mn;l)l$?{g$hsNQv%G0mL*GBah4B z?{;VSv0}T{Z6#d?_=pT+;bwk+w^IYYRfc!01iP?)SPN89N4k51H83p3RjNPjwrXLa zsaTlwoo#oFBGrnI2wY_aw*?TyM^a6cvUlf!v@IsonOfMb{uL*CYQ<%bTiBu4ih)8G7JrbZqv zQx+%#0MRL6P2o`?zyfL(tYAG8#xDR`+hmKpt}a6Wa4>$WTqcT+5IiOegkFLNbNc}~ zoe%mnw#2?Td-$>dY2I>OWXsE3XmJm3S^P=sqL@LT)u)!17}H1Xx7g~>J|t61tiiNE zi1?vIi712k`~bQcQSWL+K;g2*3s059E*tIFCu^RwhEIsMCeG~H%BuR}2ahKnk}~&1 za=FCh!Z=gl!3-6KlvO9P)^Vt~z%bhukSud$UgU4sW03^Xim1YMETFl5zu|aNKQ_^t zcRN|E-<`reX$%=>|AoC9pXbAy{-?0OfrNYaXLO-_35Nx&gOf3c!owC89%3Mg_j&1r z)=_04`p?8BMJn1VIp8LxSVk6l?+MTgaJ^6OatXO(9tEU-XeHmr1HDN|YUB*^zBHG*Z_!OubsY7&n~uN%?sa_W9!mL7=6QVdXuX{gnGR5?2Lmurtr~pqrx8x; zQDsTi*~i(4%RXgZ!ZlzvF(9;HO29Lhv612htb#Ny(7V*&Sc9mdtbw-M>m^Q|J1@4$ z;s%)Gr12-%0&zL)cIs2;#Fjl;;!fbuoOPD+Jy_1{b&UTquuK30CLhY3?_+w1tBCqJL#f8lV}?@lor>qqjg4sgI)t{suD9Y3S+Cv=?=EfA1Us|09QSt9psSP zfz8HO8BVL^8{xMval`d>Dl%#Q%24C};QBeks-J} zi1mdq1I@u+A@XDfxU!5s^X(>^eGpAa-4lk}1_92@a}n8GfI^^^)HM`b0H0kj} z2(n0J{%9UX?!@6sTQ&rk&)49RhE!9H*lr5+pC9e&muyoC5zTgj8m(f4p8!O+fU*o( zVa|w{`LaKng_9V~-$->xR|ZfR)?4#A<-2TXKx5*AHGE>AYj?t1ROZ zwHgT3MwL!h|8d=M>Z+KwIvjF(8pGo;i^d!T!zq*TVoE{RCk`XaCpU^go3POaM^8Io zR!{fge-OQ-YBNqtwGkNy)}0XHNL2rFmRJ%PSYN%C;z2$`hH&hH2`q zMF!2H=F~N-)j+EZY|I97WOPSjY-iG&DvJqRLRtA-r0pH8kLqY}MgGzSu7Q4Ed@~id z4kx71JPq86X9;N}m&3Mam+TdGtj?yHH=Id2m;xXuA>aZ0i5K~Zmk^jlV3e>ci43A2 z{S;zM{fJ2f*8hm-*PHzXTYkjz>uvtxcO~%rI$|gA|LC6|2OyMx`#XreJ|Qq6oIpJQOu=k^fj6 ZK8{I;y57$F8Ot%%yd}96>Jx?y{|j9ZI8Oio literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/none-strips.tif b/tests/fixtures/codecs/tiff/none-strips.tif new file mode 100644 index 0000000000000000000000000000000000000000..557a5155b6b531fb29f170f5bc70f78073cb2554 GIT binary patch literal 8542 zcmeHM{gW$InSSrR0m4UsGzOdj!X-9Af)F4;3o}53C~2Gl0!D}p0RlvgcKiqsB?|q+ zZ0-Dzs-5bp`5~)OH`^OEt5KtN)aYh)X4h7aI=a~{vu)H_-Kf!yZj|^Dwf8w*s`l18 z{0FzEXL9CDpL5>#d7tNbyJ}=PLf0N8T&{-}UYh%8=BH_ZCd)Jq(te0WVH!qg5T(5s zF^Q~I+KE#?LA@k(*Qk@CcA8olYG$dCqk5id1==psR*9-*+N{uqM%o5dHmO{t(iRoB zsZgVQopKGzHYwAhbemEgTJKV_M~ObgcWK2UiBW8iq63NyDLkUkJ_X0LG@-zh{4?^+ z$-5wri>L+HBP_ha+$YTZ!ZaXEmW6Rp*bfP#urQ1WgQ&0<6PP4etHMrP=qH3;Qs}M; zos`f{3$2XM%nFU1P|pjsg0Ni_wn{>^ENoVU4NcHCgvzE+t_r0sp|~v+YC^s){2#$rNi4d3y{+ZyL3*Lp` zaRnmL^@t0vIQNM&zc>wulVx!n6!$~oC@c;m;vg#S#Y85F)~dJ@7yAjZmlV5eVkafG z(_$+lHnU~tsrg}#jTQ9EsL8KaYGZe4Y9H*maAfEODt}Sg_@YJi@AoFZHk$e zm~M-yj=0_xlRYuf7vsC)iX}=+jO~fhffyNz;gJ~H7lUJQX(9%uqJJj(=Aw5YdR&o6 zay`<*E6sh<%r8v?(qvg02c`XxGzv?@h%|^wdohVglC>)B#HD^h>LsP_n$$^2?X=X& zNX@L&$Vv6QR4Yi^MQN)fRm;+5McU9LZ9}STO696l+LDUfQlTd0>r$>EWt&o_C8gU^ zsw1s;rDRV^^riT&v|>p(DYhp?2U27xg-23oUkZ+;rHK@nO8%MTn@iq>yM zN%WQYuCih&5>sM(N_3z^hDvy(g!Yx-SXr7VfvMu3DZaVlT__$`AyQqBy6~!VpE~oa z(||fzR>whgKctSr>M)`XqUv5uWs+*GsylJDpHO>AwY#QvQffP`wlZont2T0KJ+IaZ z>UL4xDyh}7x>->-G*#PBE1PP$s+P9Y;s>Y3QxknP zzN@ZSs>IaTo*Esfk)awMsiA!}I98V?YGA7RXR2?mdKaq4Rf#m$qbnF5cQtPg1os`y2Ypsmd%xaCCR?lm-g0@}M zwn|#HtZi1b4Nb#$Wm79xwbGVW+|~*;EnnAi4K3T$GA%9L)>0j9y{jdATB5JTceNEu zlb9CU)1m_{GStE&Ewrx%$J)|F3rsctO!Lh(??Usq8jfJTHlhWI1y_M0MS-p|d>v_Fa(6@{FR!Ogx z_05XDq3PO&UfI;kRlT&O7q|67P0!c$Ttm+`^-N1oxAjyLq&vTTfl#(u~c zg^gjv7(|V|n875&S~Yg!Mn7Tnl16vU=%kEx+Gu5rX4YurjC$Uv6^!kou~jmvWn;5q zY-onIVN^Daa@8np8O3d*P&4v%BiAspO(WAX(rqKvG1j|AvS%dvMts*;u?&eBu{|R? zFd{=EJTgN2MsRE_O^m?Q@Xrk2-0&_8k82Q_uE$(>&AHE<`ORs-oGhE;pt&D1M`3dq zF$Ym|FJ>~yv{ucXxYoiZg@ zZJ3o!vs^VxTV`?FEY!?=-OM%2Y}3rN%yipKb%mg}(=UTf~NW`1iLuqMmaIB4yMtWnq+Myx^9 z+KX9CvaD5WCvNoXU$=4%E8Da(Ei2u&QXOl(YbASDqHo1_trg3Xm=)Wzq5~^3w8A4R zv~LB+*3!fZOfCP+^35&p!t%Hlk?nfyh1Z_@?3v%52JFeQJr3IYA$t_IhY@=awfAB+ zlWc3%-ih1&gxyQp-8H+DvfF99m9d*yyOFc&dAnAyw~O{x$*z{|&5FID+1iF(*|f`5 zyR>B&x9vjB&e!c+!_GGCOv_HU?NrBJ@7l?po#@-~U3)-{@^|%YKJNLOWzdH@MlVx`tboWEA7K-K~;aExVf)cSCcv4Y#uCmaA@Q%PnrZ zg_@hMySav&ZMvD3n{K96XCh54c`1>H}lu2OgNs!ABna z?1``s0R07^I(Yg7+JDLW6WsoP!aPBe6C^p#K8_n6=iw(va)KnsG2^)536gMa9IOxi zhrhfI=<3f;9SrMn2p@0V2Os$YTVRiaVmx^E;IKb;8T-&V%)XbMawZ|F>8|k7jO&(`I$gs{u zY(=K)Z==jx>4y(8^Ah&Qce69jqRX$N^+)K#=diEc%;QO<>CQ*!Mww=B<(pvPf2=Va z6upsN`zHF`JJ?rN*(lAAOJ?ZSd+ATl@~};jU3xWP?cpP2t*};r$BAd|%#rVG>KtWX zyoSx*!n~)^l{e7KUq!!q8*|>k{-?+;cnL+Wqf4&jGmED=O2WDH;vm1jdNcd?SF=xr z7#-q4hNJXvN%s4v+4t{f*WF6D+(oZ^Er;>B68q_+3`wQ(^wMkSOEG5n7+`t7m!lmx zpZo#({N?O@r?48av(BN@eEhig9^vtP=T1Jee3V}DGWw@0IrzVPGkg45x@v{4zL^@Q zv%mMT&%cbFAEI=D&JNIfjO%`{Oh0mnysG^@PH`I!hnFkbUD;_Ju3h5f9@%x=G*a!+%7ephCH zdWL6;IM2O+&byF4y2RScYvy8AI2Kg_;*6Z^;W z*xirwbMML1AKt}b2O!|m9S@NITtb3C7>FSfr0|+I5`zEkYj`9miqB7n4)awYD)M@$ zOdx0GErj}h?0ojgqYMmOx`@ClM7w((Yx)_E7O&vkSiOU=Ejav}Cs`~`*C*(@+vq)q z*}uM=edIh|LBxZ~f;>NbfPMRRc5#GI#2ap>pFYNnGx^NYQ34t6$`N$&?Iip0BYg8K zZlIg*q_4-hSblIn1D~-o(gzR0Oi=XUchK_1d>_pG;!W&>es;#$bj8cLra<@)oXWWh zaFn;x*)O91Qh2fu(d*tuk5)LgKnD1L`2hS_iIFl&1Hu6FqnB~q4j(3jheVJLfQ2@% zeFc5M%WL}6$JwLrqSJi@hCn+%d6a!R!~o;v*Yl!);Q$JNXP@MP0z*(QFct*H1Bej8 zgQ&;qc%MqAc016P!bALs zZ7s{I3^F5TP!2SJx*>C*+P#EDS2&)i4&=G0FmML^0XK3L`s}5gPS6?*0ReyvA6;e$ z@^24uEuVTiT^1wHNnA?sG2{h0!Iah?CX@yR`qf(*A_P4idxiiV*ka$qJSTGjqKJ^d zkFxCNZ(wH%oM6~|T3|nWJ+~k*5D&cSJ_1jmulIV`nSQQxRA>4oPB5%R?Ou5wU2`)b zyh)z@_d}ekFl2}b1;x%Fx%X5K`yCGwaK;Sm7q}r8unwF5ILE$o7Y_+mcFa1k2@-)d zK|63fto`0=Ial!$)d9(Y)mK)yAO8C7>_toT*t>aAz$I&ihYcP=@>tbApZ)Hg3_oGE z$FhUffX{da^#Ws2CcyRF+c{m~Jh-m8g}!_P`%IX9P+)Mdqc7#=fYbmc2JrUZJjEe} zFcAs-6TrI9a#MxZf#;ALItwfg7^1R>3K~Qt&>G0ozly<*a4swh(9NGlX~bL&0azA*FKr?`JY;D{s`<}L^5K6Noy9C{EGiqk=-4+nUT4?ID!Tetw9dx9Y( zY=x8o4*DRLH_qV10R5mE1hDon?Oexjf8#b5zKTMZbDTf@6847*KM@r~Ss|Q{UBEDj zUIT)GnU6e8FmsqZmI>6J7+dLl+P@pu-Io!I6L}*aBn_DijBvW1pRC`CAGAgxKpI-j2~4kmK4z zgf0e)L$QDZ`Z)TgtPng6GsoEb;FH{uPzBTuhygcH5dr-3)g1FznKZe9x*KI{nQcG?--Mo} zY5pW<5%z&F0XSHPg}@)e1bblu5DT(^3Ba;$TH|jxpfuj@pl;M1&|wm-8Ti9XkqF*@ zun%y<4BqjeP3QtAqQuA)ods&b%MbX8TA+v^EieRmkjNLVR{5*f|NbQUl5&4#g&I}U$)z4D+t42G|eTXkV{B^d*KMx)I e)ad!&5C6@Vp5yapOUobNpNB91YiveG>3;#7PsH~C literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/packbits.tif b/tests/fixtures/codecs/tiff/packbits.tif new file mode 100644 index 0000000000000000000000000000000000000000..ebd9b5eb448124e1b8a9300596f32f2d46a472d4 GIT binary patch literal 7942 zcmeHM-M1rEoju(hn(z@Ig`v3tLKBJrX&^x07H}_3ga|3T4Frr33jzd)8m;&dAVQQ| z51BQ2$Xb(CYvm!MQ72OqHKS3Z)>Weu_1@7^j~boKEHh=)j84>OMJEpNBSOtSbU)0R z#UC&a-JQOvK3#Rr{_Wr1`&VnVCToA0@pQ+1Vo9IO!xvJ4sq8(oB;^hSam9mLt_XsT4@LNJORN#zF zZa2d9qg*e>?QC(~IM+#V?IhPqam_T>$Z+*6SIcqLJXa}jMp2A}A%HSQZKuAzu}8H6dFUG7TZ! z6jCiA*%lHVA>I`LT!{6AXkUoz2^)rhqrw9rG!%j(AutyF6TvqX)@FidF1QzhYbiKa zg2NU7T(lkH$|){g;=(P?J>twOPJQCUFOCD^C@2m?;vg(iK{PhS-H6zaioKY)vn6)p zVkaTClVU3+Hq&AwBi6HGEhkpvn5~PMhL~=Osg{^* zi;0dH?}`8}#(HA3FGlvn4MP;D7#@hBp%@&AfwAbHh`y<~HWNK_(Y+8|OVPO!9kvMI zlI@UIPHE|q7H(XRmZX&jJ7L1`G024RT`lCdf6Mx=gJ>cym;EvXxqIti(r zlv*jNnU)$Esh*W;IjNeLDg~)rluC-El%!%=DpaI=Rm#<*Y+cGUq;ykCwWMTQN_3=n zR|0S;){~-rDY7SR7?MDx@IVR;rQk>kj3xg>@=c|+ndF&E?uF!9O3sz!uq6POZHK&a z%1f8LaLaR#JoCy^pFHu)vE}^pEB_)>D#MU62rE=jj7?=XqV%ImFQ)8lDc!izNhs~4(n=}Kw9?2Z z^{i6MDb>7EDJbQlQhHfQmXu;yDO8kvRms(qY+cDTlyp-`wUlIANpzHWS2?z$#Cl4! zuSE8g4MP#A5*{d_p%NS^fwAJBD88w(Hd8!v#l28mOU1cT9JT_&RokJioa)l0F5K$e zqt3kQ)Td7T>Nuc|g6c4&4#FxGRAW=!ji~*o+KZ_>TWUA1b`okkskTyTGp#lTBxY`s+y~**}9r(sOhGfYN^S#n&_zUt_s4{SWk`i)yST@ zVW zecHsYjRV>!s0~BfAgobAGd8u|h}Ms4y_mMMrFG+4C!w{IS}UbB(^?~=)w5bHr&aS> zrJ$9IT1nBAl2$Bhg^HH1YPp)0t!tTvmTqdPmX>U5iH;WUY5=aqdRnxvMfS7}LldYL z9%!MV7944TvF4v>zNxl0(>!y{z0h1s&AHMXwg%w3?a)_Fed*E{Zhh|2XI_2k(7P4%^z?wRZEh3;DF&Xw-4bpSVPhp}=ROP8^58*`5_^BPm1G4UJYfH4Xh z!;mou8&oiiO=CA=^rJ>EX6$Sk-MG<7811CdN*T?x(a0F}tWnDu)x1$D80Df-QVgYJ z6w5}TV&tnvu4ZKGMy6q;n?|Z-B-=)!W5l}#fE%%%5$zk1J!8W#1Zso_MrddRM@C?5 z_$P*MYOKu+&)je?4A;_dt_+850Jv#8%$3tzy3B>!oO{ff*PQyyiQgOt%u&!BhRi|O zq=IQ|n!6FRA2oY1b7#x!#?4N`Y$wfD%50|1M#ijX&05Z^=FLjMEEmm^Vk#xGST+k4 zGha1xH8Wc`GYvD{G*c}z*)|g$Gu|};+>G_iXy1(NnHz>FP%}I*Lqjt-G6Q4NKQVn% zb8TjN=B9gLx|XJMWjbsVz%AQht(?}lqEZp7|K z?Ox2@*|NKFyOXfnNxPM@n`yg|vFlm8mb0sQyHc>rMZ2WfO35yk?Lx)QSM6NQ&erWr z!%jEtRLf4b?L^0pcWnT-V?8_Cw95z}WUrY~R#go7tYZ?Oxcf zrR`h+uuXp9y>jaHzS`$i)@;l92wqCzZ#}5y_cSHkUS(4-(}>Z9Q}v0>E|z} z54?qNhseg==CM8Mqhd#J@agG9>zEK+y!b=W%k2NEYv;+t>zA{@WJC zQK4JN8{bC$^d9=nO*&4n17k^Y`vc_VZ3bND>E+iEJiPw^F*a!1!;s>hd(y;p4(T4I zU%j3#-a(zGlWT4!H{D5o|1N61h5lELUU(@9-bgOHhOMlgXFPG|k@J1*^R1)n^j}|3 zKkKJtAA=bPk$;KNKR-`@@({i8c5>Ujzj}hAtayf8aXtB3m~Lw>3Ti&& zWQ=<*AZ`!&(h>T>Q)!*hv(F``yV!vrIKUA7@E*3}JxngWiu}_xtO37!JAG=KT)RQ8 zJ4%{o(7$)lFI`11@RLNAoZ}(yKS2Nd9R1!M>?z@OE#2W2*>F7TCaGrJIx?9PQ9-zO@P++{{4djuh$$d|f z>0|U;x6*$+MDKfw9ejU={N=rjdT;_o-Tg3epGQz4SO#f;f+F7VRs#4xdIN)U)1B+Y z~v&W!Ul=f(WK%>cb5H$Id7tqffrV!%V#RT#K-n|=X%T00iHh(o!$mZPy8$-)~ zc!q`}WIal5yo0=dKmGbm^y7zE8-WP@g@k_gF#W+@^pYS!CvU!s{OU=noyAtx4iiY? z-ZX(feh{O-c%1Ei_08nyJ>)wPW}2TqM4@Z!3<97==o3nP>^^{fL{M zc@DYyCT1=O|HG#-$$}s0-Q=9tkpGZay>Qc;-bJ>bC^CM*4mg4ZK>G1UqiXaAvH|ah zuVmcq-%kJ#rJx{?3zy#TTJm8hYwWL{qEEb+oZ%wS2~70MC+O$=6igmjXN`f^;oN$D8?}Oip!@hjQc_x3J^Ce;0l9S+*~HgnoS5$B2Ru zw?BB0=>ZnK_;Ti8w1q}k>!DU4g`)BE=Z~;(`1tws+FJ=adB#}`3-aOHx3MZ=7E}Nf z5CERSO6*PKwQ=&b8`xg~5ETI2R*JP6mIi7F4_biFb$*>i%Fbmpw81z@kA=pi94h zCj~}`Ep~vm!bPEBrh~fAbc47RO|U-RD{Q>o>DFf(~)RoevVI1xEXT zgP!GPo=1n~Z(CmDT6A0+@d%h3OPlt~u(3^$>x*cxJYp2n!Z`w;@Fx3Ppc z26re2>cjTGNYfwQ%RnL6j>iagK`F>7maTA&b<)T+$?8SF8)!GMMB8RTO zjeO%~`uPC;2uG1-hp%8Uf!emgC$5n7e|VO$3Wov;(iGg<+bm)ce2_bQhf#yP1C7XY zz=9b81*U_7`qxq<6V63^fxP9@6jnp0#fRBb5E{-#{M>#&i!!YI@mUt8aQdZJtrK5> zMIOle>?O>4m`boJj)$l|=3!Mn{4@#Q#*Fyl(-fGn7mD5nKNyXurFkY(2UH0A0K(Q| zWcNmj&v);jfoqBX2&4LQm(sr!*_r4fS_=bx@Wi^fuNyEMa_NBdowimsE|Jrrd4U7tGitK}I@IHgie=*2}h4%?~7P}ywFtnd~fxUtNKEik#(`xw)6BBlV zML{~$hbPekSQIKo9>6uI19^b_x^;`a`9Ruu@q^LPeb9$RjBE4&!HQDwUW9!>9ad&f zF_*$0I1+tEt(Y`$72b)U(%l=@StlW0@CXf|mM>q!oQ3z9%r@&AxWen=@vYG!=noyn zggBd!eFren3Aq)2_MN!C8rS=AeE{EI!T%8-II(_;Ldd}r*Zc8rr=PfH&%5_IUfIWq zYwmxodrn-lz0Nyv&GtWZ;{KN}BILsVb^n#PW_tq-IlAwZSFV@9a2u`YO8huQc3BY%B5z7CWB0h-Ry AX#fBK literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/planar-zip.tif b/tests/fixtures/codecs/tiff/planar-zip.tif new file mode 100644 index 0000000000000000000000000000000000000000..15390b00a52dcf37ea9fde637cd4a1ddfec4c74b GIT binary patch literal 2430 zcmYk8c|6qHAI85kmKaOP#Mq6pr7S7RwUm7;MwG14SQ@TuW9M38T(ULU$1aqzWQoMY zD9a2fW2|#6V{BnaDG_(vpFe)*yv}*v=XpJ!bIxDqbxcgo0(Kk#5Q1AH5}iLE0|4KM z7$qo=M0Ckrxp+vzPvo3P- zHeqv1S|}?LGE7KZ*I6QGFn)7E(jLm3fqxo%A)@ck*AzQg)%Fp!w)$(frzmQlJ~|zB zK>LW_Ur0V<)vEh@e!M)CvX2TK*_mGN%vfwVI0+?nijt-;pT_(AsE)mo6Srf(SosQV z%y&amwm(Kc7j)m0?ZG%S(eoOSo#*=BZeG~ryS|@4kYJaTe!qLFsNhYd9CPI)8L9EL zcaT*V!fqNOcVFC4jtc@UH7u7je7)wYW&P(@{e@FSfW)xR%#FQQ-DGmMg53%Dm+#{; zPv4rZQXjOZ6$#t&>pedCD01(oCvIpGTU91qwdh9t%q zsn`DA4z$!gR-A#(q8NAQv-ZX{>Gl0c7fANYNRCykV!s=iR39iau|Eb&;zld+Vp~++ zJxYmJ8smoDdDJgo27^2s?v-A>^~UMmHn43m7t&hBN^n?9W}xFB^s*h>o01POkZRp9)4 zeJu>B>EE-V!TM;z_s?Q^{Vy}JA;)hka|JGzK(!6-h|;||8NH;JL&a=xvxn$NkMV*ZU9P04VI&DODM z#A4gCvo42NSLi>Lr<1Q+eDrYXd=ntwTIyz9*-=RRW1FK3_9x|(cHv}1L``Z8LM?K# zF>J2XQ>O{*o{l=}jfwjserOQgZB{+(Z5npMs!|4iYAJqlJI(zH1%^H&H4 zb2pKWZHPrBBdXBwX0BMKc1#laeRxf7y{i%;cYa82sSEnn73mKV?gSPjZ+EQjG&a;y|0*k3Y71HsoKRTeu_P3RS#JyX z2yuMf7B&8Bav!e~cP;J-ub7yV#`AkBx!5UFzv|x?>Vw#1GB*=QGlqGL{_{~cWc`;gGn@v~*O1U=aU4dJ~u3k{nO znnKXW^fJ^V#hO&Im0312FL0%SAZssX)lW1}yk}sp+DbN-Y6*E=kH*&}QjOUBdh=e_ zy4!f@ECqV40Z9t~`~ttad4L9Fb-G#i$ySo7W`iPlkf8u} z8YeirO~isWW?!EXsLF}H;pPzEH#S5Qyd^`5NOexgs&sr%jxiwq;l)tddf$)T@Jciv zk`M?Kj+`N3e470RK6u`9!1%I7J%l)jX7QQwecv1AP-S$YvL^G(y&UCZerO>5t5%X@(vJ+43dk+_g)ir9)*EUI zNBjimibpIbr9$<<*uEzXiKw6r6S^#gpQBY`leyB2xB6M?mVfTlU36A-9%HKc0woVvO(9~NI2BMR5e<^P2 z`1|Z1u~oJB0Lpybf;aBsJ&YW=Z!NxLUFSgV&UgrpsOV-x&#u}$JNmJ~+Pr4|`)2kh z!N*qLII~>I5bRL8DVjEO$)9VUFXbWvQTusgNOhok6#FRC^_&{W^2ITtVwv7@6szL;aj?*;zRtJ&S8G$#G4s^&MGx zk8$Nyl1j(82nUFPvOJ?pH}5n+p_*~vRR{UfmO~>ARbji8tLg!R!FpwmnW{=tE^y-( zJ`ITrmGA&7hBL?z+#dl8+$<~vp|8e(fHZT}0 Date: Fri, 2 Oct 2026 09:37:52 +0000 Subject: [PATCH 019/188] feat(core): naming templates with tokens, formats and sanitizing Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Naming/NamingContext.cs | 36 +++ src/Titano.Core/Naming/PathTemplate.cs | 210 ++++++++++++++++++ .../Naming/PathTemplateTests.cs | 89 ++++++++ tests/Titano.Testing/Assert.cs | 11 + 4 files changed, 346 insertions(+) create mode 100644 src/Titano.Core/Naming/NamingContext.cs create mode 100644 src/Titano.Core/Naming/PathTemplate.cs create mode 100644 tests/Titano.Core.Tests/Naming/PathTemplateTests.cs diff --git a/src/Titano.Core/Naming/NamingContext.cs b/src/Titano.Core/Naming/NamingContext.cs new file mode 100644 index 00000000..59985897 --- /dev/null +++ b/src/Titano.Core/Naming/NamingContext.cs @@ -0,0 +1,36 @@ +namespace Titano.Core.Naming; + +/// Values available to folder/file templates for one frame (BRIEF §7.1). +public sealed record NamingContext +{ + /// Camera wall-clock capture time. + public DateTime CapturedAt { get; init; } + + /// Start of the session the frame belongs to. + public DateTime SessionStart { get; init; } + + /// 1-based session number within the import. + public int Session { get; init; } = 1; + + /// 1-based frame number across the import (or sequence). + public int Number { get; init; } = 1; + + /// 1-based frame number within the session. + public int NumberInSession { get; init; } = 1; + + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? Lens { get; init; } + public int? Iso { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + + /// Original file name without extension. + public string OriginalName { get; init; } = string.Empty; + + /// Original extension without the dot, as found on the card. + public string Extension { get; init; } = string.Empty; + + /// Sequence title, when the user gave one. + public string? Title { get; init; } +} diff --git a/src/Titano.Core/Naming/PathTemplate.cs b/src/Titano.Core/Naming/PathTemplate.cs new file mode 100644 index 00000000..37d50da7 --- /dev/null +++ b/src/Titano.Core/Naming/PathTemplate.cs @@ -0,0 +1,210 @@ +using System.Globalization; +using System.Text; + +namespace Titano.Core.Naming; + +/// A parse problem in a template, with the character position for live validation in the UI. +public sealed record TemplateError(int Position, string Code, string? Token); + +/// +/// Folder/file naming templates (BRIEF §7.1). Tokens are written as {name} or {name:format}, where the +/// format is passed to the .NET formatter (e.g. {n:0000}, {date:yyyyMMdd}). {{ and }} are literal +/// braces. Characters that are illegal in Windows/Linux file names are replaced, never passed through. +/// +public sealed class PathTemplate +{ + /// Every token the templates understand. Descriptions are localized resources Import.Token.<name>. + public static readonly IReadOnlyList Tokens = + [ + "year", "month", "day", "date", "time", "hm", "session", "sessionstart", "camera", "lens", + "iso", "shutter", "aperture", "n", "nsession", "name", "ext", "title", + ]; + + private static readonly HashSet TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase); + private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0']; + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + private readonly List _parts; + + private PathTemplate(string source, List parts, IReadOnlyList errors) + { + Source = source; + _parts = parts; + Errors = errors; + } + + public string Source { get; } + + /// Problems found while parsing; a template with errors still expands best-effort. + public IReadOnlyList Errors { get; } + + public bool IsValid => Errors.Count == 0; + + /// Parses a template; '/' separates folder levels (only meaningful for folder templates). + public static PathTemplate Parse(string template) + { + ArgumentNullException.ThrowIfNull(template); + var parts = new List(); + var errors = new List(); + var literal = new StringBuilder(); + for (var i = 0; i < template.Length; i++) + { + var c = template[i]; + if (c == '{') + { + if (i + 1 < template.Length && template[i + 1] == '{') + { + literal.Append('{'); + i++; + continue; + } + var close = template.IndexOf('}', i + 1); + if (close < 0) + { + errors.Add(new TemplateError(i, "UnclosedBrace", null)); + literal.Append(template, i, template.Length - i); + break; + } + if (literal.Length > 0) + { + parts.Add(Part.Literal(literal.ToString())); + literal.Clear(); + } + var body = template[(i + 1)..close]; + var colon = body.IndexOf(':', StringComparison.Ordinal); + var name = (colon < 0 ? body : body[..colon]).Trim(); + var format = colon < 0 ? null : body[(colon + 1)..]; + if (name.Length == 0) errors.Add(new TemplateError(i, "EmptyToken", null)); + else if (!TokenSet.Contains(name)) errors.Add(new TemplateError(i, "UnknownToken", name)); + parts.Add(Part.Token(name.ToLowerInvariant(), format)); + i = close; + } + else if (c == '}') + { + if (i + 1 < template.Length && template[i + 1] == '}') + { + literal.Append('}'); + i++; + continue; + } + errors.Add(new TemplateError(i, "UnopenedBrace", null)); + } + else + { + literal.Append(c); + } + } + if (literal.Length > 0) parts.Add(Part.Literal(literal.ToString())); + if (template.Trim().Length == 0) errors.Add(new TemplateError(0, "Empty", null)); + return new PathTemplate(template, parts, errors); + } + + /// Expands to a relative folder path (forward slashes; each segment sanitized). + public string ExpandFolder(NamingContext context) + { + var raw = Expand(context, allowSeparators: true); + var segments = raw.Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select(SanitizeSegment) + .Where(s => s.Length > 0); + return string.Join('/', segments); + } + + /// Expands to a file name; the original extension is appended unless the template already ends with {ext}. + public string ExpandFile(NamingContext context) + { + var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" }; + var name = SanitizeSegment(Expand(context, allowSeparators: false)); + if (name.Length == 0) name = SanitizeSegment(context.OriginalName); + if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension; + return name; + } + + private string Expand(NamingContext c, bool allowSeparators) + { + var inv = CultureInfo.InvariantCulture; + var sb = new StringBuilder(); + foreach (var part in _parts) + { + if (!part.IsToken) + { + sb.Append(allowSeparators ? part.Text.Replace('\\', '/') : part.Text); + continue; + } + var f = part.Format; + var value = part.Text switch + { + "year" => c.CapturedAt.ToString(f ?? "yyyy", inv), + "month" => c.CapturedAt.ToString(f ?? "MM", inv), + "day" => c.CapturedAt.ToString(f ?? "dd", inv), + "date" => c.CapturedAt.ToString(f ?? "yyyy-MM-dd", inv), + "time" => c.CapturedAt.ToString(f ?? "HH-mm-ss", inv), + "hm" => c.CapturedAt.ToString(f ?? "HH-mm", inv), + "sessionstart" => c.SessionStart.ToString(f ?? "yyyy-MM-dd HH-mm", inv), + "session" => c.Session.ToString(f ?? "0", inv), + "n" => c.Number.ToString(f ?? "0000", inv), + "nsession" => c.NumberInSession.ToString(f ?? "0000", inv), + "camera" => CameraName(c.CameraMake, c.CameraModel), + "lens" => c.Lens ?? string.Empty, + "iso" => c.Iso?.ToString(f ?? "0", inv) ?? string.Empty, + "shutter" => Shutter(c.ExposureTime), + "aperture" => c.FNumber is { } fn ? "f" + fn.ToString(f ?? "0.#", inv) : string.Empty, + "name" => c.OriginalName, + "ext" => c.Extension, + "title" => c.Title ?? string.Empty, + _ => string.Empty, + }; + // Token values never introduce folder levels. + sb.Append(value.Replace('/', '-').Replace('\\', '-')); + } + return sb.ToString(); + } + + /// "Canon EOS R5" from make "Canon" + model "Canon EOS R5"; avoids the duplicated brand most cameras report. + public static string CameraName(string? make, string? model) + { + make = make?.Trim(); + model = model?.Trim(); + if (string.IsNullOrEmpty(model)) return make ?? string.Empty; + if (string.IsNullOrEmpty(make)) return model; + var brand = make.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0]; + if (brand.Equals("NIKON", StringComparison.OrdinalIgnoreCase)) brand = "Nikon"; + if (model.StartsWith(brand, StringComparison.OrdinalIgnoreCase)) return brand + model[brand.Length..]; + return brand + " " + model; + } + + /// 1/250 s → "1-250", 2 s → "2s" (file-name safe). + public static string Shutter(double? seconds) + { + if (seconds is not > 0) return string.Empty; + var t = seconds.Value; + if (t >= 0.3) return t.ToString("0.#", CultureInfo.InvariantCulture) + "s"; + return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture); + } + + /// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces. + public static string SanitizeSegment(string segment) + { + var sb = new StringBuilder(segment.Length); + foreach (var ch in segment) + { + if (ch < 32 || Array.IndexOf(Illegal, ch) >= 0) sb.Append('_'); + else sb.Append(ch); + } + var s = sb.ToString().Trim().TrimEnd('.'); + while (s.Contains(" ", StringComparison.Ordinal)) s = s.Replace(" ", " ", StringComparison.Ordinal); + var stem = s.Split('.')[0]; + if (ReservedNames.Contains(stem)) s = "_" + s; + if (s is "." or "..") s = "_"; + return s.Length > 200 ? s[..200].TrimEnd() : s; + } + + private readonly record struct Part(bool IsToken, string Text, string? Format) + { + public static Part Literal(string text) => new(false, text, null); + public static Part Token(string name, string? format) => new(true, name, format); + } +} diff --git a/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs b/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs new file mode 100644 index 00000000..7b92e391 --- /dev/null +++ b/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs @@ -0,0 +1,89 @@ +using Titano.Core.Naming; +using Titano.Testing; + +namespace Titano.Core.Tests.Naming; + +public sealed class PathTemplateTests +{ + private static readonly NamingContext Frame = new() + { + CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11, 250), + SessionStart = new DateTime(2026, 9, 28, 18, 2, 11), + Session = 2, + Number = 1, + NumberInSession = 1, + CameraMake = "Canon", + CameraModel = "Canon EOS R5", + Lens = "RF24-70mm F2.8 L IS USM", + Iso = 400, + ExposureTime = 1.0 / 8, + FNumber = 8, + OriginalName = "IMG_0001", + Extension = "CR2", + Title = "Harbour sunset", + }; + + [Test] + public void DefaultTemplatesMatchTheBriefExample() + { + Assert.Equal("2026/2026-09-28 Canon EOS R5", PathTemplate.Parse(TemplateDefaults.Folder).ExpandFolder(Frame)); + Assert.Equal("2026-09-28_18-02-11_0001.CR2", PathTemplate.Parse(TemplateDefaults.File).ExpandFile(Frame)); + } + + [Theory] + [Case("{n:000000}", "000001.CR2")] + [Case("{date:yyyyMMdd}_{name}", "20260928_IMG_0001.CR2")] + [Case("{iso}_{shutter}_{aperture}", "400_1-8_f8.CR2")] + [Case("{name}.{ext}", "IMG_0001.CR2")] + [Case("{{literal}}_{n}", "{literal}_0001.CR2")] + [Case("{session}-{nsession:00}", "2-01.CR2")] + public void FileTokens(string template, string expected) => + Assert.Equal(expected, PathTemplate.Parse(template).ExpandFile(Frame)); + + [Test] + public void IllegalCharactersAreReplaced() + { + var context = Frame with { Title = "a:b*c?|e\"f" }; + Assert.Equal("a_b_c__d__e_f.CR2", PathTemplate.Parse("{title}").ExpandFile(context)); + } + + [Test] + public void TokenValuesNeverCreateFolders() + { + var context = Frame with { Lens = "18/55 mm" }; + Assert.Equal("2026/18-55 mm", PathTemplate.Parse("{year}/{lens}").ExpandFolder(context)); + } + + [Test] + public void ReservedWindowsNamesAreEscaped() => + Assert.Equal("_CON.CR2", PathTemplate.Parse("{title}").ExpandFile(Frame with { Title = "CON" })); + + [Test] + public void ErrorsCarryPositionAndToken() + { + var t = PathTemplate.Parse("{date}_{bogus}_{n"); + Assert.False(t.IsValid); + Assert.Contains(new TemplateError(7, "UnknownToken", "bogus"), t.Errors); + Assert.Contains(t.Errors, e => e.Code == "UnclosedBrace"); + } + + [Test] + public void EmptyExpansionFallsBackToOriginalName() => + Assert.Equal("IMG_0001.CR2", PathTemplate.Parse("{title}").ExpandFile(Frame with { Title = null })); + + [Theory] + [Case("NIKON CORPORATION", "NIKON Z 8", "Nikon Z 8")] + [Case("SONY", "ILCE-7M4", "SONY ILCE-7M4")] + [Case("Canon", "Canon EOS R5", "Canon EOS R5")] + [Case(null, "HERO12 Black", "HERO12 Black")] + public void CameraNameAvoidsDuplicatedBrand(string? make, string model, string expected) => + Assert.Equal(expected, PathTemplate.CameraName(make, model)); + + [Test] + public void ShutterFormatting() + { + Assert.Equal("1-250", PathTemplate.Shutter(0.004)); + Assert.Equal("2s", PathTemplate.Shutter(2)); + Assert.Equal(string.Empty, PathTemplate.Shutter(null)); + } +} diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs index 9982419f..95818620 100644 --- a/tests/Titano.Testing/Assert.cs +++ b/tests/Titano.Testing/Assert.cs @@ -142,6 +142,17 @@ public static class Assert if (!collection.Contains(expected)) Fail($"{expression}: does not contain {Format(expected)}"); } + /// At least one element satisfies . + public static T Contains(IEnumerable collection, Func predicate, [CallerArgumentExpression(nameof(predicate))] string? expression = null) + { + foreach (var item in collection) + { + if (predicate(item)) return item; + } + Fail($"No element matches {expression}"); + return default!; + } + public static void DoesNotContain(T unexpected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) { if (collection.Contains(unexpected)) Fail($"{expression}: unexpectedly contains {Format(unexpected)}"); From 2944e6ebb5e764e2ca5ddf793359eba10e4ca2aa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:38:20 +0000 Subject: [PATCH 020/188] ci: pin LF line endings and run CI once per pull request Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .gitattributes | 22 ++++++++++++++++++++++ .github/workflows/ci.yml | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..ee132e42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Normalise to LF everywhere (matches .editorconfig); Windows checkouts keep LF. +* text=auto eol=lf + +*.png binary +*.jpg binary +*.jpeg binary +*.ico binary +*.dng binary +*.tif binary +*.tiff binary +*.cr2 binary +*.cr3 binary +*.nef binary +*.arw binary +*.raf binary +*.heic binary +*.webp binary +*.gif binary +*.mp4 binary +*.avi binary +*.zip binary +*.pfx binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6088ed24..d7ba5ae9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: ["**"] + branches: [main] pull_request: workflow_dispatch: From f9b742b3b7384197e45ea7314db251324c3f5b83 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:38:57 +0000 Subject: [PATCH 021/188] feat(video): add NV12/P010 BT.709 limited-range converter with SIMD luma and parallel rows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/Yuv/Nv12Converter.cs | 299 ++++++++++++++++++ .../Video/Nv12ConverterTests.cs | 181 +++++++++++ 2 files changed, 480 insertions(+) create mode 100644 src/Titano.Core/Video/Yuv/Nv12Converter.cs create mode 100644 tests/Titano.Core.Tests/Video/Nv12ConverterTests.cs diff --git a/src/Titano.Core/Video/Yuv/Nv12Converter.cs b/src/Titano.Core/Video/Yuv/Nv12Converter.cs new file mode 100644 index 00000000..44b7f477 --- /dev/null +++ b/src/Titano.Core/Video/Yuv/Nv12Converter.cs @@ -0,0 +1,299 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; +using Titano.Core.Imaging; + +namespace Titano.Core.Video.Yuv; + +/// Position of 4:2:0 chroma samples relative to luma. +public enum ChromaSiting +{ + /// Co-sited with the left luma sample, vertically between rows (MPEG-2/H.264/HEVC default, chroma_sample_loc_type 0). + Left, + + /// Centred between four luma samples (JPEG/MPEG-1, chroma_sample_loc_type 1). + Center, +} + +/// +/// Linear-light RGB ⇄ BT.709 limited-range Y'CbCr 4:2:0: NV12 (8-bit) and P010 +/// (10-bit in the top bits of 16-bit words). The sRGB transfer is applied before the matrix, as encoders expect +/// display-referred input. Width and height must be even; luma is vectorised, rows run in parallel. +/// +public static class Nv12Converter +{ + private const float Kr = 0.2126f, Kg = 0.7152f, Kb = 0.0722f; + private const float CbScale = 1 / (2 * (1 - Kb)); // 1 / 1.8556 + private const float CrScale = 1 / (2 * (1 - Kr)); // 1 / 1.5748 + private const int ParallelThreshold = 1 << 16; + private static readonly float[] EncodeLut = BuildEncodeLut(); + + /// Bytes of an NV12 frame (elements of a P010 frame) for a row stride in bytes (elements). + public static int FrameLength(int stride, int height) => checked(stride * height * 3 / 2); + + /// Writes NV12: Y rows of bytes, then interleaved CbCr rows of the same stride. + public static unsafe void ToNv12(ImageBuffer source, Span destination, ChromaSiting siting = ChromaSiting.Left, int stride = 0) + { + stride = Validate(source.Width, source.Height, stride, destination.Length); + fixed (byte* d = destination) Convert(source, (nint)d, stride, siting, tenBit: false); + } + + /// Writes P010: as NV12 with 16-bit elements holding 10-bit codes in the top bits; counts elements. + public static unsafe void ToP010(ImageBuffer source, Span destination, ChromaSiting siting = ChromaSiting.Left, int stride = 0) + { + stride = Validate(source.Width, source.Height, stride, destination.Length); + fixed (ushort* d = destination) Convert(source, (nint)d, stride, siting, tenBit: true); + } + + /// NV12 back to linear RGB (chroma upsampled for the given siting); used for verification. + public static void FromNv12(ReadOnlySpan source, ImageBuffer destination, ChromaSiting siting = ChromaSiting.Left, int stride = 0) + { + stride = Validate(destination.Width, destination.Height, stride, source.Length); + var (luma, cb, cr) = Planes(destination.Width, destination.Height); + var w = destination.Width; + for (var y = 0; y < destination.Height; y++) + { + for (var x = 0; x < w; x++) luma[y * w + x] = (source[y * stride + x] - 16) / 219f; + } + var uv = source[(stride * destination.Height)..]; + for (var j = 0; j < destination.Height / 2; j++) + { + for (var i = 0; i < w / 2; i++) + { + cb[j * (w / 2) + i] = (uv[j * stride + 2 * i] - 128) / 224f; + cr[j * (w / 2) + i] = (uv[j * stride + 2 * i + 1] - 128) / 224f; + } + } + Reverse(destination, siting, luma, cb, cr); + } + + /// P010 back to linear RGB; used for verification. + public static void FromP010(ReadOnlySpan source, ImageBuffer destination, ChromaSiting siting = ChromaSiting.Left, int stride = 0) + { + stride = Validate(destination.Width, destination.Height, stride, source.Length); + var (luma, cb, cr) = Planes(destination.Width, destination.Height); + var w = destination.Width; + for (var y = 0; y < destination.Height; y++) + { + for (var x = 0; x < w; x++) luma[y * w + x] = ((source[y * stride + x] >> 6) - 64) / 876f; + } + var uv = source[(stride * destination.Height)..]; + for (var j = 0; j < destination.Height / 2; j++) + { + for (var i = 0; i < w / 2; i++) + { + cb[j * (w / 2) + i] = ((uv[j * stride + 2 * i] >> 6) - 512) / 896f; + cr[j * (w / 2) + i] = ((uv[j * stride + 2 * i + 1] >> 6) - 512) / 896f; + } + } + Reverse(destination, siting, luma, cb, cr); + } + + private static (float[] Luma, float[] Cb, float[] Cr) Planes(int width, int height) => + (new float[width * height], new float[width * height / 4], new float[width * height / 4]); + + private static int Validate(int width, int height, int stride, int length) + { + if ((width & 1) != 0 || (height & 1) != 0) throw new ArgumentException("4:2:0 needs even width and height"); + stride = stride == 0 ? width : stride; + if (stride < width) throw new ArgumentOutOfRangeException(nameof(stride)); + if (length < FrameLength(stride, height)) throw new ArgumentException("Buffer too small for the frame"); + return stride; + } + + private static void Convert(ImageBuffer source, nint destination, int stride, ChromaSiting siting, bool tenBit) + { + var pairs = source.Height / 2; + if (source.Width * source.Height < ParallelThreshold) + { + var scratch = new Scratch(source.Width); + for (var j = 0; j < pairs; j++) ConvertRowPair(source, destination, stride, j, siting, tenBit, scratch); + return; + } + Parallel.For(0, pairs, () => new Scratch(source.Width), (j, _, scratch) => + { + ConvertRowPair(source, destination, stride, j, siting, tenBit, scratch); + return scratch; + }, static _ => { }); + } + + private sealed class Scratch(int width) + { + public readonly float[] R0 = new float[width], G0 = new float[width], B0 = new float[width]; + public readonly float[] R1 = new float[width], G1 = new float[width], B1 = new float[width]; + } + + private static unsafe void ConvertRowPair(ImageBuffer source, nint destination, int stride, int pair, ChromaSiting siting, bool tenBit, Scratch s) + { + var width = source.Width; + var y0 = pair * 2; + EncodeRow(source, y0, s.R0, s.G0, s.B0); + EncodeRow(source, y0 + 1, s.R1, s.G1, s.B1); + var chromaRow = source.Height + pair; + if (tenBit) + { + var d = (ushort*)destination; + LumaRow10(s.R0, s.G0, s.B0, new Span(d + (long)y0 * stride, width)); + LumaRow10(s.R1, s.G1, s.B1, new Span(d + (long)(y0 + 1) * stride, width)); + var uv = new Span(d + (long)chromaRow * stride, width); + for (var i = 0; i < width / 2; i++) + { + var (cb, cr) = Chroma(s, i, siting); + uv[2 * i] = (ushort)(Quantize(cb, 896, 512, 1023) << 6); + uv[2 * i + 1] = (ushort)(Quantize(cr, 896, 512, 1023) << 6); + } + } + else + { + var d = (byte*)destination; + LumaRow8(s.R0, s.G0, s.B0, new Span(d + (long)y0 * stride, width)); + LumaRow8(s.R1, s.G1, s.B1, new Span(d + (long)(y0 + 1) * stride, width)); + var uv = new Span(d + (long)chromaRow * stride, width); + for (var i = 0; i < width / 2; i++) + { + var (cb, cr) = Chroma(s, i, siting); + uv[2 * i] = (byte)Quantize(cb, 224, 128, 255); + uv[2 * i + 1] = (byte)Quantize(cr, 224, 128, 255); + } + } + } + + /// sRGB-encodes one row into R'G'B' scratch rows (grey sources fill all three). + private static void EncodeRow(ImageBuffer source, int y, float[] r, float[] g, float[] b) + { + Encode(source.Row(0, y), r); + if (source.Channels == 1) + { + r.CopyTo(g, 0); + r.CopyTo(b, 0); + return; + } + Encode(source.Row(1, y), g); + Encode(source.Row(2, y), b); + } + + /// + /// Direct 16-bit lookup of the sRGB transfer: the steepest slope (12.92) keeps the error below 1e-4, + /// a tenth of a 10-bit code, at a fraction of the cost of the interpolated encoder. + /// + private static void Encode(ReadOnlySpan linear, float[] encoded) + { + var lut = EncodeLut; + for (var x = 0; x < linear.Length; x++) + { + var v = linear[x]; + v = v > 0f ? (v < 1f ? v : 1f) : 0f; // NaN → 0 + encoded[x] = lut[(int)(v * 65535f + 0.5f)]; + } + } + + private static float[] BuildEncodeLut() + { + var lut = new float[65536]; + for (var i = 0; i < lut.Length; i++) lut[i] = (float)ColorSpace.LinearToSrgb(i / 65535.0); + return lut; + } + + /// Filters R'G'B' of the 2×2 (centre) or 3×2 [1 2 1] (left) footprint, then applies the matrix. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static (float Cb, float Cr) Chroma(Scratch s, int i, ChromaSiting siting) + { + var x = 2 * i; + float r, g, b; + if (siting == ChromaSiting.Center) + { + r = (s.R0[x] + s.R0[x + 1] + s.R1[x] + s.R1[x + 1]) * 0.25f; + g = (s.G0[x] + s.G0[x + 1] + s.G1[x] + s.G1[x + 1]) * 0.25f; + b = (s.B0[x] + s.B0[x + 1] + s.B1[x] + s.B1[x + 1]) * 0.25f; + } + else + { + var l = x == 0 ? 0 : x - 1; + r = (s.R0[l] + 2 * s.R0[x] + s.R0[x + 1] + s.R1[l] + 2 * s.R1[x] + s.R1[x + 1]) * 0.125f; + g = (s.G0[l] + 2 * s.G0[x] + s.G0[x + 1] + s.G1[l] + 2 * s.G1[x] + s.G1[x + 1]) * 0.125f; + b = (s.B0[l] + 2 * s.B0[x] + s.B0[x + 1] + s.B1[l] + 2 * s.B1[x] + s.B1[x + 1]) * 0.125f; + } + var y = Kr * r + Kg * g + Kb * b; + return ((b - y) * CbScale, (r - y) * CrScale); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Quantize(float value, float scale, float offset, int max) => Math.Clamp((int)(value * scale + offset + 0.5f), 0, max); + + private static void LumaRow8(float[] r, float[] g, float[] b, Span y) + { + var x = 0; + if (Vector256.IsHardwareAccelerated) + { + var max = Vector256.Create(255); + for (; x <= r.Length - 32; x += 32) + { + var a = Luma(r, g, b, x, 219f, 16.5f, max); + var c = Luma(r, g, b, x + 8, 219f, 16.5f, max); + var e = Luma(r, g, b, x + 16, 219f, 16.5f, max); + var f = Luma(r, g, b, x + 24, 219f, 16.5f, max); + var low = Vector256.Narrow(a.AsUInt32(), c.AsUInt32()); + var high = Vector256.Narrow(e.AsUInt32(), f.AsUInt32()); + Vector256.Narrow(low, high).CopyTo(y[x..]); + } + } + for (; x < r.Length; x++) y[x] = (byte)Math.Clamp((int)((Kr * r[x] + Kg * g[x] + Kb * b[x]) * 219f + 16.5f), 0, 255); + } + + private static void LumaRow10(float[] r, float[] g, float[] b, Span y) + { + var x = 0; + if (Vector256.IsHardwareAccelerated) + { + var max = Vector256.Create(1023); + for (; x <= r.Length - 16; x += 16) + { + var a = Vector256.ShiftLeft(Luma(r, g, b, x, 876f, 64.5f, max), 6); + var c = Vector256.ShiftLeft(Luma(r, g, b, x + 8, 876f, 64.5f, max), 6); + Vector256.Narrow(a.AsUInt32(), c.AsUInt32()).CopyTo(y[x..]); + } + } + for (; x < r.Length; x++) y[x] = (ushort)(Math.Clamp((int)((Kr * r[x] + Kg * g[x] + Kb * b[x]) * 876f + 64.5f), 0, 1023) << 6); + } + + /// Eight luma codes: round(Y' × scale + offset) clamped to [0, max]. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector256 Luma(float[] r, float[] g, float[] b, int x, float scale, float offset, Vector256 max) + { + var y = Vector256.Create(r, x) * Kr + Vector256.Create(g, x) * Kg + Vector256.Create(b, x) * Kb; + var code = Vector256.ConvertToInt32(y * scale + Vector256.Create(offset)); + return Vector256.Min(Vector256.Max(code, Vector256.Zero), max); + } + + private static void Reverse(ImageBuffer destination, ChromaSiting siting, float[] luma, float[] cbPlane, float[] crPlane) + { + int width = destination.Width, height = destination.Height, half = width / 2; + for (var y = 0; y < height; y++) + { + var row = y / 2 * half; + for (var x = 0; x < width; x++) + { + var i = x / 2; + float cb = cbPlane[row + i], cr = crPlane[row + i]; + if (siting == ChromaSiting.Left && (x & 1) == 1) + { + // Odd luma columns sit halfway between two co-sited chroma samples. + var n = Math.Min(i + 1, half - 1); + cb = (cb + cbPlane[row + n]) * 0.5f; + cr = (cr + crPlane[row + n]) * 0.5f; + } + var yv = luma[y * width + x]; + if (destination.Channels == 1) + { + destination[0, x, y] = (float)ColorSpace.SrgbToLinear(Math.Clamp(yv, 0, 1)); + continue; + } + var r = yv + cr / CrScale; + var b = yv + cb / CbScale; + var g = (yv - Kr * r - Kb * b) / Kg; + destination[0, x, y] = (float)ColorSpace.SrgbToLinear(Math.Clamp(r, 0, 1)); + destination[1, x, y] = (float)ColorSpace.SrgbToLinear(Math.Clamp(g, 0, 1)); + destination[2, x, y] = (float)ColorSpace.SrgbToLinear(Math.Clamp(b, 0, 1)); + } + } + } +} diff --git a/tests/Titano.Core.Tests/Video/Nv12ConverterTests.cs b/tests/Titano.Core.Tests/Video/Nv12ConverterTests.cs new file mode 100644 index 00000000..5231b8a9 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/Nv12ConverterTests.cs @@ -0,0 +1,181 @@ +using Titano.Core.Imaging; +using Titano.Core.Video.Yuv; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class Nv12ConverterTests +{ + [Theory] + [Case(1f, 1f, 1f, 235, 128, 128)] + [Case(0f, 0f, 0f, 16, 128, 128)] + [Case(1f, 0f, 0f, 63, 102, 240)] + [Case(0f, 1f, 0f, 173, 42, 26)] + [Case(0f, 0f, 1f, 32, 240, 118)] + public void FlatColoursHitBt709LimitedRangeCodes(float r, float g, float b, int y, int u, int v) + { + using var image = Flat(8, 4, r, g, b); + var nv12 = new byte[Nv12Converter.FrameLength(8, 4)]; + Nv12Converter.ToNv12(image, nv12); + Assert.True(nv12.AsSpan(0, 32).ToArray().All(c => c == y), $"luma {nv12[0]} expected {y}"); + Assert.Equal((byte)u, nv12[32]); + Assert.Equal((byte)v, nv12[33]); + + var p010 = new ushort[Nv12Converter.FrameLength(8, 4)]; + Nv12Converter.ToP010(image, p010); + Assert.InRange(p010[0] >> 6, y * 4 - 2, y * 4 + 2); + Assert.Equal(0, p010[0] & 0x3F); + Assert.InRange(p010[32] >> 6, u * 4 - 2, u * 4 + 2); + } + + [Test] + public void TenBitWhiteAndBlackAreExact() + { + using var white = Flat(4, 2, 1, 1, 1); + var p010 = new ushort[Nv12Converter.FrameLength(4, 2)]; + Nv12Converter.ToP010(white, p010); + Assert.Equal((ushort)(940 << 6), p010[0]); + Assert.Equal((ushort)(512 << 6), p010[8]); + using var black = Flat(4, 2, 0, 0, 0); + Nv12Converter.ToP010(black, p010); + Assert.Equal((ushort)(64 << 6), p010[3]); + } + + [Theory] + [Case(70, 34)] + [Case(512, 256)] + public void LumaMatchesScalarReferenceIncludingRemainders(int width, int height) + { + using var image = Gradient(width, height); + var nv12 = new byte[Nv12Converter.FrameLength(width, height)]; + var p010 = new ushort[Nv12Converter.FrameLength(width, height)]; + Nv12Converter.ToNv12(image, nv12); + Nv12Converter.ToP010(image, p010); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var luma = 0.2126f * ColorSpace.EncodeFast(image[0, x, y]) + 0.7152f * ColorSpace.EncodeFast(image[1, x, y]) + 0.0722f * ColorSpace.EncodeFast(image[2, x, y]); + Assert.InRange(nv12[y * width + x], luma * 219 + 16 - 1, luma * 219 + 17); + Assert.InRange(p010[y * width + x] >> 6, luma * 876 + 64 - 1, luma * 876 + 65); + } + } + } + + [Theory] + [Case(ChromaSiting.Left)] + [Case(ChromaSiting.Center)] + public void RoundTripStaysWithinQuantisationError(ChromaSiting siting) + { + const int w = 256, h = 128; + using var image = Gradient(w, h); + using var back = new ImageBuffer(w, h); + var nv12 = new byte[Nv12Converter.FrameLength(w, h)]; + Nv12Converter.ToNv12(image, nv12, siting); + Nv12Converter.FromNv12(nv12, back, siting); + var maxNv12 = MaxEncodedError(image, back); + + var p010 = new ushort[Nv12Converter.FrameLength(w, h)]; + Nv12Converter.ToP010(image, p010, siting); + Nv12Converter.FromP010(p010, back, siting); + var maxP010 = MaxEncodedError(image, back); + + Assert.LessOrEqual(maxNv12, 3.5 / 255); + Assert.LessOrEqual(maxP010, 2.0 / 255); + Assert.Less(maxP010, maxNv12); + } + + [Test] + public void GreyRampRoundTripOnlyCarriesLumaQuantisation() + { + const int w = 256, h = 4; + using var image = new ImageBuffer(w, h, 1); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) image[0, x, y] = ColorSpace.Linear8((byte)x); + } + using var back = new ImageBuffer(w, h, 1); + var nv12 = new byte[Nv12Converter.FrameLength(w, h)]; + Nv12Converter.ToNv12(image, nv12); + Assert.True(nv12.AsSpan(w * h).ToArray().All(c => c == 128), "grey has neutral chroma"); + Nv12Converter.FromNv12(nv12, back); + double max = 0; + for (var i = 0; i < w * h; i++) max = Math.Max(max, Math.Abs(ColorSpace.LinearToSrgb(image.Plane(0)[i]) - ColorSpace.LinearToSrgb(back.Plane(0)[i]))); + // One limited-range step is 255/219 full-range levels; rounding keeps half of it. + Assert.LessOrEqual(max, 0.6 / 219); + } + + [Test] + public void SitingChangesTheChromaFilterFootprint() + { + // Columns: red, red | blue, blue. Centre siting keeps the second chroma pure blue, + // left siting (co-sited with column 2, taps 1:2:1) mixes in a quarter of red. + using var image = new ImageBuffer(4, 2); + for (var y = 0; y < 2; y++) + { + image[0, 0, y] = image[0, 1, y] = 1; + image[2, 2, y] = image[2, 3, y] = 1; + } + var centre = new byte[Nv12Converter.FrameLength(4, 2)]; + var left = new byte[Nv12Converter.FrameLength(4, 2)]; + Nv12Converter.ToNv12(image, centre, ChromaSiting.Center); + Nv12Converter.ToNv12(image, left, ChromaSiting.Left); + Assert.Equal((byte)240, centre[8 + 2]); // Cb of pure blue + Assert.Equal((byte)118, centre[8 + 3]); // Cr of pure blue + Assert.Equal((byte)240, left[8 + 1]); // Cr of pure red at column 0 + // R'G'B' = (0.25, 0, 0.75): Cb = (0.75 − 0.1073) / 1.8556 → 206, Cr = (0.25 − 0.1073) / 1.5748 → 148. + Assert.Equal((byte)206, left[8 + 2]); + Assert.Equal((byte)148, left[8 + 3]); + } + + [Test] + public void RespectsStrideAndRejectsOddSizes() + { + using var image = Flat(6, 2, 1, 1, 1); + var nv12 = new byte[Nv12Converter.FrameLength(16, 2)]; + nv12.AsSpan().Fill(7); + Nv12Converter.ToNv12(image, nv12, stride: 16); + Assert.Equal((byte)235, nv12[5]); + Assert.Equal((byte)7, nv12[6]); // padding untouched + Assert.Equal((byte)128, nv12[32]); + using var odd = new ImageBuffer(5, 2); + Assert.Throws(() => Nv12Converter.ToNv12(odd, new byte[64])); + } + + private static double MaxEncodedError(ImageBuffer a, ImageBuffer b) + { + double max = 0; + for (var c = 0; c < 3; c++) + { + var pa = a.Plane(c); + var pb = b.Plane(c); + for (var i = 0; i < pa.Length; i++) max = Math.Max(max, Math.Abs(ColorSpace.LinearToSrgb(pa[i]) - ColorSpace.LinearToSrgb(pb[i]))); + } + return max; + } + + private static ImageBuffer Flat(int w, int h, float r, float g, float b) + { + var image = new ImageBuffer(w, h); + image.Plane(0).Fill(r); + image.Plane(1).Fill(g); + image.Plane(2).Fill(b); + return image; + } + + /// Smooth colour ramps in encoded space (linearised), so 4:2:0 loss stays small. + private static ImageBuffer Gradient(int w, int h) + { + var image = new ImageBuffer(w, h); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + image[0, x, y] = (float)ColorSpace.SrgbToLinear(0.1 + 0.8 * x / w); + image[1, x, y] = (float)ColorSpace.SrgbToLinear(0.2 + 0.6 * y / h); + image[2, x, y] = (float)ColorSpace.SrgbToLinear(0.5 + 0.2 * Math.Sin((x + y) * 0.02)); + } + } + return image; + } +} From a09aa168763517babe0196b9be05a189dfcd311a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:40:33 +0000 Subject: [PATCH 022/188] feat(data): add database abstractions and SQLite binding IDatabase/IDbSession/IDbTransaction with positional $n parameters, typed DbParam and DbRow, SqlDialect helpers, and a P/Invoke binding to the system SQLite (winsqlite3 / libsqlite3) with WAL pragmas, statement cache, serialized writes, busy retry, interrupt-based cancellation, VACUUM INTO backups and restore. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/ConnectionString.cs | 111 ++++++++ src/Titano.Data/DatabaseException.cs | 34 +++ src/Titano.Data/DbParam.cs | 125 ++++++++ src/Titano.Data/DbRow.cs | 200 +++++++++++++ src/Titano.Data/DbSessionExtensions.cs | 55 ++++ src/Titano.Data/IDatabase.cs | 60 ++++ src/Titano.Data/SqlDialect.cs | 78 +++++ src/Titano.Data/Sqlite/SqliteConnection.cs | 209 ++++++++++++++ src/Titano.Data/Sqlite/SqliteDatabase.cs | 265 +++++++++++++++++ src/Titano.Data/Sqlite/SqliteException.cs | 19 ++ src/Titano.Data/Sqlite/SqliteNative.cs | 104 +++++++ src/Titano.Data/Sqlite/SqliteSession.cs | 315 +++++++++++++++++++++ src/Titano.Data/Sqlite/SqliteStatement.cs | 170 +++++++++++ src/Titano.Data/TextValues.cs | 135 +++++++++ 14 files changed, 1880 insertions(+) create mode 100644 src/Titano.Data/ConnectionString.cs create mode 100644 src/Titano.Data/DatabaseException.cs create mode 100644 src/Titano.Data/DbParam.cs create mode 100644 src/Titano.Data/DbRow.cs create mode 100644 src/Titano.Data/DbSessionExtensions.cs create mode 100644 src/Titano.Data/IDatabase.cs create mode 100644 src/Titano.Data/SqlDialect.cs create mode 100644 src/Titano.Data/Sqlite/SqliteConnection.cs create mode 100644 src/Titano.Data/Sqlite/SqliteDatabase.cs create mode 100644 src/Titano.Data/Sqlite/SqliteException.cs create mode 100644 src/Titano.Data/Sqlite/SqliteNative.cs create mode 100644 src/Titano.Data/Sqlite/SqliteSession.cs create mode 100644 src/Titano.Data/Sqlite/SqliteStatement.cs create mode 100644 src/Titano.Data/TextValues.cs diff --git a/src/Titano.Data/ConnectionString.cs b/src/Titano.Data/ConnectionString.cs new file mode 100644 index 00000000..849656e4 --- /dev/null +++ b/src/Titano.Data/ConnectionString.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using System.Text; + +namespace Titano.Data; + +/// +/// key=value;… connection strings. Keys are case- and space-insensitive (SslMode = Ssl Mode); +/// values may be single- or double-quoted, with the quote doubled inside. +/// +internal sealed class ConnectionString +{ + private readonly Dictionary _values = new(StringComparer.Ordinal); + private readonly HashSet _used = new(StringComparer.Ordinal); + + public ConnectionString(string text) + { + var i = 0; + while (i < text.Length) + { + var eq = text.IndexOf('=', i); + if (eq < 0) + { + if (text.AsSpan(i).Trim().Trim(';').IsEmpty) break; + throw new FormatException($"Connection string segment '{text[i..].Trim()}' has no '='."); + } + var key = Normalize(text.AsSpan(i, eq - i).Trim().TrimStart(';')); + i = eq + 1; + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + string value; + if (i < text.Length && text[i] is '"' or '\'') + { + var quote = text[i++]; + var sb = new StringBuilder(); + while (true) + { + if (i >= text.Length) throw new FormatException("Unterminated quoted value in connection string."); + if (text[i] == quote) + { + if (i + 1 < text.Length && text[i + 1] == quote) + { + sb.Append(quote); + i += 2; + continue; + } + i++; + break; + } + sb.Append(text[i++]); + } + value = sb.ToString(); + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (i < text.Length && text[i] != ';') throw new FormatException("Unexpected text after a quoted connection string value."); + } + else + { + var end = text.IndexOf(';', i); + if (end < 0) end = text.Length; + value = text[i..end].Trim(); + i = end; + } + if (key.Length == 0) throw new FormatException("Empty key in connection string."); + _values[key] = value; + if (i < text.Length && text[i] == ';') i++; + } + } + + /// First present key among (synonyms), or null. + public string? Get(params string[] keys) + { + foreach (var key in keys) + { + var normalized = Normalize(key); + if (_values.TryGetValue(normalized, out var value)) + { + _used.Add(normalized); + return value; + } + } + return null; + } + + public int GetInt(int defaultValue, params string[] keys) + { + var text = Get(keys); + if (text is null) return defaultValue; + return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) + ? value + : throw new FormatException($"Connection string value '{keys[0]}' must be an integer."); + } + + public bool Contains(string key) => _values.ContainsKey(Normalize(key)); + + /// Rejects keys that no call consumed, so typos do not pass silently. + public void ThrowOnUnknownKeys() + { + foreach (var key in _values.Keys) + { + if (!_used.Contains(key)) throw new FormatException($"Unknown connection string key '{key}'."); + } + } + + private static string Normalize(ReadOnlySpan key) + { + var sb = new StringBuilder(key.Length); + foreach (var c in key) + { + if (!char.IsWhiteSpace(c)) sb.Append(char.ToLowerInvariant(c)); + } + return sb.ToString(); + } +} diff --git a/src/Titano.Data/DatabaseException.cs b/src/Titano.Data/DatabaseException.cs new file mode 100644 index 00000000..413c271b --- /dev/null +++ b/src/Titano.Data/DatabaseException.cs @@ -0,0 +1,34 @@ +using System.Data.Common; + +namespace Titano.Data; + +/// Base of errors reported by a database engine; repositories test the kind without knowing the dialect. +public abstract class DatabaseException : DbException +{ + protected DatabaseException(string message, Exception? innerException = null) + : base(message, innerException) + { + } + + /// A UNIQUE or PRIMARY KEY constraint rejected the statement. + public virtual bool IsUniqueViolation => false; + + /// A FOREIGN KEY constraint rejected the statement. + public virtual bool IsForeignKeyViolation => false; +} + +/// The connection to the database server could not be established or was lost. +public sealed class DatabaseConnectionException(string message, Exception? innerException = null) + : DatabaseException(message, innerException) +{ + public override bool IsTransient => true; +} + +/// The database was migrated by a newer build; opening it would risk corrupting data this build does not know. +public sealed class SchemaTooNewException(int databaseVersion, int supportedVersion) + : InvalidOperationException($"The database schema version {databaseVersion} is newer than the version {supportedVersion} this build supports.") +{ + public int DatabaseVersion { get; } = databaseVersion; + + public int SupportedVersion { get; } = supportedVersion; +} diff --git a/src/Titano.Data/DbParam.cs b/src/Titano.Data/DbParam.cs new file mode 100644 index 00000000..f6790b84 --- /dev/null +++ b/src/Titano.Data/DbParam.cs @@ -0,0 +1,125 @@ +namespace Titano.Data; + +/// Logical type of a : decides the SQLite binding and the PostgreSQL parameter type. +public enum DbValueType +{ + /// Inferred from the CLR type of the value; a null stays untyped. + Auto, + Text, + Int32, + Int64, + Double, + Bool, + Uuid, + + /// An instant, stored in UTC (timestamptz / ISO-8601 text ending in Z). + Timestamp, + + /// A wall-clock date and time without offset (timestamp / ISO-8601 text without zone). + LocalDateTime, + + Bytes, + + /// JSON text (jsonb on PostgreSQL, TEXT on SQLite). + Json, +} + +/// +/// A positional statement parameter: the n-th parameter binds to $n in the SQL text on both dialects. +/// Implicit conversions keep the CLR type even for nulls, so (Guid?)null is still a typed uuid. +/// +public readonly struct DbParam +{ + public DbParam(object? value, DbValueType type = DbValueType.Auto, string? name = null) + { + Name = name; + Type = type == DbValueType.Auto && value is not null ? Infer(value) : type; + Value = value is null ? null : Normalize(value, Type); + } + + /// Optional label used in diagnostics only; binding is by position. + public string? Name { get; } + + /// + /// The value in the canonical CLR form of : string (Text, Json), int, long, double, bool, + /// Guid, DateTimeOffset (Timestamp), DateTime (LocalDateTime) or byte[]. + /// + public object? Value { get; } + + /// Effective type; only for an untyped null. + public DbValueType Type { get; } + + /// An untyped SQL NULL. + public static DbParam Null => default; + + public static DbParam Text(string? value) => new(value, DbValueType.Text); + public static DbParam Json(string? value) => new(value, DbValueType.Json); + public static DbParam Bytes(byte[]? value) => new(value, DbValueType.Bytes); + + /// Maps a CLR value to the type it binds as; throws for unsupported types. + public static DbValueType Infer(object value) => value switch + { + string => DbValueType.Text, + int or short or byte or sbyte or ushort => DbValueType.Int32, + long or uint or ulong => DbValueType.Int64, + double or float => DbValueType.Double, + bool => DbValueType.Bool, + Guid => DbValueType.Uuid, + DateTimeOffset => DbValueType.Timestamp, + DateTime d => d.Kind == DateTimeKind.Unspecified ? DbValueType.LocalDateTime : DbValueType.Timestamp, + byte[] => DbValueType.Bytes, + Enum => DbValueType.Int64, + _ => throw new NotSupportedException($"Parameter values of type {value.GetType().Name} are not supported."), + }; + + private static object Normalize(object value, DbValueType type) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + return type switch + { + DbValueType.Text or DbValueType.Json => value as string ?? Convert.ToString(value, inv) ?? string.Empty, + DbValueType.Int32 => value is int ? value : Convert.ToInt32(value, inv), + DbValueType.Int64 => value is long ? value : Convert.ToInt64(value, inv), + DbValueType.Double => value is double ? value : Convert.ToDouble(value, inv), + DbValueType.Bool => value is bool ? value : Convert.ToBoolean(value, inv), + DbValueType.Uuid => value is Guid ? value : Guid.Parse(Convert.ToString(value, inv)!), + DbValueType.Timestamp => value switch + { + DateTimeOffset o => o, + DateTime { Kind: DateTimeKind.Unspecified } d => new DateTimeOffset(d, TimeSpan.Zero), + DateTime d => new DateTimeOffset(d.ToUniversalTime()), + _ => throw new NotSupportedException($"Cannot bind {value.GetType().Name} as a timestamp."), + }, + DbValueType.LocalDateTime => value switch + { + DateTime d => d, + DateTimeOffset o => o.DateTime, + _ => throw new NotSupportedException($"Cannot bind {value.GetType().Name} as a date-time."), + }, + DbValueType.Bytes => value as byte[] ?? throw new NotSupportedException($"Cannot bind {value.GetType().Name} as bytes."), + _ => value, + }; + } + + public static implicit operator DbParam(string? value) => new(value, DbValueType.Text); + public static implicit operator DbParam(byte[]? value) => new(value, DbValueType.Bytes); + public static implicit operator DbParam(int value) => new(value, DbValueType.Int32); + public static implicit operator DbParam(int? value) => new(value, DbValueType.Int32); + public static implicit operator DbParam(long value) => new(value, DbValueType.Int64); + public static implicit operator DbParam(long? value) => new(value, DbValueType.Int64); + public static implicit operator DbParam(double value) => new(value, DbValueType.Double); + public static implicit operator DbParam(double? value) => new(value, DbValueType.Double); + public static implicit operator DbParam(bool value) => new(value, DbValueType.Bool); + public static implicit operator DbParam(bool? value) => new(value, DbValueType.Bool); + public static implicit operator DbParam(Guid value) => new(value, DbValueType.Uuid); + public static implicit operator DbParam(Guid? value) => new(value, DbValueType.Uuid); + public static implicit operator DbParam(DateTimeOffset value) => new(value, DbValueType.Timestamp); + public static implicit operator DbParam(DateTimeOffset? value) => new(value, DbValueType.Timestamp); + + /// Unspecified-kind values are wall-clock times; UTC/local kinds are instants. + public static implicit operator DbParam(DateTime value) => new(value); + + public static implicit operator DbParam(DateTime? value) => value is { } v ? new(v) : new(null, DbValueType.LocalDateTime); + + public override string ToString() => $"{Name ?? "?"}:{Type}={Value ?? "NULL"}"; +} diff --git a/src/Titano.Data/DbRow.cs b/src/Titano.Data/DbRow.cs new file mode 100644 index 00000000..7af799c7 --- /dev/null +++ b/src/Titano.Data/DbRow.cs @@ -0,0 +1,200 @@ +using System.Globalization; + +namespace Titano.Data; + +/// Column names of a result set, shared by all of its rows. +internal sealed class DbColumns(string[] names) +{ + private Dictionary? _ordinals; + + public string[] Names { get; } = names; + + public int GetOrdinal(string name) + { + if (_ordinals is null) + { + var map = new Dictionary(Names.Length, StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < Names.Length; i++) map.TryAdd(Names[i], i); + _ordinals = map; + } + return _ordinals.TryGetValue(name, out var ordinal) + ? ordinal + : throw new IndexOutOfRangeException($"No column named '{name}' in the result."); + } +} + +/// +/// One materialised result row. Values keep the provider's natural CLR type (SQLite: long, double, string, +/// byte[]; PostgreSQL: decoded by type OID) and the typed getters convert between compatible forms, so the +/// same mapping code reads both dialects (e.g. a SQLite TEXT uuid through ). +/// Rows stay valid after the enumeration that produced them ends. +/// +public sealed class DbRow +{ + private readonly DbColumns _columns; + private readonly object?[] _values; + + internal DbRow(DbColumns columns, object?[] values) + { + _columns = columns; + _values = values; + } + + public int FieldCount => _values.Length; + + public string GetName(int ordinal) => _columns.Names[ordinal]; + + /// Case-insensitive column lookup; the first column with that name wins. + public int GetOrdinal(string name) => _columns.GetOrdinal(name); + + public bool IsNull(int ordinal) => _values[ordinal] is null; + + public object? GetValue(int ordinal) => _values[ordinal]; + + public string GetString(int ordinal) => GetStringOrNull(ordinal) ?? throw NullValue(ordinal); + public int GetInt32(int ordinal) => GetInt32OrNull(ordinal) ?? throw NullValue(ordinal); + public long GetInt64(int ordinal) => GetInt64OrNull(ordinal) ?? throw NullValue(ordinal); + public double GetDouble(int ordinal) => GetDoubleOrNull(ordinal) ?? throw NullValue(ordinal); + public bool GetBool(int ordinal) => GetBoolOrNull(ordinal) ?? throw NullValue(ordinal); + public Guid GetGuid(int ordinal) => GetGuidOrNull(ordinal) ?? throw NullValue(ordinal); + public DateTimeOffset GetDateTimeOffset(int ordinal) => GetDateTimeOffsetOrNull(ordinal) ?? throw NullValue(ordinal); + public DateTime GetDateTime(int ordinal) => GetDateTimeOrNull(ordinal) ?? throw NullValue(ordinal); + public byte[] GetBytes(int ordinal) => GetBytesOrNull(ordinal) ?? throw NullValue(ordinal); + + public string? GetStringOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + string s => s, + Guid g => TextValues.FormatGuid(g), + DateTimeOffset o => TextValues.FormatTimestamp(o), + DateTime d => TextValues.FormatLocal(d), + byte[] => throw Mismatch(ordinal, "string"), + var v => Convert.ToString(v, CultureInfo.InvariantCulture), + }; + + public int? GetInt32OrNull(int ordinal) => _values[ordinal] switch + { + null => null, + int i => i, + var v => checked((int)ToInt64(ordinal, v)), + }; + + public long? GetInt64OrNull(int ordinal) => _values[ordinal] is { } v ? ToInt64(ordinal, v) : null; + + public double? GetDoubleOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + double d => d, + long l => l, + int i => i, + float f => f, + string s => double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture), + _ => throw Mismatch(ordinal, "double"), + }; + + public bool? GetBoolOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + bool b => b, + long l => l != 0, + int i => i != 0, + _ => throw Mismatch(ordinal, "bool"), + }; + + public Guid? GetGuidOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + Guid g => g, + string s => Guid.Parse(s), + _ => throw Mismatch(ordinal, "Guid"), + }; + + /// Instants: timestamptz values, ISO-8601 text, or timestamp values taken as UTC. + public DateTimeOffset? GetDateTimeOffsetOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + DateTimeOffset o => o, + string s => TextValues.ParseTimestamp(s), + DateTime d => new DateTimeOffset(DateTime.SpecifyKind(d, DateTimeKind.Utc)), + _ => throw Mismatch(ordinal, "DateTimeOffset"), + }; + + /// Wall-clock date-times (unspecified kind); instants are returned as UTC. + public DateTime? GetDateTimeOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + DateTime d => d, + string s => TextValues.ParseLocal(s), + DateTimeOffset o => o.UtcDateTime, + DateOnly d => d.ToDateTime(TimeOnly.MinValue), + _ => throw Mismatch(ordinal, "DateTime"), + }; + + public byte[]? GetBytesOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + byte[] b => b, + _ => throw Mismatch(ordinal, "byte[]"), + }; + + public string GetString(string name) => GetString(GetOrdinal(name)); + public string? GetStringOrNull(string name) => GetStringOrNull(GetOrdinal(name)); + public int GetInt32(string name) => GetInt32(GetOrdinal(name)); + public int? GetInt32OrNull(string name) => GetInt32OrNull(GetOrdinal(name)); + public long GetInt64(string name) => GetInt64(GetOrdinal(name)); + public long? GetInt64OrNull(string name) => GetInt64OrNull(GetOrdinal(name)); + public double GetDouble(string name) => GetDouble(GetOrdinal(name)); + public double? GetDoubleOrNull(string name) => GetDoubleOrNull(GetOrdinal(name)); + public bool GetBool(string name) => GetBool(GetOrdinal(name)); + public bool? GetBoolOrNull(string name) => GetBoolOrNull(GetOrdinal(name)); + public Guid GetGuid(string name) => GetGuid(GetOrdinal(name)); + public Guid? GetGuidOrNull(string name) => GetGuidOrNull(GetOrdinal(name)); + public DateTimeOffset GetDateTimeOffset(string name) => GetDateTimeOffset(GetOrdinal(name)); + public DateTimeOffset? GetDateTimeOffsetOrNull(string name) => GetDateTimeOffsetOrNull(GetOrdinal(name)); + public DateTime GetDateTime(string name) => GetDateTime(GetOrdinal(name)); + public DateTime? GetDateTimeOrNull(string name) => GetDateTimeOrNull(GetOrdinal(name)); + public byte[] GetBytes(string name) => GetBytes(GetOrdinal(name)); + public byte[]? GetBytesOrNull(string name) => GetBytesOrNull(GetOrdinal(name)); + + /// + /// Generic read used by scalar helpers: string, int, long, double, bool, Guid, DateTimeOffset, DateTime, + /// byte[], their nullable forms and enums (from integers). A null reads as default. + /// + public T? Get(int ordinal) + { + if (_values[ordinal] is null) return default; + var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); + object value = target switch + { + _ when target == typeof(string) => GetString(ordinal), + _ when target == typeof(int) => GetInt32(ordinal), + _ when target == typeof(long) => GetInt64(ordinal), + _ when target == typeof(double) => GetDouble(ordinal), + _ when target == typeof(bool) => GetBool(ordinal), + _ when target == typeof(Guid) => GetGuid(ordinal), + _ when target == typeof(DateTimeOffset) => GetDateTimeOffset(ordinal), + _ when target == typeof(DateTime) => GetDateTime(ordinal), + _ when target == typeof(byte[]) => GetBytes(ordinal), + { IsEnum: true } => Enum.ToObject(target, GetInt64(ordinal)), + _ => _values[ordinal] is T ? _values[ordinal]! : throw Mismatch(ordinal, target.Name), + }; + return (T)value; + } + + private long ToInt64(int ordinal, object value) => value switch + { + long l => l, + int i => i, + short s => s, + bool b => b ? 1 : 0, + double d when d == Math.Floor(d) && d is >= long.MinValue and < long.MaxValue => (long)d, + string s => long.Parse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture), + _ => throw Mismatch(ordinal, "integer"), + }; + + private InvalidCastException NullValue(int ordinal) => + new($"Column '{_columns.Names[ordinal]}' is NULL."); + + private InvalidCastException Mismatch(int ordinal, string target) => + new($"Column '{_columns.Names[ordinal]}' holds {_values[ordinal]!.GetType().Name}, which cannot be read as {target}."); +} diff --git a/src/Titano.Data/DbSessionExtensions.cs b/src/Titano.Data/DbSessionExtensions.cs new file mode 100644 index 00000000..af6fb729 --- /dev/null +++ b/src/Titano.Data/DbSessionExtensions.cs @@ -0,0 +1,55 @@ +namespace Titano.Data; + +/// Single-row, list and scalar helpers over . +public static class DbSessionExtensions +{ + /// The only row, or null when there is none; more than one row is an error. + public static async Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + DbRow? found = null; + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + { + if (found is not null) throw new InvalidOperationException("The query returned more than one row."); + found = row; + } + return found; + } + + public static Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.QuerySingleOrDefaultAsync(sql, parameters, CancellationToken.None); + + /// The only row; none or more than one is an error. + public static async Task QuerySingleAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) => + await session.QuerySingleOrDefaultAsync(sql, parameters, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("The query returned no rows."); + + public static Task QuerySingleAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.QuerySingleAsync(sql, parameters, CancellationToken.None); + + /// Maps the only row, or returns default when there is none. + public static async Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) + { + var row = await session.QuerySingleOrDefaultAsync(sql, parameters, cancellationToken).ConfigureAwait(false); + return row is null ? default : map(row); + } + + /// Maps every row into a list. + public static async Task> QueryListAsync(this IDbSession session, string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) + { + var list = new List(); + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + list.Add(map(row)); + return list; + } + + /// First column of the first row converted with ; default when there is no row or it is NULL. + public static async Task ScalarAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + return row.Get(0); + return default; + } + + public static Task ScalarAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.ScalarAsync(sql, parameters, CancellationToken.None); +} diff --git a/src/Titano.Data/IDatabase.cs b/src/Titano.Data/IDatabase.cs new file mode 100644 index 00000000..9c58d185 --- /dev/null +++ b/src/Titano.Data/IDatabase.cs @@ -0,0 +1,60 @@ +namespace Titano.Data; + +/// A database (SQLite file or PostgreSQL server) that hands out pooled sessions (BRIEF §6.1). +public interface IDatabase : IAsyncDisposable +{ + Dialect Dialect { get; } + + /// Rents a connection from the pool; dispose the session to return it. + Task OpenAsync(CancellationToken cancellationToken); +} + +/// +/// One pooled connection. SQL uses positional $1…$n placeholders on both dialects. A session is not +/// thread-safe: run one command at a time and finish (or dispose) a query enumeration before the next command. +/// +public interface IDbSession : IAsyncDisposable +{ + Dialect Dialect { get; } + + /// True between and commit/rollback. + bool InTransaction { get; } + + /// Runs one statement and returns the number of rows it inserted, updated or deleted. + Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken); + + /// Streams the rows of one statement. + IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken); + + /// Runs a parameterless multi-statement script (migrations, maintenance). + Task ExecuteScriptAsync(string script, CancellationToken cancellationToken); + + /// + /// Starts a transaction (BEGIN IMMEDIATE on SQLite, so writers queue up front instead of failing later). + /// Nested transactions are not supported. + /// + Task BeginAsync(CancellationToken cancellationToken); + + /// + /// Inserts many rows: COPY … FROM STDIN on PostgreSQL, multi-row INSERTs in one transaction on SQLite. + /// Each row array is consumed before the next one is requested, so producers may reuse it. + /// + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows, CancellationToken cancellationToken); + + Task ExecuteAsync(string sql, params DbParam[] parameters) => ExecuteAsync(sql, parameters, CancellationToken.None); + + IAsyncEnumerable QueryAsync(string sql, params DbParam[] parameters) => QueryAsync(sql, parameters, CancellationToken.None); + + Task BeginAsync() => BeginAsync(CancellationToken.None); + + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows) => + BulkInsertAsync(table, columns, rows, CancellationToken.None); +} + +/// An open transaction; disposing it without rolls it back. +public interface IDbTransaction : IAsyncDisposable +{ + Task CommitAsync(CancellationToken cancellationToken = default); + + Task RollbackAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Titano.Data/SqlDialect.cs b/src/Titano.Data/SqlDialect.cs new file mode 100644 index 00000000..1581a9ad --- /dev/null +++ b/src/Titano.Data/SqlDialect.cs @@ -0,0 +1,78 @@ +using System.Text; + +namespace Titano.Data; + +/// +/// The few SQL fragments that differ between SQLite (≥ 3.31) and PostgreSQL. Everything else in the +/// repositories is plain SQL that both accept: $n placeholders, ON CONFLICT … DO UPDATE, +/// TRUE/FALSE, NULLS LAST, LIKE … ESCAPE. +/// +public sealed class SqlDialect +{ + /// Separator of lists (ASCII unit separator, never part of a tag). + public const char ListSeparator = '\u001f'; + + private SqlDialect(Dialect dialect) => Dialect = dialect; + + public static SqlDialect Sqlite { get; } = new(Dialect.Sqlite); + + public static SqlDialect Postgres { get; } = new(Dialect.Postgres); + + public Dialect Dialect { get; } + + public bool IsPostgres => Dialect == Dialect.Postgres; + + public static SqlDialect For(Dialect dialect) => dialect == Dialect.Postgres ? Postgres : Sqlite; + + /// Row lock for read-modify-write inside a transaction; empty on SQLite, whose BEGIN IMMEDIATE already holds the write lock. + public string ForUpdate => IsPostgres ? " FOR UPDATE" : string.Empty; + + /// Calendar year of a timestamp column (SQLite stores ISO-8601 text). + public string Year(string expression) => IsPostgres + ? $"CAST(EXTRACT(YEAR FROM {expression}) AS integer)" + : $"CAST(substr({expression}, 1, 4) AS INTEGER)"; + + /// Month (1–12) of a timestamp column. + public string Month(string expression) => IsPostgres + ? $"CAST(EXTRACT(MONTH FROM {expression}) AS integer)" + : $"CAST(substr({expression}, 6, 2) AS INTEGER)"; + + /// Aggregate that joins the group's values with (order unspecified). + public string StringAgg(string expression) => IsPostgres + ? $"string_agg({expression}, chr(31))" + : $"group_concat({expression}, char(31))"; + + /// + /// INSERT … VALUES ($1…$n) ON CONFLICT (keys) DO UPDATE SET …; the first + /// columns form the conflict target. The syntax is shared by SQLite ≥ 3.24 and PostgreSQL ≥ 9.5. + /// + public static string Upsert(string table, IReadOnlyList columns, int keyCount) + { + ArgumentOutOfRangeException.ThrowIfLessThan(keyCount, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(keyCount, columns.Count); + var sb = new StringBuilder("INSERT INTO ").Append(table).Append(" (").AppendJoin(", ", columns).Append(") VALUES ("); + for (var i = 1; i <= columns.Count; i++) sb.Append(i > 1 ? ", $" : "$").Append(i); + sb.Append(") ON CONFLICT ("); + for (var i = 0; i < keyCount; i++) sb.Append(i > 0 ? ", " : string.Empty).Append(columns[i]); + if (keyCount == columns.Count) return sb.Append(") DO NOTHING").ToString(); + sb.Append(") DO UPDATE SET "); + for (var i = keyCount; i < columns.Count; i++) + sb.Append(i > keyCount ? ", " : string.Empty).Append(columns[i]).Append(" = excluded.").Append(columns[i]); + return sb.ToString(); + } + + /// Double-quotes an identifier (both dialects). + public static string QuoteIdentifier(string name) => "\"" + name.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""; + + /// A LIKE … ESCAPE '\' pattern that matches anywhere. + public static string ContainsPattern(string text) + { + var sb = new StringBuilder(text.Length + 2).Append('%'); + foreach (var c in text) + { + if (c is '%' or '_' or '\\') sb.Append('\\'); + sb.Append(c); + } + return sb.Append('%').ToString(); + } +} diff --git a/src/Titano.Data/Sqlite/SqliteConnection.cs b/src/Titano.Data/Sqlite/SqliteConnection.cs new file mode 100644 index 00000000..b81c7f10 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteConnection.cs @@ -0,0 +1,209 @@ +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// One native SQLite connection with its pragmas and an LRU cache of prepared statements. +internal sealed unsafe class SqliteConnection : IDisposable +{ + private const int StatementCacheCapacity = 64; + private const string Pragmas = + "PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA temp_store=MEMORY; " + + "PRAGMA cache_size=-65536; PRAGMA mmap_size=268435456;"; + + private readonly Dictionary> _cache = new(StringComparer.Ordinal); + private readonly LinkedList _lru = new(); + + private SqliteConnection(nint handle) => Handle = handle; + + public nint Handle { get; private set; } + + public bool IsAutoCommit => sqlite3_get_autocommit(Handle) != 0; + + /// Rows changed by INSERT/UPDATE/DELETE since the connection opened (DDL does not count). + public int TotalChanges => sqlite3_total_changes(Handle); + + /// Rows changed by the most recent INSERT/UPDATE/DELETE. + public int Changes => sqlite3_changes(Handle); + + /// Opens a read-write connection and applies the BRIEF §6.2 pragmas (WAL only for files). + public static SqliteConnection Open(string filename, bool isMemory, int busyTimeoutMs) + { + var connection = OpenRaw(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI | SQLITE_OPEN_NOMUTEX); + try + { + sqlite3_busy_timeout(connection.Handle, busyTimeoutMs); + connection.Exec(isMemory ? Pragmas : "PRAGMA journal_mode=WAL; " + Pragmas); + return connection; + } + catch + { + connection.Dispose(); + throw; + } + } + + public static SqliteConnection OpenReadOnly(string path) => + OpenRaw(path, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX); + + private static SqliteConnection OpenRaw(string filename, int flags) + { + nint db; + int rc; + fixed (byte* p = NullTerminated(filename)) rc = sqlite3_open_v2(p, out db, flags, null); + if (rc != SQLITE_OK) + { + var message = db != 0 ? Utf8(sqlite3_errmsg(db)) : null; + if (db != 0) sqlite3_close_v2(db); + throw new SqliteException($"Cannot open SQLite database '{filename}': {message ?? "error " + rc}", rc); + } + sqlite3_extended_result_codes(db, 1); + return new SqliteConnection(db); + } + + /// Runs one or more parameterless statements. + public void Exec(string sql) + { + byte* error; + int rc; + fixed (byte* p = NullTerminated(sql)) rc = sqlite3_exec(Handle, p, 0, 0, out error); + if (rc == SQLITE_OK) return; + var message = Utf8(error) ?? $"SQLite error {rc}"; + sqlite3_free(error); + throw new SqliteException(message, rc); + } + + /// Takes a statement from the cache (or prepares one); give it back with . + public SqliteStatement Rent(string sql) + { + if (_cache.TryGetValue(sql, out var node)) + { + if (!node.Value.InUse) + { + _lru.Remove(node); + _lru.AddFirst(node); + node.Value.InUse = true; + return node.Value; + } + // Same SQL already running on this connection (nested enumeration): use a private copy. + var copy = Prepare(sql); + copy.InUse = true; + return copy; + } + + var statement = Prepare(sql); + statement.InUse = true; + statement.Cached = true; + _cache[sql] = _lru.AddFirst(statement); + if (_lru.Count > StatementCacheCapacity && _lru.Last is { Value.InUse: false } last) + { + _lru.RemoveLast(); + _cache.Remove(last.Value.Sql); + last.Value.Dispose(); + } + return statement; + } + + public void Return(SqliteStatement statement) + { + statement.InUse = false; + if (statement.Cached) statement.Reset(); + else statement.Dispose(); + } + + public void Interrupt() => sqlite3_interrupt(Handle); + + public SqliteException Error(int rc) => new(Utf8(sqlite3_errmsg(Handle)) ?? $"SQLite error {rc}", rc); + + public void Dispose() + { + if (Handle == 0) return; + foreach (var statement in _lru) statement.Dispose(); + _lru.Clear(); + _cache.Clear(); + sqlite3_close_v2(Handle); + Handle = 0; + } + + private SqliteStatement Prepare(string sql) + { + var bytes = Encoding.UTF8.GetBytes(SqliteSqlText.TranslatePlaceholders(sql)); + fixed (byte* p = bytes) + { + var rc = sqlite3_prepare_v2(Handle, p, bytes.Length, out var statement, out var tail); + if (rc != SQLITE_OK) throw Error(rc); + if (statement == 0) throw new ArgumentException("The SQL text contains no statement.", nameof(sql)); + var rest = bytes.Length - (int)(tail - p); + if (rest > 0 && HasStatement(tail, rest)) + { + sqlite3_finalize(statement); + throw new ArgumentException("Only one statement per command is allowed; use ExecuteScriptAsync for scripts.", nameof(sql)); + } + return new SqliteStatement(this, statement, sql); + } + } + + /// True when the remaining text holds more than whitespace and comments. + private bool HasStatement(byte* text, int length) + { + var rc = sqlite3_prepare_v2(Handle, text, length, out var statement, out _); + if (statement != 0) sqlite3_finalize(statement); + return rc != SQLITE_OK || statement != 0; + } + + private static byte[] NullTerminated(string s) + { + var bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1]; + Encoding.UTF8.GetBytes(s, bytes); + return bytes; + } +} + +/// Rewrites $n placeholders for SQLite, which numbers $name parameters by first appearance. +internal static class SqliteSqlText +{ + /// Turns $n into ?n outside string literals, quoted identifiers and comments. + public static string TranslatePlaceholders(string sql) + { + if (!sql.Contains('$', StringComparison.Ordinal)) return sql; + var sb = new StringBuilder(sql.Length); + var i = 0; + while (i < sql.Length) + { + var c = sql[i]; + var next = i + 1 < sql.Length ? sql[i + 1] : '\0'; + int end; + switch (c) + { + case '\'' or '"' or '`': + end = sql.IndexOf(c, i + 1); + break; + case '[': + end = sql.IndexOf(']', i + 1); + break; + case '-' when next == '-': + end = sql.IndexOf('\n', i + 2); + break; + case '/' when next == '*': + end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal); + if (end >= 0) end++; + break; + case '$' when char.IsAsciiDigit(next) && (i == 0 || !IsIdentifierChar(sql[i - 1])): + sb.Append('?'); + i++; + continue; + default: + sb.Append(c); + i++; + continue; + } + // Copy the literal, identifier or comment verbatim (to the end of the text if unterminated). + end = end < 0 ? sql.Length : end + 1; + sb.Append(sql, i, end - i); + i = end; + } + return sb.ToString(); + } + + private static bool IsIdentifierChar(char c) => char.IsLetterOrDigit(c) || c is '_' or '$'; +} diff --git a/src/Titano.Data/Sqlite/SqliteDatabase.cs b/src/Titano.Data/Sqlite/SqliteDatabase.cs new file mode 100644 index 00000000..eb64e302 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteDatabase.cs @@ -0,0 +1,265 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// Parsed SQLite connection string: Data Source=<path>|:memory:;Pool Size=4. +internal sealed record SqliteSettings(string DataSource, int PoolSize) +{ + public bool IsMemory => DataSource == ":memory:"; + + public static SqliteSettings Parse(string connectionString) + { + var cs = new ConnectionString(connectionString); + var source = cs.Get("Data Source", "DataSource", "Filename") + ?? throw new FormatException("A SQLite connection string needs 'Data Source'."); + var pool = cs.GetInt(4, "Pool Size", "Max Pool Size"); + cs.ThrowOnUnknownKeys(); + if (pool < 1) throw new FormatException("'Pool Size' must be at least 1."); + return new SqliteSettings(source, pool); + } +} + +/// +/// SQLite through the system library (BRIEF §6.2). Up to Pool Size connections serve concurrent +/// readers (WAL); writes are serialised in-process by one async write lock, so writers wait in a queue instead +/// of spinning on SQLITE_BUSY. In-memory databases use a single shared-cache connection. +/// +public sealed class SqliteDatabase : IDatabase +{ + /// 3.31.0, the oldest library accepted: it has UPSERT, NULLS LAST and VACUUM INTO. + public const int MinimumVersionNumber = 3_031_000; + + internal const int BusyTimeoutMs = 5000; + private const string LogCategory = "Data.Sqlite"; + + private readonly string _filename; + private readonly bool _memory; + private readonly int _maxConnections; + private readonly SemaphoreSlim _slots; + private readonly SemaphoreSlim _writeLock = new(1, 1); + private readonly Stack _idle = new(); + private readonly Lock _gate = new(); + private bool _disposed; + + private SqliteDatabase(SqliteSettings settings) + { + _memory = settings.IsMemory; + if (_memory) + { + _filename = $"file:titano-{Guid.NewGuid():N}?mode=memory&cache=shared"; + _maxConnections = 1; + } + else + { + Path = System.IO.Path.GetFullPath(settings.DataSource); + var directory = System.IO.Path.GetDirectoryName(Path); + if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); + _filename = Path; + _maxConnections = settings.PoolSize; + } + _slots = new SemaphoreSlim(_maxConnections, _maxConnections); + } + + public Dialect Dialect => Dialect.Sqlite; + + /// Full path of the database file; null for an in-memory database. + public string? Path { get; } + + /// Version string of the loaded SQLite library, e.g. "3.45.1". + public static string LibraryVersion + { + get + { + EnsureLibrary(); + unsafe + { + return Utf8(sqlite3_libversion()) ?? "?"; + } + } + } + + internal static SqliteDatabase Open(SqliteSettings settings) + { + EnsureLibrary(); + var database = new SqliteDatabase(settings); + // The first connection validates the path, switches the file to WAL and keeps a memory database alive. + database._idle.Push(database.CreateConnection()); + return database; + } + + public async Task OpenAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + await _slots.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + SqliteConnection? connection; + lock (_gate) _idle.TryPop(out connection); + return new SqliteSession(this, connection ?? CreateConnection()); + } + catch + { + _slots.Release(); + throw; + } + } + + /// + /// Writes a consistent copy with VACUUM INTO to as + /// <name>-yyyyMMdd-HHmmss-fff.db and deletes all but the newest copies. + /// Readers and writers continue meanwhile. Returns the new file. + /// + public async Task BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(keep, 1); + Directory.CreateDirectory(directory); + var stem = BackupStem; + string target; + while (true) + { + target = System.IO.Path.Combine(directory, string.Create(CultureInfo.InvariantCulture, $"{stem}-{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}.db")); + if (!File.Exists(target)) break; + await Task.Delay(2, cancellationToken).ConfigureAwait(false); + } + var temp = target + ".tmp"; + await using (var session = (SqliteSession)await OpenAsync(cancellationToken).ConfigureAwait(false)) + await Task.Run(() => session.VacuumInto(temp, cancellationToken), cancellationToken).ConfigureAwait(false); + File.Move(temp, target); + + var pattern = new Regex("^" + Regex.Escape(stem) + @"-\d{8}-\d{6}-\d{3}\.db$", RegexOptions.CultureInvariant); + var backups = Directory.EnumerateFiles(directory) + .Where(f => pattern.IsMatch(System.IO.Path.GetFileName(f))) + .OrderByDescending(f => System.IO.Path.GetFileName(f), StringComparer.Ordinal) + .ToList(); + foreach (var old in backups.Skip(keep)) File.Delete(old); + Log.Info(LogCategory, $"Backup written to {target}"); + return target; + } + + /// + /// Replaces the database file with a backup after checking it with PRAGMA quick_check. Waits until + /// every session of this instance is returned; no other process may have the file open. + /// + public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default) + { + if (Path is null) throw new NotSupportedException("An in-memory database cannot be restored."); + if (!File.Exists(backupPath)) throw new FileNotFoundException("Backup file not found.", backupPath); + Validate(backupPath); + + await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + var taken = 0; + try + { + for (; taken < _maxConnections; taken++) await _slots.WaitAsync(cancellationToken).ConfigureAwait(false); + lock (_gate) + { + while (_idle.TryPop(out var connection)) connection.Dispose(); + } + var temp = AtomicFile.TempPathFor(Path); + File.Copy(backupPath, temp); + // A WAL left behind belongs to the old file and would be replayed onto the restored one. + File.Delete(Path + "-wal"); + File.Delete(Path + "-shm"); + AtomicFile.Commit(temp, Path); + Log.Info(LogCategory, $"Database restored from {backupPath}"); + } + finally + { + if (taken > 0) _slots.Release(taken); + _writeLock.Release(); + } + } + + public ValueTask DisposeAsync() + { + lock (_gate) + { + if (_disposed) return ValueTask.CompletedTask; + _disposed = true; + while (_idle.TryPop(out var connection)) connection.Dispose(); + } + return ValueTask.CompletedTask; + } + + internal Task AcquireWriteAsync(CancellationToken cancellationToken) => _writeLock.WaitAsync(cancellationToken); + + internal void ReleaseWrite() => _writeLock.Release(); + + /// Takes back a session's connection; one left inside a transaction is rolled back or dropped. + internal void Return(SqliteConnection connection) + { + try + { + if (!connection.IsAutoCommit) + { + try + { + connection.Exec("ROLLBACK"); + } + catch (SqliteException ex) + { + Log.Warning(LogCategory, "Dropping a connection whose transaction could not be rolled back.", ex); + connection.Dispose(); + return; + } + } + lock (_gate) + { + if (_disposed) connection.Dispose(); + else _idle.Push(connection); + } + } + finally + { + _slots.Release(); + } + } + + private string BackupStem => Path is null ? "titano" : System.IO.Path.GetFileNameWithoutExtension(Path); + + private SqliteConnection CreateConnection() => SqliteConnection.Open(_filename, _memory, BusyTimeoutMs); + + private static void EnsureLibrary() + { + EnsureResolver(); + int version; + try + { + version = sqlite3_libversion_number(); + } + catch (DllNotFoundException ex) + { + throw new NotSupportedException("The system SQLite library was not found (winsqlite3.dll, libsqlite3.so.0 or libsqlite3.dylib).", ex); + } + if (version < MinimumVersionNumber) + throw new NotSupportedException($"SQLite {version / 1_000_000}.{version / 1000 % 1000}.{version % 1000} is too old; 3.31 or newer is required."); + } + + private static void Validate(string backupPath) + { + try + { + using var connection = SqliteConnection.OpenReadOnly(backupPath); + var statement = connection.Rent("PRAGMA quick_check"); + try + { + var rc = statement.Step(); + if (rc != SQLITE_ROW) throw connection.Error(rc); + var result = statement.ReadRow(statement.ReadColumns()).GetStringOrNull(0); + if (result != "ok") throw new InvalidDataException($"The backup failed its integrity check: {result}"); + } + finally + { + connection.Return(statement); + } + } + catch (SqliteException ex) + { + throw new InvalidDataException("The file is not a readable SQLite database.", ex); + } + } +} diff --git a/src/Titano.Data/Sqlite/SqliteException.cs b/src/Titano.Data/Sqlite/SqliteException.cs new file mode 100644 index 00000000..360c977f --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteException.cs @@ -0,0 +1,19 @@ +namespace Titano.Data.Sqlite; + +/// An error returned by SQLite, with its primary and extended result codes. +public sealed class SqliteException(string message, int extendedResultCode) : DatabaseException(message) +{ + /// Primary result code (low byte), e.g. 19 = SQLITE_CONSTRAINT. + public int ResultCode => ExtendedResultCode & 0xFF; + + /// Extended result code, e.g. 2067 = SQLITE_CONSTRAINT_UNIQUE. + public int ExtendedResultCode { get; } = extendedResultCode; + + public override int ErrorCode => ExtendedResultCode; + + public override bool IsTransient => ResultCode is SqliteNative.SQLITE_BUSY or SqliteNative.SQLITE_LOCKED; + + public override bool IsUniqueViolation => ExtendedResultCode is SqliteNative.SQLITE_CONSTRAINT_UNIQUE or SqliteNative.SQLITE_CONSTRAINT_PRIMARYKEY; + + public override bool IsForeignKeyViolation => ExtendedResultCode == SqliteNative.SQLITE_CONSTRAINT_FOREIGNKEY; +} diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs new file mode 100644 index 00000000..95fe8590 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -0,0 +1,104 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Titano.Data.Sqlite; + +/// +/// P/Invoke surface of the system SQLite library: winsqlite3.dll (Windows 10 1709+), libsqlite3.so.0 +/// (Linux) or libsqlite3.dylib (macOS). Strings cross the boundary as UTF-8 encoded by hand; the default +/// calling convention matches winsqlite3's __stdcall exports on x86 and is cdecl elsewhere. +/// +internal static unsafe class SqliteNative +{ + private const string Library = "titano-sqlite3"; + private static int _resolverInstalled; + + public const int SQLITE_OK = 0; + public const int SQLITE_ERROR = 1; + public const int SQLITE_INTERRUPT = 9; + public const int SQLITE_BUSY = 5; + public const int SQLITE_LOCKED = 6; + public const int SQLITE_CONSTRAINT = 19; + public const int SQLITE_ROW = 100; + public const int SQLITE_DONE = 101; + + public const int SQLITE_CONSTRAINT_FOREIGNKEY = SQLITE_CONSTRAINT | (3 << 8); + public const int SQLITE_CONSTRAINT_PRIMARYKEY = SQLITE_CONSTRAINT | (6 << 8); + public const int SQLITE_CONSTRAINT_UNIQUE = SQLITE_CONSTRAINT | (8 << 8); + + public const int SQLITE_OPEN_READONLY = 0x00000001; + public const int SQLITE_OPEN_READWRITE = 0x00000002; + public const int SQLITE_OPEN_CREATE = 0x00000004; + public const int SQLITE_OPEN_URI = 0x00000040; + public const int SQLITE_OPEN_NOMUTEX = 0x00008000; + + public const int SQLITE_INTEGER = 1; + public const int SQLITE_FLOAT = 2; + public const int SQLITE_TEXT = 3; + public const int SQLITE_BLOB = 4; + public const int SQLITE_NULL = 5; + + /// Destructor sentinel that makes SQLite copy bound text/blobs before the call returns. + public static readonly nint SQLITE_TRANSIENT = -1; + + /// Routes the logical library name to the platform's system SQLite (once per process). + public static void EnsureResolver() + { + if (Interlocked.Exchange(ref _resolverInstalled, 1) == 0) + NativeLibrary.SetDllImportResolver(typeof(SqliteNative).Assembly, Resolve); + } + + private static nint Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + if (name != Library) return 0; + string[] candidates = OperatingSystem.IsWindows() ? ["winsqlite3.dll"] + : OperatingSystem.IsMacOS() ? ["libsqlite3.dylib", "/usr/lib/libsqlite3.dylib"] + : ["libsqlite3.so.0", "libsqlite3.so"]; + foreach (var candidate in candidates) + { + if (NativeLibrary.TryLoad(candidate, assembly, searchPath, out var handle)) return handle; + } + return 0; + } + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_libversion_number(); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_libversion(); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_open_v2(byte* filename, out nint db, int flags, byte* vfs); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_close_v2(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_result_codes(nint db, int onoff); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_busy_timeout(nint db, int ms); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_exec(nint db, byte* sql, nint callback, nint arg, out byte* errmsg); + [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_free(void* p); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_errcode(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_interrupt(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_changes(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_total_changes(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_get_autocommit(nint db); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_prepare_v2(nint db, byte* sql, int nBytes, out nint stmt, out byte* tail); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_step(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_reset(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_clear_bindings(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_finalize(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_stmt_readonly(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_parameter_count(nint stmt); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_null(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_int64(nint stmt, int index, long value); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_double(nint stmt, int index, double value); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_text(nint stmt, int index, byte* text, int nBytes, nint destructor); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_blob(nint stmt, int index, void* data, int nBytes, nint destructor); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_count(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_name(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_type(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern long sqlite3_column_int64(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern double sqlite3_column_double(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_text(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern void* sqlite3_column_blob(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_bytes(nint stmt, int index); + + /// Decodes a NUL-terminated UTF-8 string owned by SQLite. + public static string? Utf8(byte* p) => p is null ? null : Marshal.PtrToStringUTF8((nint)p); +} diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs new file mode 100644 index 00000000..eeee6552 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -0,0 +1,315 @@ +using System.Runtime.CompilerServices; +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// +/// A pooled SQLite connection. Statements that write take the database write lock for their duration when no +/// transaction holds it already; SQLITE_BUSY/LOCKED from other processes is retried a few times outside +/// transactions. Cancellation interrupts the running statement with sqlite3_interrupt. +/// +internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession +{ + private const int MaxBusyRetries = 3; + private SqliteTransaction? _transaction; + private bool _disposed; + + public Dialect Dialect => Dialect.Sqlite; + + public bool InTransaction => _transaction is not null; + + public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var statement = connection.Rent(sql); + var locked = false; + try + { + statement.Bind(parameters); + if (!statement.IsReadOnly && _transaction is null) + { + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + locked = true; + } + using var interrupt = RegisterInterrupt(cancellationToken); + var before = connection.TotalChanges; + while (await StepAsync(statement, _transaction is null, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + { + } + // sqlite3_changes keeps the last DML count across DDL; only trust it when this statement changed rows. + return connection.TotalChanges != before ? connection.Changes : 0; + } + finally + { + connection.Return(statement); + if (locked) database.ReleaseWrite(); + } + } + + public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var statement = connection.Rent(sql); + var locked = false; + try + { + statement.Bind(parameters); + if (!statement.IsReadOnly && _transaction is null) + { + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + locked = true; + } + using var interrupt = RegisterInterrupt(cancellationToken); + DbColumns? columns = null; + var retry = _transaction is null; + while (await StepAsync(statement, retry, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + { + retry = false; // restarting after rows were yielded would repeat them + columns ??= statement.ReadColumns(); + yield return statement.ReadRow(columns); + cancellationToken.ThrowIfCancellationRequested(); + } + } + finally + { + connection.Return(statement); + if (locked) database.ReleaseWrite(); + } + } + + public async Task ExecuteScriptAsync(string script, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var locked = _transaction is null; + if (locked) await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + try + { + using var interrupt = RegisterInterrupt(cancellationToken); + connection.Exec(script); + } + catch (SqliteException ex) when (ex.ResultCode == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(ex.Message, ex, cancellationToken); + } + finally + { + if (locked) database.ReleaseWrite(); + } + } + + public async Task BeginAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_transaction is not null) throw new InvalidOperationException("A transaction is already active on this session."); + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + try + { + await RunAsync("BEGIN IMMEDIATE", retryBusy: true, cancellationToken).ConfigureAwait(false); + } + catch + { + database.ReleaseWrite(); + throw; + } + return _transaction = new SqliteTransaction(this); + } + + public async Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (columns.Count == 0) throw new ArgumentException("At least one column is required.", nameof(columns)); + // 999 is the variable limit of SQLite builds before 3.32. + var rowsPerStatement = Math.Clamp(999 / columns.Count, 1, 100); + var buffer = new object?[rowsPerStatement * columns.Count]; + var ownTransaction = _transaction is null ? await BeginAsync(cancellationToken).ConfigureAwait(false) : null; + try + { + long total = 0; + var buffered = 0; + using (RegisterInterrupt(cancellationToken)) + { + await foreach (var row in rows.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + if (row.Length != columns.Count) + throw new ArgumentException($"A row has {row.Length} values for {columns.Count} columns.", nameof(rows)); + Array.Copy(row, 0, buffer, buffered * columns.Count, row.Length); + if (++buffered == rowsPerStatement) + { + await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false); + total += buffered; + buffered = 0; + } + } + if (buffered > 0) + { + await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false); + total += buffered; + } + } + if (ownTransaction is not null) await ownTransaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return total; + } + finally + { + if (ownTransaction is not null) await ownTransaction.DisposeAsync().ConfigureAwait(false); + } + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + if (_transaction is { } transaction) + { + try + { + await EndTransactionAsync(transaction, commit: false, CancellationToken.None).ConfigureAwait(false); + } + catch (SqliteException) + { + // The pool rolls the connection back or drops it below. + } + if (_transaction is not null) + { + _transaction = null; + database.ReleaseWrite(); + } + } + database.Return(connection); + } + + /// Ends if it is still the active one; a failed COMMIT leaves it open for rollback. + internal async Task EndTransactionAsync(SqliteTransaction transaction, bool commit, CancellationToken cancellationToken) + { + if (_transaction != transaction) return; + try + { + await RunAsync(commit ? "COMMIT" : "ROLLBACK", retryBusy: commit, cancellationToken).ConfigureAwait(false); + } + finally + { + if (connection.IsAutoCommit) + { + _transaction = null; + database.ReleaseWrite(); + } + } + } + + /// Runs VACUUM INTO (backups); it only reads, so no write lock is taken. + internal void VacuumInto(string path, CancellationToken cancellationToken) + { + var statement = connection.Rent("VACUUM INTO $1"); + try + { + statement.Bind([path]); + using var interrupt = RegisterInterrupt(cancellationToken); + var rc = statement.Step(); + if (rc == SQLITE_DONE) return; + if ((rc & 0xFF) == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) throw new OperationCanceledException(cancellationToken); + throw connection.Error(rc); + } + finally + { + connection.Return(statement); + } + } + + private async Task InsertBufferedAsync(string table, IReadOnlyList columns, object?[] buffer, int rowCount, CancellationToken cancellationToken) + { + var statement = connection.Rent(InsertSql(table, columns, rowCount)); + try + { + for (var i = 0; i < rowCount * columns.Count; i++) statement.BindValue(i + 1, buffer[i]); + await StepAsync(statement, retryBusy: false, cancellationToken).ConfigureAwait(false); + } + finally + { + connection.Return(statement); + } + } + + private static string InsertSql(string table, IReadOnlyList columns, int rowCount) + { + var sb = new StringBuilder("INSERT INTO ").Append(SqlDialect.QuoteIdentifier(table)).Append(" ("); + for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", " : string.Empty).Append(SqlDialect.QuoteIdentifier(columns[c])); + sb.Append(") VALUES "); + var n = 1; + for (var r = 0; r < rowCount; r++) + { + sb.Append(r > 0 ? ", (" : "("); + for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", ?" : "?").Append(n++); + sb.Append(')'); + } + return sb.ToString(); + } + + private async Task RunAsync(string sql, bool retryBusy, CancellationToken cancellationToken) + { + var statement = connection.Rent(sql); + try + { + await StepAsync(statement, retryBusy, cancellationToken).ConfigureAwait(false); + } + finally + { + connection.Return(statement); + } + } + + private async ValueTask StepAsync(SqliteStatement statement, bool retryBusy, CancellationToken cancellationToken) + { + for (var attempt = 0; ; attempt++) + { + var rc = statement.Step(); + if (rc is SQLITE_ROW or SQLITE_DONE) return rc; + var primary = rc & 0xFF; + if (primary == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) + throw new OperationCanceledException(cancellationToken); + if (retryBusy && primary is SQLITE_BUSY or SQLITE_LOCKED && attempt < MaxBusyRetries) + { + // busy_timeout already waited; another process holds the lock for long. Back off and restart. + statement.Rewind(); + await Task.Delay(50 * (attempt + 1) + Random.Shared.Next(50), cancellationToken).ConfigureAwait(false); + continue; + } + throw connection.Error(rc); + } + } + + private CancellationTokenRegistration RegisterInterrupt(CancellationToken cancellationToken) => + cancellationToken.CanBeCanceled + ? cancellationToken.UnsafeRegister(static state => ((SqliteConnection)state!).Interrupt(), connection) + : default; +} + +/// A BEGIN IMMEDIATE transaction holding the database write lock until it ends. +internal sealed class SqliteTransaction(SqliteSession session) : IDbTransaction +{ + private bool _completed; + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false); + _completed = true; + } + + public async Task RollbackAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + _completed = true; + await session.EndTransactionAsync(this, commit: false, cancellationToken).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + if (_completed) return; + _completed = true; + await session.EndTransactionAsync(this, commit: false, CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Titano.Data/Sqlite/SqliteStatement.cs b/src/Titano.Data/Sqlite/SqliteStatement.cs new file mode 100644 index 00000000..3b96b7d2 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteStatement.cs @@ -0,0 +1,170 @@ +using System.Buffers; +using System.Globalization; +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// A prepared statement owned by one ; reused through its statement cache. +internal sealed unsafe class SqliteStatement : IDisposable +{ + private const int StackTextBytes = 256; + private readonly SqliteConnection _connection; + + public SqliteStatement(SqliteConnection connection, nint handle, string sql) + { + _connection = connection; + Handle = handle; + Sql = sql; + IsReadOnly = sqlite3_stmt_readonly(handle) != 0; + ParameterCount = sqlite3_bind_parameter_count(handle); + } + + public nint Handle { get; private set; } + + /// The SQL text as the caller wrote it (cache key). + public string Sql { get; } + + /// The statement does not write the database (no write lock needed). + public bool IsReadOnly { get; } + + /// Highest parameter number used by the statement. + public int ParameterCount { get; } + + public bool InUse { get; set; } + + public bool Cached { get; set; } + + public void Bind(DbParam[] parameters) + { + if (parameters.Length != ParameterCount) + throw new ArgumentException($"The statement uses {ParameterCount} parameter(s) but {parameters.Length} were supplied.", nameof(parameters)); + for (var i = 0; i < parameters.Length; i++) Bind(i + 1, parameters[i].Value, parameters[i].Type); + } + + /// Binds a raw CLR value (bulk insert rows); the type is inferred like does. + public void BindValue(int index, object? value) => Bind(index, value, DbValueType.Auto); + + public int Step() => sqlite3_step(Handle); + + /// Rewinds for another execution with the same bindings. + public void Rewind() => sqlite3_reset(Handle); + + /// Rewinds after an execution; a step error was already reported, so the code is ignored. + public void Reset() + { + sqlite3_reset(Handle); + sqlite3_clear_bindings(Handle); + } + + public DbColumns ReadColumns() + { + var names = new string[sqlite3_column_count(Handle)]; + for (var i = 0; i < names.Length; i++) names[i] = Utf8(sqlite3_column_name(Handle, i)) ?? string.Empty; + return new DbColumns(names); + } + + public DbRow ReadRow(DbColumns columns) + { + var values = new object?[columns.Names.Length]; + for (var i = 0; i < values.Length; i++) + { + values[i] = sqlite3_column_type(Handle, i) switch + { + SQLITE_INTEGER => sqlite3_column_int64(Handle, i), + SQLITE_FLOAT => sqlite3_column_double(Handle, i), + SQLITE_TEXT => ReadText(i), + SQLITE_BLOB => ReadBlob(i), + _ => null, + }; + } + return new DbRow(columns, values); + } + + public void Dispose() + { + if (Handle != 0) + { + sqlite3_finalize(Handle); + Handle = 0; + } + } + + private void Bind(int index, object? value, DbValueType type) + { + var rc = value switch + { + null => sqlite3_bind_null(Handle, index), + string s => BindText(index, s), + long l => sqlite3_bind_int64(Handle, index, l), + int n => sqlite3_bind_int64(Handle, index, n), + double d => sqlite3_bind_double(Handle, index, d), + bool b => sqlite3_bind_int64(Handle, index, b ? 1 : 0), + Guid g => BindFormatted(index, g, "D"), + DateTimeOffset o => BindFormatted(index, o.UtcDateTime, "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"), + DateTime d when type == DbValueType.LocalDateTime || (type == DbValueType.Auto && d.Kind == DateTimeKind.Unspecified) + => BindFormatted(index, d, "yyyy-MM-dd'T'HH:mm:ss.ffffff"), + DateTime d => BindFormatted(index, d.ToUniversalTime(), "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"), + byte[] b => BindBlob(index, b), + _ => BindNormalized(index, new DbParam(value)), + }; + if (rc != SQLITE_OK) throw _connection.Error(rc); + } + + private int BindNormalized(int index, DbParam p) + { + Bind(index, p.Value, p.Type); + return SQLITE_OK; + } + + private int BindText(int index, string s) + { + if (s.Length <= StackTextBytes / 3) + { + var buffer = stackalloc byte[StackTextBytes]; + var n = Encoding.UTF8.GetBytes(s, new Span(buffer, StackTextBytes)); + return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT); + } + var rented = ArrayPool.Shared.Rent(Encoding.UTF8.GetByteCount(s)); + try + { + var n = Encoding.UTF8.GetBytes(s, rented); + fixed (byte* p = rented) return sqlite3_bind_text(Handle, index, p, n, SQLITE_TRANSIENT); + } + finally + { + ArrayPool.Shared.Return(rented); + } + } + + private int BindFormatted(int index, T value, string format) where T : IUtf8SpanFormattable + { + var buffer = stackalloc byte[64]; + var span = new Span(buffer, 64); + if (!value.TryFormat(span, out var n, format, CultureInfo.InvariantCulture)) + throw new FormatException($"Cannot format {value} for SQLite."); + return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT); + } + + private int BindBlob(int index, byte[] data) + { + byte empty = 0; + // A null pointer would bind NULL; an empty blob needs any valid address. + if (data.Length == 0) return sqlite3_bind_blob(Handle, index, &empty, 0, SQLITE_TRANSIENT); + fixed (byte* p = data) return sqlite3_bind_blob(Handle, index, p, data.Length, SQLITE_TRANSIENT); + } + + private string ReadText(int column) + { + var p = sqlite3_column_text(Handle, column); + var n = sqlite3_column_bytes(Handle, column); + return n == 0 ? string.Empty : Encoding.UTF8.GetString(p, n); + } + + private byte[] ReadBlob(int column) + { + var p = (byte*)sqlite3_column_blob(Handle, column); + var n = sqlite3_column_bytes(Handle, column); + return n == 0 ? [] : new ReadOnlySpan(p, n).ToArray(); + } +} diff --git a/src/Titano.Data/TextValues.cs b/src/Titano.Data/TextValues.cs new file mode 100644 index 00000000..cb1143fa --- /dev/null +++ b/src/Titano.Data/TextValues.cs @@ -0,0 +1,135 @@ +using System.Globalization; + +namespace Titano.Data; + +/// +/// Canonical text forms of values without a native SQLite type, also used for PostgreSQL text parameters. +/// Date-times are fixed-width ISO-8601 with microseconds, so text order equals chronological order. +/// +internal static class TextValues +{ + private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"; + private const string LocalFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff"; + + public static string FormatTimestamp(DateTimeOffset value) => value.UtcDateTime.ToString(TimestampFormat, CultureInfo.InvariantCulture); + + public static string FormatLocal(DateTime value) => value.ToString(LocalFormat, CultureInfo.InvariantCulture); + + public static string FormatGuid(Guid value) => value.ToString("D"); + + /// Parses an ISO-8601 or PostgreSQL timestamp; a missing offset means UTC. + public static DateTimeOffset ParseTimestamp(ReadOnlySpan text) + { + if (!TryParse(text, out var value, out var offset)) + throw new FormatException($"Invalid timestamp '{text}'."); + if (value == DateTime.MaxValue || value == DateTime.MinValue) + return new DateTimeOffset(value, TimeSpan.Zero); + return new DateTimeOffset(DateTime.SpecifyKind(value - (offset ?? TimeSpan.Zero), DateTimeKind.Utc)); + } + + /// Parses a wall-clock date-time (unspecified kind); a value carrying an offset is returned in UTC. + public static DateTime ParseLocal(ReadOnlySpan text) + { + if (!TryParse(text, out var value, out var offset)) + throw new FormatException($"Invalid date-time '{text}'."); + return offset is { } o ? DateTime.SpecifyKind(value - o, DateTimeKind.Utc) : value; + } + + /// Accepts yyyy-MM-dd[(T| )HH:mm[:ss[.f…]]][Z|±HH[[:]mm[[:]ss]]] and ±infinity. + private static bool TryParse(ReadOnlySpan s, out DateTime value, out TimeSpan? offset) + { + value = default; + offset = null; + s = s.Trim(); + if (s.SequenceEqual("infinity")) + { + value = DateTime.MaxValue; + return true; + } + if (s.SequenceEqual("-infinity")) + { + value = DateTime.MinValue; + return true; + } + if (s.Length < 10 || s[4] != '-' || s[7] != '-' + || !Digits(s[..4], out var year) || !Digits(s.Slice(5, 2), out var month) || !Digits(s.Slice(8, 2), out var day)) + return false; + + int hour = 0, minute = 0, second = 0; + long fraction = 0; + var i = 10; + if (i < s.Length && s[i] is 'T' or ' ') + { + if (s.Length < i + 6 || s[i + 3] != ':' || !Digits(s.Slice(i + 1, 2), out hour) || !Digits(s.Slice(i + 4, 2), out minute)) + return false; + i += 6; + if (i < s.Length && s[i] == ':') + { + if (s.Length < i + 3 || !Digits(s.Slice(i + 1, 2), out second)) + return false; + i += 3; + if (i < s.Length && s[i] == '.') + { + var start = ++i; + var digits = 0; + for (; i < s.Length && char.IsAsciiDigit(s[i]); i++) + { + if (digits++ < 7) fraction = fraction * 10 + (s[i] - '0'); + } + if (i == start) return false; + for (; digits < 7; digits++) fraction *= 10; + } + } + } + + if (i < s.Length) + { + if (s[i] == 'Z' && i == s.Length - 1) + { + offset = TimeSpan.Zero; + } + else if (s[i] is '+' or '-') + { + var negative = s[i++] == '-'; + if (!OffsetPart(s, ref i, out var oh, colon: false)) return false; + var om = 0; + var os = 0; + if (i < s.Length && !OffsetPart(s, ref i, out om, colon: true)) return false; + if (i < s.Length && !OffsetPart(s, ref i, out os, colon: true)) return false; + if (i != s.Length) return false; + var span = new TimeSpan(oh, om, os); + offset = negative ? -span : span; + } + else + { + return false; + } + } + + if (year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) + || hour > 23 || minute > 59 || second > 59) + return false; + value = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified).AddTicks(fraction); + return true; + } + + private static bool OffsetPart(ReadOnlySpan s, ref int i, out int value, bool colon) + { + if (colon && s[i] == ':') i++; + value = 0; + if (s.Length < i + 2 || !Digits(s.Slice(i, 2), out value)) return false; + i += 2; + return true; + } + + private static bool Digits(ReadOnlySpan s, out int value) + { + value = 0; + foreach (var c in s) + { + if (!char.IsAsciiDigit(c)) return false; + value = value * 10 + (c - '0'); + } + return true; + } +} From 46cee365dc2b547b45f6edb4af8678f01c0f132b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:40:40 +0000 Subject: [PATCH 023/188] feat(data): add in-house PostgreSQL wire protocol v3 client TCP with optional TLS (disable/prefer/require/verify-full), SCRAM-SHA-256, MD5, cleartext and trust authentication, simple and extended query with a per-connection LRU of prepared statements, text-format parameters with binary bytea, OID-based result decoding, COPY FROM STDIN, LISTEN/NOTIFY, CancelRequest cancellation, typed PostgresException, and a connection pool with health checks, idle eviction and one retry for reads that hit a lost connection. DatabaseFactory opens either engine from options. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/DatabaseOptions.cs | 54 + src/Titano.Data/Postgres/PgAuthentication.cs | 137 +++ src/Titano.Data/Postgres/PgConnector.cs | 1025 +++++++++++++++++ src/Titano.Data/Postgres/PgListener.cs | 96 ++ src/Titano.Data/Postgres/PgPool.cs | 128 ++ src/Titano.Data/Postgres/PgTypes.cs | 219 ++++ src/Titano.Data/Postgres/PgWriteBuffer.cs | 98 ++ src/Titano.Data/Postgres/PostgresDatabase.cs | 216 ++++ src/Titano.Data/Postgres/PostgresException.cs | 47 + src/Titano.Data/Postgres/PostgresSettings.cs | 84 ++ 10 files changed, 2104 insertions(+) create mode 100644 src/Titano.Data/DatabaseOptions.cs create mode 100644 src/Titano.Data/Postgres/PgAuthentication.cs create mode 100644 src/Titano.Data/Postgres/PgConnector.cs create mode 100644 src/Titano.Data/Postgres/PgListener.cs create mode 100644 src/Titano.Data/Postgres/PgPool.cs create mode 100644 src/Titano.Data/Postgres/PgTypes.cs create mode 100644 src/Titano.Data/Postgres/PgWriteBuffer.cs create mode 100644 src/Titano.Data/Postgres/PostgresDatabase.cs create mode 100644 src/Titano.Data/Postgres/PostgresException.cs create mode 100644 src/Titano.Data/Postgres/PostgresSettings.cs diff --git a/src/Titano.Data/DatabaseOptions.cs b/src/Titano.Data/DatabaseOptions.cs new file mode 100644 index 00000000..6d857a27 --- /dev/null +++ b/src/Titano.Data/DatabaseOptions.cs @@ -0,0 +1,54 @@ +using Titano.Data.Postgres; +using Titano.Data.Sqlite; + +namespace Titano.Data; + +/// Which engine to open and how to reach it. +/// +/// SQLite: Data Source=<path>|:memory:;Pool Size=4. +/// PostgreSQL: Host=…;Port=5432;Database=…;Username=…;Password=…;SslMode=disable|prefer|require|verify-full +/// plus the optional keys listed on . +/// +public sealed record DatabaseOptions +{ + public required Dialect Dialect { get; init; } + + public required string ConnectionString { get; init; } + + public static DatabaseOptions Sqlite(string path) => new() + { + Dialect = Dialect.Sqlite, + ConnectionString = "Data Source='" + path.Replace("'", "''", StringComparison.Ordinal) + "'", + }; + + /// A private in-memory SQLite database that lives until the is disposed. + public static DatabaseOptions SqliteInMemory() => new() { Dialect = Dialect.Sqlite, ConnectionString = "Data Source=:memory:" }; + + public static DatabaseOptions Postgres(string connectionString) => new() { Dialect = Dialect.Postgres, ConnectionString = connectionString }; + + /// + /// Infers the dialect: a string with Host/Server is PostgreSQL; Data Source or a bare + /// path (no =) is SQLite. + /// + public static DatabaseOptions Parse(string connectionString) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionString); + if (!connectionString.Contains('=', StringComparison.Ordinal)) return Sqlite(connectionString.Trim()); + var cs = new ConnectionString(connectionString); + if (cs.Contains("Host") || cs.Contains("Server")) return Postgres(connectionString); + if (cs.Contains("Data Source") || cs.Contains("Filename")) return new() { Dialect = Dialect.Sqlite, ConnectionString = connectionString }; + throw new FormatException("The connection string names neither a PostgreSQL host nor a SQLite data source."); + } +} + +/// Builds the implementation for a set of options. +public static class DatabaseFactory +{ + /// Creates the database object; SQLite opens the file now, PostgreSQL connects on the first session. + public static IDatabase Open(DatabaseOptions options) => options.Dialect switch + { + Dialect.Sqlite => SqliteDatabase.Open(SqliteSettings.Parse(options.ConnectionString)), + Dialect.Postgres => new PostgresDatabase(PostgresSettings.Parse(options.ConnectionString)), + _ => throw new ArgumentOutOfRangeException(nameof(options), options.Dialect, "Unknown dialect."), + }; +} diff --git a/src/Titano.Data/Postgres/PgAuthentication.cs b/src/Titano.Data/Postgres/PgAuthentication.cs new file mode 100644 index 00000000..f3933958 --- /dev/null +++ b/src/Titano.Data/Postgres/PgAuthentication.cs @@ -0,0 +1,137 @@ +using System.Globalization; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Data.Postgres; + +/// +/// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding +/// (n,, GS2 header) and an empty user name, since the server takes the user from the startup packet. +/// +internal sealed class ScramSha256 +{ + private readonly string _password; + private readonly string _username; + private readonly string _clientNonce; + private string? _clientFirstBare; + private byte[]? _expectedServerSignature; + + public ScramSha256(string password, string username = "", string? clientNonce = null) + { + _password = password; + _username = username.Replace("=", "=3D", StringComparison.Ordinal).Replace(",", "=2C", StringComparison.Ordinal); + _clientNonce = clientNonce ?? Convert.ToBase64String(RandomNumberGenerator.GetBytes(18)); + } + + public const string Mechanism = "SCRAM-SHA-256"; + + public byte[] ClientFirstMessage() + { + _clientFirstBare = $"n={_username},r={_clientNonce}"; + return Encoding.UTF8.GetBytes("n,," + _clientFirstBare); + } + + /// Checks the server-first message and returns client-final with the proof. + public byte[] ClientFinalMessage(ReadOnlySpan serverFirst) + { + if (_clientFirstBare is null) throw new InvalidOperationException("ClientFirstMessage must be sent first."); + var serverFirstText = Encoding.UTF8.GetString(serverFirst); + string? nonce = null, salt = null, iterations = null; + foreach (var part in serverFirstText.Split(',')) + { + if (part.StartsWith("r=", StringComparison.Ordinal)) nonce = part[2..]; + else if (part.StartsWith("s=", StringComparison.Ordinal)) salt = part[2..]; + else if (part.StartsWith("i=", StringComparison.Ordinal)) iterations = part[2..]; + } + if (nonce is null || salt is null || iterations is null + || !nonce.StartsWith(_clientNonce, StringComparison.Ordinal) || nonce.Length == _clientNonce.Length + || !int.TryParse(iterations, NumberStyles.None, CultureInfo.InvariantCulture, out var count) || count < 1) + throw new AuthenticationException("Invalid SCRAM server-first message."); + + var saltedPassword = Rfc2898DeriveBytes.Pbkdf2( + Encoding.UTF8.GetBytes(SaslPrep(_password)), Convert.FromBase64String(salt), count, HashAlgorithmName.SHA256, 32); + var clientKey = HMACSHA256.HashData(saltedPassword, "Client Key"u8); + var storedKey = SHA256.HashData(clientKey); + var withoutProof = "c=biws,r=" + nonce; + var authMessage = Encoding.UTF8.GetBytes(_clientFirstBare + "," + serverFirstText + "," + withoutProof); + var proof = HMACSHA256.HashData(storedKey, authMessage); + for (var i = 0; i < proof.Length; i++) proof[i] ^= clientKey[i]; + _expectedServerSignature = HMACSHA256.HashData(HMACSHA256.HashData(saltedPassword, "Server Key"u8), authMessage); + return Encoding.UTF8.GetBytes(withoutProof + ",p=" + Convert.ToBase64String(proof)); + } + + /// Verifies the server signature, proving the server knows the password too. + public void VerifyServerFinal(ReadOnlySpan serverFinal) + { + var text = Encoding.UTF8.GetString(serverFinal); + if (text.StartsWith("e=", StringComparison.Ordinal)) throw new AuthenticationException("SCRAM authentication failed: " + text[2..]); + var end = text.IndexOf(',', StringComparison.Ordinal); + var value = text.StartsWith("v=", StringComparison.Ordinal) ? text[2..(end < 0 ? text.Length : end)] : null; + if (_expectedServerSignature is null || value is null + || !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(value), _expectedServerSignature)) + throw new AuthenticationException("The server's SCRAM signature is invalid."); + } + + /// + /// SASLprep (RFC 4013) as PostgreSQL applies it: non-ASCII spaces become U+0020, "mapped to nothing" + /// characters are dropped, then NFKC; a result with prohibited code points falls back to the raw password. + /// The unassigned-code-point and bidi checks are omitted. + /// + internal static string SaslPrep(string password) + { + var ascii = true; + foreach (var c in password) + { + if (c > 0x7F) + { + ascii = false; + break; + } + } + // Printable ASCII is unchanged by SASLprep; ASCII controls are prohibited, which also means "use raw". + if (ascii) return password; + + var mapped = new StringBuilder(password.Length); + foreach (var rune in password.EnumerateRunes()) + { + var v = rune.Value; + if (v is 0x00A0 or 0x1680 or (>= 0x2000 and <= 0x200B) or 0x202F or 0x205F or 0x3000) mapped.Append(' '); + else if (v is 0x00AD or 0x034F or 0x1806 or (>= 0x180B and <= 0x180D) or (>= 0x200C and <= 0x200D) or 0x2060 + or (>= 0xFE00 and <= 0xFE0F) or 0xFEFF) continue; + else mapped.Append(rune.ToString()); + } + var normalized = mapped.ToString().Normalize(NormalizationForm.FormKC); + foreach (var rune in normalized.EnumerateRunes()) + { + if (IsProhibited(rune.Value)) return password; + } + return normalized; + } + + private static bool IsProhibited(int v) => + v < 0x20 || v is >= 0x7F and <= 0x9F // C.2.1, C.2.2 controls + || v is 0x06DD or 0x070F or 0x180E or 0x2028 or 0x2029 or (>= 0x2060 and <= 0x2063) // C.2.2 + || v is >= 0x1D173 and <= 0x1D17A + || v is >= 0xE000 and <= 0xF8FF || v >= 0xF0000 // C.3 private use + || v is >= 0xFDD0 and <= 0xFDEF || (v & 0xFFFE) == 0xFFFE // C.4 non-characters + || v is >= 0xFFF9 and <= 0xFFFD // C.6 + || v is >= 0x2FF0 and <= 0x2FFB // C.7 + || v is 0x0340 or 0x0341 or 0x200E or 0x200F or (>= 0x202A and <= 0x202E) or (>= 0x206A and <= 0x206F) // C.8 + || v is 0xE0001 or (>= 0xE0020 and <= 0xE007F); // C.9 +} + +/// PostgreSQL's MD5 password response: "md5" + md5hex(md5hex(password + user) + salt). +internal static class PgMd5 +{ + public static string Response(string username, string password, ReadOnlySpan salt) + { + var inner = Hex(MD5.HashData(Encoding.UTF8.GetBytes(password + username))); + var buffer = new byte[inner.Length + salt.Length]; + Encoding.ASCII.GetBytes(inner, buffer); + salt.CopyTo(buffer.AsSpan(inner.Length)); + return "md5" + Hex(MD5.HashData(buffer)); + } + + private static string Hex(byte[] bytes) => Convert.ToHexStringLower(bytes); +} diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs new file mode 100644 index 00000000..59c5f38d --- /dev/null +++ b/src/Titano.Data/Postgres/PgConnector.cs @@ -0,0 +1,1025 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// A NOTIFY delivered to a listening connection. +public sealed record PgNotification(int ProcessId, string Channel, string Payload); + +/// +/// One physical connection speaking protocol v3 (BRIEF §6.3): startup and authentication, simple and extended +/// query with a per-connection LRU of named prepared statements, COPY FROM STDIN, notices and notifications, +/// and cancellation through a CancelRequest on a second socket. Not thread-safe; the pool lends it to one +/// session at a time. +/// +internal sealed class PgConnector : IAsyncDisposable +{ + private const int ProtocolVersion3 = 196608; + private const int SslRequestCode = 80877103; + private const int CancelRequestCode = 80877102; + private const int CopyChunkBytes = 64 * 1024; + private const string LogCategory = "Data.Postgres"; + private static readonly TimeSpan CancelGracePeriod = TimeSpan.FromSeconds(5); + private static readonly DbColumns NoColumns = new([]); + + private readonly PostgresSettings _settings; + private readonly Socket _socket; + private readonly Stream _stream; + private readonly PgWriteBuffer _write = new(); + private readonly Dictionary> _statements = new(StringComparer.Ordinal); + private readonly LinkedList _statementLru = new(); + private readonly List _statementsToClose = []; + private readonly Dictionary _serverParameters = new(StringComparer.Ordinal); + private byte[] _read = new byte[16 * 1024]; + private int _readPos; + private int _readEnd; + private int _messageStart; + private int _messageLength; + private int _statementCounter; + private int _secretKey; + private long _idleSince; + private int _disposed; + private CancellationTokenSource _ioAbort = new(); + private Task _pendingCancel = Task.CompletedTask; + + private PgConnector(PostgresSettings settings, Socket socket, Stream stream) + { + _settings = settings; + _socket = socket; + _stream = stream; + } + + public int ProcessId { get; private set; } + + /// The connection failed or the server ended the session; it must be discarded. + public bool IsBroken { get; private set; } + + /// Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction. + public char TransactionStatus { get; private set; } = 'I'; + + public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); + + public IReadOnlyDictionary ServerParameters => _serverParameters; + + /// Receives NotificationResponse messages (listener connections). + public Action? NotificationReceived { get; set; } + + private ReadOnlySpan Payload => _read.AsSpan(_messageStart, _messageLength); + + public static async Task OpenAsync(PostgresSettings settings, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(settings.ConnectTimeout); + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + Stream? stream = null; + try + { + await socket.ConnectAsync(settings.Host, settings.Port, timeout.Token).ConfigureAwait(false); + stream = new NetworkStream(socket, ownsSocket: false); + if (settings.SslMode != SslMode.Disable) + stream = await NegotiateTlsAsync(stream, settings, timeout.Token).ConfigureAwait(false); + var connector = new PgConnector(settings, socket, stream); + await connector.StartupAsync(timeout.Token).ConfigureAwait(false); + connector.MarkIdle(); + return connector; + } + catch (Exception ex) + { + if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); + socket.Dispose(); + if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested) + throw new DatabaseConnectionException($"Timed out connecting to {settings.Host}:{settings.Port}.", ex); + if (ex is SocketException or IOException) + throw new DatabaseConnectionException($"Cannot connect to {settings.Host}:{settings.Port}: {ex.Message}", ex); + throw; + } + } + + public void MarkIdle() => _idleSince = Environment.TickCount64; + + /// Runs one statement with the extended protocol and returns the rows it changed. + public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + var op = StartOperation(sql, parameters, decodeRows: false, cancellationToken); + try + { + await SendExtendedAsync(op).ConfigureAwait(false); + while (await ReadRowAsync(op).ConfigureAwait(false) is not null) + { + } + return op.Affected; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Streams the rows of one statement; abandoning the enumeration drains the rest of the response. + public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) + { + var op = StartOperation(sql, parameters, decodeRows: true, cancellationToken); + try + { + await SendExtendedAsync(op).ConfigureAwait(false); + while (await ReadRowAsync(op).ConfigureAwait(false) is { } row) yield return row; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Runs a simple-protocol query (scripts, transaction control) and returns the last command tag. + public async Task SimpleQueryAsync(string sql, CancellationToken cancellationToken) + { + var op = StartOperation(sql, [], decodeRows: false, cancellationToken); + try + { + WriteQuery(sql); + await FlushAsync(op).ConfigureAwait(false); + await DrainAsync(op).ConfigureAwait(false); + return op.Tag; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// True when SELECT 1 succeeds within the connect timeout; marks the connection broken otherwise. + public async Task PingAsync(CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_settings.ConnectTimeout); + try + { + await SimpleQueryAsync("SELECT 1", timeout.Token).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is DatabaseException or OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + IsBroken = true; + return false; + } + } + + /// + /// Streams rows through COPY … FROM STDIN in text format. A failing producer aborts the copy with + /// CopyFail, so the table is left untouched, and its exception is rethrown. + /// + public async Task CopyInAsync(string copySql, int columnCount, IAsyncEnumerable rows, CancellationToken cancellationToken) + { + var op = StartOperation(copySql, [], decodeRows: false, cancellationToken); + try + { + WriteQuery(copySql); + await FlushAsync(op).ConfigureAwait(false); + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + if (type == 'G') break; + if (type == 'E') OnError(op); + else if (type == 'Z') throw Complete(op) ?? ProtocolViolation(type); + } + + ExceptionDispatchInfo? failure = null; + try + { + _write.StartMessage('d'); + await foreach (var row in rows.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + if (row.Length != columnCount) + throw new ArgumentException($"A row has {row.Length} values for {columnCount} columns.", nameof(rows)); + for (var i = 0; i < row.Length; i++) + { + if (i > 0) _write.WriteByte((byte)'\t'); + PgTypes.WriteCopyValue(row[i], _write); + } + _write.WriteByte((byte)'\n'); + if (_write.Length >= CopyChunkBytes) + { + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + _write.StartMessage('d'); + } + } + _write.EndMessage(); + _write.StartMessage('c'); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + } + catch (Exception ex) when (!IsBroken) + { + failure = ExceptionDispatchInfo.Capture(ex); + _write.Clear(); + _write.StartMessage('f'); + _write.WriteCString(ex.Message); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + } + + try + { + await DrainAsync(op).ConfigureAwait(false); + } + catch (PostgresException) when (failure is not null) + { + // The server reports our CopyFail; the producer's exception is the real cause. + } + catch (OperationCanceledException) when (failure is not null) + { + } + failure?.Throw(); + return op.Affected; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Sends a simple query without reading the response (listener commands; the read loop completes them). + public async Task SendQueryAsync(string sql, CancellationToken cancellationToken) + { + WriteQuery(sql); + try + { + await _stream.WriteAsync(_write.Written, cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _write.Clear(); + } + } + + /// + /// Listener read loop: notifications go to ; each ReadyForQuery reports the + /// error (or null) of the command it ends. Runs until or the connection fails. + /// + public async Task RunListenerAsync(Action commandCompleted, CancellationToken stop) + { + PostgresException? error = null; + while (true) + { + var type = await ReadMessageAsync(stop).ConfigureAwait(false); + if (type == 'E') + { + error = ParseError(); + if (error.IsFatal) + { + IsBroken = true; + throw error; + } + } + else if (type == 'Z') + { + TransactionStatus = (char)Payload[0]; + commandCompleted(error); + error = null; + } + } + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (!IsBroken) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); + _write.Clear(); + _write.StartMessage('X'); + _write.EndMessage(); + await _stream.WriteAsync(_write.Written, timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or ObjectDisposedException) + { + // Terminate is a courtesy; the socket closes either way. + } + } + IsBroken = true; + try + { + await _stream.DisposeAsync().ConfigureAwait(false); + } + catch (IOException) + { + } + _socket.Dispose(); + _ioAbort.Dispose(); + } + + private static async Task NegotiateTlsAsync(Stream stream, PostgresSettings settings, CancellationToken cancellationToken) + { + var request = new byte[8]; + BinaryPrimitives.WriteInt32BigEndian(request, 8); + BinaryPrimitives.WriteInt32BigEndian(request.AsSpan(4), SslRequestCode); + await stream.WriteAsync(request, cancellationToken).ConfigureAwait(false); + var answer = new byte[1]; + await stream.ReadExactlyAsync(answer, cancellationToken).ConfigureAwait(false); + if (answer[0] == 'N') + { + if (settings.SslMode == SslMode.Prefer) return stream; + throw new DatabaseConnectionException($"The server at {settings.Host}:{settings.Port} does not support TLS, which SslMode={settings.SslMode} requires."); + } + if (answer[0] != 'S') throw new DatabaseConnectionException("Unexpected answer to the TLS request."); + + var tls = new SslStream(stream, leaveInnerStreamOpen: false); + var options = new SslClientAuthenticationOptions + { + TargetHost = settings.Host, + RemoteCertificateValidationCallback = (_, certificate, chain, errors) => + settings.SslMode != SslMode.VerifyFull || IsTrusted(settings, certificate, chain, errors), + }; + await tls.AuthenticateAsClientAsync(options, cancellationToken).ConfigureAwait(false); + return tls; + } + + /// verify-full: the system trust store, or the configured root certificate, plus a host name match. + private static bool IsTrusted(PostgresSettings settings, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors) + { + if (settings.RootCertificate is null) return errors == SslPolicyErrors.None; + if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNotAvailable | SslPolicyErrors.RemoteCertificateNameMismatch)) != 0) + return false; + using var custom = new X509Chain(); + custom.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + custom.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + custom.ChainPolicy.CustomTrustStore.ImportFromPemFile(settings.RootCertificate); + if (chain is not null) + { + foreach (var element in chain.ChainElements) custom.ChainPolicy.ExtraStore.Add(element.Certificate); + } + using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); + return custom.Build(leaf); + } + + private async Task StartupAsync(CancellationToken cancellationToken) + { + _write.StartUntypedMessage(); + _write.WriteInt32(ProtocolVersion3); + void Parameter(string name, string value) + { + _write.WriteCString(name); + _write.WriteCString(value); + } + Parameter("user", _settings.Username); + Parameter("database", _settings.Database); + Parameter("application_name", _settings.ApplicationName); + Parameter("client_encoding", "UTF8"); + Parameter("TimeZone", "UTC"); + Parameter("DateStyle", "ISO, MDY"); + Parameter("extra_float_digits", "3"); + if (_settings.SearchPath is { } searchPath) Parameter("search_path", searchPath); + _write.WriteByte(0); + _write.EndMessage(); + await WriteAndClearAsync(cancellationToken).ConfigureAwait(false); + + ScramSha256? scram = null; + while (true) + { + var type = await ReadMessageAsync(cancellationToken).ConfigureAwait(false); + switch (type) + { + case (byte)'R': + scram = Authenticate(scram); + if (_write.Length > 0) await WriteAndClearAsync(cancellationToken).ConfigureAwait(false); + break; + case (byte)'K': + ProcessId = BinaryPrimitives.ReadInt32BigEndian(Payload); + _secretKey = BinaryPrimitives.ReadInt32BigEndian(Payload[4..]); + break; + case (byte)'Z': + TransactionStatus = (char)Payload[0]; + return; + case (byte)'E': + throw ParseError(); + case (byte)'v': + break; // NegotiateProtocolVersion: we request no protocol extensions. + default: + throw ProtocolViolation(type); + } + } + } + + /// Answers one Authentication* message, queuing the response in the write buffer. + private ScramSha256? Authenticate(ScramSha256? scram) + { + var payload = Payload; + var code = BinaryPrimitives.ReadInt32BigEndian(payload); + switch (code) + { + case 0: + return scram; + case 3: + WritePassword(RequirePassword()); + return scram; + case 5: + WritePassword(PgMd5.Response(_settings.Username, RequirePassword(), payload.Slice(4, 4))); + return scram; + case 10: + { + var mechanisms = new List(); + var pos = 4; + while (pos < payload.Length && payload[pos] != 0) mechanisms.Add(ReadCString(payload, ref pos)); + if (!mechanisms.Contains(ScramSha256.Mechanism)) + throw new NotSupportedException($"The server offers SASL mechanisms {string.Join(", ", mechanisms)}; only {ScramSha256.Mechanism} is supported."); + scram = new ScramSha256(RequirePassword()); + var first = scram.ClientFirstMessage(); + _write.StartMessage('p'); + _write.WriteCString(ScramSha256.Mechanism); + _write.WriteInt32(first.Length); + _write.Write(first); + _write.EndMessage(); + return scram; + } + case 11: + var final = (scram ?? throw ProtocolViolation((byte)'R')).ClientFinalMessage(payload[4..]); + _write.StartMessage('p'); + _write.Write(final); + _write.EndMessage(); + return scram; + case 12: + (scram ?? throw ProtocolViolation((byte)'R')).VerifyServerFinal(payload[4..]); + return scram; + default: + throw new NotSupportedException($"PostgreSQL authentication method {code} is not supported (use scram-sha-256, md5, password or trust)."); + } + } + + private string RequirePassword() => + _settings.Password ?? throw new InvalidOperationException($"The server requires a password for user '{_settings.Username}'."); + + private void WritePassword(string password) + { + _write.StartMessage('p'); + _write.WriteCString(password); + _write.EndMessage(); + } + + private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken) + { + if (IsBroken) throw new DatabaseConnectionException("The connection is broken."); + cancellationToken.ThrowIfCancellationRequested(); + var op = new Operation(this, sql, parameters, decodeRows, cancellationToken); + if (cancellationToken.CanBeCanceled) + op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op); + return op; + } + + private void RequestCancel(Operation op) + { + if (op.Completed) return; + op.CancelSent = true; + Volatile.Write(ref _pendingCancel, SendCancelRequestAsync()); + // If the server does not react, the socket is aborted so the caller is never stuck. + _ioAbort.CancelAfter(CancelGracePeriod); + } + + private async Task SendCancelRequestAsync() + { + try + { + using var timeout = new CancellationTokenSource(CancelGracePeriod); + using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + await socket.ConnectAsync(_settings.Host, _settings.Port, timeout.Token).ConfigureAwait(false); + var packet = new byte[16]; + BinaryPrimitives.WriteInt32BigEndian(packet, 16); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(4), CancelRequestCode); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(8), ProcessId); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(12), _secretKey); + await socket.SendAsync(packet, SocketFlags.None, timeout.Token).ConfigureAwait(false); + // The postmaster closes the socket once it has signalled the backend. + await socket.ReceiveAsync(new byte[1], SocketFlags.None, timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is SocketException or OperationCanceledException or IOException) + { + Log.Warning(LogCategory, $"Cancel request to backend {ProcessId} failed: {ex.Message}"); + } + } + + /// Drains an abandoned response, then makes sure a late cancel request cannot hit the next command. + private async ValueTask EndOperationAsync(Operation op) + { + try + { + if (!op.Completed && !IsBroken) + { + try + { + await DrainAsync(op).ConfigureAwait(false); + } + catch (Exception ex) when (ex is PostgresException or OperationCanceledException) + { + // Errors after the consumer stopped reading are not its concern. + } + } + } + finally + { + op.Completed = true; + await op.Registration.DisposeAsync().ConfigureAwait(false); + if (op.CancelSent) + { + try + { + await Volatile.Read(ref _pendingCancel).WaitAsync(CancelGracePeriod).ConfigureAwait(false); + } + catch (TimeoutException) + { + IsBroken = true; + } + } + if (!_ioAbort.TryReset()) + { + IsBroken = true; + _ioAbort.Dispose(); + _ioAbort = new CancellationTokenSource(); + } + MarkIdle(); + } + } + + private async ValueTask SendExtendedAsync(Operation op) + { + var statement = Lookup(op.Sql, op.ParameterOids, out var hit); + op.Statement = statement; + op.CacheHit = hit; + try + { + foreach (var name in _statementsToClose) + { + _write.StartMessage('C'); + _write.WriteByte((byte)'S'); + _write.WriteCString(name); + _write.EndMessage(); + } + if (!hit) + { + _write.StartMessage('P'); + _write.WriteCString(statement.Name); + _write.WriteCString(op.Sql); + _write.WriteInt16(op.ParameterOids.Length); + foreach (var oid in op.ParameterOids) _write.WriteInt32((int)oid); + _write.EndMessage(); + _write.StartMessage('D'); + _write.WriteByte((byte)'S'); + _write.WriteCString(statement.Name); + _write.EndMessage(); + } + WriteBind(statement.Name, op.Parameters); + _write.StartMessage('E'); + _write.WriteCString(string.Empty); + _write.WriteInt32(0); + _write.EndMessage(); + _write.StartMessage('S'); + _write.EndMessage(); + } + catch + { + // Nothing was sent: forget the half-built batch so the connection stays usable. + _write.Clear(); + op.Completed = true; + throw; + } + _statementsToClose.Clear(); + await FlushAsync(op).ConfigureAwait(false); + } + + private void WriteBind(string statement, DbParam[] parameters) + { + _write.StartMessage('B'); + _write.WriteCString(string.Empty); + _write.WriteCString(statement); + _write.WriteInt16(parameters.Length); + foreach (var p in parameters) _write.WriteInt16(p.Type == DbValueType.Bytes ? 1 : 0); + _write.WriteInt16(parameters.Length); + foreach (var p in parameters) + { + switch (p.Value) + { + case null: + _write.WriteInt32(-1); + break; + case byte[] bytes: + _write.WriteInt32(bytes.Length); + _write.Write(bytes); + break; + case var value: + var span = _write.GetSpan(4 + PgTypes.MaxTextLength(value)); + var n = PgTypes.FormatText(value, span[4..]); + BinaryPrimitives.WriteInt32BigEndian(span, n); + _write.Advance(4 + n); + break; + } + } + _write.WriteInt16(1); + _write.WriteInt16(0); // every result column in text format + _write.EndMessage(); + } + + private void WriteQuery(string sql) + { + _write.StartMessage('Q'); + _write.WriteCString(sql); + _write.EndMessage(); + } + + /// Reads until the next DataRow (returned) or the end of the response (null), then throws any server error. + private async ValueTask ReadRowAsync(Operation op) + { + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + switch (type) + { + case (byte)'1': + Remember(op.Statement!); + break; + case (byte)'T': + op.Statement!.SetColumns(ParseRowDescription(out var oids), oids); + break; + case (byte)'n': + op.Statement!.SetColumns(NoColumns, []); + break; + case (byte)'D': + if (op.DecodeRows) return DecodeRow(op.Statement!); + break; + case (byte)'C': + op.Tag = ReadTag(); + op.Affected = AffectedRows(op.Tag); + break; + case (byte)'E': + OnError(op); + break; + case (byte)'Z': + // A cached statement invalidated by DDL is re-prepared once, if no transaction was aborted by it. + if (op.Error is { } stale && op.CacheHit && op.CanRetryStale && IsStale(stale) && Payload[0] == 'I') + { + TransactionStatus = 'I'; + op.Error = null; + op.CanRetryStale = false; + await SendExtendedAsync(op).ConfigureAwait(false); + break; + } + if (Complete(op) is { } error) throw error; + return null; + case (byte)'2' or (byte)'3' or (byte)'t' or (byte)'I' or (byte)'s': + break; + default: + throw ProtocolViolation(type); + } + } + } + + /// Reads to ReadyForQuery, keeping the command tag and the first error; answers stray COPY requests. + private async ValueTask DrainAsync(Operation op) + { + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + switch (type) + { + case (byte)'C': + op.Tag = ReadTag(); + op.Affected = AffectedRows(op.Tag); + break; + case (byte)'E': + OnError(op); + break; + case (byte)'G': + _write.StartMessage('f'); + _write.WriteCString("COPY FROM STDIN is only supported through BulkInsertAsync."); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + break; + case (byte)'Z': + if (Complete(op) is { } error) throw error; + return; + } + } + } + + /// Handles an ErrorResponse: keeps the first error, evicts a stale cached statement, and ends the operation on FATAL. + private void OnError(Operation op) + { + var error = ParseError(); + op.Error ??= error; + if (op.CacheHit && IsStale(error)) Evict(op.Statement!, close: error.SqlState != "26000"); + if (error.IsFatal) + { + // The server closes the session after FATAL; no ReadyForQuery follows. + IsBroken = true; + op.Completed = true; + throw error; + } + } + + /// Marks the operation finished at ReadyForQuery and returns the exception to raise, if any. + private Exception? Complete(Operation op) + { + TransactionStatus = (char)Payload[0]; + op.Completed = true; + return op.Error switch + { + null => null, + { SqlState: "57014" } e when op.Cancellation.IsCancellationRequested => new OperationCanceledException("The query was cancelled.", e, op.Cancellation), + var e => e, + }; + } + + private static bool IsStale(PostgresException e) => e.SqlState is "26000" or "0A000"; + + private PgStatement Lookup(string sql, uint[] oids, out bool hit) + { + if (_statements.TryGetValue(sql, out var node)) + { + if (node.Value.ParameterOids.AsSpan().SequenceEqual(oids)) + { + _statementLru.Remove(node); + _statementLru.AddFirst(node); + hit = true; + return node.Value; + } + Evict(node.Value, close: true); + } + hit = false; + var name = _settings.StatementCacheSize > 0 ? "titano_" + (++_statementCounter).ToString(CultureInfo.InvariantCulture) : string.Empty; + return new PgStatement(name, sql, oids); + } + + /// Caches a statement once the server confirmed its Parse; the least recently used one is closed when full. + private void Remember(PgStatement statement) + { + if (statement.Name.Length == 0 || _statements.ContainsKey(statement.Sql)) return; + _statements[statement.Sql] = _statementLru.AddFirst(statement); + while (_statementLru.Count > _settings.StatementCacheSize) Evict(_statementLru.Last!.Value, close: true); + } + + private void Evict(PgStatement statement, bool close) + { + if (_statements.Remove(statement.Sql, out var node)) _statementLru.Remove(node); + if (close && statement.Name.Length > 0) _statementsToClose.Add(statement.Name); + } + + private async ValueTask NextMessageAsync(Operation op) + { + try + { + return await ReadMessageAsync(_ioAbort.Token).ConfigureAwait(false); + } + catch (Exception ex) when (IsIoFailure(ex)) + { + throw ConnectionLost(ex, op); + } + } + + private async ValueTask FlushAsync(Operation op) + { + try + { + await WriteAndClearAsync(_ioAbort.Token).ConfigureAwait(false); + } + catch (Exception ex) when (IsIoFailure(ex)) + { + throw ConnectionLost(ex, op); + } + } + + private async ValueTask WriteAndClearAsync(CancellationToken cancellationToken) + { + try + { + await _stream.WriteAsync(_write.Written, cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _write.Clear(); + } + } + + private static bool IsIoFailure(Exception ex) => + ex is IOException or SocketException or ObjectDisposedException or OperationCanceledException; + + private Exception ConnectionLost(Exception ex, Operation op) + { + IsBroken = true; + op.Completed = true; + return op.Cancellation.IsCancellationRequested + ? new OperationCanceledException("The query was cancelled and the connection closed.", ex, op.Cancellation) + : new DatabaseConnectionException($"The connection to {_settings.Host}:{_settings.Port} was lost: {ex.Message}", ex); + } + + private DatabaseConnectionException ProtocolViolation(byte type) + { + IsBroken = true; + return new DatabaseConnectionException($"Protocol violation: unexpected message '{(char)type}'."); + } + + /// Reads one message into the buffer, handling notices, parameter changes and notifications inline. + private async ValueTask ReadMessageAsync(CancellationToken cancellationToken) + { + while (true) + { + await EnsureAsync(5, cancellationToken).ConfigureAwait(false); + var type = _read[_readPos]; + var length = BinaryPrimitives.ReadInt32BigEndian(_read.AsSpan(_readPos + 1)); + if (length < 4) throw ProtocolViolation(type); + _readPos += 5; + await EnsureAsync(length - 4, cancellationToken).ConfigureAwait(false); + _messageStart = _readPos; + _messageLength = length - 4; + _readPos += _messageLength; + switch (type) + { + case (byte)'N': + LogNotice(); + continue; + case (byte)'S': + { + var pos = 0; + var name = ReadCString(Payload, ref pos); + _serverParameters[name] = ReadCString(Payload, ref pos); + continue; + } + case (byte)'A': + { + var pos = 4; + var channel = ReadCString(Payload, ref pos); + var payload = ReadCString(Payload, ref pos); + NotificationReceived?.Invoke(new PgNotification(BinaryPrimitives.ReadInt32BigEndian(Payload), channel, payload)); + continue; + } + default: + return type; + } + } + } + + private async ValueTask EnsureAsync(int count, CancellationToken cancellationToken) + { + if (_readEnd - _readPos >= count) return; + if (_readPos + count > _read.Length) + { + var target = count > _read.Length ? new byte[Math.Max(count, _read.Length * 2)] : _read; + Buffer.BlockCopy(_read, _readPos, target, 0, _readEnd - _readPos); + _read = target; + _readEnd -= _readPos; + _readPos = 0; + } + while (_readEnd - _readPos < count) + { + var n = await _stream.ReadAsync(_read.AsMemory(_readEnd), cancellationToken).ConfigureAwait(false); + if (n == 0) throw new EndOfStreamException("The server closed the connection."); + _readEnd += n; + } + } + + private DbColumns ParseRowDescription(out uint[] oids) + { + var payload = Payload; + var count = BinaryPrimitives.ReadInt16BigEndian(payload); + var names = new string[count]; + oids = new uint[count]; + var pos = 2; + for (var i = 0; i < count; i++) + { + names[i] = ReadCString(payload, ref pos); + oids[i] = BinaryPrimitives.ReadUInt32BigEndian(payload[(pos + 6)..]); + pos += 18; // table oid, column number, type oid, type size, type modifier, format + } + return new DbColumns(names); + } + + private DbRow DecodeRow(PgStatement statement) + { + var payload = Payload; + var oids = statement.ColumnOids ?? throw ProtocolViolation((byte)'D'); + var values = new object?[BinaryPrimitives.ReadInt16BigEndian(payload)]; + var pos = 2; + for (var i = 0; i < values.Length; i++) + { + var length = BinaryPrimitives.ReadInt32BigEndian(payload[pos..]); + pos += 4; + if (length < 0) continue; + values[i] = PgTypes.Decode(oids[i], payload.Slice(pos, length)); + pos += length; + } + return new DbRow(statement.Columns!, values); + } + + private string ReadTag() + { + var pos = 0; + return ReadCString(Payload, ref pos); + } + + /// Row count of an INSERT/UPDATE/DELETE/MERGE/COPY tag ("INSERT 0 5" → 5); 0 for other commands. + private static int AffectedRows(string tag) + { + var space = tag.LastIndexOf(' '); + if (space < 0) return 0; + var command = tag[..tag.IndexOf(' ', StringComparison.Ordinal)]; + if (command is not ("INSERT" or "UPDATE" or "DELETE" or "MERGE" or "COPY")) return 0; + return long.TryParse(tag.AsSpan(space + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? (int)Math.Min(n, int.MaxValue) : 0; + } + + private PostgresException ParseError() + { + var fields = ParseFields(); + fields.TryGetValue('V', out var severity); + fields.TryGetValue('S', out var localized); + fields.TryGetValue('C', out var code); + fields.TryGetValue('M', out var message); + fields.TryGetValue('P', out var position); + return new PostgresException(severity ?? localized ?? "ERROR", code ?? "XX000", message ?? string.Empty) + { + Detail = fields.GetValueOrDefault('D'), + Hint = fields.GetValueOrDefault('H'), + Position = int.TryParse(position, NumberStyles.None, CultureInfo.InvariantCulture, out var p) ? p : null, + Where = fields.GetValueOrDefault('W'), + SchemaName = fields.GetValueOrDefault('s'), + TableName = fields.GetValueOrDefault('t'), + ColumnName = fields.GetValueOrDefault('c'), + ConstraintName = fields.GetValueOrDefault('n'), + }; + } + + private void LogNotice() + { + var fields = ParseFields(); + var severity = fields.GetValueOrDefault('V') ?? fields.GetValueOrDefault('S') ?? "NOTICE"; + var text = $"{severity} {fields.GetValueOrDefault('C')}: {fields.GetValueOrDefault('M')}"; + if (severity == "WARNING") Log.Warning(LogCategory, text); + else if (severity is "DEBUG" or "LOG") Log.Debug(LogCategory, text); + else Log.Info(LogCategory, text); + } + + private Dictionary ParseFields() + { + var payload = Payload; + var fields = new Dictionary(); + var pos = 0; + while (pos < payload.Length && payload[pos] != 0) + { + var field = (char)payload[pos++]; + fields[field] = ReadCString(payload, ref pos); + } + return fields; + } + + private static string ReadCString(ReadOnlySpan payload, ref int pos) + { + var end = payload[pos..].IndexOf((byte)0); + if (end < 0) throw new DatabaseConnectionException("Protocol violation: unterminated string."); + var value = Encoding.UTF8.GetString(payload.Slice(pos, end)); + pos += end + 1; + return value; + } + + /// State of one command: its statement, the first server error, and cancellation bookkeeping. + private sealed class Operation(PgConnector owner, string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellation) + { + public PgConnector Owner { get; } = owner; + public string Sql { get; } = sql; + public DbParam[] Parameters { get; } = parameters; + public uint[] ParameterOids { get; } = Array.ConvertAll(parameters, p => PgTypes.OidOf(p.Type)); + public bool DecodeRows { get; } = decodeRows; + public CancellationToken Cancellation { get; } = cancellation; + public CancellationTokenRegistration Registration { get; set; } + public PgStatement? Statement { get; set; } + public bool CacheHit { get; set; } + public bool CanRetryStale { get; set; } = true; + public PostgresException? Error { get; set; } + public string? Tag { get; set; } + public int Affected { get; set; } + public bool Completed { get; set; } + public bool CancelSent { get; set; } + } + + /// A server-side prepared statement and its result shape. + private sealed class PgStatement(string name, string sql, uint[] parameterOids) + { + public string Name { get; } = name; + public string Sql { get; } = sql; + public uint[] ParameterOids { get; } = parameterOids; + public DbColumns? Columns { get; private set; } + public uint[]? ColumnOids { get; private set; } + + public void SetColumns(DbColumns columns, uint[] oids) + { + Columns = columns; + ColumnOids = oids; + } + } +} diff --git a/src/Titano.Data/Postgres/PgListener.cs b/src/Titano.Data/Postgres/PgListener.cs new file mode 100644 index 00000000..dd5455c8 --- /dev/null +++ b/src/Titano.Data/Postgres/PgListener.cs @@ -0,0 +1,96 @@ +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// +/// LISTEN/NOTIFY on a dedicated connection (multi-instance job wake-ups). is raised on +/// a background thread; ends when the listener is disposed or faults if the connection +/// is lost, after which a new listener must be created. +/// +public sealed class PgListener : IAsyncDisposable +{ + private const string LogCategory = "Data.Postgres"; + private readonly PgConnector _connector; + private readonly SemaphoreSlim _commandLock = new(1, 1); + private readonly CancellationTokenSource _stop = new(); + private TaskCompletionSource? _pending; + + internal PgListener(PgConnector connector) + { + _connector = connector; + connector.NotificationReceived = Raise; + Completion = Task.Run(RunAsync); + } + + public event EventHandler? Notification; + + public Task Completion { get; } + + public Task ListenAsync(string channel, CancellationToken cancellationToken = default) => + CommandAsync("LISTEN " + SqlDialect.QuoteIdentifier(channel), cancellationToken); + + public Task UnlistenAsync(string channel, CancellationToken cancellationToken = default) => + CommandAsync("UNLISTEN " + SqlDialect.QuoteIdentifier(channel), cancellationToken); + + public async ValueTask DisposeAsync() + { + if (_stop.IsCancellationRequested) return; + await _stop.CancelAsync().ConfigureAwait(false); + await _connector.DisposeAsync().ConfigureAwait(false); + try + { + await Completion.ConfigureAwait(false); + } + catch (Exception ex) when (ex is DatabaseException or OperationCanceledException) + { + // The loop ends with whatever the closed socket raised. + } + _stop.Dispose(); + } + + private async Task CommandAsync(string sql, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_stop.IsCancellationRequested, this); + await _commandLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (Completion.IsCompleted) throw new DatabaseConnectionException("The listener connection is closed.", Completion.Exception?.InnerException); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Volatile.Write(ref _pending, pending); + await _connector.SendQueryAsync(sql, cancellationToken).ConfigureAwait(false); + if (await pending.Task.WaitAsync(cancellationToken).ConfigureAwait(false) is { } error) throw error; + } + finally + { + _commandLock.Release(); + } + } + + private async Task RunAsync() + { + try + { + await _connector.RunListenerAsync(error => Volatile.Read(ref _pending)?.TrySetResult(error), _stop.Token).ConfigureAwait(false); + } + catch (Exception) when (_stop.IsCancellationRequested) + { + } + finally + { + Volatile.Read(ref _pending)?.TrySetException(new DatabaseConnectionException("The listener connection is closed.")); + } + } + + private void Raise(PgNotification notification) + { + try + { + Notification?.Invoke(this, notification); + } + catch (Exception ex) + { + // A faulty handler must not stop delivery to the others. + Log.Error(LogCategory, $"Notification handler failed for channel '{notification.Channel}'.", ex); + } + } +} diff --git a/src/Titano.Data/Postgres/PgPool.cs b/src/Titano.Data/Postgres/PgPool.cs new file mode 100644 index 00000000..2e2002b6 --- /dev/null +++ b/src/Titano.Data/Postgres/PgPool.cs @@ -0,0 +1,128 @@ +using System.Net.Sockets; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// +/// Connection pool: at most Maximum Pool Size connections, reused most-recent-first; a connection idle +/// longer than Health Check Interval is pinged with SELECT 1 before reuse; broken connections and +/// those left inside a transaction are discarded; idle ones beyond Minimum Pool Size are closed after +/// Connection Idle Lifetime. +/// +internal sealed class PgPool : IAsyncDisposable +{ + private const string LogCategory = "Data.Postgres"; + private static readonly TimeSpan PruneInterval = TimeSpan.FromSeconds(10); + + private readonly PostgresSettings _settings; + private readonly SemaphoreSlim _slots; + private readonly LinkedList _idle = new(); + private readonly Lock _gate = new(); + private readonly Timer _pruner; + private bool _disposed; + + public PgPool(PostgresSettings settings) + { + _settings = settings; + _slots = new SemaphoreSlim(settings.MaxPoolSize, settings.MaxPoolSize); + var interval = settings.IdleLifetime < PruneInterval ? settings.IdleLifetime : PruneInterval; + _pruner = new Timer(static state => ((PgPool)state!).Prune(), this, interval, interval); + } + + public async Task RentAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!await _slots.WaitAsync(_settings.ConnectTimeout, cancellationToken).ConfigureAwait(false)) + throw new DatabaseConnectionException($"No pooled connection became free within {_settings.ConnectTimeout.TotalSeconds} s (Maximum Pool Size={_settings.MaxPoolSize})."); + try + { + while (TakeIdle() is { } connector) + { + if (!connector.IsBroken + && (connector.IdleTime < _settings.HealthCheckInterval || await connector.PingAsync(cancellationToken).ConfigureAwait(false))) + return connector; + await connector.DisposeAsync().ConfigureAwait(false); + } + return await OpenAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + _slots.Release(); + throw; + } + } + + /// Takes a connection back; a broken one, or one not idle at transaction level, is closed instead. + public void Return(PgConnector connector) + { + PgConnector? discard = connector; + if (!connector.IsBroken && connector.TransactionStatus == 'I') + { + connector.MarkIdle(); + lock (_gate) + { + if (!_disposed) + { + _idle.AddFirst(connector); + discard = null; + } + } + } + if (discard is not null) _ = discard.DisposeAsync().AsTask(); + _slots.Release(); + } + + public async ValueTask DisposeAsync() + { + List idle; + lock (_gate) + { + if (_disposed) return; + _disposed = true; + idle = [.. _idle]; + _idle.Clear(); + } + await _pruner.DisposeAsync().ConfigureAwait(false); + foreach (var connector in idle) await connector.DisposeAsync().ConfigureAwait(false); + } + + /// Opens a connection, retrying once after a second when the server is starting up or refused it. + private async Task OpenAsync(CancellationToken cancellationToken) + { + try + { + return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is PostgresException { IsConnectionFailure: true } or DatabaseConnectionException { InnerException: SocketException }) + { + Log.Warning(LogCategory, $"Connecting to {_settings.Host}:{_settings.Port} failed ({ex.Message}); retrying once."); + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false); + return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false); + } + } + + private PgConnector? TakeIdle() + { + lock (_gate) + { + if (_idle.First is not { } first) return null; + _idle.RemoveFirst(); + return first.Value; + } + } + + private void Prune() + { + List? expired = null; + lock (_gate) + { + while (_idle.Count > _settings.MinPoolSize && _idle.Last is { } last && last.Value.IdleTime >= _settings.IdleLifetime) + { + _idle.RemoveLast(); + (expired ??= []).Add(last.Value); + } + } + if (expired is null) return; + foreach (var connector in expired) _ = connector.DisposeAsync().AsTask(); + } +} diff --git a/src/Titano.Data/Postgres/PgTypes.cs b/src/Titano.Data/Postgres/PgTypes.cs new file mode 100644 index 00000000..0f8d3302 --- /dev/null +++ b/src/Titano.Data/Postgres/PgTypes.cs @@ -0,0 +1,219 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Globalization; +using System.Text; + +namespace Titano.Data.Postgres; + +/// Type OIDs, text-format value encoding and result decoding (BRIEF §6.3 type mapping). +internal static class PgTypes +{ + public const uint Bool = 16; + public const uint Bytea = 17; + public const uint Char = 18; + public const uint Name = 19; + public const uint Int8 = 20; + public const uint Int2 = 21; + public const uint Int4 = 23; + public const uint Text = 25; + public const uint Oid = 26; + public const uint Json = 114; + public const uint Float4 = 700; + public const uint Float8 = 701; + public const uint Bpchar = 1042; + public const uint Varchar = 1043; + public const uint Date = 1082; + public const uint Timestamp = 1114; + public const uint TimestampTz = 1184; + public const uint Numeric = 1700; + public const uint Uuid = 2950; + public const uint Jsonb = 3802; + + private static readonly SearchValues CopySpecials = SearchValues.Create("\\\t\n\r"); + + /// Parameter type sent in Parse; 0 lets the server infer an untyped NULL. + public static uint OidOf(DbValueType type) => type switch + { + DbValueType.Text => Text, + DbValueType.Int32 => Int4, + DbValueType.Int64 => Int8, + DbValueType.Double => Float8, + DbValueType.Bool => Bool, + DbValueType.Uuid => Uuid, + DbValueType.Timestamp => TimestampTz, + DbValueType.LocalDateTime => Timestamp, + DbValueType.Bytes => Bytea, + DbValueType.Json => Jsonb, + _ => 0, + }; + + /// + /// Writes the text form of a canonical value (anything but byte[]) as UTF-8 and returns + /// the byte count. must hold bytes. + /// + public static int FormatText(object value, Span destination) + { + var inv = CultureInfo.InvariantCulture; + int written; + bool ok; + switch (value) + { + case string s: + return Encoding.UTF8.GetBytes(s, destination); + case bool b: + destination[0] = b ? (byte)'t' : (byte)'f'; + return 1; + case int i: + ok = i.TryFormat(destination, out written, default, inv); + break; + case long l: + ok = l.TryFormat(destination, out written, default, inv); + break; + case double d: + ok = d.TryFormat(destination, out written, "R", inv); + break; + case Guid g: + ok = g.TryFormat(destination, out written, "D"); + break; + case DateTimeOffset o: + ok = o.UtcDateTime.TryFormat(destination, out written, "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'", inv); + break; + case DateTime d: + ok = d.TryFormat(destination, out written, "yyyy-MM-dd'T'HH:mm:ss.ffffff", inv); + break; + default: + throw new NotSupportedException($"Cannot send {value.GetType().Name} as text."); + } + return ok ? written : throw new FormatException($"Cannot format {value}."); + } + + /// Upper bound of output for . + public static int MaxTextLength(object value) => value is string s ? Encoding.UTF8.GetMaxByteCount(s.Length) : 64; + + /// + /// Writes a value in COPY text format: \N for NULL, specials in strings backslash-escaped, bytea in + /// hex form (\\x…). Values of other CLR types go through normalisation. + /// + public static void WriteCopyValue(object? value, IBufferWriter writer) + { + switch (value) + { + case null: + writer.Write("\\N"u8); + return; + case string s: + WriteCopyEscaped(s, writer); + return; + case byte[] bytes: + { + var span = writer.GetSpan(3 + bytes.Length * 2); + "\\\\x"u8.CopyTo(span); + for (var i = 0; i < bytes.Length; i++) + { + span[3 + 2 * i] = HexDigits[bytes[i] >> 4]; + span[4 + 2 * i] = HexDigits[bytes[i] & 0xF]; + } + writer.Advance(3 + bytes.Length * 2); + return; + } + case int or long or double or bool or Guid or DateTimeOffset: + case DateTime { Kind: DateTimeKind.Unspecified }: + writer.Advance(FormatText(value, writer.GetSpan(64))); + return; + default: + var normalized = new DbParam(value); + WriteCopyValue(normalized.Value, writer); + return; + } + } + + private static void WriteCopyEscaped(string s, IBufferWriter writer) + { + var rest = s.AsSpan(); + while (!rest.IsEmpty) + { + var special = rest.IndexOfAny(CopySpecials); + var plain = special < 0 ? rest : rest[..special]; + if (!plain.IsEmpty) + { + var n = Encoding.UTF8.GetBytes(plain, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(plain.Length))); + writer.Advance(n); + } + if (special < 0) return; + writer.Write(rest[special] switch + { + '\\' => "\\\\"u8, + '\t' => "\\t"u8, + '\n' => "\\n"u8, + _ => "\\r"u8, + }); + rest = rest[(special + 1)..]; + } + } + + /// Decodes a text-format result value by its type OID; unknown types stay strings. + public static object Decode(uint oid, ReadOnlySpan utf8) + { + var inv = CultureInfo.InvariantCulture; + switch (oid) + { + case Bool: + return utf8.Length > 0 && utf8[0] == (byte)'t'; + case Int2 or Int4: + return int.Parse(utf8, NumberStyles.AllowLeadingSign, inv); + case Int8 or Oid: + return long.Parse(utf8, NumberStyles.AllowLeadingSign, inv); + case Float4 or Float8: + return double.Parse(utf8, NumberStyles.Float, inv); + case Uuid: + return Utf8Parser.TryParse(utf8, out Guid guid, out var consumed) && consumed == utf8.Length + ? guid + : throw new FormatException("Malformed uuid."); + case Bytea: + return DecodeBytea(utf8); + case TimestampTz or Timestamp or Date when utf8.Length <= 64: + Span chars = stackalloc char[utf8.Length]; + Encoding.ASCII.GetChars(utf8, chars); + return oid switch + { + TimestampTz => TextValues.ParseTimestamp(chars), + Timestamp => TextValues.ParseLocal(chars), + _ => DateOnly.ParseExact(chars, "yyyy-MM-dd", inv), + }; + default: + return Encoding.UTF8.GetString(utf8); + } + } + + /// bytea output: hex (\x0a0b, the default since 9.0) or the legacy escape format. + private static byte[] DecodeBytea(ReadOnlySpan text) + { + if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x') + return Convert.FromHexString(Encoding.ASCII.GetString(text[2..])); + var result = new List(text.Length); + for (var i = 0; i < text.Length; i++) + { + if (text[i] != '\\') + { + result.Add(text[i]); + } + else if (i + 1 < text.Length && text[i + 1] == '\\') + { + result.Add((byte)'\\'); + i++; + } + else if (i + 3 < text.Length) + { + result.Add((byte)(((text[i + 1] - '0') << 6) | ((text[i + 2] - '0') << 3) | (text[i + 3] - '0'))); + i += 3; + } + else + { + throw new FormatException("Malformed bytea escape sequence."); + } + } + return [.. result]; + } + + private static ReadOnlySpan HexDigits => "0123456789abcdef"u8; +} diff --git a/src/Titano.Data/Postgres/PgWriteBuffer.cs b/src/Titano.Data/Postgres/PgWriteBuffer.cs new file mode 100644 index 00000000..6c761553 --- /dev/null +++ b/src/Titano.Data/Postgres/PgWriteBuffer.cs @@ -0,0 +1,98 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Data.Postgres; + +/// Growable outgoing buffer that frames protocol messages (type byte + big-endian length). +internal sealed class PgWriteBuffer : IBufferWriter +{ + private byte[] _buffer = new byte[8192]; + private int _messageStart = -1; + + public int Length { get; private set; } + + public ReadOnlyMemory Written => _buffer.AsMemory(0, Length); + + /// Starts a message; its length is patched by . + public void StartMessage(char type) + { + GetSpan(1)[0] = (byte)type; + Advance(1); + StartUntypedMessage(); + } + + /// Starts a message without a type byte (startup, SSL and cancel requests). + public void StartUntypedMessage() + { + _messageStart = Length; + Advance(4); + } + + public void EndMessage() + { + BinaryPrimitives.WriteInt32BigEndian(_buffer.AsSpan(_messageStart), Length - _messageStart); + _messageStart = -1; + } + + public void WriteByte(byte value) + { + GetSpan(1)[0] = value; + Advance(1); + } + + public void WriteInt16(int value) + { + BinaryPrimitives.WriteInt16BigEndian(GetSpan(2), checked((short)value)); + Advance(2); + } + + public void WriteInt32(int value) + { + BinaryPrimitives.WriteInt32BigEndian(GetSpan(4), value); + Advance(4); + } + + public void Write(ReadOnlySpan bytes) + { + bytes.CopyTo(GetSpan(bytes.Length)); + Advance(bytes.Length); + } + + /// UTF-8 text followed by a NUL terminator. + public void WriteCString(string text) + { + var n = Encoding.UTF8.GetBytes(text, GetSpan(Encoding.UTF8.GetMaxByteCount(text.Length) + 1)); + _buffer[Length + n] = 0; + Advance(n + 1); + } + + /// Empties the buffer; an oversized one (a big bytea parameter) is released so pooled connections stay small. + public void Clear() + { + Length = 0; + _messageStart = -1; + if (_buffer.Length > 1 << 20) _buffer = new byte[8192]; + } + + public void Advance(int count) => Length += count; + + public Memory GetMemory(int sizeHint = 0) + { + Ensure(sizeHint); + return _buffer.AsMemory(Length); + } + + public Span GetSpan(int sizeHint = 0) + { + Ensure(sizeHint); + return _buffer.AsSpan(Length); + } + + private void Ensure(int sizeHint) + { + var needed = Length + Math.Max(sizeHint, 1); + if (needed <= _buffer.Length) return; + Array.Resize(ref _buffer, Math.Max(needed, _buffer.Length * 2)); + } +} diff --git a/src/Titano.Data/Postgres/PostgresDatabase.cs b/src/Titano.Data/Postgres/PostgresDatabase.cs new file mode 100644 index 00000000..81fc0417 --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresDatabase.cs @@ -0,0 +1,216 @@ +using System.Runtime.CompilerServices; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// A PostgreSQL server reached through the in-house protocol v3 client and its connection pool. +public sealed class PostgresDatabase(PostgresSettings settings) : IDatabase +{ + private readonly PgPool _pool = new(settings); + + public PostgresSettings Settings { get; } = settings; + + public Dialect Dialect => Dialect.Postgres; + + public async Task OpenAsync(CancellationToken cancellationToken) => + new PostgresSession(_pool, await _pool.RentAsync(cancellationToken).ConfigureAwait(false)); + + /// Opens a dedicated (unpooled) connection that raises an event for every NOTIFY on its channels. + public async Task CreateListenerAsync(CancellationToken cancellationToken = default) => + new(await PgConnector.OpenAsync(Settings, cancellationToken).ConfigureAwait(false)); + + public ValueTask DisposeAsync() => _pool.DisposeAsync(); +} + +/// +/// A pooled PostgreSQL connection. Reads (SELECT/VALUES/SHOW/TABLE) outside a transaction are retried once on a +/// fresh connection when the first attempt fails with a connection error before returning any row. +/// +internal sealed class PostgresSession(PgPool pool, PgConnector connector) : IDbSession +{ + private const string LogCategory = "Data.Postgres"; + private PgConnector? _connector = connector; + private PostgresTransaction? _transaction; + private bool _disposed; + + public Dialect Dialect => Dialect.Postgres; + + public bool InTransaction => _transaction is not null; + + private PgConnector Connector + { + get + { + ObjectDisposedException.ThrowIf(_disposed, this); + return _connector ?? throw new DatabaseConnectionException("The session lost its connection."); + } + } + + public Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + Connector.ExecuteAsync(sql, parameters, cancellationToken); + + public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) + { + var retry = _transaction is null && IsReadOnlyQuery(sql); + while (true) + { + var rows = Connector.QueryAsync(sql, parameters, cancellationToken).GetAsyncEnumerator(CancellationToken.None); + var yielded = false; + Exception? failure = null; + try + { + while (true) + { + bool more; + try + { + more = await rows.MoveNextAsync().ConfigureAwait(false); + } + catch (Exception ex) when (retry && !yielded && IsConnectionFailure(ex)) + { + failure = ex; + break; + } + if (!more) yield break; + yielded = true; + yield return rows.Current; + } + } + finally + { + await rows.DisposeAsync().ConfigureAwait(false); + } + Log.Warning(LogCategory, $"Retrying a read on a new connection after: {failure!.Message}"); + retry = false; + var broken = _connector!; + _connector = null; + pool.Return(broken); + _connector = await pool.RentAsync(cancellationToken).ConfigureAwait(false); + } + } + + public Task ExecuteScriptAsync(string script, CancellationToken cancellationToken) => + Connector.SimpleQueryAsync(script, cancellationToken); + + public async Task BeginAsync(CancellationToken cancellationToken) + { + if (_transaction is not null) throw new InvalidOperationException("A transaction is already active on this session."); + await Connector.SimpleQueryAsync("BEGIN", cancellationToken).ConfigureAwait(false); + return _transaction = new PostgresTransaction(this); + } + + public Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows, CancellationToken cancellationToken) + { + if (columns.Count == 0) throw new ArgumentException("At least one column is required.", nameof(columns)); + var sql = $"COPY {SqlDialect.QuoteIdentifier(table)} ({string.Join(", ", columns.Select(SqlDialect.QuoteIdentifier))}) FROM STDIN"; + return Connector.CopyInAsync(sql, columns.Count, rows, cancellationToken); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + if (_connector is not { } connection) return; + _connector = null; + if (_transaction is not null && !connection.IsBroken) + { + try + { + await connection.SimpleQueryAsync("ROLLBACK", CancellationToken.None).ConfigureAwait(false); + } + catch (DatabaseException ex) + { + Log.Warning(LogCategory, "Rollback on session close failed; the connection is discarded.", ex); + } + } + _transaction = null; + pool.Return(connection); + } + + /// Ends if it is still active. COMMIT of an aborted transaction is reported, not silently rolled back. + internal async Task EndTransactionAsync(PostgresTransaction transaction, bool commit, CancellationToken cancellationToken) + { + if (_transaction != transaction) return; + try + { + if (!commit) + { + await Connector.SimpleQueryAsync("ROLLBACK", cancellationToken).ConfigureAwait(false); + } + else if (Connector.TransactionStatus == 'E') + { + await Connector.SimpleQueryAsync("ROLLBACK", cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("The transaction was aborted by an earlier error and has been rolled back."); + } + else if (await Connector.SimpleQueryAsync("COMMIT", cancellationToken).ConfigureAwait(false) == "ROLLBACK") + { + throw new InvalidOperationException("The server rolled the transaction back instead of committing it."); + } + } + finally + { + if (_connector is not { IsBroken: false, TransactionStatus: not 'I' }) _transaction = null; + } + } + + private static bool IsConnectionFailure(Exception ex) => + ex is DatabaseConnectionException or PostgresException { IsConnectionFailure: true }; + + /// True for statements that only read, so running them twice is harmless. + internal static bool IsReadOnlyQuery(string sql) + { + var s = sql.AsSpan(); + while (true) + { + s = s.TrimStart(); + if (s.StartsWith("--", StringComparison.Ordinal)) + { + var newline = s.IndexOf('\n'); + s = newline < 0 ? default : s[(newline + 1)..]; + } + else if (s.StartsWith("/*", StringComparison.Ordinal)) + { + var end = s.IndexOf("*/", StringComparison.Ordinal); + s = end < 0 ? default : s[(end + 2)..]; + } + else + { + break; + } + } + foreach (var keyword in (ReadOnlySpan)["SELECT", "VALUES", "SHOW", "TABLE"]) + { + if (s.StartsWith(keyword, StringComparison.OrdinalIgnoreCase) + && (s.Length == keyword.Length || !(char.IsLetterOrDigit(s[keyword.Length]) || s[keyword.Length] == '_'))) + return true; + } + return false; + } +} + +/// A BEGIN … COMMIT block on one session. +internal sealed class PostgresTransaction(PostgresSession session) : IDbTransaction +{ + private bool _completed; + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + _completed = true; + await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false); + } + + public async Task RollbackAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + _completed = true; + await session.EndTransactionAsync(this, commit: false, cancellationToken).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + if (_completed) return; + _completed = true; + await session.EndTransactionAsync(this, commit: false, CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Titano.Data/Postgres/PostgresException.cs b/src/Titano.Data/Postgres/PostgresException.cs new file mode 100644 index 00000000..92a1159c --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresException.cs @@ -0,0 +1,47 @@ +namespace Titano.Data.Postgres; + +/// An ErrorResponse from the server, with the standard fields of the PostgreSQL protocol. +public sealed class PostgresException : DatabaseException +{ + internal PostgresException(string severity, string sqlState, string messageText) + : base($"{severity} {sqlState}: {messageText}") + { + Severity = severity; + SqlState = sqlState; + MessageText = messageText; + } + + /// ERROR, FATAL or PANIC (non-localised when the server sends it). + public string Severity { get; } + + /// Five-character SQLSTATE, e.g. 23505 (unique_violation). + public override string SqlState { get; } + + /// The primary human-readable message. + public string MessageText { get; } + + public string? Detail { get; internal init; } + public string? Hint { get; internal init; } + + /// 1-based character position of the error in the statement text. + public int? Position { get; internal init; } + + public string? Where { get; internal init; } + public string? SchemaName { get; internal init; } + public string? TableName { get; internal init; } + public string? ColumnName { get; internal init; } + public string? ConstraintName { get; internal init; } + + /// The server ends the session after FATAL/PANIC errors. + public bool IsFatal => Severity is "FATAL" or "PANIC"; + + /// Server shutdown/startup or connection failures (57P01, 57P02, 57P03, class 08): a new connection may succeed. + public bool IsConnectionFailure => SqlState is "57P01" or "57P02" or "57P03" || SqlState.StartsWith("08", StringComparison.Ordinal); + + /// Connection failures plus serialization failures and deadlocks. + public override bool IsTransient => IsConnectionFailure || SqlState is "40001" or "40P01"; + + public override bool IsUniqueViolation => SqlState == "23505"; + + public override bool IsForeignKeyViolation => SqlState == "23503"; +} diff --git a/src/Titano.Data/Postgres/PostgresSettings.cs b/src/Titano.Data/Postgres/PostgresSettings.cs new file mode 100644 index 00000000..76e003d6 --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresSettings.cs @@ -0,0 +1,84 @@ +namespace Titano.Data.Postgres; + +/// TLS policy, with libpq's meaning. +public enum SslMode +{ + /// Plain TCP. + Disable, + + /// TLS when the server offers it, without certificate verification; plain TCP otherwise. + Prefer, + + /// TLS or fail; the certificate is not verified. + Require, + + /// TLS with a trusted chain whose certificate matches the host name. + VerifyFull, +} + +/// +/// PostgreSQL connection settings. Keys (case/space-insensitive): Host, Port (5432), Database +/// (defaults to the user), Username, Password, SslMode (prefer), Root Certificate +/// (PEM trusted by verify-full), Application Name (titano-server), Search Path, Timeout +/// (connect, 15 s), Minimum Pool Size (0), Maximum Pool Size (20), Connection Idle Lifetime +/// (300 s), Health Check Interval (30 s idle before a pooled connection is pinged), +/// Statement Cache Size (128 prepared statements per connection; 0 disables). +/// +public sealed record PostgresSettings +{ + public required string Host { get; init; } + public int Port { get; init; } = 5432; + public required string Database { get; init; } + public required string Username { get; init; } + public string? Password { get; init; } + public SslMode SslMode { get; init; } = SslMode.Prefer; + public string? RootCertificate { get; init; } + public string ApplicationName { get; init; } = "titano-server"; + public string? SearchPath { get; init; } + public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(15); + public int MinPoolSize { get; init; } + public int MaxPoolSize { get; init; } = 20; + public TimeSpan IdleLifetime { get; init; } = TimeSpan.FromSeconds(300); + public TimeSpan HealthCheckInterval { get; init; } = TimeSpan.FromSeconds(30); + public int StatementCacheSize { get; init; } = 128; + + public static PostgresSettings Parse(string connectionString) + { + var cs = new ConnectionString(connectionString); + var host = cs.Get("Host", "Server") ?? throw new FormatException("A PostgreSQL connection string needs 'Host'."); + var user = cs.Get("Username", "User Id", "User", "UserName") ?? throw new FormatException("A PostgreSQL connection string needs 'Username'."); + var settings = new PostgresSettings + { + Host = host, + Port = cs.GetInt(5432, "Port"), + Username = user, + Database = cs.Get("Database", "DB") ?? user, + Password = cs.Get("Password", "Pwd"), + SslMode = ParseSslMode(cs.Get("SslMode", "Ssl Mode")), + RootCertificate = cs.Get("Root Certificate", "SslRootCert"), + ApplicationName = cs.Get("Application Name") ?? "titano-server", + SearchPath = cs.Get("Search Path"), + ConnectTimeout = TimeSpan.FromSeconds(cs.GetInt(15, "Timeout", "Connect Timeout")), + MinPoolSize = cs.GetInt(0, "Minimum Pool Size", "Min Pool Size"), + MaxPoolSize = cs.GetInt(20, "Maximum Pool Size", "Max Pool Size"), + IdleLifetime = TimeSpan.FromSeconds(cs.GetInt(300, "Connection Idle Lifetime")), + HealthCheckInterval = TimeSpan.FromSeconds(cs.GetInt(30, "Health Check Interval")), + StatementCacheSize = cs.GetInt(128, "Statement Cache Size", "Max Auto Prepare"), + }; + cs.ThrowOnUnknownKeys(); + if (settings.MaxPoolSize < 1 || settings.MinPoolSize < 0 || settings.MinPoolSize > settings.MaxPoolSize) + throw new FormatException("Pool sizes must satisfy 0 ≤ Minimum Pool Size ≤ Maximum Pool Size, Maximum ≥ 1."); + if (settings.StatementCacheSize < 0 || settings.ConnectTimeout <= TimeSpan.Zero) + throw new FormatException("'Statement Cache Size' must be ≥ 0 and 'Timeout' > 0."); + return settings; + } + + private static SslMode ParseSslMode(string? value) => value?.Trim().ToLowerInvariant() switch + { + null or "" or "prefer" => SslMode.Prefer, + "disable" => SslMode.Disable, + "require" => SslMode.Require, + "verify-full" or "verifyfull" => SslMode.VerifyFull, + _ => throw new FormatException($"Unsupported SslMode '{value}' (use disable, prefer, require or verify-full)."), + }; +} From 83d8cd79bdb400cfa271fbc19c883179b2303600 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:41:20 +0000 Subject: [PATCH 024/188] feat(protocol): API v1 contract and typed client DTOs for auth, users, sequences, frames, manifests, uploads, jobs, render nodes, events and LAN discovery; TitanoClient with TOFU certificate pinning, bearer auth, resumable SHA-256-verified chunked uploads with retry/backoff, shared bandwidth limiter and the event WebSocket stream. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Protocol/Auth.cs | 31 ++ .../Client/BandwidthLimiter.cs | 45 +++ .../Client/CertificatePinning.cs | 34 ++ .../Client/TitanoApiException.cs | 23 ++ src/Titano.Protocol/Client/TitanoClient.cs | 359 ++++++++++++++++++ src/Titano.Protocol/Discovery.cs | 31 ++ src/Titano.Protocol/Dtos.cs | 11 - src/Titano.Protocol/Events.cs | 22 ++ src/Titano.Protocol/Jobs.cs | 36 ++ src/Titano.Protocol/ProtocolJson.cs | 48 +++ src/Titano.Protocol/Sequences.cs | 104 +++++ src/Titano.Protocol/Uploads.cs | 18 + 12 files changed, 751 insertions(+), 11 deletions(-) create mode 100644 src/Titano.Protocol/Auth.cs create mode 100644 src/Titano.Protocol/Client/BandwidthLimiter.cs create mode 100644 src/Titano.Protocol/Client/CertificatePinning.cs create mode 100644 src/Titano.Protocol/Client/TitanoApiException.cs create mode 100644 src/Titano.Protocol/Client/TitanoClient.cs create mode 100644 src/Titano.Protocol/Discovery.cs create mode 100644 src/Titano.Protocol/Events.cs create mode 100644 src/Titano.Protocol/Jobs.cs create mode 100644 src/Titano.Protocol/ProtocolJson.cs create mode 100644 src/Titano.Protocol/Sequences.cs create mode 100644 src/Titano.Protocol/Uploads.cs diff --git a/src/Titano.Protocol/Auth.cs b/src/Titano.Protocol/Auth.cs new file mode 100644 index 00000000..077009c1 --- /dev/null +++ b/src/Titano.Protocol/Auth.cs @@ -0,0 +1,31 @@ +namespace Titano.Protocol; + +/// POST /api/v1/auth/login. = true asks for an HttpOnly session cookie (web admin). +public sealed record LoginRequest(string Username, string Password, string ClientName, bool Cookie = false); + +public sealed record LoginResponse(string? Token, UserDto User, bool MustChangePassword, DateTimeOffset ExpiresAt); + +/// POST /api/v1/auth/password. +public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword); + +public sealed record UserDto( + Guid Id, + string Username, + string? DisplayName, + string Role, + long Permissions, + long QuotaBytes, + long UsedBytes, + bool Disabled, + bool MustChangePassword, + DateTimeOffset Created, + DateTimeOffset? LastLogin); + +/// POST /api/v1/users (admin). +public sealed record CreateUserRequest(string Username, string? DisplayName, string Role, long QuotaBytes, string? Password, bool AllowRenderNode); + +/// PATCH /api/v1/users/{id} (admin); null fields stay unchanged. +public sealed record UpdateUserRequest(string? DisplayName, string? Role, long? QuotaBytes, bool? Disabled, bool? AllowRenderNode); + +/// Response of POST /api/v1/users and /users/{id}/reset-password: a temporary password shown once. +public sealed record TemporaryPasswordResponse(UserDto User, string TemporaryPassword); diff --git a/src/Titano.Protocol/Client/BandwidthLimiter.cs b/src/Titano.Protocol/Client/BandwidthLimiter.cs new file mode 100644 index 00000000..10361151 --- /dev/null +++ b/src/Titano.Protocol/Client/BandwidthLimiter.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; + +namespace Titano.Protocol.Client; + +/// Token bucket shared by concurrent uploads (Uploader "Limit … MB/s"). 0 = unlimited. +public sealed class BandwidthLimiter +{ + private readonly Lock _gate = new(); + private readonly Stopwatch _clock = Stopwatch.StartNew(); + private double _tokens; + private double _last; + private long _bytesPerSecond; + + public BandwidthLimiter(long bytesPerSecond = 0) => BytesPerSecond = bytesPerSecond; + + public long BytesPerSecond + { + get => Interlocked.Read(ref _bytesPerSecond); + set => Interlocked.Exchange(ref _bytesPerSecond, Math.Max(0, value)); + } + + /// Waits until may be sent. + public async ValueTask AcquireAsync(int bytes, CancellationToken cancellationToken) + { + while (true) + { + var rate = BytesPerSecond; + if (rate == 0) return; + TimeSpan wait; + lock (_gate) + { + var now = _clock.Elapsed.TotalSeconds; + _tokens = Math.Min(rate, _tokens + (now - _last) * rate); + _last = now; + if (_tokens >= bytes || _tokens >= rate) + { + _tokens -= bytes; + return; + } + wait = TimeSpan.FromSeconds(Math.Min(1.0, (bytes - _tokens) / rate)); + } + await Task.Delay(wait, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Titano.Protocol/Client/CertificatePinning.cs b/src/Titano.Protocol/Client/CertificatePinning.cs new file mode 100644 index 00000000..f905b429 --- /dev/null +++ b/src/Titano.Protocol/Client/CertificatePinning.cs @@ -0,0 +1,34 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Titano.Protocol.Client; + +/// +/// Trust-on-first-use certificate validation: a certificate is accepted when it chains to a trusted root or when +/// its SHA-256 fingerprint is in the caller's trusted set. The last unknown fingerprint is remembered so the UI can +/// ask the user once and add it. +/// +public sealed class CertificatePinning(IEnumerable trustedFingerprints) +{ + private readonly HashSet _trusted = new(trustedFingerprints.Select(Normalize), StringComparer.Ordinal); + + public string? LastRejectedFingerprint { get; private set; } + + public void Trust(string fingerprint) => _trusted.Add(Normalize(fingerprint)); + + public bool Validate(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors) + { + if (certificate is null) return false; + if (errors == SslPolicyErrors.None) return true; + var fingerprint = Fingerprint(certificate); + if (_trusted.Contains(fingerprint)) return true; + LastRejectedFingerprint = fingerprint; + return false; + } + + public static string Fingerprint(X509Certificate certificate) => + string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + + private static string Normalize(string fingerprint) => fingerprint.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); +} diff --git a/src/Titano.Protocol/Client/TitanoApiException.cs b/src/Titano.Protocol/Client/TitanoApiException.cs new file mode 100644 index 00000000..03a3aef5 --- /dev/null +++ b/src/Titano.Protocol/Client/TitanoApiException.cs @@ -0,0 +1,23 @@ +using System.Net; + +namespace Titano.Protocol.Client; + +/// A non-success API response carrying the server's . +public sealed class TitanoApiException(HttpStatusCode status, ApiError error) + : Exception($"{(int)status} {error.Code}: {error.Message}") +{ + public HttpStatusCode Status { get; } = status; + public ApiError Error { get; } = error; + + /// True for errors worth retrying (server busy, gateway, timeout). + public bool IsTransient => Status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests + or HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout; +} + +/// The server presented a certificate whose fingerprint is not trusted yet (trust-on-first-use, BRIEF §12.7). +public sealed class UntrustedCertificateException(string fingerprint) + : Exception("Server certificate is not trusted: " + fingerprint) +{ + /// SHA-256 fingerprint (XX:XX:…) to show the user before trusting it. + public string Fingerprint { get; } = fingerprint; +} diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs new file mode 100644 index 00000000..d8f57f51 --- /dev/null +++ b/src/Titano.Protocol/Client/TitanoClient.cs @@ -0,0 +1,359 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Net.WebSockets; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace Titano.Protocol.Client; + +/// Upload progress for one file. +public readonly record struct UploadProgress(long BytesSent, long BytesTotal); + +/// +/// Typed client for Titano Server API v1 (BRIEF §14.3), used by the desktop client and the uploader. +/// Thread-safe; one instance per server connection. +/// +public sealed class TitanoClient : IDisposable +{ + private readonly HttpClient _http; + private readonly CertificatePinning _pinning; + private string? _token; + + public TitanoClient(Uri baseAddress, CertificatePinning pinning, string clientName, HttpMessageHandler? handler = null) + { + _pinning = pinning; + ClientName = clientName; + BaseAddress = baseAddress; + var socketsHandler = handler ?? new SocketsHttpHandler + { + SslOptions = { RemoteCertificateValidationCallback = pinning.Validate }, + PooledConnectionLifetime = TimeSpan.FromMinutes(5), + ConnectTimeout = TimeSpan.FromSeconds(10), + AutomaticDecompression = DecompressionMethods.None, + }; + _http = new HttpClient(socketsHandler) { BaseAddress = baseAddress, Timeout = Timeout.InfiniteTimeSpan }; + _http.DefaultRequestHeaders.Add(ApiVersion.Header, ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture)); + _http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Titano", typeof(TitanoClient).Assembly.GetName().Version?.ToString(3) ?? "0")); + } + + public Uri BaseAddress { get; } + public string ClientName { get; } + public CertificatePinning Pinning => _pinning; + + /// Bearer token; set after or restored from secure storage. + public string? Token + { + get => _token; + set + { + _token = value; + _http.DefaultRequestHeaders.Authorization = value is null ? null : new AuthenticationHeaderValue("Bearer", value); + } + } + + /// Shared upload rate limit. + public BandwidthLimiter Bandwidth { get; } = new(); + + // ---------------- Server ---------------- + + /// Reads server info; throws when the TLS certificate needs confirmation. + public Task GetInfoAsync(CancellationToken ct = default) => GetAsync("api/v1/server/info", ProtocolJson.Default.ServerInfo, ct); + + // ---------------- Auth ---------------- + + public async Task LoginAsync(string username, string password, CancellationToken ct = default) + { + var response = await SendAsync(HttpMethod.Post, "api/v1/auth/login", new LoginRequest(username, password, ClientName), ProtocolJson.Default.LoginRequest, ProtocolJson.Default.LoginResponse, ct).ConfigureAwait(false); + Token = response.Token; + return response; + } + + public async Task LogoutAsync(CancellationToken ct = default) + { + await SendNoContentAsync(HttpMethod.Post, "api/v1/auth/logout", ct).ConfigureAwait(false); + Token = null; + } + + public Task MeAsync(CancellationToken ct = default) => GetAsync("api/v1/auth/me", ProtocolJson.Default.UserDto, ct); + + public Task ChangePasswordAsync(string current, string next, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/auth/password", new ChangePasswordRequest(current, next), ProtocolJson.Default.ChangePasswordRequest, ct); + + // ---------------- Sequences ---------------- + + public Task> ListSequencesAsync(string? query = null, string? cursor = null, int limit = 200, CancellationToken ct = default) => + GetAsync($"api/v1/sequences?limit={limit}{Q("q", query)}{Q("cursor", cursor)}", ProtocolJson.Default.PageSequenceDto, ct); + + public Task GetSequenceAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/sequences/{id}", ProtocolJson.Default.SequenceDto, ct); + + public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/sequences", request, ProtocolJson.Default.CreateSequenceRequest, ProtocolJson.Default.SequenceDto, ct); + + /// Updates metadata/settings; a 409 means the settings changed on the server. + public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Patch, $"api/v1/sequences/{id}", request, ProtocolJson.Default.UpdateSequenceRequest, ProtocolJson.Default.SequenceDto, ct); + + public Task GetManifestAsync(Guid id, CancellationToken ct = default) => + GetAsync($"api/v1/sequences/{id}/manifest", ProtocolJson.Default.SequenceManifest, ct); + + public Task> ListFramesAsync(Guid sequenceId, string? cursor = null, int limit = 1000, CancellationToken ct = default) => + GetAsync($"api/v1/sequences/{sequenceId}/frames?limit={limit}{Q("cursor", cursor)}", ProtocolJson.Default.PageFrameDto, ct); + + /// Streams a frame resource (original, proxy or thumb) to , resuming with Range from its current length. + public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, IProgress? progress = null, CancellationToken ct = default) + { + if (kind is not ("original" or "proxy" or "thumb")) throw new ArgumentOutOfRangeException(nameof(kind)); + using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v1/frames/{frameId}/{kind}"); + if (destination.CanSeek && destination.Length > 0) + { + destination.Seek(0, SeekOrigin.End); + request.Headers.Range = new RangeHeaderValue(destination.Length, null); + } + using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.OK && destination.CanSeek) destination.SetLength(0); + await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + var buffer = new byte[1 << 16]; + long total = 0; + int read; + while ((read = await body.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) + { + await destination.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + total += read; + progress?.Report(total); + } + } + + // ---------------- Uploads ---------------- + + /// + /// Uploads one file with resumable, idempotent chunks; the server verifies the SHA-256 before committing it + /// (BRIEF §14.4). Returns the committed frame id. Transient failures retry with exponential backoff. + /// + public async Task UploadFileAsync( + string path, + Guid? sequenceId, + DateTime? capturedAt, + string? sessionKey = null, + string? knownSha256 = null, + IProgress? progress = null, + CancellationToken ct = default) + { + var info = new FileInfo(path); + var sha = knownSha256 ?? await HashFileAsync(path, ct).ConfigureAwait(false); + var start = await RetryAsync(() => SendAsync(HttpMethod.Post, "api/v1/uploads", + new StartUploadRequest(sequenceId, info.Name, info.Length, sha, capturedAt, sessionKey), + ProtocolJson.Default.StartUploadRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false); + if (start.AlreadyExists) + { + progress?.Report(new UploadProgress(info.Length, info.Length)); + return start.FrameId is { } existing ? new CompleteUploadResponse(existing, sequenceId ?? Guid.Empty, -1) : null; + } + + var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id."); + var chunkSize = start.ChunkSize; + var received = new HashSet(start.Received); + var chunks = (int)((info.Length + chunkSize - 1) / chunkSize); + var buffer = new byte[chunkSize]; + await using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + long sent = received.Count == 0 ? 0 : received.Sum(i => (long)Math.Min(chunkSize, info.Length - (long)i * chunkSize)); + progress?.Report(new UploadProgress(sent, info.Length)); + for (var n = 0; n < chunks; n++) + { + if (received.Contains(n)) continue; + var offset = (long)n * chunkSize; + var length = (int)Math.Min(chunkSize, info.Length - offset); + file.Position = offset; + await file.ReadExactlyAsync(buffer.AsMemory(0, length), ct).ConfigureAwait(false); + await Bandwidth.AcquireAsync(length, ct).ConfigureAwait(false); + await RetryAsync(async () => + { + using var content = new ByteArrayContent(buffer, 0, length); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{n}", content, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return true; + }, ct).ConfigureAwait(false); + sent += length; + progress?.Report(new UploadProgress(sent, info.Length)); + } + } + return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false); + } + + /// Lower-case hex SHA-256 of a file, streamed. + public static async Task HashFileAsync(string path, CancellationToken ct = default) + { + await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan); + var hash = await SHA256.HashDataAsync(file, ct).ConfigureAwait(false); + return Convert.ToHexStringLower(hash); + } + + // ---------------- Jobs and render nodes ---------------- + + public Task> ListJobsAsync(string? state = null, string? cursor = null, CancellationToken ct = default) => + GetAsync($"api/v1/jobs?limit=200{Q("state", state)}{Q("cursor", cursor)}", ProtocolJson.Default.PageJobDto, ct); + + public Task CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct); + + public Task CancelJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/cancel", ProtocolJson.Default.JobDto, ct); + + public Task RetryJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/retry", ProtocolJson.Default.JobDto, ct); + + public Task RegisterNodeAsync(RegisterNodeRequest request, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, "api/v1/nodes/register", request, ProtocolJson.Default.RegisterNodeRequest, ProtocolJson.Default.RenderNodeDto, ct); + + public Task HeartbeatAsync(Guid nodeId, CancellationToken ct = default) => SendNoContentAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/heartbeat", ct); + + /// Claims the next render job matching this node; null when there is none. + public async Task ClaimAsync(Guid nodeId, CancellationToken ct = default) + { + using var response = await _http.PostAsync($"api/v1/nodes/{nodeId}/claim", null, ct).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NoContent) return null; + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ClaimedJob, ct).ConfigureAwait(false); + } + + public Task ReportNodeProgressAsync(Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/progress", progress, ProtocolJson.Default.NodeProgress, ct); + + // ---------------- Events ---------------- + + /// Server events over WebSocket until cancelled; reconnect is the caller's policy. + public async IAsyncEnumerable EventsAsync([EnumeratorCancellation] CancellationToken ct = default) + { + using var socket = new ClientWebSocket(); + socket.Options.RemoteCertificateValidationCallback = _pinning.Validate; + if (_token is not null) socket.Options.SetRequestHeader("Authorization", "Bearer " + _token); + var ws = new UriBuilder(new Uri(BaseAddress, "api/v1/events")) { Scheme = BaseAddress.Scheme == "https" ? "wss" : "ws" }.Uri; + await socket.ConnectAsync(ws, ct).ConfigureAwait(false); + var buffer = new byte[64 * 1024]; + using var message = new MemoryStream(); + while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested) + { + var result = await socket.ReceiveAsync(buffer, ct).ConfigureAwait(false); + if (result.MessageType == WebSocketMessageType.Close) yield break; + message.Write(buffer, 0, result.Count); + if (!result.EndOfMessage) continue; + ServerEvent? e = null; + try + { + e = JsonSerializer.Deserialize(message.GetBuffer().AsSpan(0, (int)message.Length), ProtocolJson.Default.ServerEvent); + } + catch (JsonException) + { + // Unknown event types from a newer server are ignored. + } + message.SetLength(0); + if (e is not null) yield return e; + } + } + + public void Dispose() => _http.Dispose(); + + // ---------------- Plumbing ---------------- + + private async Task GetAsync(string url, JsonTypeInfo type, CancellationToken ct) + { + using var response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, url), ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return (await response.Content.ReadFromJsonAsync(type, ct).ConfigureAwait(false))!; + } + + private async Task SendAsync(HttpMethod method, string url, TRequest body, JsonTypeInfo requestType, JsonTypeInfo responseType, CancellationToken ct) + { + using var request = new HttpRequestMessage(method, url) { Content = JsonContent.Create(body, requestType) }; + using var response = await SendRawAsync(request, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return (await response.Content.ReadFromJsonAsync(responseType, ct).ConfigureAwait(false))!; + } + + private async Task SendAsync(HttpMethod method, string url, TRequest body, JsonTypeInfo requestType, CancellationToken ct) + { + using var request = new HttpRequestMessage(method, url) { Content = JsonContent.Create(body, requestType) }; + using var response = await SendRawAsync(request, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + } + + private async Task SendAsync(HttpMethod method, string url, JsonTypeInfo responseType, CancellationToken ct) + { + using var response = await SendRawAsync(new HttpRequestMessage(method, url), ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return (await response.Content.ReadFromJsonAsync(responseType, ct).ConfigureAwait(false))!; + } + + private async Task SendNoContentAsync(HttpMethod method, string url, CancellationToken ct) + { + using var response = await SendRawAsync(new HttpRequestMessage(method, url), ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + } + + private async Task SendRawAsync(HttpRequestMessage request, CancellationToken ct) + { + using (request) + { + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(100)); + return await _http.SendAsync(request, timeout.Token).ConfigureAwait(false); + } + catch (HttpRequestException) when (_pinning.LastRejectedFingerprint is { } fingerprint) + { + throw new UntrustedCertificateException(fingerprint); + } + } + } + + private static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct) + { + if (response.IsSuccessStatusCode) return; + ApiError error; + try + { + error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false) + ?? new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error"); + } + catch (JsonException) + { + error = new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error"); + } + catch (NotSupportedException) + { + error = new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error"); + } + throw new TitanoApiException(response.StatusCode, error); + } + + /// Retries transient failures 5 times with exponential backoff (1, 2, 4, 8, 16 s). + private static async Task RetryAsync(Func> action, CancellationToken ct) + { + for (var attempt = 0; ; attempt++) + { + try + { + return await action().ConfigureAwait(false); + } + catch (Exception ex) when (attempt < 5 && !ct.IsCancellationRequested && IsTransient(ex)) + { + await Task.Delay(TimeSpan.FromSeconds(1 << attempt), ct).ConfigureAwait(false); + } + } + } + + private static bool IsTransient(Exception ex) => ex switch + { + TitanoApiException api => api.IsTransient, + HttpRequestException => true, + TaskCanceledException => true, + IOException => true, + _ => false, + }; + + private static string Q(string name, string? value) => string.IsNullOrEmpty(value) ? string.Empty : "&" + name + "=" + Uri.EscapeDataString(value); +} diff --git a/src/Titano.Protocol/Discovery.cs b/src/Titano.Protocol/Discovery.cs new file mode 100644 index 00000000..d0d63465 --- /dev/null +++ b/src/Titano.Protocol/Discovery.cs @@ -0,0 +1,31 @@ +using System.Text; +using System.Text.Json; + +namespace Titano.Protocol; + +/// +/// LAN discovery (TITANO_DISCOVERY): the server broadcasts a small UDP beacon on port 48300 every few seconds; +/// clients listen and offer "Studio NAS found on this network" on first run. +/// +public sealed record DiscoveryBeacon(string Name, string Version, int HttpPort, int HttpsPort, string? TlsFingerprint) +{ + public const int Port = 48300; + private const string Magic = "TITANO1 "; + + public byte[] ToBytes() => Encoding.UTF8.GetBytes(Magic + JsonSerializer.Serialize(this, ProtocolJson.Default.DiscoveryBeacon)); + + public static DiscoveryBeacon? TryParse(ReadOnlySpan datagram) + { + if (datagram.Length > 2048) return null; + var text = Encoding.UTF8.GetString(datagram); + if (!text.StartsWith(Magic, StringComparison.Ordinal)) return null; + try + { + return JsonSerializer.Deserialize(text[Magic.Length..], ProtocolJson.Default.DiscoveryBeacon); + } + catch (JsonException) + { + return null; + } + } +} diff --git a/src/Titano.Protocol/Dtos.cs b/src/Titano.Protocol/Dtos.cs index c2408a07..d841902d 100644 --- a/src/Titano.Protocol/Dtos.cs +++ b/src/Titano.Protocol/Dtos.cs @@ -20,14 +20,3 @@ public sealed record ServerInfo( /// GET /health. public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary Checks); - -/// Source-generated JSON contracts shared by server and clients (camelCase, enums as strings). -[JsonSourceGenerationOptions( - PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - UseStringEnumConverter = true)] -[JsonSerializable(typeof(ApiError))] -[JsonSerializable(typeof(ServerInfo))] -[JsonSerializable(typeof(HealthStatus))] -[JsonSerializable(typeof(Dictionary))] -public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Titano.Protocol/Events.cs b/src/Titano.Protocol/Events.cs new file mode 100644 index 00000000..e149000c --- /dev/null +++ b/src/Titano.Protocol/Events.cs @@ -0,0 +1,22 @@ +using System.Text.Json.Serialization; + +namespace Titano.Protocol; + +/// +/// Messages pushed on WS /api/v1/events. Each frame is one JSON object with a type discriminator: +/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState. +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")] +[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")] +[JsonDerivedType(typeof(JobStateEvent), "jobState")] +[JsonDerivedType(typeof(SequenceChangedEvent), "sequenceChanged")] +[JsonDerivedType(typeof(NodeStateEvent), "nodeState")] +public abstract record ServerEvent; + +public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent; + +public sealed record JobStateEvent(Guid JobId, string State, string? Error) : ServerEvent; + +public sealed record SequenceChangedEvent(Guid SequenceId, string Change, int FramesVersion, int SettingsVersion) : ServerEvent; + +public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State) : ServerEvent; diff --git a/src/Titano.Protocol/Jobs.cs b/src/Titano.Protocol/Jobs.cs new file mode 100644 index 00000000..e5655af4 --- /dev/null +++ b/src/Titano.Protocol/Jobs.cs @@ -0,0 +1,36 @@ +namespace Titano.Protocol; + +public sealed record JobDto( + Guid Id, + string Kind, + IReadOnlyList TargetIds, + string? TargetLabel, + string State, + string Priority, + long ProgressDone, + long ProgressTotal, + double? ItemsPerSecond, + double? EtaSeconds, + string? LogTail, + string? NodeId, + int Attempts, + string? Error, + DateTimeOffset Created, + DateTimeOffset? Started, + DateTimeOffset? Finished); + +/// POST /api/v1/jobs: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance… +public sealed record CreateJobRequest(string Kind, IReadOnlyList Target, string? ParametersJson); + +/// POST /api/v1/nodes/register: a client offers its GPU encoders (BRIEF §14.7). +public sealed record RegisterNodeRequest(string ClientName, IReadOnlyList Encoders, int MaxWidth, int MaxHeight); + +public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit); + +public sealed record RenderNodeDto(Guid Id, string ClientName, string Username, IReadOnlyList Encoders, DateTimeOffset LastHeartbeat, string State); + +/// POST /api/v1/nodes/{id}/claim: the job and everything needed to run it, or 204 when none matches. +public sealed record ClaimedJob(JobDto Job, Guid SequenceId, string SettingsJson, string PresetJson, bool UseProxies, IReadOnlyList Frames); + +/// POST /api/v1/nodes/{id}/jobs/{jobId}/progress. +public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine); diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs new file mode 100644 index 00000000..2f3dad46 --- /dev/null +++ b/src/Titano.Protocol/ProtocolJson.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization; + +namespace Titano.Protocol; + +/// Source-generated JSON contracts shared by server and clients (camelCase, enums as strings). +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNameCaseInsensitive = true, + UseStringEnumConverter = true)] +[JsonSerializable(typeof(ApiError))] +[JsonSerializable(typeof(ServerInfo))] +[JsonSerializable(typeof(HealthStatus))] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(LoginRequest))] +[JsonSerializable(typeof(LoginResponse))] +[JsonSerializable(typeof(ChangePasswordRequest))] +[JsonSerializable(typeof(UserDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(CreateUserRequest))] +[JsonSerializable(typeof(UpdateUserRequest))] +[JsonSerializable(typeof(TemporaryPasswordResponse))] +[JsonSerializable(typeof(SequenceDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(CreateSequenceRequest))] +[JsonSerializable(typeof(UpdateSequenceRequest))] +[JsonSerializable(typeof(FrameDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(SequenceManifest))] +[JsonSerializable(typeof(RenderDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(ArchiveStatsDto))] +[JsonSerializable(typeof(StartUploadRequest))] +[JsonSerializable(typeof(StartUploadResponse))] +[JsonSerializable(typeof(ChunkReceived))] +[JsonSerializable(typeof(CompleteUploadResponse))] +[JsonSerializable(typeof(UploadState))] +[JsonSerializable(typeof(JobDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(CreateJobRequest))] +[JsonSerializable(typeof(RegisterNodeRequest))] +[JsonSerializable(typeof(RenderNodeDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(ClaimedJob))] +[JsonSerializable(typeof(NodeProgress))] +[JsonSerializable(typeof(ServerEvent))] +[JsonSerializable(typeof(DiscoveryBeacon))] +public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Titano.Protocol/Sequences.cs b/src/Titano.Protocol/Sequences.cs new file mode 100644 index 00000000..ab3bb730 --- /dev/null +++ b/src/Titano.Protocol/Sequences.cs @@ -0,0 +1,104 @@ +namespace Titano.Protocol; + +/// Sequence summary for lists (BRIEF §12.2 card data). +public sealed record SequenceDto( + Guid Id, + string? Title, + string DisplayTitle, + string Folder, + string? CameraMake, + string? CameraModel, + string? Lens, + DateTime? FirstCapture, + DateTime? LastCapture, + int FrameCount, + double? MedianInterval, + long TotalBytes, + long Status, + int RenderedCount, + Guid? HeroFrameId, + IReadOnlyList Tags, + int Rating, + string? Notes, + int SettingsVersion, + int FramesVersion, + int WarningCount, + Guid? OwnerUserId, + DateTimeOffset UpdatedAt); + +/// A page of results with an opaque keyset cursor; null cursor = last page. +public sealed record Page(IReadOnlyList Items, string? NextCursor, long? Total); + +/// POST /api/v1/sequences. +public sealed record CreateSequenceRequest(string? Title, string? CameraHint); + +/// PATCH /api/v1/sequences/{id}. enables conflict detection (409). +public sealed record UpdateSequenceRequest( + string? Title, + IReadOnlyList? Tags, + int? Rating, + string? Notes, + string? SettingsJson, + int? ExpectedSettingsVersion); + +public sealed record FrameDto( + Guid Id, + Guid SequenceId, + int Index, + string FileName, + long Size, + string? Sha256, + DateTime? CapturedAt, + int? UtcOffsetMinutes, + double? ExposureTime, + double? FNumber, + int? Iso, + double? FocalLength, + int Orientation, + int Width, + int Height, + string Format, + long Flags); + +/// GET /api/v1/sequences/{id}/manifest: what a client needs to diff a sequence (BRIEF §14.5). +public sealed record SequenceManifest( + Guid SequenceId, + int FramesVersion, + int SettingsVersion, + string? SettingsJson, + IReadOnlyList Tags, + IReadOnlyList Frames, + IReadOnlyList Renders); + +public sealed record ManifestFrame(Guid Id, int Index, string FileName, long Size, string Sha256, bool HasProxy, bool HasThumb); + +public sealed record RenderDto( + Guid Id, + string PresetName, + string? Codec, + int Width, + int Height, + double Fps, + double DurationSeconds, + long Bytes, + DateTimeOffset Created, + string? ProducedBy); + +/// Aggregates for the archive dashboard and the admin panel. +public sealed record ArchiveStatsDto( + long Sequences, + long Photos, + long Bytes, + long FreeBytes, + long CapacityBytes, + int Cameras, + int? FirstYear, + int? LastYear, + IReadOnlyList ByYear, + IReadOnlyList ByMonth, + IReadOnlyList ByCamera, + IReadOnlyList ByFormat, + int SequencesWithoutProxies, + int UnverifiedSequences); + +public sealed record KeyValueCount(string Key, long Count, long Bytes); diff --git a/src/Titano.Protocol/Uploads.cs b/src/Titano.Protocol/Uploads.cs new file mode 100644 index 00000000..b2ff863c --- /dev/null +++ b/src/Titano.Protocol/Uploads.cs @@ -0,0 +1,18 @@ +namespace Titano.Protocol; + +/// +/// POST /api/v1/uploads (BRIEF §14.4). The client hashes the file first; when the server already holds that +/// SHA-256 it answers 200 with and no upload is needed. +/// +public sealed record StartUploadRequest(Guid? SequenceId, string FileName, long Size, string Sha256, DateTime? CapturedAt, string? SessionKey); + +public sealed record StartUploadResponse(Guid? UploadId, int ChunkSize, IReadOnlyList Received, bool AlreadyExists, Guid? FrameId); + +/// PUT /api/v1/uploads/{id}/chunks/{n} response. +public sealed record ChunkReceived(int Index, IReadOnlyList Received); + +/// POST /api/v1/uploads/{id}/complete response: the committed frame. +public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int Index); + +/// GET /api/v1/uploads/{id}: resume state. +public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList Received, string State); From e15bbb997410e0d7b75fd56e0eb881bfd14cce8f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:41:34 +0000 Subject: [PATCH 025/188] feat(video): add AVI MJPEG writer with idx1 and OpenDML indexes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/Avi/AviMjpegWriter.cs | 312 ++++++++++++++++++ .../Video/AviMjpegWriterTests.cs | 205 ++++++++++++ 2 files changed, 517 insertions(+) create mode 100644 src/Titano.Core/Video/Avi/AviMjpegWriter.cs create mode 100644 tests/Titano.Core.Tests/Video/AviMjpegWriterTests.cs diff --git a/src/Titano.Core/Video/Avi/AviMjpegWriter.cs b/src/Titano.Core/Video/Avi/AviMjpegWriter.cs new file mode 100644 index 00000000..1e42fb5b --- /dev/null +++ b/src/Titano.Core/Video/Avi/AviMjpegWriter.cs @@ -0,0 +1,312 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Video.Avi; + +/// +/// Streaming RIFF AVI writer for already-encoded JPEG frames ('MJPG', chunks '00dc'). Writes the legacy idx1 index +/// for the first RIFF and OpenDML indexes ('indx' super index, one 'ix00' per RIFF) so files can continue in +/// 'AVIX' RIFF lists past the per-RIFF size limit. AVI is constant frame rate: repeat a frame to hold it longer. +/// The output stream must be seekable and is not disposed. +/// +public sealed class AviMjpegWriter +{ + /// Default size of each RIFF list; 1 GiB keeps the first RIFF readable by AVI 1.0 software. + public const long DefaultRiffSizeLimit = 1L << 30; + + private const int SuperIndexCapacity = 256; + private const uint KeyFrameFlag = 0x10; // AVIIF_KEYFRAME + private static readonly uint ChunkId = FourCc("00dc"); + + private readonly Stream _stream; + private readonly int _width; + private readonly int _height; + private readonly uint _rate; + private readonly uint _scale; + private readonly long _riffLimit; + private readonly long _start; + private readonly List<(long Offset, uint Size, uint Frames)> _superIndex = []; + private readonly List<(long DataOffset, uint Size)> _segmentFrames = []; + private long _avih, _strh, _indx, _dmlh; + private long _riffStart, _moviStart, _position; + private int _framesInFirstRiff; + private int _totalFrames; + private uint _maxFrame; + private bool _completed; + + /// Bytes per RIFF list before an 'AVIX' list starts (tests use small values). + public AviMjpegWriter(Stream output, int width, int height, Rational frameRate, long riffSizeLimit = DefaultRiffSizeLimit) + { + ArgumentNullException.ThrowIfNull(output); + if (!output.CanSeek || !output.CanWrite) throw new ArgumentException("The output stream must be writable and seekable", nameof(output)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate)); + ArgumentOutOfRangeException.ThrowIfLessThan(riffSizeLimit, 16 * 1024); + ArgumentOutOfRangeException.ThrowIfGreaterThan(riffSizeLimit, uint.MaxValue); + _stream = output; + _width = width; + _height = height; + var g = Gcd(frameRate.Numerator, frameRate.Denominator); + _rate = (uint)(frameRate.Numerator / g); + _scale = (uint)(frameRate.Denominator / g); + _riffLimit = riffSizeLimit; + _start = output.Position; + WriteHeaders(); + } + + public int FrameCount => _totalFrames; + + /// Appends one JPEG (SOI-prefixed) frame. + public void WriteFrame(ReadOnlySpan jpeg) + { + if (_completed) throw new InvalidOperationException("The writer is complete"); + if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) throw new ArgumentException("Not a JPEG frame", nameof(jpeg)); + var chunk = 8L + jpeg.Length + (jpeg.Length & 1); + if (_segmentFrames.Count > 0 && _position - _riffStart + chunk + IndexOverhead(_segmentFrames.Count + 1) > _riffLimit) + { + CloseSegment(); + OpenSegment("AVIX"); + } + + Span header = stackalloc byte[8]; + BinaryPrimitives.WriteUInt32LittleEndian(header, ChunkId); + BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)jpeg.Length); + _stream.Write(header); + _stream.Write(jpeg); + if ((jpeg.Length & 1) != 0) _stream.WriteByte(0); + _segmentFrames.Add((_position + 8, (uint)jpeg.Length)); + _position += chunk; + _maxFrame = Math.Max(_maxFrame, (uint)jpeg.Length); + _totalFrames++; + } + + /// Writes the indexes, patches sizes and frame counts, and flushes. + public void Complete() + { + if (_completed) throw new InvalidOperationException("The writer is already complete"); + CloseSegment(); + var buffer = _maxFrame + 8; + var bytesPerSecond = (uint)Math.Min(uint.MaxValue, (double)_maxFrame * _rate / _scale); + Patch(_avih + 4, bytesPerSecond); + Patch(_avih + 16, (uint)_framesInFirstRiff); + Patch(_avih + 28, buffer); + Patch(_strh + 32, (uint)_totalFrames); + Patch(_strh + 36, buffer); + Patch(_dmlh, (uint)_totalFrames); + Patch(_indx + 4, (uint)_superIndex.Count); + Span entry = stackalloc byte[16]; + for (var i = 0; i < _superIndex.Count; i++) + { + BinaryPrimitives.WriteInt64LittleEndian(entry, _superIndex[i].Offset); + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], _superIndex[i].Size); + BinaryPrimitives.WriteUInt32LittleEndian(entry[12..], _superIndex[i].Frames); + _stream.Position = _indx + 24 + i * 16; + _stream.Write(entry); + } + _stream.Position = _position; + _stream.Flush(); + _completed = true; + } + + /// Bytes the segment's ix00 (and idx1 in the first RIFF) will need for frames. + private long IndexOverhead(int frames) => 32 + 8L * frames + (_superIndex.Count == 0 ? 8 + 16L * frames : 0); + + private void WriteHeaders() + { + var h = new List(4800); + var riff = Begin(h, "RIFF", "AVI "); + var hdrl = Begin(h, "LIST", "hdrl"); + + _avih = ChunkStart(h, "avih", 56); + Add32(h, (uint)Math.Round(1_000_000.0 * _scale / _rate)); // dwMicroSecPerFrame + Add32(h, 0); // dwMaxBytesPerSec (patched) + Add32(h, 0); // dwPaddingGranularity + Add32(h, 0x10 | 0x100); // AVIF_HASINDEX | AVIF_ISINTERLEAVED + Add32(h, 0); // dwTotalFrames of the first RIFF (patched) + Add32(h, 0); // dwInitialFrames + Add32(h, 1); // dwStreams + Add32(h, 0); // dwSuggestedBufferSize (patched) + Add32(h, (uint)_width); + Add32(h, (uint)_height); + AddZeros(h, 16); + + var strl = Begin(h, "LIST", "strl"); + _strh = ChunkStart(h, "strh", 56); + Add32(h, FourCc("vids")); + Add32(h, FourCc("MJPG")); + Add32(h, 0); // dwFlags + Add32(h, 0); // wPriority, wLanguage + Add32(h, 0); // dwInitialFrames + Add32(h, _scale); + Add32(h, _rate); + Add32(h, 0); // dwStart + Add32(h, 0); // dwLength (patched) + Add32(h, 0); // dwSuggestedBufferSize (patched) + Add32(h, uint.MaxValue); // dwQuality: default + Add32(h, 0); // dwSampleSize: variable + Add16(h, 0); + Add16(h, 0); + Add16(h, (ushort)Math.Min(_width, short.MaxValue)); + Add16(h, (ushort)Math.Min(_height, short.MaxValue)); + + ChunkStart(h, "strf", 40); + Add32(h, 40); // BITMAPINFOHEADER.biSize + Add32(h, (uint)_width); + Add32(h, (uint)_height); + Add16(h, 1); // biPlanes + Add16(h, 24); // biBitCount + Add32(h, FourCc("MJPG")); + Add32(h, (uint)Math.Min(uint.MaxValue, (long)_width * _height * 3)); + AddZeros(h, 16); + + _indx = ChunkStart(h, "indx", 24 + 16 * SuperIndexCapacity); + Add16(h, 4); // wLongsPerEntry + h.Add(0); // bIndexSubType + h.Add(0); // bIndexType = AVI_INDEX_OF_INDEXES + Add32(h, 0); // nEntriesInUse (patched) + Add32(h, ChunkId); + AddZeros(h, 12 + 16 * SuperIndexCapacity); + End(h, strl); + + var odml = Begin(h, "LIST", "odml"); + _dmlh = ChunkStart(h, "dmlh", 248); + AddZeros(h, 248); + End(h, odml); + End(h, hdrl); + + // The RIFF size is patched when the first segment closes; the movi list follows directly. + _riffStart = _start + riff; + _stream.Write(h.ToArray()); + _avih += _start; + _strh += _start; + _indx += _start; + _dmlh += _start; + _position = _start + h.Count; + OpenMovi(); + } + + private void OpenSegment(string type) + { + _riffStart = _position; + Span header = stackalloc byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(header, FourCc("RIFF")); + BinaryPrimitives.WriteUInt32LittleEndian(header[8..], FourCc(type)); + _stream.Write(header); + _position += 12; + OpenMovi(); + } + + private void OpenMovi() + { + Span header = stackalloc byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(header, FourCc("LIST")); + BinaryPrimitives.WriteUInt32LittleEndian(header[8..], FourCc("movi")); + _stream.Write(header); + _moviStart = _position + 8; // offsets in idx1 and ix00 are relative to the 'movi' four-cc + _position += 12; + } + + private void CloseSegment() + { + if (_superIndex.Count == SuperIndexCapacity) throw new InvalidOperationException("AVI super index is full"); + var frames = _segmentFrames.Count; + + // Standard index (OpenDML ix00) closes the movi list. + var ixOffset = _position; + var ix = new byte[32 + 8 * frames]; + BinaryPrimitives.WriteUInt32LittleEndian(ix, FourCc("ix00")); + BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(4), (uint)(ix.Length - 8)); + BinaryPrimitives.WriteUInt16LittleEndian(ix.AsSpan(8), 2); // wLongsPerEntry + ix[11] = 1; // AVI_INDEX_OF_CHUNKS + BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(12), (uint)frames); + BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(16), ChunkId); + BinaryPrimitives.WriteInt64LittleEndian(ix.AsSpan(20), _moviStart); + for (var i = 0; i < frames; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(32 + i * 8), (uint)(_segmentFrames[i].DataOffset - _moviStart)); + BinaryPrimitives.WriteUInt32LittleEndian(ix.AsSpan(36 + i * 8), _segmentFrames[i].Size); // bit 31 clear: key frame + } + _stream.Position = ixOffset; + _stream.Write(ix); + _position += ix.Length; + Patch(_moviStart - 4, (uint)(_position - _moviStart)); + + if (_superIndex.Count == 0) + { + var idx1 = new byte[8 + 16 * frames]; + BinaryPrimitives.WriteUInt32LittleEndian(idx1, FourCc("idx1")); + BinaryPrimitives.WriteUInt32LittleEndian(idx1.AsSpan(4), (uint)(idx1.Length - 8)); + for (var i = 0; i < frames; i++) + { + var e = idx1.AsSpan(8 + i * 16); + BinaryPrimitives.WriteUInt32LittleEndian(e, ChunkId); + BinaryPrimitives.WriteUInt32LittleEndian(e[4..], KeyFrameFlag); + BinaryPrimitives.WriteUInt32LittleEndian(e[8..], (uint)(_segmentFrames[i].DataOffset - 8 - _moviStart)); + BinaryPrimitives.WriteUInt32LittleEndian(e[12..], _segmentFrames[i].Size); + } + _stream.Position = _position; + _stream.Write(idx1); + _position += idx1.Length; + _framesInFirstRiff = frames; + } + Patch(_riffStart + 4, (uint)(_position - _riffStart - 8)); + _superIndex.Add((ixOffset, (uint)ix.Length, (uint)frames)); + _segmentFrames.Clear(); + _stream.Position = _position; + } + + private void Patch(long offset, uint value) + { + Span bytes = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, value); + _stream.Position = offset; + _stream.Write(bytes); + } + + private static int Begin(List h, string id, string type) + { + var start = h.Count; + Add32(h, FourCc(id)); + Add32(h, 0); + Add32(h, FourCc(type)); + return start; + } + + private static void End(List h, int start) + { + var size = (uint)(h.Count - start - 8); + for (var i = 0; i < 4; i++) h[start + 4 + i] = (byte)(size >> (8 * i)); + } + + /// Writes a chunk header and returns the offset of its data. + private static int ChunkStart(List h, string id, int size) + { + Add32(h, FourCc(id)); + Add32(h, (uint)size); + return h.Count; + } + + private static void Add16(List h, ushort v) + { + h.Add((byte)v); + h.Add((byte)(v >> 8)); + } + + private static void Add32(List h, uint v) + { + for (var i = 0; i < 4; i++) h.Add((byte)(v >> (8 * i))); + } + + private static void AddZeros(List h, int count) + { + for (var i = 0; i < count; i++) h.Add(0); + } + + private static uint FourCc(string s) => (uint)(s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24); + + private static int Gcd(int a, int b) + { + while (b != 0) (a, b) = (b, a % b); + return a; + } +} diff --git a/tests/Titano.Core.Tests/Video/AviMjpegWriterTests.cs b/tests/Titano.Core.Tests/Video/AviMjpegWriterTests.cs new file mode 100644 index 00000000..47ee61f6 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/AviMjpegWriterTests.cs @@ -0,0 +1,205 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Video; +using Titano.Core.Video.Avi; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class AviMjpegWriterTests +{ + [Test] + public void SingleRiffHasHeadersIdx1AndStandardIndex() + { + var frames = Frames(10, 1); + var bytes = Write(frames, Rational.Fps2997, AviMjpegWriter.DefaultRiffSizeLimit); + var file = Riff.Parse(bytes); + Assert.Equal(bytes.Length, file.Sum(r => r.Size + 8)); + Assert.Count(1, file); + var riff = file[0]; + Assert.Equal("RIFF", riff.Id); + Assert.Equal("AVI ", riff.Type); + + var hdrl = riff.List("hdrl"); + var avih = hdrl.Chunk("avih").Data; + Assert.Equal(33367u, U32(avih, 0)); + Assert.Equal(10u, U32(avih, 16)); + Assert.Equal(1u, U32(avih, 24)); + Assert.Equal(64u, U32(avih, 32)); + Assert.Equal(48u, U32(avih, 36)); + var strl = hdrl.List("strl"); + var strh = strl.Chunk("strh").Data; + Assert.Equal("vids", Encoding.ASCII.GetString(strh, 0, 4)); + Assert.Equal("MJPG", Encoding.ASCII.GetString(strh, 4, 4)); + Assert.Equal(1001u, U32(strh, 20)); + Assert.Equal(30000u, U32(strh, 24)); + Assert.Equal(10u, U32(strh, 32)); + Assert.Equal("MJPG", Encoding.ASCII.GetString(strl.Chunk("strf").Data, 16, 4)); + Assert.Equal(10u, U32(hdrl.List("odml").Chunk("dmlh").Data, 0)); + + var movi = riff.List("movi"); + var chunks = movi.Children.Where(c => c.Id == "00dc").ToList(); + Assert.Equal(10, chunks.Count); + for (var i = 0; i < 10; i++) + { + Assert.BytesEqual(frames[i], chunks[i].Data); + Assert.Equal(0L, chunks[i].Offset % 2, "chunks stay word aligned after odd frames"); + } + + var idx1 = riff.Chunk("idx1").Data; + Assert.Equal(160, idx1.Length); + for (var i = 0; i < 10; i++) + { + Assert.Equal("00dc", Encoding.ASCII.GetString(idx1, i * 16, 4)); + Assert.Equal(0x10u, U32(idx1, i * 16 + 4)); + Assert.Equal(chunks[i].Offset, movi.TypeOffset + U32(idx1, i * 16 + 8)); + Assert.Equal((uint)frames[i].Length, U32(idx1, i * 16 + 12)); + } + AssertOpenDmlIndex(bytes, file, frames); + } + + [Test] + public void LargeOutputsContinueInAvixLists() + { + var frames = Frames(40, 2); + const long limit = 16 * 1024; + var bytes = Write(frames, new Rational(25, 1), limit); + var file = Riff.Parse(bytes); + Assert.Equal(bytes.Length, file.Sum(r => r.Size + 8)); + Assert.Greater(file.Count, 3); + Assert.Equal("AVI ", file[0].Type); + Assert.True(file.Skip(1).All(r => r.Type == "AVIX" && r.Children.All(c => c.Id != "idx1"))); + Assert.True(file.All(r => r.Size + 8 <= limit), "every RIFF respects the limit"); + + var first = file[0].List("movi").Children.Count(c => c.Id == "00dc"); + Assert.Equal((uint)first, U32(file[0].List("hdrl").Chunk("avih").Data, 16)); + Assert.Equal(first * 16, file[0].Chunk("idx1").Data.Length); + Assert.Equal(40u, U32(file[0].List("hdrl").List("strl").Chunk("strh").Data, 32)); + Assert.Equal(40u, U32(file[0].List("hdrl").List("odml").Chunk("dmlh").Data, 0)); + AssertOpenDmlIndex(bytes, file, frames); + } + + [Theory] + [Case(24, 1, 41667u)] + [Case(25, 1, 40000u)] + [Case(60000, 1001, 16683u)] + [Case(48, 2, 41667u)] + public void FrameRateFieldsAreExact(int numerator, int denominator, uint microseconds) + { + var bytes = Write(Frames(2, 3), new Rational(numerator, denominator), AviMjpegWriter.DefaultRiffSizeLimit); + var hdrl = Riff.Parse(bytes)[0].List("hdrl"); + Assert.Equal(microseconds, U32(hdrl.Chunk("avih").Data, 0)); + var strh = hdrl.List("strl").Chunk("strh").Data; + var g = (uint)System.Numerics.BigInteger.GreatestCommonDivisor(numerator, denominator); + Assert.Equal((uint)denominator / g, U32(strh, 20)); + Assert.Equal((uint)numerator / g, U32(strh, 24)); + } + + [Test] + public void RejectsNonJpegFrames() + { + using var ms = new MemoryStream(); + var writer = new AviMjpegWriter(ms, 64, 48, new Rational(30, 1)); + Assert.Throws(() => writer.WriteFrame([0x89, 0x50, 0x4E, 0x47])); + } + + private static void AssertOpenDmlIndex(byte[] bytes, List file, List frames) + { + var indx = file[0].List("hdrl").List("strl").Chunk("indx").Data; + Assert.Equal(4, BinaryPrimitives.ReadUInt16LittleEndian(indx)); + Assert.Equal((byte)0, indx[3]); // AVI_INDEX_OF_INDEXES + var entries = U32(indx, 4); + Assert.Equal((uint)file.Count, entries); + var frame = 0; + for (var e = 0; e < entries; e++) + { + var offset = BinaryPrimitives.ReadInt64LittleEndian(indx.AsSpan(24 + e * 16)); + var size = U32(indx, 32 + e * 16); + var duration = U32(indx, 36 + e * 16); + Assert.Equal("ix00", Encoding.ASCII.GetString(bytes, (int)offset, 4)); + Assert.Equal(size, U32(bytes, (int)offset + 4) + 8); + var ix = bytes.AsSpan((int)offset + 8); + Assert.Equal((byte)1, ix[3]); // AVI_INDEX_OF_CHUNKS + Assert.Equal(duration, U32(bytes, (int)offset + 12)); + var baseOffset = BinaryPrimitives.ReadInt64LittleEndian(ix[12..]); + for (var i = 0; i < duration; i++, frame++) + { + var dataOffset = baseOffset + U32(bytes, (int)offset + 32 + i * 8); + var length = U32(bytes, (int)offset + 36 + i * 8); + Assert.Equal(0u, length & 0x8000_0000u, "every MJPEG frame is a key frame"); + Assert.BytesEqual(frames[frame], bytes.AsSpan((int)dataOffset, (int)length)); + } + } + Assert.Equal(frames.Count, frame); + } + + private static byte[] Write(List frames, Rational rate, long limit) + { + using var ms = new MemoryStream(); + var writer = new AviMjpegWriter(ms, 64, 48, rate, limit); + foreach (var f in frames) writer.WriteFrame(f); + writer.Complete(); + Assert.Equal(frames.Count, writer.FrameCount); + return ms.ToArray(); + } + + /// JPEG-shaped payloads (SOI … EOI) of odd and even lengths. + private static List Frames(int count, int seed) + { + var rng = new Random(seed); + var list = new List(); + for (var i = 0; i < count; i++) + { + var f = new byte[1500 + rng.Next(2000)]; + rng.NextBytes(f); + f[0] = 0xFF; + f[1] = 0xD8; + f[^2] = 0xFF; + f[^1] = 0xD9; + list.Add(f); + } + return list; + } + + private static uint U32(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset)); + + /// Minimal RIFF tree reader for verification. + private static class Riff + { + public sealed record Node(string Id, string? Type, long Offset, uint Size, byte[] Data, List Children) + { + /// File offset of the list type four-cc (the base of idx1 offsets). + public long TypeOffset => Offset + 8; + + public Node List(string type) => Children.Single(c => c.Type == type); + + public Node Chunk(string id) => Children.Single(c => c.Id == id); + } + + public static List Parse(byte[] bytes) => ParseRange(bytes, 0, bytes.Length); + + private static List ParseRange(byte[] bytes, long start, long end) + { + var nodes = new List(); + var pos = start; + while (pos + 8 <= end) + { + var id = Encoding.ASCII.GetString(bytes, (int)pos, 4); + var size = U32(bytes, (int)pos + 4); + Assert.True(pos + 8 + size <= end, $"chunk {id} at {pos} overruns its parent"); + if (id is "RIFF" or "LIST") + { + var type = Encoding.ASCII.GetString(bytes, (int)pos + 8, 4); + nodes.Add(new Node(id, type, pos, size, [], ParseRange(bytes, pos + 12, pos + 8 + size))); + } + else + { + nodes.Add(new Node(id, null, pos, size, bytes.AsSpan((int)pos + 8, (int)size).ToArray(), [])); + } + pos += 8 + size + (size & 1); + } + Assert.Equal(end, pos); + return nodes; + } + } +} From 4bab7d035f8e059b9c8c223b6e5dcea06f2bf198 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:42:33 +0000 Subject: [PATCH 026/188] feat(motion): add flow-based frame interpolation with occlusion reasoning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FrameInterpolator synthesises a frame at fractional time t from the bidirectional flow: of the two candidate velocities at each pixel (A's flow, B's reversed flow) it keeps the one whose path is forward–backward consistent through both frames, samples both frames with Catmull-Rom and blends them by (1-t, t) weighted by each sample's agreement, so samples occluded in the other frame drop out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/FrameInterpolator.cs | 150 ++++++++++++++++++ .../Motion/FrameInterpolatorTests.cs | 119 ++++++++++++++ 2 files changed, 269 insertions(+) create mode 100644 src/Titano.Core/Motion/FrameInterpolator.cs create mode 100644 tests/Titano.Core.Tests/Motion/FrameInterpolatorTests.cs diff --git a/src/Titano.Core/Motion/FrameInterpolator.cs b/src/Titano.Core/Motion/FrameInterpolator.cs new file mode 100644 index 00000000..8552f9fb --- /dev/null +++ b/src/Titano.Core/Motion/FrameInterpolator.cs @@ -0,0 +1,150 @@ +using System.Runtime.Intrinsics; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; + +namespace Titano.Core.Motion; + +/// +/// Synthesises a frame at fractional time t between frames A and B from the bidirectional flow. The +/// content at output pixel x moves with one of two candidate velocities: A's flow at x, or B's reversed +/// flow at x (they differ only near motion boundaries, where each belongs to a different object). Each +/// candidate v gives the samples A(x − t·v) and B(x + (1−t)·v); the candidate whose path is forward–backward +/// consistent through both frames, |F(A→B)(x − t·v) − v| + |F(B→A)(x + (1−t)·v) + v| smallest, is taken. +/// The two Catmull-Rom samples are blended by (1−t, t), each weighted by how well its own flow agrees with v, +/// so a sample that is occluded in the other frame or belongs to another object drops out (occlusion +/// reasoning after Baker et al. 2011). +/// +public sealed class FrameInterpolator : IDisposable +{ + private readonly OpticalFlowEngine _engine; + + public FrameInterpolator(FlowQuality quality = FlowQuality.Best) => _engine = new OpticalFlowEngine(quality); + + /// Flow disagreement (px) at which a sample's weight halves. + public double OcclusionThreshold { get; init; } = 3.0; + + /// Computes both flows and writes the frame at ∈ [0, 1] into . + public void Interpolate(ImageBuffer a, ImageBuffer b, double t, ImageBuffer destination, CancellationToken cancellationToken = default) + { + var (forward, backward) = _engine.ComputeBidirectional(a, b, cancellationToken); + using (forward) + using (backward) + { + Synthesize(a, b, forward, backward, t, destination, OcclusionThreshold, cancellationToken); + } + } + + /// Frame at from precomputed flows (forward = A→B, backward = B→A). + public static void Synthesize(ImageBuffer a, ImageBuffer b, MotionField forward, MotionField backward, double t, ImageBuffer destination, + double occlusionThreshold = 3.0, CancellationToken cancellationToken = default) + { + if (b.Width != a.Width || b.Height != a.Height || b.Channels != a.Channels + || destination.Width != a.Width || destination.Height != a.Height || destination.Channels != a.Channels) + throw new ArgumentException("Frames and destination must share size and channels.", nameof(destination)); + if (!(t is >= 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(t), "t must lie in [0, 1]."); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(occlusionThreshold); + + var w = a.Width; + var h = a.Height; + var channels = a.Channels; + var tau2 = occlusionThreshold * occlusionThreshold; + var dst = destination.Storage; + var plane = destination.PlaneLength; + + void Row(int y) + { + Span va = stackalloc float[4]; + Span vb = stackalloc float[4]; + for (var x = 0; x < w; x++) + { + // Candidate velocities: A's motion at x, and B's motion at x reversed. + var (fu, fv) = forward.Sample(x, y); + var (bu, bv) = backward.Sample(x, y); + var errorF = PathError(forward, backward, x, y, fu, fv, t, out var agreeAF, out var agreeBF); + var errorB = PathError(forward, backward, x, y, -bu, -bv, t, out var agreeAB, out var agreeBB); + var useForward = errorF <= errorB; + double vu = useForward ? fu : -bu, vv = useForward ? fv : -bv; + var ax = x - t * vu; + var ay = y - t * vv; + var bx = x + (1 - t) * vu; + var by = y + (1 - t) * vv; + + var wa = (1 - t) * Reliability(useForward ? agreeAF : agreeAB, tau2); + var wb = t * Reliability(useForward ? agreeBF : agreeBB, tau2); + if (wa + wb < 1e-6) + { + wa = 1 - t; + wb = t; + } + var norm = 1 / (wa + wb); + wa *= norm; + wb *= norm; + + var o = y * w + x; + va.Clear(); + vb.Clear(); + if (wa > 0) CatmullRom(a, ax, ay, va); + if (wb > 0) CatmullRom(b, bx, by, vb); + for (var c = 0; c < channels; c++) dst[c * plane + o] = (float)(wa * va[c] + wb * vb[c]); + } + } + + if ((long)w * h < PlaneOps.ParallelThreshold) + { + for (var y = 0; y < h; y++) + { + cancellationToken.ThrowIfCancellationRequested(); + Row(y); + } + } + else + { + Parallel.For(0, h, new ParallelOptions { CancellationToken = cancellationToken }, Row); + } + } + + public void Dispose() => _engine.Dispose(); + + private static double Reliability(double disagreement, double tau2) => tau2 / (tau2 + disagreement * disagreement); + + /// + /// Forward–backward consistency of moving with velocity (vu, vv) through x at time t: how far A's flow at + /// the A sample and B's reversed flow at the B sample are from that velocity. + /// + private static double PathError(MotionField forward, MotionField backward, int x, int y, double vu, double vv, double t, out double agreeA, out double agreeB) + { + var (au, av) = forward.Sample(x - t * vu, y - t * vv); + var (bu, bv) = backward.Sample(x + (1 - t) * vu, y + (1 - t) * vv); + agreeA = double.Hypot(au - vu, av - vv); + agreeB = double.Hypot(bu + vu, bv + vv); + return agreeA + agreeB; + } + + /// Adds the clamped Catmull-Rom sample of every channel at pixel-centre coordinates to . + private static void CatmullRom(ImageBuffer image, double x, double y, Span values) + { + var w = image.Width; + var h = image.Height; + x = double.Clamp(x, 0, w - 1); + y = double.Clamp(y, 0, h - 1); + var fx = double.Floor(x); + var fy = double.Floor(y); + var ix = (int)fx; + var iy = (int)fy; + var wx = GeometryStage.CatmullRomWeights((float)(x - fx)); + var wy = GeometryStage.CatmullRomWeights((float)(y - fy)); + var data = image.Storage; + var plane = image.PlaneLength; + for (var j = 0; j < 4; j++) + { + var row = int.Clamp(iy - 1 + j, 0, h - 1) * w; + for (var i = 0; i < 4; i++) + { + var weight = wy.GetElement(j) * wx.GetElement(i); + if (weight == 0) continue; + var s = row + int.Clamp(ix - 1 + i, 0, w - 1); + for (var c = 0; c < image.Channels; c++) values[c] += weight * data[c * plane + s]; + } + } + } +} diff --git a/tests/Titano.Core.Tests/Motion/FrameInterpolatorTests.cs b/tests/Titano.Core.Tests/Motion/FrameInterpolatorTests.cs new file mode 100644 index 00000000..8e8c9fd3 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/FrameInterpolatorTests.cs @@ -0,0 +1,119 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class FrameInterpolatorTests +{ + private const int Base = 256; + private const int Frame = 160; + private const int Margin = 16; + + private readonly TestContext _context; + + public FrameInterpolatorTests(TestContext context) => _context = context; + + [Test] + public void EndpointsReproduceTheKeyFrames() + { + var texture = SyntheticImages.Natural(Base, seed: 13); + using var a = Shifted(texture, 0, 0); + using var b = Shifted(texture, 3, -1.5); + using var interpolator = new FrameInterpolator(FlowQuality.Balanced); + using var output = new ImageBuffer(Frame, Frame); + interpolator.Interpolate(a, b, 0, output); + Assert.True(a.Data.SequenceEqual(output.Data)); + interpolator.Interpolate(a, b, 1, output); + Assert.True(b.Data.SequenceEqual(output.Data)); + } + + [Theory] + [Case(0.5)] + [Case(0.25)] + public void TranslationIsInterpolatedAlongTheMotion(double t) + { + const double dx = 4, dy = -2; + var texture = SyntheticImages.Natural(Base, seed: 13); + using var a = Shifted(texture, 0, 0); + using var b = Shifted(texture, dx, dy); + using var truth = Shifted(texture, t * dx, t * dy); + using var interpolator = new FrameInterpolator(); + using var output = new ImageBuffer(Frame, Frame); + interpolator.Interpolate(a, b, t, output); + var psnr = SyntheticImages.Psnr(truth.Plane(1), output.Plane(1), Frame, Margin, Margin, Frame - Margin, Frame - Margin); + + using var fade = new ImageBuffer(Frame, Frame); + for (var i = 0; i < fade.Data.Length; i++) fade.Data[i] = (float)((1 - t) * a.Data[i] + t * b.Data[i]); + var fadePsnr = SyntheticImages.Psnr(truth.Plane(1), fade.Plane(1), Frame, Margin, Margin, Frame - Margin, Frame - Margin); + _context.Log($"t = {t}: interpolated {psnr:F1} dB, cross-fade {fadePsnr:F1} dB"); + Assert.GreaterOrEqual(psnr, 35); + Assert.Greater(psnr, fadePsnr + 10); + } + + [Test] + public void OcclusionReasoningPicksTheVisibleFrame() + { + // Exact flows: the square moves 12 px right; at t = 0.5 a 6 px strip behind it is visible only in B + // and the strip ahead of it shows the square, which must be fetched along the square's motion. + var background = SyntheticImages.Natural(Base, seed: 3); + var foreground = SyntheticImages.Noise(Base, 1.2, seed: 4); + using var a = Composite(background, foreground, 50); + using var b = Composite(background, foreground, 62); + using var truth = Composite(background, foreground, 56); + using var forward = new MotionField(Frame, Frame, 1); + using var backward = new MotionField(Frame, Frame, 1); + for (var y = 50; y < 98; y++) + { + forward.U.Slice(y * Frame + 50, 48).Fill(12); + backward.U.Slice(y * Frame + 62, 48).Fill(-12); + } + using var handled = new ImageBuffer(Frame, Frame); + using var unweighted = new ImageBuffer(Frame, Frame); + FrameInterpolator.Synthesize(a, b, forward, backward, 0.5, handled); + FrameInterpolator.Synthesize(a, b, forward, backward, 0.5, unweighted, occlusionThreshold: 1e9); + // Rows through the object, columns around its trailing and leading edges. + var withWeights = SyntheticImages.Psnr(truth.Plane(1), handled.Plane(1), Frame, 36, 50, 124, 98); + var without = SyntheticImages.Psnr(truth.Plane(1), unweighted.Plane(1), Frame, 36, 50, 124, 98); + _context.Log($"exact flows, object region: occlusion-aware {withWeights:F1} dB, without sample weighting {without:F1} dB"); + Assert.GreaterOrEqual(withWeights, 42); + Assert.Greater(withWeights, without + 10); + } + + [Test] + public void MovingObjectIsInterpolatedWithEstimatedFlow() + { + var background = SyntheticImages.Natural(Base, seed: 3); + var foreground = SyntheticImages.Noise(Base, 1.2, seed: 4); + using var a = Composite(background, foreground, 50); + using var b = Composite(background, foreground, 62); + using var truth = Composite(background, foreground, 56); + using var interpolator = new FrameInterpolator(); + using var output = new ImageBuffer(Frame, Frame); + interpolator.Interpolate(a, b, 0.5, output); + using var fade = new ImageBuffer(Frame, Frame); + for (var i = 0; i < fade.Data.Length; i++) fade.Data[i] = 0.5f * (a.Data[i] + b.Data[i]); + var psnr = SyntheticImages.Psnr(truth.Plane(1), output.Plane(1), Frame, 36, 50, 124, 98); + var fadePsnr = SyntheticImages.Psnr(truth.Plane(1), fade.Plane(1), Frame, 36, 50, 124, 98); + _context.Log($"estimated flows, object region: {psnr:F1} dB, cross-fade {fadePsnr:F1} dB"); + Assert.GreaterOrEqual(psnr, 33); + Assert.Greater(psnr, fadePsnr + 5); + } + + private static ImageBuffer Shifted(double[] texture, double dx, double dy) + { + var shifted = dx == 0 && dy == 0 ? texture : SyntheticImages.Shift(texture, Base, dx, dy); + return SyntheticImages.ToRgb(SyntheticImages.Crop(shifted, Base, 48, 48, Frame, Frame), Frame, Frame); + } + + /// Static background with a 48×48 textured square whose left edge is at ; the square carries its texture along. + private static ImageBuffer Composite(double[] background, double[] foreground, int x0) + { + var plane = SyntheticImages.Crop(background, Base, 0, 0, Frame, Frame); + for (var y = 50; y < 98; y++) + { + for (var x = 0; x < 48; x++) plane[y * Frame + x0 + x] = (float)(0.3 + 0.8 * (foreground[y * Base + x] - 0.5)); + } + return SyntheticImages.ToRgb(plane, Frame, Frame); + } +} From 02afd4673b081a235b43ad84a47c75455e9b819e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:44:11 +0000 Subject: [PATCH 027/188] feat(motion): add temporal median/mean stacking and star-trail accumulation TemporalStacker keeps a sliding window of pooled frame copies and renders an exact per-pixel median (vectorised odd-even transposition network up to 32 frames, Hoare selection beyond) or mean. StarTrailStacker keeps a progressive maximum with exponential decay; trail length in frames maps to the decay that fades a trail to 1 %. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/TemporalStacker.cs | 262 ++++++++++++++++++ .../Motion/TemporalStackerTests.cs | 194 +++++++++++++ 2 files changed, 456 insertions(+) create mode 100644 src/Titano.Core/Motion/TemporalStacker.cs create mode 100644 tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs diff --git a/src/Titano.Core/Motion/TemporalStacker.cs b/src/Titano.Core/Motion/TemporalStacker.cs new file mode 100644 index 00000000..27a965a7 --- /dev/null +++ b/src/Titano.Core/Motion/TemporalStacker.cs @@ -0,0 +1,262 @@ +using System.Numerics; +using Titano.Core.Imaging; + +namespace Titano.Core.Motion; + +/// How a combines its window. +public enum StackMode +{ + /// Per-pixel median: removes transients (aircraft, birds, people) present in under half the frames. + Median, + + /// Per-pixel mean: noise reduction by √N for static scenes. + Mean, +} + +/// +/// Sliding-window temporal stacking. copies frames into a ring of pooled buffers; +/// combines the frames currently in the window. Medians are exact: for up to +/// frames an odd–even transposition sorting network runs on Vector<float> +/// lanes (many pixels per instruction, no branches), beyond that Hoare's selection runs per pixel. +/// +public sealed class TemporalStacker : IDisposable +{ + /// Largest frame count sorted by the vectorised network (N² min/max per lane block). + public const int NetworkLimit = 32; + + private readonly ImageBuffer?[] _ring; + private int _next; + + public TemporalStacker(int window, StackMode mode) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(window); + Window = window; + Mode = mode; + _ring = new ImageBuffer?[window]; + } + + public int Window { get; } + + public StackMode Mode { get; } + + /// Frames currently in the window. + public int Count { get; private set; } + + public bool IsFull => Count == Window; + + /// Adds a copy of , evicting the oldest frame once the window is full. + public void Push(ImageBuffer frame) + { + var first = _ring[0]; + if (first is not null && (first.Width != frame.Width || first.Height != frame.Height || first.Channels != frame.Channels)) + throw new ArgumentException("Frame differs in size or channels from the window.", nameof(frame)); + var slot = _ring[_next] ??= new ImageBuffer(frame.Width, frame.Height, frame.Channels, clear: false); + frame.CopyTo(slot); + _next = (_next + 1) % Window; + Count = int.Min(Count + 1, Window); + } + + /// Combines the frames in the window into . + public void Render(ImageBuffer destination, CancellationToken cancellationToken = default) + { + if (Count == 0) throw new InvalidOperationException("The window is empty."); + var frames = new ImageBuffer[Count]; + for (var i = 0; i < Count; i++) frames[i] = _ring[i]!; + if (Mode == StackMode.Median) Median(frames, destination, cancellationToken); + else Mean(frames, destination, cancellationToken); + } + + /// Empties the window (buffers are kept for reuse). + public void Clear() + { + Count = 0; + _next = 0; + } + + public void Dispose() + { + for (var i = 0; i < _ring.Length; i++) + { + _ring[i]?.Dispose(); + _ring[i] = null; + } + Clear(); + } + + /// Exact per-pixel, per-channel median (mean of the middle pair for even counts). + public static void Median(IReadOnlyList frames, ImageBuffer destination, CancellationToken cancellationToken = default) + { + var planes = Validate(frames, destination); + var n = frames.Count; + var dst = destination.Storage; + ForRows(destination, cancellationToken, (offset, length) => + { + var i = 0; + if (n <= NetworkLimit && Vector.IsHardwareAccelerated) + { + Span> lanes = stackalloc Vector[n]; + var vc = Vector.Count; + for (; i <= length - vc; i += vc) + { + var at = offset + i; + for (var k = 0; k < n; k++) lanes[k] = new Vector(planes[k], at); + // n passes of odd–even transposition sort every lane. + for (var pass = 0; pass < n; pass++) + { + for (var k = pass & 1; k + 1 < n; k += 2) + { + var lo = Vector.Min(lanes[k], lanes[k + 1]); + lanes[k + 1] = Vector.Max(lanes[k], lanes[k + 1]); + lanes[k] = lo; + } + } + var median = (n & 1) != 0 ? lanes[n / 2] : (lanes[n / 2 - 1] + lanes[n / 2]) * 0.5f; + median.CopyTo(dst, at); + } + } + Span values = n <= 256 ? stackalloc float[n] : new float[n]; + for (; i < length; i++) + { + var at = offset + i; + for (var k = 0; k < n; k++) values[k] = planes[k][at]; + dst[at] = PlaneOps.Median(values); + } + }); + } + + /// Per-pixel, per-channel arithmetic mean. + public static void Mean(IReadOnlyList frames, ImageBuffer destination, CancellationToken cancellationToken = default) + { + var planes = Validate(frames, destination); + var dst = destination.Storage; + var scale = 1f / frames.Count; + ForRows(destination, cancellationToken, (offset, length) => + { + var span = dst.AsSpan(offset, length); + planes[0].AsSpan(offset, length).CopyTo(span); + for (var k = 1; k < planes.Length; k++) Accumulate(span, planes[k].AsSpan(offset, length)); + Scale(span, scale); + }); + } + + private static float[][] Validate(IReadOnlyList frames, ImageBuffer destination) + { + if (frames.Count == 0) throw new ArgumentException("At least one frame is required.", nameof(frames)); + var planes = new float[frames.Count][]; + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + if (f.Width != destination.Width || f.Height != destination.Height || f.Channels != destination.Channels) + throw new ArgumentException("Frames and destination must share size and channels.", nameof(frames)); + planes[i] = f.Storage; + } + return planes; + } + + /// Runs (offset, length) over every row of every channel, in parallel when large. + private static void ForRows(ImageBuffer destination, CancellationToken cancellationToken, Action body) + { + var rows = destination.Height * destination.Channels; + var width = destination.Width; + if ((long)rows * width < PlaneOps.ParallelThreshold) + { + for (var r = 0; r < rows; r++) + { + cancellationToken.ThrowIfCancellationRequested(); + body(r * width, width); + } + } + else + { + Parallel.For(0, rows, new ParallelOptions { CancellationToken = cancellationToken }, r => body(r * width, width)); + } + } + + private static void Accumulate(Span sum, ReadOnlySpan values) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + for (; i <= sum.Length - Vector.Count; i += Vector.Count) + (new Vector(sum[i..]) + new Vector(values[i..])).CopyTo(sum[i..]); + } + for (; i < sum.Length; i++) sum[i] += values[i]; + } + + private static void Scale(Span values, float factor) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + for (; i <= values.Length - Vector.Count; i += Vector.Count) + (new Vector(values[i..]) * factor).CopyTo(values[i..]); + } + for (; i < values.Length; i++) values[i] *= factor; + } +} + +/// +/// Star trails by progressive maximum with exponential decay: acc ← max(acc · decay, frame) per pixel and +/// channel. Decay 1 keeps every trail forever (the accumulator never decreases); smaller values make +/// trails fade behind the stars (see ). +/// +public sealed class StarTrailStacker : IDisposable +{ + /// Relative brightness a trail point has fallen to after its trail length. + public const double TrailFloor = 0.01; + + private ImageBuffer? _accumulator; + + public StarTrailStacker(double decay = 1.0) + { + if (!(decay is > 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(decay), "Decay must lie in (0, 1]."); + Decay = decay; + } + + public double Decay { get; } + + /// Frames added so far. + public int Count { get; private set; } + + /// The running result (null before the first frame); owned by the stacker. + public ImageBuffer? Result => _accumulator; + + /// + /// Decay that fades a trail point to (1 %) of its brightness after + /// frames: 0.01^(1/frames). Infinite or non-positive lengths give 1 (endless trails). + /// + public static double DecayForTrailLength(double frames) => + frames > 0 && double.IsFinite(frames) ? double.Pow(TrailFloor, 1 / frames) : 1.0; + + /// Folds the next frame into the trails. + public void Add(ImageBuffer frame) + { + if (_accumulator is null) + { + _accumulator = frame.Clone(); + Count = 1; + return; + } + if (frame.Width != _accumulator.Width || frame.Height != _accumulator.Height || frame.Channels != _accumulator.Channels) + throw new ArgumentException("Frame differs in size or channels.", nameof(frame)); + + var acc = _accumulator.Data; + var src = frame.Data; + var decay = (float)Decay; + var i = 0; + if (Vector.IsHardwareAccelerated) + { + for (; i <= acc.Length - Vector.Count; i += Vector.Count) + Vector.Max(new Vector(acc[i..]) * decay, new Vector(src[i..])).CopyTo(acc[i..]); + } + for (; i < acc.Length; i++) acc[i] = float.Max(acc[i] * decay, src[i]); + Count++; + } + + public void Dispose() + { + _accumulator?.Dispose(); + _accumulator = null; + Count = 0; + } +} diff --git a/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs b/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs new file mode 100644 index 00000000..44950896 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs @@ -0,0 +1,194 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class TemporalStackerTests +{ + private const int Size = 96; + + private readonly TestContext _context; + + public TemporalStackerTests(TestContext context) => _context = context; + + [Test] + public void StarTrailLuminanceNeverDecreasesWithUnitDecay() + { + var random = new Random(5); + using var stacker = new StarTrailStacker(1.0); + using var frame = new ImageBuffer(Size, Size); + var previous = new float[Size * Size]; + var current = new float[Size * Size]; + long steps = 0, nonDecreasing = 0; + for (var k = 0; k < 40; k++) + { + NightFrame(frame, random, k); + stacker.Add(frame); + ColorSpace.Luminance(stacker.Result!, current); + if (k > 0) + { + for (var i = 0; i < current.Length; i++) + { + steps++; + if (current[i] >= previous[i]) nonDecreasing++; + } + } + (previous, current) = (current, previous); + } + var fraction = nonDecreasing / (double)steps; + _context.Log($"non-decreasing on {fraction:P3} of {steps} pixel steps"); + Assert.GreaterOrEqual(fraction, 0.99); + Assert.Equal(40, stacker.Count); + // The trail of the first star position is still lit after 40 frames. + Assert.Greater(stacker.Result![1, StarX(0), StarY(0)], 0.5f); + } + + [Test] + public void FiniteTrailsFadeToOnePercentOverTheirLength() + { + Assert.Equal(1.0, StarTrailStacker.DecayForTrailLength(double.PositiveInfinity)); + Assert.Equal(1.0, StarTrailStacker.DecayForTrailLength(0)); + var decay = StarTrailStacker.DecayForTrailLength(20); + Assert.Approximately(0.01, double.Pow(decay, 20), 1e-12); + + using var stacker = new StarTrailStacker(decay); + using var lit = new ImageBuffer(8, 8, 1); + using var dark = new ImageBuffer(8, 8, 1); + lit[0, 3, 3] = 1f; + stacker.Add(lit); + for (var k = 0; k < 20; k++) stacker.Add(dark); + Assert.Approximately(0.01, stacker.Result![0, 3, 3], 1e-5); + } + + [Test] + public void MedianRemovesATransientOutlierFrame() + { + var plane = SyntheticImages.Crop(SyntheticImages.Natural(128, seed: 12), 128, 0, 0, Size, Size); + var random = new Random(8); + using var stacker = new TemporalStacker(7, StackMode.Median); + for (var k = 0; k < 7; k++) + { + using var frame = SyntheticImages.ToRgb(plane, Size, Size); + var data = frame.Data; + for (var i = 0; i < data.Length; i++) data[i] += 0.01f * (float)(random.NextDouble() - 0.5); + if (k == 3) + { + // An aircraft light streak crossing one frame. + for (var c = 0; c < 3; c++) + for (var x = 10; x < 80; x++) + frame[c, x, 40 + x / 8] = 5f; + } + stacker.Push(frame); + } + Assert.True(stacker.IsFull); + using var output = new ImageBuffer(Size, Size); + stacker.Render(output); + using var reference = SyntheticImages.ToRgb(plane, Size, Size); + double maxError = 0; + for (var i = 0; i < output.Data.Length; i++) maxError = double.Max(maxError, double.Abs(output.Data[i] - reference.Data[i])); + _context.Log($"max deviation from the clean frame {maxError:F4}"); + Assert.Less(maxError, 0.01); + } + + [Theory] + [Case(1)] + [Case(5)] + [Case(6)] + [Case(32)] + [Case(33)] + public void MedianIsExact(int count) + { + var random = new Random(count); + var frames = new List(); + try + { + for (var k = 0; k < count; k++) + { + var frame = new ImageBuffer(37, 5, 3); + var data = frame.Data; + for (var i = 0; i < data.Length; i++) data[i] = (float)random.NextDouble(); + frames.Add(frame); + } + using var output = new ImageBuffer(37, 5, 3); + TemporalStacker.Median(frames, output); + for (var i = 0; i < output.Data.Length; i++) + { + var sorted = frames.Select(f => f.Data[i]).Order().ToArray(); + var expected = count % 2 == 1 ? sorted[count / 2] : 0.5f * (sorted[count / 2 - 1] + sorted[count / 2]); + Assert.Equal(expected, output.Data[i]); + } + } + finally + { + foreach (var f in frames) f.Dispose(); + } + } + + [Test] + public void MeanReducesNoiseBySquareRootOfN() + { + const int n = 16; + const double sigma = 0.05; + var random = new Random(3); + using var stacker = new TemporalStacker(n, StackMode.Mean); + using var frame = new ImageBuffer(Size, Size, 1); + for (var k = 0; k < n; k++) + { + var data = frame.Data; + for (var i = 0; i < data.Length; i++) data[i] = 0.4f + (float)(sigma * Gaussian(random)); + stacker.Push(frame); + } + using var output = new ImageBuffer(Size, Size, 1); + stacker.Render(output); + var values = output.Data.ToArray(); + var mean = values.Average(v => (double)v); + var std = double.Sqrt(values.Average(v => (v - mean) * (v - mean))); + _context.Log($"residual σ {std:F5} (expected {sigma / double.Sqrt(n):F5})"); + Assert.Approximately(0.4, mean, 0.002); + Assert.Approximately(sigma / double.Sqrt(n), std, 0.15 * sigma / double.Sqrt(n)); + } + + [Test] + public void WindowSlidesOverTheNewestFrames() + { + using var stacker = new TemporalStacker(3, StackMode.Median); + using var frame = new ImageBuffer(4, 4, 1); + for (var k = 0; k < 10; k++) + { + frame.Data.Fill(k); + stacker.Push(frame); + } + Assert.Equal(3, stacker.Count); + using var output = new ImageBuffer(4, 4, 1); + stacker.Render(output); + Assert.True(output.Data.ToArray().All(v => v == 8f)); + using var other = new ImageBuffer(5, 4, 1); + Assert.Throws(() => stacker.Push(other)); + stacker.Clear(); + Assert.Throws(() => stacker.Render(output)); + } + + private static int StarX(int k) => 20 + k; + + private static int StarY(int k) => 30 + k / 3; + + /// Dark noisy sky with one star drifting one pixel per frame and a few twinkling faint ones. + private static void NightFrame(ImageBuffer frame, Random random, int k) + { + var data = frame.Data; + for (var i = 0; i < data.Length; i++) data[i] = 0.002f + 0.001f * (float)random.NextDouble(); + for (var c = 0; c < 3; c++) + { + frame[c, StarX(k), StarY(k)] = 0.9f; + frame[c, 60, 70] = 0.1f + 0.05f * (k % 3); + } + } + + private static double Gaussian(Random random) + { + var u1 = 1.0 - random.NextDouble(); + var u2 = random.NextDouble(); + return double.Sqrt(-2 * double.Log(u1)) * double.Cos(2 * double.Pi * u2); + } +} From a1d8287faa11d316c2dbf22a8558ef472d4d65f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:44:20 +0000 Subject: [PATCH 028/188] fix(codecs): harden JPEG restart resync and Huffman table checks Port libjpeg's resync_to_restart decision rules (skip bogus markers and stale RSTs, account for lost intervals), reject oversubscribed Huffman tables before filling the lookahead table (found by fuzzing), and keep triangle chroma upsampling at 1/8 scale for better thumbnails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs | 33 ++++++++++++++++++- .../Codecs/Jpeg/JpegLosslessDecoder.cs | 10 ++---- src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs | 2 +- .../Codecs/Jpeg/JpegScanDecoder.cs | 11 ++----- 4 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs index 5a41440f..9a125079 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs @@ -31,11 +31,11 @@ internal sealed class JpegHuffmanTable Delta[len] = k - code; for (var i = 0; i < counts[len - 1]; i++, code++, k++) { + if (code >= 1 << len) throw new InvalidDataException("JPEG: Huffman table oversubscribed"); if (len > FastBits) continue; var first = code << (FastBits - len); Fast.AsSpan(first, 1 << (FastBits - len)).Fill((ushort)(len << 8 | values[k])); } - if (code > 1 << len) throw new InvalidDataException("JPEG: Huffman table oversubscribed"); MaxCode[len] = code << (16 - len); code <<= 1; } @@ -238,4 +238,35 @@ internal ref struct JpegBitReader _pos = _markerPos + 2; _marker = 0; } + + /// + /// Restart processing with libjpeg's resync_to_restart rules: skips invalid markers and stale RSTs, accepts the + /// expected RSTn, and reports how many whole intervals were lost when RSTn+1/RSTn+2 shows up instead. + /// Returns false when a non-restart marker (or the end of data) ends the scan. + /// + public bool NextRestart(ref int expected, out int lostIntervals) + { + lostIntervals = 0; + while (true) + { + var marker = FindMarker(); + if (marker < 0) return false; + if (marker < 0xC0) + { + AcceptMarker(); // corrupt data that happened to look like a marker + continue; + } + if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) return false; + var delta = (marker - JpegTables.Rst0 - expected) & 7; + if (delta is 6 or 7) + { + AcceptMarker(); // a restart we already passed + continue; + } + if (delta is 1 or 2) lostIntervals = delta; + AcceptMarker(); + expected = (marker - JpegTables.Rst0 + 1) & 7; + return true; + } + } } diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs index 3ae36db9..fce195ae 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs @@ -100,21 +100,17 @@ public static class JpegLosslessDecoder } if (mcu >= total || interval == 0) break; - var marker = reader.FindMarker(); - if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) + if (!reader.NextRestart(ref expectedRst, out var lost)) { parser.Warn("JPEG: restart marker missing; scan truncated"); break; } - var found = marker - JpegTables.Rst0; - if (found != expectedRst) + if (lost > 0) { - var lost = (found - expectedRst) & 7; + // Intervals between the expected and the found marker were lost: leave their samples untouched. parser.Warn($"JPEG: {lost} restart interval(s) lost"); mcu += (long)lost * interval; } - reader.AcceptMarker(); - expectedRst = (found + 1) & 7; x = (int)(mcu % width); y = (int)(mcu / width); restartRow = y; diff --git a/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs index 1140772f..2bbe45cf 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs @@ -31,7 +31,7 @@ internal sealed class JpegRenderer _frame = parser.Frame!; var options = parser.Options; _n = BlockSize(_frame, options.MaxLongEdge); - _fancy = options.FancyUpsampling && _n > 1; + _fancy = options.FancyUpsampling; _max = (1 << _frame.Precision) - 1; _colorSpace = parser.ColorSpace(); _invertedCmyk = parser.AdobeTransform >= 0 || _colorSpace == JpegColorSpace.Ycck; diff --git a/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs index 9e90a42b..3bd8b679 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs @@ -74,22 +74,17 @@ internal static class JpegScanDecoder } if (mcu >= total || interval == 0) break; - var marker = reader.FindMarker(); - if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) + if (!reader.NextRestart(ref expectedRst, out var lost)) { parser.Warn("JPEG: restart marker missing; scan truncated"); break; } - var found = marker - JpegTables.Rst0; - if (found != expectedRst) + if (lost > 0) { - // Intervals between the expected and the found marker were lost: leave their blocks untouched. - var lost = (found - expectedRst) & 7; + // Intervals between the expected and the found marker were lost: leave their samples untouched. parser.Warn($"JPEG: {lost} restart interval(s) lost"); mcu += (long)lost * interval; } - reader.AcceptMarker(); - expectedRst = (found + 1) & 7; state.EobRun = 0; foreach (var c in comps) c.DcPred = 0; } From 990c515b3b1c841e90d3ad78d8cbb54dc6badac2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:44:20 +0000 Subject: [PATCH 029/188] feat(codecs): add baseline and lossless JPEG encoders Baseline encoder: IJG quality scaling, 4:4:4/4:2:2/4:2:0, optional optimised Huffman tables, restart intervals, caller APP1 segments, ImageBuffer input with optional ordered dither; parallel colour conversion and float FDCT per MCU row, sequential entropy coding. Lossless (SOF3) encoder with predictors 1-7 and point transform for DNG. Tests: round-trip PSNR gates, monotonic quality, lossless round trips for every predictor and precision, seeded fuzzing, restart resync, DCT scaling and a 24 MP single-core decode benchmark. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs | 477 ++++++++++++++++++ .../Codecs/Jpeg/JpegHuffmanEncoding.cs | 151 ++++++ .../Codecs/Jpeg/JpegLosslessEncoder.cs | 169 +++++++ .../Codecs/JpegEncoderTests.cs | 309 ++++++++++++ .../Codecs/JpegLosslessTests.cs | 107 ++++ .../Codecs/JpegPerformanceTests.cs | 66 +++ .../Codecs/JpegRobustnessTests.cs | 157 ++++++ .../Codecs/JpegScalingTests.cs | 94 ++++ 8 files changed, 1530 insertions(+) create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs create mode 100644 src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs create mode 100644 tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs diff --git a/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs new file mode 100644 index 00000000..dfc85e28 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs @@ -0,0 +1,477 @@ +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Jpeg; + +/// Chroma subsampling written by . +public enum JpegSubsampling +{ + Yuv444, + Yuv422, + Yuv420, +} + +/// Options for . +public sealed record JpegEncodeOptions +{ + public static JpegEncodeOptions Default { get; } = new(); + + /// IJG quality 1–100 (scales the Annex K tables). + public int Quality { get; init; } = 90; + + public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Yuv420; + + /// Two-pass encoding with Huffman tables built from the image's statistics (smaller files). + public bool OptimizeHuffman { get; init; } + + /// Restart interval in MCUs (0 = none). + public int RestartInterval { get; init; } + + /// APP1 payloads written after SOI, each including its identifier (e.g. "Exif\0\0" + TIFF, or the XMP + /// namespace + packet); at most 65533 bytes each. When present the JFIF APP0 segment is omitted (Exif layout). + public IReadOnlyList? App1Segments { get; init; } + + /// Ordered dither when quantising linear float input to 8-bit sRGB. + public bool Dither { get; init; } + + /// Worker limit for colour conversion and forward DCT (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// Baseline JPEG encoder (8-bit, Huffman, 1 or 3 components). Colour conversion and float forward DCT run in +/// parallel per MCU row; entropy coding is sequential. +/// +public static class JpegEncoder +{ + private static readonly float[] BasisT = Transpose(JpegTables.Basis); + + /// Encodes a linear-light buffer (1 channel → gray JPEG, 3/4 → YCbCr; alpha is dropped). + public static byte[] Encode(ImageBuffer image, JpegEncodeOptions? options = null) + { + using var ms = new MemoryStream(); + Encode(ms, image, options); + return ms.ToArray(); + } + + public static void Encode(Stream output, ImageBuffer image, JpegEncodeOptions? options = null) + { + var o = options ?? JpegEncodeOptions.Default; + var channels = image.Channels == 1 ? 1 : 3; + EncodeCore(output, image.Width, image.Height, channels, (y, row) => PixelConvert.EncodeRow8(image, y, row, channels, TransferFunction.Srgb, o.Dither), o); + } + + /// Encodes interleaved 8-bit sRGB pixels: 1 = gray, 3 = RGB, 4 = RGBA (alpha ignored). + public static byte[] Encode(ReadOnlySpan pixels, int width, int height, int channels, JpegEncodeOptions? options = null) + { + using var ms = new MemoryStream(); + Encode(ms, pixels, width, height, channels, options); + return ms.ToArray(); + } + + public static unsafe void Encode(Stream output, ReadOnlySpan pixels, int width, int height, int channels, JpegEncodeOptions? options = null) + { + if (channels is not (1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(channels)); + if (pixels.Length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small", nameof(pixels)); + var outChannels = channels == 1 ? 1 : 3; + fixed (byte* p = pixels) + { + var ptr = (nint)p; + EncodeCore(output, width, height, outChannels, (y, row) => + { + var src = new ReadOnlySpan((byte*)ptr + (long)y * width * channels, width * channels); + if (channels == outChannels) + { + src.CopyTo(row); + return; + } + for (var x = 0; x < width; x++) + { + row[3 * x] = src[4 * x]; + row[3 * x + 1] = src[4 * x + 1]; + row[3 * x + 2] = src[4 * x + 2]; + } + }, options ?? JpegEncodeOptions.Default); + } + } + + /// IJG quality scaling of a base table (jcparam.c), clamped to baseline 1..255. + internal static int[] ScaleTable(ReadOnlySpan table, int quality) + { + quality = Math.Clamp(quality, 1, 100); + var scale = quality < 50 ? 5000 / quality : 200 - quality * 2; + var result = new int[64]; + for (var i = 0; i < 64; i++) result[i] = Math.Clamp((table[i] * scale + 50) / 100, 1, 255); + return result; + } + + private delegate void RowReader(int y, Span row); + + private sealed class Plan + { + public required int Width, Height, Components, HY, VY, McusX, McusY; + public required int[][] Quant; + public required short[][] Coefficients; + + public int BlocksPerLine(int c) => c == 0 ? McusX * HY : McusX; + } + + private static void EncodeCore(Stream output, int width, int height, int components, RowReader read, JpegEncodeOptions o) + { + if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width), "JPEG dimensions are 1..65535"); + if (o.RestartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(o), "Restart interval is 0..65535"); + var (hy, vy) = components == 1 ? (1, 1) : o.Subsampling switch + { + JpegSubsampling.Yuv444 => (1, 1), + JpegSubsampling.Yuv422 => (2, 1), + _ => (2, 2), + }; + var mcusX = JpegParser.DivUp(width, 8 * hy); + var mcusY = JpegParser.DivUp(height, 8 * vy); + var plan = new Plan + { + Width = width, Height = height, Components = components, HY = hy, VY = vy, McusX = mcusX, McusY = mcusY, + Quant = [ScaleTable(JpegTables.LumaQuant, o.Quality), ScaleTable(JpegTables.ChromaQuant, o.Quality)], + Coefficients = new short[components][], + }; + plan.Coefficients[0] = new short[checked(mcusX * hy * mcusY * vy * 64)]; + for (var c = 1; c < components; c++) plan.Coefficients[c] = new short[checked(mcusX * mcusY * 64)]; + + Transform(plan, read, o.MaxDegreeOfParallelism); + + JpegHuffmanCode dcY, acY, dcC, acC; + if (o.OptimizeHuffman) + { + var freq = new long[4][]; + for (var i = 0; i < 4; i++) freq[i] = new long[256]; + Entropy(plan, o.RestartInterval, null, freq, null); + dcY = JpegHuffmanCode.Optimal(freq[0]); + acY = JpegHuffmanCode.Optimal(freq[1]); + dcC = components > 1 ? JpegHuffmanCode.Optimal(freq[2]) : dcY; + acC = components > 1 ? JpegHuffmanCode.Optimal(freq[3]) : acY; + } + else + { + dcY = new JpegHuffmanCode(JpegTables.DcLumaBits, JpegTables.DcLumaValues); + acY = new JpegHuffmanCode(JpegTables.AcLumaBits, JpegTables.AcLumaValues); + dcC = new JpegHuffmanCode(JpegTables.DcChromaBits, JpegTables.DcChromaValues); + acC = new JpegHuffmanCode(JpegTables.AcChromaBits, JpegTables.AcChromaValues); + } + + var writer = new JpegBitWriter(width * height * components / 4); + Entropy(plan, o.RestartInterval, writer, null, [dcY, acY, dcC, acC]); + WriteHeaders(output, plan, o, dcY, acY, dcC, acC); + output.Write(writer.Written); + output.Write([0xFF, JpegTables.Eoi]); + } + + /// Colour conversion, chroma downsampling (box average), forward DCT and quantisation per MCU row. + private static void Transform(Plan p, RowReader read, int parallelism) + { + int hy = p.HY, vy = p.VY, mcuH = 8 * vy, paddedW = p.McusX * 8 * hy, nc = p.Components; + var recip = new float[2][]; + for (var t = 0; t < 2; t++) + { + recip[t] = new float[64]; + for (var i = 0; i < 64; i++) recip[t][i] = 1f / p.Quant[t][i]; + } + Parallel.For(0, p.McusY, new ParallelOptions { MaxDegreeOfParallelism = parallelism }, my => + { + var rgb = new byte[p.Width * nc]; + var planes = new float[nc][]; + for (var c = 0; c < nc; c++) planes[c] = new float[paddedW * mcuH]; + for (var r = 0; r < mcuH; r++) + { + var y = Math.Min(my * mcuH + r, p.Height - 1); + read(y, rgb); + var row = r * paddedW; + if (nc == 1) + { + var g = planes[0]; + for (var x = 0; x < p.Width; x++) g[row + x] = rgb[x] - 128f; + } + else + { + float[] yp = planes[0], cb = planes[1], cr = planes[2]; + for (var x = 0; x < p.Width; x++) + { + float rr = rgb[3 * x], gg = rgb[3 * x + 1], bb = rgb[3 * x + 2]; + yp[row + x] = 0.299f * rr + 0.587f * gg + 0.114f * bb - 128f; + cb[row + x] = -0.168736f * rr - 0.331264f * gg + 0.5f * bb; + cr[row + x] = 0.5f * rr - 0.418688f * gg - 0.081312f * bb; + } + } + for (var c = 0; c < nc; c++) + { + var plane = planes[c]; + plane.AsSpan(row + p.Width, paddedW - p.Width).Fill(plane[row + p.Width - 1]); + } + } + + Span block = stackalloc float[64]; + Span coef = stackalloc float[64]; + var bpl = p.BlocksPerLine(0); + for (var by = 0; by < vy; by++) + { + for (var bx = 0; bx < bpl; bx++) + { + for (var r = 0; r < 8; r++) planes[0].AsSpan((by * 8 + r) * paddedW + bx * 8, 8).CopyTo(block.Slice(r * 8, 8)); + ForwardDct(block, coef); + Quantize(coef, recip[0], p.Coefficients[0].AsSpan(((my * vy + by) * bpl + bx) * 64, 64)); + } + } + var area = 1f / (hy * vy); + for (var c = 1; c < nc; c++) + { + var plane = planes[c]; + for (var bx = 0; bx < p.McusX; bx++) + { + for (var r = 0; r < 8; r++) + { + for (var i = 0; i < 8; i++) + { + var sum = 0f; + var x0 = (bx * 8 + i) * hy; + for (var dy = 0; dy < vy; dy++) + { + var at = (r * vy + dy) * paddedW + x0; + for (var dx = 0; dx < hy; dx++) sum += plane[at + dx]; + } + block[r * 8 + i] = sum * area; + } + } + ForwardDct(block, coef); + Quantize(coef, recip[1], p.Coefficients[c].AsSpan((my * p.McusX + bx) * 64, 64)); + } + } + }); + } + + /// F = B·f·Bᵀ with the orthonormal basis (DC = 8 × mean), Vector256 rows when available. + private static void ForwardDct(ReadOnlySpan f, Span output) + { + var basis = JpegTables.Basis; + if (Vector256.IsHardwareAccelerated) + { + ref var bt = ref MemoryMarshal.GetArrayDataReference(BasisT); + Span> t = stackalloc Vector256[8]; + for (var y = 0; y < 8; y++) + { + var acc = Vector256.Zero; + for (var x = 0; x < 8; x++) acc += Vector256.Create(f[y * 8 + x]) * Vector256.LoadUnsafe(ref bt, (nuint)(x * 8)); + t[y] = acc; + } + for (var v = 0; v < 8; v++) + { + var acc = Vector256.Zero; + for (var y = 0; y < 8; y++) acc += Vector256.Create(basis[v * 8 + y]) * t[y]; + acc.CopyTo(output.Slice(v * 8, 8)); + } + return; + } + Span tmp = stackalloc float[64]; + for (var y = 0; y < 8; y++) + { + for (var u = 0; u < 8; u++) + { + var s = 0f; + for (var x = 0; x < 8; x++) s += f[y * 8 + x] * basis[u * 8 + x]; + tmp[y * 8 + u] = s; + } + } + for (var v = 0; v < 8; v++) + { + for (var u = 0; u < 8; u++) + { + var s = 0f; + for (var y = 0; y < 8; y++) s += basis[v * 8 + y] * tmp[y * 8 + u]; + output[v * 8 + u] = s; + } + } + } + + private static void Quantize(ReadOnlySpan coef, float[] recip, Span destination) + { + destination[0] = (short)Math.Clamp(MathF.Round(coef[0] * recip[0]), -1024f, 1023f); + for (var i = 1; i < 64; i++) destination[i] = (short)Math.Clamp(MathF.Round(coef[i] * recip[i]), -1023f, 1023f); + } + + /// Walks every MCU in order: counts symbol frequencies () or emits codes. + private static void Entropy(Plan p, int restartInterval, JpegBitWriter? writer, long[][]? freq, JpegHuffmanCode[]? codes) + { + var preds = new int[p.Components]; + var total = p.McusX * p.McusY; + var rst = 0; + for (var mcu = 0; mcu < total; mcu++) + { + if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0) + { + Array.Clear(preds); + if (writer is not null) + { + writer.Flush(); + writer.WriteMarker((byte)(JpegTables.Rst0 + rst)); + } + rst = (rst + 1) & 7; + } + writer?.Reserve(4096); + int mx = mcu % p.McusX, my = mcu / p.McusX; + for (var c = 0; c < p.Components; c++) + { + int h = c == 0 ? p.HY : 1, v = c == 0 ? p.VY : 1, bpl = p.BlocksPerLine(c), table = c == 0 ? 0 : 2; + for (var by = 0; by < v; by++) + { + for (var bx = 0; bx < h; bx++) + { + var block = p.Coefficients[c].AsSpan(((my * v + by) * bpl + mx * h + bx) * 64, 64); + if (writer is null) CountBlock(block, ref preds[c], freq![table], freq[table + 1]); + else EncodeBlock(writer, block, ref preds[c], codes![table], codes[table + 1]); + } + } + } + } + writer?.Flush(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Category(int v) => v == 0 ? 0 : 32 - BitOperations.LeadingZeroCount((uint)Math.Abs(v)); + + private static void CountBlock(ReadOnlySpan block, ref int pred, long[] dc, long[] ac) + { + dc[Category(block[0] - pred)]++; + pred = block[0]; + var run = 0; + var order = JpegTables.NaturalOrder; + for (var k = 1; k < 64; k++) + { + int v = block[order[k]]; + if (v == 0) + { + run++; + continue; + } + for (; run >= 16; run -= 16) ac[0xF0]++; + ac[run << 4 | Category(v)]++; + run = 0; + } + if (run > 0) ac[0]++; + } + + private static void EncodeBlock(JpegBitWriter w, ReadOnlySpan block, ref int pred, JpegHuffmanCode dc, JpegHuffmanCode ac) + { + var diff = block[0] - pred; + pred = block[0]; + var s = Category(diff); + w.Write((uint)(dc.Code[s] << s | ((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1))), dc.Length[s] + s); + var run = 0; + var order = JpegTables.NaturalOrder; + for (var k = 1; k < 64; k++) + { + int v = block[order[k]]; + if (v == 0) + { + run++; + continue; + } + for (; run >= 16; run -= 16) w.Write(ac.Code[0xF0], ac.Length[0xF0]); + s = Category(v); + var symbol = run << 4 | s; + w.Write((uint)(ac.Code[symbol] << s | ((v < 0 ? v - 1 : v) & ((1 << s) - 1))), ac.Length[symbol] + s); + run = 0; + } + if (run > 0) w.Write(ac.Code[0], ac.Length[0]); + } + + private static void WriteHeaders(Stream output, Plan p, JpegEncodeOptions o, JpegHuffmanCode dcY, JpegHuffmanCode acY, JpegHuffmanCode dcC, JpegHuffmanCode acC) + { + var h = new MemoryStream(); + h.Write([0xFF, JpegTables.Soi]); + if (o.App1Segments is { Count: > 0 } apps) + { + foreach (var app in apps) + { + if (app.Length > 65533) throw new ArgumentException("APP1 payload exceeds 65533 bytes", nameof(o)); + Segment(h, JpegTables.App1, app); + } + } + else + { + Segment(h, JpegTables.App0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]); + } + var tables = p.Components == 1 ? 1 : 2; + var dqt = new byte[65 * tables]; + for (var t = 0; t < tables; t++) + { + dqt[65 * t] = (byte)t; + for (var k = 0; k < 64; k++) dqt[65 * t + 1 + k] = (byte)p.Quant[t][JpegTables.NaturalOrder[k]]; + } + Segment(h, JpegTables.Dqt, dqt); + + var sof = new byte[6 + 3 * p.Components]; + sof[0] = 8; + sof[1] = (byte)(p.Height >> 8); + sof[2] = (byte)p.Height; + sof[3] = (byte)(p.Width >> 8); + sof[4] = (byte)p.Width; + sof[5] = (byte)p.Components; + for (var c = 0; c < p.Components; c++) + { + sof[6 + 3 * c] = (byte)(c + 1); + sof[7 + 3 * c] = c == 0 ? (byte)(p.HY << 4 | p.VY) : (byte)0x11; + sof[8 + 3 * c] = (byte)(c == 0 ? 0 : 1); + } + Segment(h, JpegTables.Sof0, sof); + + var dht = new MemoryStream(); + Huffman(dht, 0x00, dcY); + Huffman(dht, 0x10, acY); + if (p.Components > 1) + { + Huffman(dht, 0x01, dcC); + Huffman(dht, 0x11, acC); + } + Segment(h, JpegTables.Dht, dht.ToArray()); + if (o.RestartInterval > 0) Segment(h, JpegTables.Dri, [(byte)(o.RestartInterval >> 8), (byte)o.RestartInterval]); + + var sos = new byte[4 + 2 * p.Components]; + sos[0] = (byte)p.Components; + for (var c = 0; c < p.Components; c++) + { + sos[1 + 2 * c] = (byte)(c + 1); + sos[2 + 2 * c] = c == 0 ? (byte)0x00 : (byte)0x11; + } + sos[^3] = 0; + sos[^2] = 63; + sos[^1] = 0; + Segment(h, JpegTables.Sos, sos); + h.Position = 0; + h.CopyTo(output); + } + + private static void Huffman(Stream s, byte classAndId, JpegHuffmanCode code) + { + s.WriteByte(classAndId); + s.Write(code.Bits); + s.Write(code.Values); + } + + internal static void Segment(Stream s, byte marker, ReadOnlySpan payload) + { + var length = payload.Length + 2; + s.Write([0xFF, marker, (byte)(length >> 8), (byte)length]); + s.Write(payload); + } + + private static float[] Transpose(float[] m) + { + var t = new float[64]; + for (var i = 0; i < 8; i++) + { + for (var j = 0; j < 8; j++) t[j * 8 + i] = m[i * 8 + j]; + } + return t; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs b/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs new file mode 100644 index 00000000..071d76d1 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs @@ -0,0 +1,151 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// Huffman code table for encoding (code and length per symbol) plus its DHT representation. +internal sealed class JpegHuffmanCode +{ + public readonly byte[] Bits; + public readonly byte[] Values; + public readonly ushort[] Code = new ushort[256]; + public readonly byte[] Length = new byte[256]; + + public JpegHuffmanCode(ReadOnlySpan bits, ReadOnlySpan values) + { + Bits = bits.ToArray(); + Values = values.ToArray(); + int code = 0, k = 0; + for (var len = 1; len <= 16; len++) + { + for (var i = 0; i < bits[len - 1]; i++, k++, code++) + { + Code[values[k]] = (ushort)code; + Length[values[k]] = (byte)len; + } + code <<= 1; + } + } + + /// Optimal length-limited (16-bit) table for symbol frequencies (T.81 Annex K.2, as libjpeg). + public static JpegHuffmanCode Optimal(ReadOnlySpan frequencies) + { + var freq = new long[257]; + frequencies.CopyTo(freq); + freq[256] = 1; // reserved code point guarantees no all-ones code + var codeSize = new int[257]; + var others = new int[257]; + Array.Fill(others, -1); + while (true) + { + int c1 = -1, c2 = -1; + long v1 = long.MaxValue, v2 = long.MaxValue; + for (var i = 0; i <= 256; i++) + { + if (freq[i] != 0 && freq[i] <= v1) + { + v1 = freq[i]; + c1 = i; + } + } + for (var i = 0; i <= 256; i++) + { + if (freq[i] != 0 && freq[i] <= v2 && i != c1) + { + v2 = freq[i]; + c2 = i; + } + } + if (c2 < 0) break; + freq[c1] += freq[c2]; + freq[c2] = 0; + codeSize[c1]++; + while (others[c1] >= 0) + { + c1 = others[c1]; + codeSize[c1]++; + } + others[c1] = c2; + codeSize[c2]++; + while (others[c2] >= 0) + { + c2 = others[c2]; + codeSize[c2]++; + } + } + var bits = new int[33]; + for (var i = 0; i <= 256; i++) + { + if (codeSize[i] > 0) bits[codeSize[i]]++; + } + for (var i = 32; i > 16; i--) + { + while (bits[i] > 0) + { + var j = i - 2; + while (bits[j] == 0) j--; + bits[i] -= 2; + bits[i - 1]++; + bits[j + 1] += 2; + bits[j]--; + } + } + var top = 16; + while (bits[top] == 0) top--; + bits[top]--; // drop the reserved symbol + var counts = new byte[16]; + for (var i = 1; i <= 16; i++) counts[i - 1] = (byte)bits[i]; + var values = new List(); + for (var len = 1; len <= 32; len++) + { + for (var s = 0; s < 256; s++) + { + if (codeSize[s] == len) values.Add((byte)s); + } + } + return new JpegHuffmanCode(counts, values.ToArray()); + } +} + +/// MSB-first bit writer with 0xFF byte stuffing into a growable buffer. +internal sealed class JpegBitWriter(int initialCapacity) +{ + private byte[] _buffer = new byte[Math.Max(1024, initialCapacity)]; + private int _length; + private ulong _acc; + private int _bits; + + public ReadOnlySpan Written => _buffer.AsSpan(0, _length); + + /// Guarantees room for more output bytes (stuffing included). + public void Reserve(int bytes) + { + if (_length + bytes <= _buffer.Length) return; + Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + bytes)); + } + + /// Appends the low bits of (size ≤ 32). + public void Write(uint value, int size) + { + _acc = (_acc << size) | (value & (uint)((1UL << size) - 1)); + _bits += size; + while (_bits >= 8) + { + _bits -= 8; + var b = (byte)(_acc >> _bits); + _buffer[_length++] = b; + if (b == 0xFF) _buffer[_length++] = 0; + } + } + + /// Pads the last byte with 1-bits (T.81 F.1.2.3). + public void Flush() + { + if (_bits > 0) Write((1u << (8 - _bits)) - 1, 8 - _bits); + _acc = 0; + } + + public void WriteMarker(byte marker) + { + Reserve(2); + _buffer[_length++] = 0xFF; + _buffer[_length++] = marker; + } +} diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs new file mode 100644 index 00000000..8bd6eb31 --- /dev/null +++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs @@ -0,0 +1,169 @@ +namespace Titano.Core.Codecs.Jpeg; + +/// +/// Lossless JPEG (SOF3) encoder: one interleaved scan, optimal Huffman table per component, predictors 1–7, +/// point transform and restart intervals. Used for DNG tiles (DNG Compression = 7). +/// +public static class JpegLosslessEncoder +{ + /// Encodes interleaved samples (each < 2^). + /// Restart interval in samples per component (0 = none). + public static byte[] Encode(ReadOnlySpan samples, int width, int height, int components, int precision, + int predictor = 1, int pointTransform = 0, int restartInterval = 0) + { + if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width)); + if (components is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(components)); + if (precision is < 2 or > 16) throw new ArgumentOutOfRangeException(nameof(precision)); + if (predictor is < 1 or > 7) throw new ArgumentOutOfRangeException(nameof(predictor)); + if (pointTransform < 0 || pointTransform >= precision) throw new ArgumentOutOfRangeException(nameof(pointTransform)); + if (restartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(restartInterval)); + if (samples.Length < (long)width * height * components) throw new ArgumentException("Sample buffer too small", nameof(samples)); + var limit = 1 << precision; + foreach (var s in samples[..(width * height * components)]) + { + if (s >= limit) throw new ArgumentException($"Sample {s} exceeds {precision}-bit precision", nameof(samples)); + } + + var layout = new Layout(width, height, components, predictor, pointTransform, restartInterval, precision); + var counter = new Counter { Frequencies = new long[components][] }; + for (var c = 0; c < components; c++) counter.Frequencies[c] = new long[256]; + Walk(samples, layout, ref counter); + var codes = new JpegHuffmanCode[components]; + for (var c = 0; c < components; c++) codes[c] = JpegHuffmanCode.Optimal(counter.Frequencies[c]); + + var emitter = new Emitter { Writer = new JpegBitWriter(width * height * components), Codes = codes }; + Walk(samples, layout, ref emitter); + emitter.Writer.Flush(); + + using var output = new MemoryStream(); + output.Write([0xFF, JpegTables.Soi]); + var sof = new byte[6 + 3 * components]; + sof[0] = (byte)precision; + sof[1] = (byte)(height >> 8); + sof[2] = (byte)height; + sof[3] = (byte)(width >> 8); + sof[4] = (byte)width; + sof[5] = (byte)components; + for (var c = 0; c < components; c++) + { + sof[6 + 3 * c] = (byte)(c + 1); + sof[7 + 3 * c] = 0x11; + } + JpegEncoder.Segment(output, JpegTables.Sof3, sof); + var dht = new MemoryStream(); + for (var c = 0; c < components; c++) + { + dht.WriteByte((byte)c); + dht.Write(codes[c].Bits); + dht.Write(codes[c].Values); + } + JpegEncoder.Segment(output, JpegTables.Dht, dht.ToArray()); + if (restartInterval > 0) JpegEncoder.Segment(output, JpegTables.Dri, [(byte)(restartInterval >> 8), (byte)restartInterval]); + var sos = new byte[4 + 2 * components]; + sos[0] = (byte)components; + for (var c = 0; c < components; c++) + { + sos[1 + 2 * c] = (byte)(c + 1); + sos[2 + 2 * c] = (byte)(c << 4); + } + sos[^3] = (byte)predictor; + sos[^2] = 0; + sos[^1] = (byte)pointTransform; + JpegEncoder.Segment(output, JpegTables.Sos, sos); + output.Write(emitter.Writer.Written); + output.Write([0xFF, JpegTables.Eoi]); + return output.ToArray(); + } + + private readonly record struct Layout(int Width, int Height, int Components, int Predictor, int PointTransform, int RestartInterval, int Precision); + + private interface ISink + { + void Difference(int component, int diff); + void Restart(int index); + } + + /// Visits every residual in stream order with the decoder's prediction rules (T.81 H.1.2). + private static void Walk(ReadOnlySpan samples, Layout l, ref TSink sink) where TSink : struct, ISink + { + int w = l.Width, nc = l.Components, stride = w * nc, pt = l.PointTransform; + var initial = 1 << (l.Precision - pt - 1); + var total = (long)w * l.Height; + int restartRow = 0, x = 0, y = 0, rst = 0; + var first = true; + for (long mcu = 0; mcu < total; mcu++) + { + if (l.RestartInterval > 0 && mcu > 0 && mcu % l.RestartInterval == 0) + { + sink.Restart(rst); + rst = (rst + 1) & 7; + first = true; + restartRow = y; + } + var at = y * stride + x * nc; + for (var c = 0; c < nc; c++) + { + var idx = at + c; + int pred; + if (first) pred = initial; + else if (y == restartRow) pred = samples[idx - nc] >> pt; + else if (x == 0) pred = samples[idx - stride] >> pt; + else + { + int ra = samples[idx - nc] >> pt, rb = samples[idx - stride] >> pt, rc = samples[idx - stride - nc] >> pt; + pred = l.Predictor switch + { + 1 => ra, + 2 => rb, + 3 => rc, + 4 => ra + rb - rc, + 5 => ra + ((rb - rc) >> 1), + 6 => rb + ((ra - rc) >> 1), + _ => (ra + rb) >> 1, + }; + } + sink.Difference(c, (short)((samples[idx] >> pt) - pred)); + } + first = false; + if (++x == w) + { + x = 0; + y++; + } + } + } + + private static int Category(int diff) => diff == -32768 ? 16 : diff == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(diff)); + + private struct Counter : ISink + { + public long[][] Frequencies; + + public readonly void Difference(int component, int diff) => Frequencies[component][Category(diff)]++; + + public readonly void Restart(int index) + { + } + } + + private struct Emitter : ISink + { + public JpegBitWriter Writer; + public JpegHuffmanCode[] Codes; + + public readonly void Difference(int component, int diff) + { + var code = Codes[component]; + var s = Category(diff); + Writer.Reserve(16); + Writer.Write(code.Code[s], code.Length[s]); + if (s is > 0 and < 16) Writer.Write((uint)((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1)), s); + } + + public readonly void Restart(int index) + { + Writer.Flush(); + Writer.WriteMarker((byte)(JpegTables.Rst0 + index)); + } + } +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs b/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs new file mode 100644 index 00000000..a0ffe104 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs @@ -0,0 +1,309 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +/// Encoder → decoder round trips on synthetic content. +public sealed class JpegEncoderTests(TestContext context) +{ + private const int W = 160, H = 120; + + /// The four synthetic content classes: smooth gradients, colour bars, sensor-like noise, text-like edges. + private static byte[] Content(string kind) + { + var rgb = new byte[W * H * 3]; + var rng = new Random(11); + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + int r, g, b; + switch (kind) + { + case "gradients": + r = x * 255 / (W - 1); + g = y * 255 / (H - 1); + b = (x + y) * 255 / (W + H - 2); + break; + case "bars": + var bar = x / (W / 8); + r = (bar & 4) != 0 ? 235 : 16; + g = (bar & 2) != 0 ? 235 : 16; + b = (bar & 1) != 0 ? 235 : 16; + break; + case "noise": + // Sensor-like: mostly luma noise (σ ≈ 3.7 levels) plus weak chroma noise. + var n = rng.Next(-6, 7); + r = 120 + x / 4 + n + rng.Next(-2, 3); + g = 110 + y / 4 + n + rng.Next(-2, 3); + b = 100 + n + rng.Next(-2, 3); + break; + default: + var ink = (x % 11 is 2 or 3 && y % 16 < 12) || (y % 16 is 5 && x % 11 < 8); + r = g = b = ink ? 24 : 232; + break; + } + var i = (y * W + x) * 3; + rgb[i] = (byte)r; + rgb[i + 1] = (byte)g; + rgb[i + 2] = (byte)b; + } + } + return rgb; + } + + private static double RoundTripPsnr(byte[] rgb, JpegEncodeOptions options, int channels = 3) + { + var jpeg = JpegEncoder.Encode(rgb, W, H, channels, options); + var decoded = JpegDecoder.Decode(jpeg); + return Psnr(decoded.Pixels8, rgb); + } + + /// PSNR of Rec.601 luma (Y′). 4:2:0 halves chroma resolution by design, so saturated chroma edges + /// (colour bars) lose a quarter of the step under triangle upsampling in any codec (libjpeg: 26.7 dB RGB on + /// the same bars); the codec's own fidelity is measured on Y′. + private static double RoundTripLumaPsnr(byte[] rgb, JpegEncodeOptions options) + { + var decoded = JpegDecoder.Decode(JpegEncoder.Encode(rgb, W, H, 3, options)).Pixels8!; + static double[] Luma(byte[] p) + { + var y = new double[p.Length / 3]; + for (var i = 0; i < y.Length; i++) y[i] = 0.299 * p[3 * i] + 0.587 * p[3 * i + 1] + 0.114 * p[3 * i + 2]; + return y; + } + return Psnr(Luma(decoded), Luma(rgb), 255); + } + + [Theory] + [Case("gradients")] + [Case("bars")] + [Case("noise")] + [Case("text")] + public void HighQuality444Above40Db(string kind) + { + var psnr = RoundTripPsnr(Content(kind), new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 }); + context.Log($"{kind} q95 4:4:4: {psnr:F2} dB"); + Assert.GreaterOrEqual(psnr, 40); + } + + [Theory] + [Case("gradients")] + [Case("bars")] + [Case("noise")] + [Case("text")] + public void Quality90Yuv420Above34Db(string kind) + { + var options = new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 }; + var psnr = RoundTripLumaPsnr(Content(kind), options); + context.Log($"{kind} q90 4:2:0: Y′ {psnr:F2} dB, RGB {RoundTripPsnr(Content(kind), options):F2} dB"); + Assert.GreaterOrEqual(psnr, 34); + } + + [Test] + public void PsnrAndSizeGrowWithQuality() + { + var rgb = TestCard(W, H); + var psnr = new List(); + var sizes = new List(); + foreach (var q in new[] { 5, 20, 40, 60, 75, 85, 95, 100 }) + { + var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = q, Subsampling = JpegSubsampling.Yuv422 }); + sizes.Add(jpeg.Length); + psnr.Add(Psnr(JpegDecoder.Decode(jpeg).Pixels8, rgb)); + } + context.Log("PSNR: " + string.Join(", ", psnr.Select(p => p.ToString("F1")))); + Assert.Monotonic(psnr, strict: true); + Assert.Monotonic(sizes, strict: true); + } + + [Test] + public void OptimizedHuffmanIsSmallerAndPixelIdentical() + { + var rgb = TestCard(W, H); + var standard = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85 }); + var optimized = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85, OptimizeHuffman = true }); + context.Log($"standard {standard.Length} B, optimized {optimized.Length} B"); + Assert.Less(optimized.Length, standard.Length); + Assert.BytesEqual(JpegDecoder.Decode(standard).Pixels8, JpegDecoder.Decode(optimized).Pixels8); + } + + [Theory] + [Case(1)] + [Case(7)] + [Case(40)] + public void RestartIntervalsDecodeIdentically(int interval) + { + var rgb = TestCard(W, H); + var plain = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80 }); + var restart = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80, RestartInterval = interval, OptimizeHuffman = true }); + Assert.Equal(interval, JpegDecoder.ReadInfo(restart).RestartInterval); + var decoded = JpegDecoder.Decode(restart); + Assert.Empty(decoded.Warnings); + Assert.BytesEqual(JpegDecoder.Decode(plain).Pixels8, decoded.Pixels8); + } + + [Test] + public void App1SegmentsFollowSoiAndReplaceJfif() + { + var exif = "Exif\0\0II*\0\b\0\0\0\0\0\0\0"u8.ToArray(); + var xmp = "http://ns.adobe.com/xap/1.0/\0"u8.ToArray(); + var jpeg = JpegEncoder.Encode(TestCard(32, 16), 32, 16, 3, new JpegEncodeOptions { App1Segments = [exif, xmp] }); + Assert.Equal(0xE1, jpeg[3]); + Assert.BytesEqual(exif, jpeg.AsSpan(6, exif.Length)); + var second = 4 + (jpeg[4] << 8 | jpeg[5]); + Assert.Equal(0xE1, jpeg[second + 1]); + Assert.False(jpeg.AsSpan().IndexOf("JFIF"u8) >= 0, "JFIF must be omitted when APP1 is supplied"); + Assert.Equal(32, JpegDecoder.Decode(jpeg).Width); + Assert.Throws(() => JpegEncoder.Encode(TestCard(8, 8), 8, 8, 3, new JpegEncodeOptions { App1Segments = [new byte[65534]] })); + } + + [Test] + public void GrayBufferEncodesSingleComponent() + { + using var gray = new ImageBuffer(50, 30, 1); + for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = (i % 50) / 49f; + var jpeg = JpegEncoder.Encode(gray, new JpegEncodeOptions { Quality = 95 }); + var info = JpegDecoder.ReadInfo(jpeg); + Assert.Equal(1, info.Components); + using var back = JpegDecoder.DecodeToLinear(jpeg); + Assert.Equal(1, back.Channels); + for (var x = 0; x < 50; x += 7) Assert.Approximately(gray[0, x, 15], back[0, x, 15], 0.02); + } + + [Test] + public void LinearBufferRoundTripWithDither() + { + using var image = new ImageBuffer(96, 64); + for (var y = 0; y < 64; y++) + { + for (var x = 0; x < 96; x++) + { + image[0, x, y] = x / 95f; + image[1, x, y] = y / 63f * 0.5f; + image[2, x, y] = 0.18f; + } + } + var jpeg = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444, Dither = true }); + using var back = JpegDecoder.DecodeToLinear(jpeg); + var reference = PixelConvert.ToInterleaved8(image, 3); + var decoded = PixelConvert.ToInterleaved8(back, 3); + var psnr = Psnr(decoded, reference); + context.Log($"linear round trip {psnr:F1} dB"); + Assert.Greater(psnr, 40); + } + + [Test] + public void TwelveBitExtendedSequentialDecodes() + { + const int w = 40, h = 24; + var samples = new ushort[w * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) samples[y * w + x] = (ushort)(x * 4095 / (w - 1) ^ (y * 37 % 256)); + } + var jpeg = TwelveBitEncoder.EncodeGray(samples, w, h); + var image = JpegDecoder.Decode(jpeg); + Assert.Equal(12, image.BitDepth); + Assert.Equal(JpegProcess.ExtendedSequential, image.Info.Process); + var psnr = Psnr(image.Pixels16, samples, 4095); + context.Log($"12-bit PSNR {psnr:F1} dB"); + Assert.Greater(psnr, 50); + using var linear = JpegDecoder.DecodeToLinear(jpeg); + Assert.Approximately(ColorSpace.SrgbToLinear(image.Pixels16![5] / 4095.0), linear[0, 5, 0], 1e-4); + } + + /// Minimal SOF1 12-bit gray encoder (quantiser 1, optimal tables) for decoder tests. + private static class TwelveBitEncoder + { + public static byte[] EncodeGray(ushort[] samples, int width, int height) + { + int bw = (width + 7) / 8, bh = (height + 7) / 8; + var blocks = new short[bw * bh][]; + for (var by = 0; by < bh; by++) + { + for (var bx = 0; bx < bw; bx++) + { + var coef = new short[64]; + for (var v = 0; v < 8; v++) + { + for (var u = 0; u < 8; u++) + { + double sum = 0; + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + var s = samples[Math.Min(by * 8 + y, height - 1) * width + Math.Min(bx * 8 + x, width - 1)] - 2048.0; + sum += s * JpegTables.Basis[u * 8 + x] * JpegTables.Basis[v * 8 + y]; + } + } + coef[v * 8 + u] = (short)Math.Round(sum); + } + } + blocks[by * bw + bx] = coef; + } + } + var dcFreq = new long[256]; + var acFreq = new long[256]; + Walk(blocks, (dc, s) => (dc ? dcFreq : acFreq)[s]++, null); + var dcCode = JpegHuffmanCode.Optimal(dcFreq); + var acCode = JpegHuffmanCode.Optimal(acFreq); + var writer = new JpegBitWriter(1 << 16); + Walk(blocks, (dc, s) => { var c = dc ? dcCode : acCode; writer.Reserve(8); writer.Write(c.Code[s], c.Length[s]); }, (v, s) => writer.Write((uint)((v < 0 ? v - 1 : v) & ((1 << s) - 1)), s)); + writer.Flush(); + + using var ms = new MemoryStream(); + ms.Write([0xFF, 0xD8]); + var dqt = new byte[129]; + dqt[0] = 0x10; + for (var k = 0; k < 64; k++) dqt[2 + 2 * k] = 1; + JpegEncoder.Segment(ms, 0xDB, dqt); + JpegEncoder.Segment(ms, 0xC1, [12, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 1, 1, 0x11, 0]); + var dht = new MemoryStream(); + dht.WriteByte(0x00); + dht.Write(dcCode.Bits); + dht.Write(dcCode.Values); + dht.WriteByte(0x10); + dht.Write(acCode.Bits); + dht.Write(acCode.Values); + JpegEncoder.Segment(ms, 0xC4, dht.ToArray()); + JpegEncoder.Segment(ms, 0xDA, [1, 1, 0x00, 0, 63, 0]); + ms.Write(writer.Written); + ms.Write([0xFF, 0xD9]); + return ms.ToArray(); + } + + private static void Walk(short[][] blocks, Action symbol, Action? bits) + { + var pred = 0; + foreach (var b in blocks) + { + var diff = b[0] - pred; + pred = b[0]; + var s = Size(diff); + symbol(true, s); + if (s > 0) bits?.Invoke(diff, s); + var run = 0; + for (var k = 1; k < 64; k++) + { + int v = b[JpegTables.NaturalOrder[k]]; + if (v == 0) + { + run++; + continue; + } + for (; run >= 16; run -= 16) symbol(false, 0xF0); + s = Size(v); + symbol(false, run << 4 | s); + bits?.Invoke(v, s); + run = 0; + } + if (run > 0) symbol(false, 0); + } + } + + private static int Size(int v) => v == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(v)); + } +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs b/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs new file mode 100644 index 00000000..65ba7c54 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs @@ -0,0 +1,107 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Testing; + +namespace Titano.Core.Tests.Codecs; + +/// Lossless JPEG (SOF3) round trips: every predictor, precisions 2–16, components, restarts. +public sealed class JpegLosslessTests +{ + private static ushort[] Raw(int width, int height, int components, int precision, int seed) + { + var rng = new Random(seed); + var max = (1 << precision) - 1; + var samples = new ushort[width * height * components]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + for (var c = 0; c < components; c++) + { + // Smooth ramp + sensor noise, with a few clipped highlights and black pixels. + var v = (x * 3 + y * 5 + c * 97) % (max + 1) * 0.7 + rng.Next(Math.Max(1, max / 64)); + if (rng.Next(200) == 0) v = max; + if (rng.Next(300) == 0) v = 0; + samples[(y * width + x) * components + c] = (ushort)Math.Clamp((int)v, 0, max); + } + } + } + return samples; + } + + [Theory] + [Case(1)] + [Case(2)] + [Case(3)] + [Case(4)] + [Case(5)] + [Case(6)] + [Case(7)] + public void EveryPredictorRoundTrips(int predictor) + { + var samples = Raw(37, 23, 3, 12, predictor); + var jpeg = JpegLosslessEncoder.Encode(samples, 37, 23, 3, 12, predictor); + var decoded = JpegLosslessDecoder.Decode(jpeg); + Assert.Equal(37, decoded.Width); + Assert.Equal(23, decoded.Height); + Assert.Equal(3, decoded.Components); + Assert.Equal(12, decoded.Precision); + Assert.SequenceEqual(samples, decoded.Samples); + } + + [Theory] + [Case(2, 1)] + [Case(8, 1)] + [Case(14, 2)] + [Case(16, 1)] + [Case(16, 4)] + public void PrecisionsAndComponentCounts(int precision, int components) + { + var samples = Raw(19, 11, components, precision, precision); + foreach (var predictor in new[] { 1, 4, 7 }) + { + var decoded = JpegLosslessDecoder.Decode(JpegLosslessEncoder.Encode(samples, 19, 11, components, precision, predictor)); + Assert.SequenceEqual(samples, decoded.Samples); + } + } + + [Theory] + [Case(1)] + [Case(19)] + [Case(25)] + [Case(64)] + public void RestartIntervalsRoundTrip(int interval) + { + var samples = Raw(19, 13, 2, 14, interval); + foreach (var predictor in new[] { 1, 6 }) + { + var jpeg = JpegLosslessEncoder.Encode(samples, 19, 13, 2, 14, predictor, restartInterval: interval); + Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples); + } + } + + [Test] + public void PointTransformRestoresScaledSamples() + { + var samples = Raw(16, 9, 1, 16, 3).Select(s => (ushort)(s & ~7)).ToArray(); + var jpeg = JpegLosslessEncoder.Encode(samples, 16, 9, 1, 16, predictor: 5, pointTransform: 3); + Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples); + } + + [Test] + public void GeneralDecoderExposesLosslessAsImage() + { + var samples = Raw(10, 6, 3, 8, 1); + var image = JpegDecoder.Decode(JpegLosslessEncoder.Encode(samples, 10, 6, 3, 8)); + Assert.Equal(JpegProcess.Lossless, image.Info.Process); + Assert.Equal(3, image.Components); + Assert.SequenceEqual(samples.Select(s => (byte)s), image.Pixels8!); + var wide = Raw(10, 6, 1, 14, 2); + var gray = JpegDecoder.Decode(JpegLosslessEncoder.Encode(wide, 10, 6, 1, 14)); + Assert.Equal(14, gray.BitDepth); + Assert.SequenceEqual(wide, gray.Pixels16!); + } + + [Test] + public void DctStreamIsRejectedByLosslessDecoder() => + Assert.Throws(() => JpegLosslessDecoder.Decode(JpegEncoder.Encode(new byte[48], 4, 4, 3))); +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs new file mode 100644 index 00000000..105e6d29 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs @@ -0,0 +1,66 @@ +using System.Diagnostics; +using Titano.Core.Codecs.Jpeg; +using Titano.Testing; + +namespace Titano.Core.Tests.Codecs; + +/// 24-megapixel baseline 4:2:0 encode/decode timing (decode measured single-threaded). +[Serial] +[Category("Performance")] +public sealed class JpegPerformanceTests(TestContext context) +{ + private const int W = 6000, H = 4000; + + [Test] + [Timeout(60_000)] + public void Decodes24MegapixelOnOneCoreUnderThreeSeconds() + { + var rgb = Photo(); + var sw = Stopwatch.StartNew(); + var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 }); + var encode = sw.Elapsed; + + // Best of two runs: the machine is shared, the first run also pays JIT warm-up. + var single = TimeSpan.MaxValue; + JpegImage? image = null; + for (var run = 0; run < 2; run++) + { + sw.Restart(); + image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxDegreeOfParallelism = 1 }); + single = sw.Elapsed < single ? sw.Elapsed : single; + } + sw.Restart(); + JpegDecoder.Decode(jpeg); + var parallel = sw.Elapsed; + + context.Log($"encode {encode.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / encode.TotalSeconds:F1} MP/s, {jpeg.Length / 1e6:F2} MB); " + + $"decode 1 core {single.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / single.TotalSeconds:F1} MP/s); " + + $"decode all cores {parallel.TotalMilliseconds:F0} ms"); + Console.WriteLine($"[perf] {context.LogText.Trim()}"); + Assert.Equal(W, image!.Width); + Assert.Less(single.TotalSeconds, 3.0); + } + + /// Photo-like content: smooth illumination, texture and mild noise (≈ q90 file size of a real photo). + private static byte[] Photo() + { + var rgb = new byte[W * H * 3]; + Parallel.For(0, H, y => + { + var state = (uint)(y * 2654435761u + 1); + for (var x = 0; x < W; x++) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + var noise = (int)(state & 7) - 4; + var texture = ((x >> 3) ^ (y >> 3)) & 15; + var i = (y * W + x) * 3; + rgb[i] = (byte)Math.Clamp(60 + x * 150 / W + texture + noise, 0, 255); + rgb[i + 1] = (byte)Math.Clamp(80 + y * 120 / H + texture + noise, 0, 255); + rgb[i + 2] = (byte)Math.Clamp(200 - (x + y) * 140 / (W + H) + noise, 0, 255); + } + }); + return rgb; + } +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs b/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs new file mode 100644 index 00000000..1b1dd8f9 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs @@ -0,0 +1,157 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +/// Corrupt, truncated and hostile JPEG input: only may escape. +public sealed class JpegRobustnessTests(TestContext context) +{ + private static byte[] LosslessSample() + { + var samples = new ushort[24 * 10 * 2]; + for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i * 37 % 4096); + return JpegLosslessEncoder.Encode(samples, 24, 10, 2, 12, predictor: 6, restartInterval: 24); + } + + [Theory] + [Case("jpeg/b420.jpg")] + [Case("jpeg/b411.jpg")] + [Case("jpeg/p420.jpg")] + [Case("jpeg/p444.jpg")] + [Case("jpeg/r420.jpg")] + [Case("jpeg/pgray.jpg")] + [Case("jpeg/cmyk.jpg")] + [Case("lossless")] + public void FuzzedInputOnlyThrowsInvalidData(string source) + { + var valid = source == "lossless" ? LosslessSample() : Fixture(source); + var options = new[] { JpegDecodeOptions.Default, new JpegDecodeOptions { MaxLongEdge = 16, FancyUpsampling = false } }; + int decoded = 0, rejected = 0; + var i = 0; + foreach (var input in Corruptions(valid, 120, seed: source.Sum(c => c))) + { + try + { + JpegDecoder.ReadInfo(input); + if (source == "lossless") + { + var raw = JpegLosslessDecoder.Decode(input); + Assert.Equal(raw.Width * raw.Height * raw.Components, raw.Samples.Length); + } + else + { + var image = JpegDecoder.Decode(input, options[i++ % 2]); + Assert.True(image.Width > 0 && image.Height > 0); + } + decoded++; + } + catch (InvalidDataException) + { + rejected++; + } + } + context.Log($"{source}: {decoded} decoded (possibly partial), {rejected} rejected"); + } + + [Test] + public void CorruptRestartIntervalIsResynchronised() + { + var data = Fixture("jpeg/r420.jpg"); + var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples; + var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]); + var rst1 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD1]); + Assert.True(rst0 > 0 && rst1 > rst0, "fixture has restart markers"); + var corrupt = (byte[])data.Clone(); + var rng = new Random(5); + for (var p = rst0 + 6; p < rst1 - 4; p += 3) + { + if (corrupt[p - 1] != 0xFF) corrupt[p] = (byte)rng.Next(0xFF); + } + // A bogus marker inside the damaged interval must be skipped, as libjpeg's resync does. + corrupt[rst0 + 10] = 0xFF; + corrupt[rst0 + 11] = 0x3A; + var image = JpegDecoder.Decode(corrupt); + context.Log(string.Join("; ", image.Warnings)); + Assert.NotEmpty(image.Warnings); + AssertRowsMatch(image.Pixels8!, reference, 0, 14); + AssertRowsMatch(image.Pixels8!, reference, 34, 45); + } + + [Test] + public void MissingRestartMarkerSkipsTheLostInterval() + { + var data = Fixture("jpeg/r420.jpg"); + var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples; + var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]); + var cut = data.AsSpan(0, rst0).ToArray().Concat(data.AsSpan(rst0 + 2).ToArray()).ToArray(); + var image = JpegDecoder.Decode(cut); + Assert.NotEmpty(image.Warnings); + AssertRowsMatch(image.Pixels8!, reference, 0, 14); + AssertRowsMatch(image.Pixels8!, reference, 34, 45); + } + + [Theory] + [Case("jpeg/p420.jpg")] + [Case("jpeg/b444.jpg")] + public void TruncatedScanDataYieldsPartialImage(string name) + { + var data = Fixture(name); + var image = JpegDecoder.Decode(data.AsSpan(0, data.Length * 2 / 3)); + Assert.Equal(61, image.Width); + Assert.Equal(45, image.Height); + Assert.NotEmpty(image.Warnings); + } + + [Test] + public void StructuralErrorsAreRejected() + { + Assert.Throws(() => JpegDecoder.Decode([])); + Assert.Throws(() => JpegDecoder.Decode([0xFF, 0xD8, 0xFF, 0xD9])); + Assert.Throws(() => JpegDecoder.ReadInfo([0x89, 0x50, 0x4E, 0x47])); + var arithmetic = Fixture("jpeg/b420.jpg"); + var sof = arithmetic.AsSpan().IndexOf([(byte)0xFF, (byte)0xC0]); + arithmetic[sof + 1] = 0xC9; + Assert.Throws(() => JpegDecoder.Decode(arithmetic)); + var huge = Fixture("jpeg/b420.jpg"); + huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF; + Assert.Throws(() => JpegDecoder.Decode(huge)); + } + + [Test] + public void TablesStreamFeedsAbbreviatedImage() + { + // TIFF JPEGTables layout: tables in one SOI..EOI stream, the image without DQT/DHT. + var full = Fixture("jpeg/b420.jpg"); + var tables = new MemoryStream(); + var image = new MemoryStream(); + tables.Write([0xFF, 0xD8]); + image.Write([0xFF, 0xD8]); + var pos = 2; + while (pos < full.Length) + { + var marker = full[pos + 1]; + if (marker == 0xDA) + { + image.Write(full.AsSpan(pos)); + break; + } + var length = full[pos + 2] << 8 | full[pos + 3]; + (marker is 0xDB or 0xC4 ? tables : image).Write(full.AsSpan(pos, length + 2)); + pos += length + 2; + } + tables.Write([0xFF, 0xD9]); + Assert.Throws(() => JpegDecoder.Decode(image.ToArray())); + var decoded = JpegDecoder.Decode(image.ToArray(), new JpegDecodeOptions { Tables = tables.ToArray() }); + Assert.BytesEqual(JpegDecoder.Decode(full).Pixels8, decoded.Pixels8); + } + + private static void AssertRowsMatch(byte[] actual, int[] reference, int fromRow, int toRow) + { + var rowBytes = 61 * 3; + for (var i = fromRow * rowBytes; i < toRow * rowBytes; i++) + { + if (Math.Abs(actual[i] - reference[i]) > 2) Assert.Fail($"row {i / rowBytes} differs from the reference"); + } + } +} diff --git a/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs b/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs new file mode 100644 index 00000000..ef970575 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs @@ -0,0 +1,94 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +/// DCT-domain scaling (1/2, 1/4, 1/8) and the linear-light decode path. +public sealed class JpegScalingTests(TestContext context) +{ + private const int W = 256, H = 192; + + [Theory] + [Case(0, 256, 192)] + [Case(200, 256, 192)] + [Case(128, 128, 96)] + [Case(100, 128, 96)] + [Case(64, 64, 48)] + [Case(33, 64, 48)] + [Case(32, 32, 24)] + [Case(1, 32, 24)] + public void MaxLongEdgePicksSmallestSufficientScale(int maxLongEdge, int width, int height) + { + var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3); + var image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = maxLongEdge }); + Assert.Equal(width, image.Width); + Assert.Equal(height, image.Height); + Assert.Equal(W, image.Info.Width); + } + + [Theory] + [Case(2, 38.0)] + [Case(4, 34.0)] + [Case(8, 30.0)] + public void ScaledDecodeApproximatesAreaAverage(int factor, double minPsnr) + { + var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3, new JpegEncodeOptions { Quality = 92 }); + var full = JpegDecoder.Decode(jpeg).Pixels8!; + var scaled = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = W / factor }); + Assert.Equal(W / factor, scaled.Width); + int sw = W / factor, sh = H / factor; + var expected = new byte[sw * sh * 3]; + for (var y = 0; y < sh; y++) + { + for (var x = 0; x < sw; x++) + { + for (var c = 0; c < 3; c++) + { + var sum = 0; + for (var dy = 0; dy < factor; dy++) + { + for (var dx = 0; dx < factor; dx++) sum += full[((y * factor + dy) * W + x * factor + dx) * 3 + c]; + } + expected[(y * sw + x) * 3 + c] = (byte)((sum + factor * factor / 2) / (factor * factor)); + } + } + } + var psnr = Psnr(scaled.Pixels8, expected); + context.Log($"1/{factor}: {psnr:F1} dB vs area average"); + Assert.Greater(psnr, minPsnr); + } + + [Test] + public void ScaledOddSizeKeepsEdges() + { + var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { MaxLongEdge = 31 }); + Assert.Equal(31, image.Width); + Assert.Equal(23, image.Height); + var reference = ReadPnm(Fixture("src.ppm")); + // Bottom-right pixel of the scaled image must still resemble the source corner (no padding garbage). + var pixels = image.Pixels8!; + var last = pixels.AsSpan(pixels.Length - 3); + var src = reference.Samples.AsSpan(reference.Samples.Length - 3); + for (var c = 0; c < 3; c++) Assert.InRange(last[c], src[c] - 70, src[c] + 70); + } + + [Test] + public void LinearDecodeMatchesLookupOfEightBitDecode() + { + var data = Fixture("jpeg/b422.jpg"); + var bytes = JpegDecoder.Decode(data).Pixels8!; + using var linear = JpegDecoder.DecodeToLinear(data); + Assert.Equal(3, linear.Channels); + for (var i = 0; i < 61 * 45; i += 17) + { + for (var c = 0; c < 3; c++) Assert.Equal(ColorSpace.Linear8(bytes[i * 3 + c]), linear.Plane(c)[i]); + } + using var gray = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg")); + Assert.Equal(1, gray.Channels); + using var expanded = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg"), expandGray: true); + Assert.Equal(3, expanded.Channels); + Assert.SequenceEqual(gray.Plane(0).ToArray(), expanded.Plane(2).ToArray()); + } +} From 0e6c15cb13db20401a343319c2f3aa1752ba0a3f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:02 +0000 Subject: [PATCH 030/188] feat(windows): add shared COM, window and shell-stream interop helpers Win32Com joins threads to the MTA on demand, creates in-process COM objects and releases wrappers deterministically; PropVariant (x64 layout) with PropVariantClear; Win32Window validates HWNDs; ShellStream opens files through SHCreateStreamOnFileEx with STGM_SHARE_DENY_NONE so readers never block writers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Interop/ShellStream.cs | 27 ++++++++ src/Titano.Core.Windows/Interop/Win32Com.cs | 63 +++++++++++++++++++ .../Interop/Win32PropVariant.cs | 63 +++++++++++++++++++ .../Interop/Win32Window.cs | 14 +++++ 4 files changed, 167 insertions(+) create mode 100644 src/Titano.Core.Windows/Interop/ShellStream.cs create mode 100644 src/Titano.Core.Windows/Interop/Win32Com.cs create mode 100644 src/Titano.Core.Windows/Interop/Win32PropVariant.cs create mode 100644 src/Titano.Core.Windows/Interop/Win32Window.cs diff --git a/src/Titano.Core.Windows/Interop/ShellStream.cs b/src/Titano.Core.Windows/Interop/ShellStream.cs new file mode 100644 index 00000000..6c3b1d04 --- /dev/null +++ b/src/Titano.Core.Windows/Interop/ShellStream.cs @@ -0,0 +1,27 @@ +using System.Runtime.InteropServices; +using Titano.Core.IO; + +namespace Titano.Core.Windows.Interop; + +/// IStream over a file through SHCreateStreamOnFileEx. +internal static partial class ShellStream +{ + private const uint STGM_READ = 0x0; + private const uint STGM_SHARE_DENY_NONE = 0x40; + private const uint FILE_ATTRIBUTE_NORMAL = 0x80; + + /// + /// Opens read-only while letting other processes read and write it (FileShare.ReadWrite), + /// so a camera tether or a copy in progress is never blocked. Returns an owned IStream pointer the caller must + /// . Failures surface as the matching .NET exception (FileNotFoundException, …). + /// + public static nint OpenRead(string path) + { + var hr = SHCreateStreamOnFileEx(LongPath.Normalize(path), STGM_READ | STGM_SHARE_DENY_NONE, FILE_ATTRIBUTE_NORMAL, 0, 0, out var stream); + Marshal.ThrowExceptionForHR(hr); + return stream; + } + + [LibraryImport("shlwapi.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream); +} diff --git a/src/Titano.Core.Windows/Interop/Win32Com.cs b/src/Titano.Core.Windows/Interop/Win32Com.cs new file mode 100644 index 00000000..7ea3e1e7 --- /dev/null +++ b/src/Titano.Core.Windows/Interop/Win32Com.cs @@ -0,0 +1,63 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Interop; + +/// COM apartment, activation and release helpers shared by the WIC, shell and taskbar interop. +internal static partial class Win32Com +{ + public const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106); + public const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154); + + private const uint COINIT_MULTITHREADED = 0x0; + private const uint CLSCTX_INPROC_SERVER = 0x1; + + [ThreadStatic] + private static bool t_initialized; + + /// + /// Joins the calling thread to the multithreaded apartment unless it already has one (an STA UI thread keeps + /// its apartment, which free-threaded WIC also accepts). Idempotent per thread. COM stays initialised until the + /// thread exits, as the runtime does for the threads it initialises itself. + /// + public static void EnsureInitialized() + { + if (t_initialized) return; + var hr = CoInitializeEx(0, COINIT_MULTITHREADED); + if (hr < 0 && hr != RPC_E_CHANGED_MODE) Marshal.ThrowExceptionForHR(hr); + t_initialized = true; + } + + /// Creates an in-process COM object and wraps it; returns the HRESULT (instance is null on failure). + public static int TryCreateInstance(Guid clsid, Guid iid, out object? instance) + { + EnsureInitialized(); + var hr = CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, iid, out var pointer); + if (hr < 0) + { + instance = null; + return hr; + } + try + { + instance = Marshal.GetObjectForIUnknown(pointer); + } + finally + { + // The wrapper holds its own reference. + Marshal.Release(pointer); + } + return hr; + } + + /// Releases the wrapper's reference to the native object now rather than at finalization. + public static void Release(object? comObject) + { + if (comObject is not null && Marshal.IsComObject(comObject)) Marshal.ReleaseComObject(comObject); + } + + [LibraryImport("ole32.dll")] + private static partial int CoInitializeEx(nint reserved, uint coInit); + + [LibraryImport("ole32.dll")] + private static partial int CoCreateInstance(in Guid clsid, nint outer, uint context, in Guid iid, out nint instance); +} diff --git a/src/Titano.Core.Windows/Interop/Win32PropVariant.cs b/src/Titano.Core.Windows/Interop/Win32PropVariant.cs new file mode 100644 index 00000000..bc39fc3a --- /dev/null +++ b/src/Titano.Core.Windows/Interop/Win32PropVariant.cs @@ -0,0 +1,63 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Interop; + +/// +/// x64 PROPVARIANT (24 bytes: VARTYPE + three reserved WORDs, then a 16-byte union). Only the integer members +/// Titano reads are mapped; anything the callee allocates is freed by . +/// +[StructLayout(LayoutKind.Explicit, Size = 24)] +internal partial struct PropVariant +{ + private const ushort VT_I2 = 2, VT_I4 = 3, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19; + + [FieldOffset(0)] + public ushort VarType; + + [FieldOffset(8)] + private byte _byte; + + [FieldOffset(8)] + private short _int16; + + [FieldOffset(8)] + private ushort _uint16; + + [FieldOffset(8)] + private int _int32; + + [FieldOffset(8)] + private uint _uint32; + + /// Reads an 8/16/32-bit integer value; false for any other type. + public readonly bool TryGetInt32(out int value) + { + switch (VarType) + { + case VT_UI1: + value = _byte; + return true; + case VT_I2: + value = _int16; + return true; + case VT_UI2: + value = _uint16; + return true; + case VT_I4: + value = _int32; + return true; + case VT_UI4 when _uint32 <= int.MaxValue: + value = (int)_uint32; + return true; + default: + value = 0; + return false; + } + } + + /// Frees whatever the callee allocated and resets the value to VT_EMPTY. + public static void Clear(ref PropVariant value) => PropVariantClear(ref value); + + [LibraryImport("ole32.dll")] + private static partial int PropVariantClear(ref PropVariant value); +} diff --git a/src/Titano.Core.Windows/Interop/Win32Window.cs b/src/Titano.Core.Windows/Interop/Win32Window.cs new file mode 100644 index 00000000..ce535139 --- /dev/null +++ b/src/Titano.Core.Windows/Interop/Win32Window.cs @@ -0,0 +1,14 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Interop; + +/// Window handle validation shared by the DWM and taskbar helpers. +internal static partial class Win32Window +{ + /// True when names an existing window; rejects null and stale handles up front. + public static bool Exists(nint window) => window != 0 && IsWindow(window); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool IsWindow(nint window); +} From 2b37f486e2ad5ffd54d8452d4da086db90ecb040 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:10 +0000 Subject: [PATCH 031/188] feat(windows): add shell launcher, taskbar progress and app paths ShellLauncher opens only http(s) and ms-windows-store URLs and reveals files (SHOpenFolderAndSelectItems) or folders ("explore") on an STA. TaskbarProgress wraps ITaskbarList3 and returns false for null or stale windows. KnownFolders reads LocalAppData/Pictures via SHGetKnownFolderPath. AppPaths resolves the data root (%LOCALAPPDATA%\Titano or .\data in portable mode) and refuses to create it inside a OneDrive sync root (environment variables and HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core.Windows/Shell/AppPaths.cs | 64 +++++++++ src/Titano.Core.Windows/Shell/KnownFolders.cs | 38 +++++ .../Shell/OneDriveFolders.cs | 48 +++++++ src/Titano.Core.Windows/Shell/PortableMode.cs | 10 ++ .../Shell/ShellLauncher.cs | 132 ++++++++++++++++++ .../Shell/TaskbarProgress.cs | 84 +++++++++++ .../Shell/AppPathsTests.cs | 75 ++++++++++ .../Shell/ShellTests.cs | 57 ++++++++ 8 files changed, 508 insertions(+) create mode 100644 src/Titano.Core.Windows/Shell/AppPaths.cs create mode 100644 src/Titano.Core.Windows/Shell/KnownFolders.cs create mode 100644 src/Titano.Core.Windows/Shell/OneDriveFolders.cs create mode 100644 src/Titano.Core.Windows/Shell/PortableMode.cs create mode 100644 src/Titano.Core.Windows/Shell/ShellLauncher.cs create mode 100644 src/Titano.Core.Windows/Shell/TaskbarProgress.cs create mode 100644 tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs diff --git a/src/Titano.Core.Windows/Shell/AppPaths.cs b/src/Titano.Core.Windows/Shell/AppPaths.cs new file mode 100644 index 00000000..e2cfd70e --- /dev/null +++ b/src/Titano.Core.Windows/Shell/AppPaths.cs @@ -0,0 +1,64 @@ +namespace Titano.Core.Windows.Shell; + +/// +/// Where the desktop programs keep their data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the +/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is +/// reported by and refused by . +/// +public sealed class AppPaths +{ + public const string ProductFolderName = "Titano"; + public const string DatabaseFileName = "titano.db"; + + private AppPaths(string dataRoot, bool isPortable, string? syncedFolder) + { + DataRoot = dataRoot; + IsPortable = isPortable; + SyncedFolder = syncedFolder; + } + + public bool IsPortable { get; } + + public string DataRoot { get; } + + public string DatabasePath => Path.Combine(DataRoot, DatabaseFileName); + + public string LogsDirectory => Path.Combine(DataRoot, "logs"); + + public string CacheDirectory => Path.Combine(DataRoot, "cache"); + + public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails"); + + /// The OneDrive sync root containing , or null when the location is safe. + public string? SyncedFolder { get; } + + public bool IsInSyncedFolder => SyncedFolder is not null; + + /// Paths for this process: the executable's folder decides portable mode. + public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData); + + /// Paths for an executable in , checked against the user's OneDrive roots. + public static AppPaths Resolve(string applicationDirectory, string localAppData) => + Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots()); + + internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList syncRoots) + { + var portable = PortableMode.IsEnabled(applicationDirectory); + var root = Path.GetFullPath(portable + ? Path.Combine(applicationDirectory, PortableMode.DataFolderName) + : Path.Combine(localAppData, ProductFolderName)); + return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots)); + } + + /// Creates the data, logs, cache and thumbnails folders. + /// The data root lies inside a OneDrive-synced folder. + public void CreateDirectories() + { + if (SyncedFolder is not null) + throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation."); + Directory.CreateDirectory(DataRoot); + Directory.CreateDirectory(LogsDirectory); + Directory.CreateDirectory(CacheDirectory); + Directory.CreateDirectory(ThumbnailsDirectory); + } +} diff --git a/src/Titano.Core.Windows/Shell/KnownFolders.cs b/src/Titano.Core.Windows/Shell/KnownFolders.cs new file mode 100644 index 00000000..928addbd --- /dev/null +++ b/src/Titano.Core.Windows/Shell/KnownFolders.cs @@ -0,0 +1,38 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Shell; + +/// Known folder paths through SHGetKnownFolderPath (honours folder redirection). +public static partial class KnownFolders +{ + /// FOLDERID_LocalAppData. + public static readonly Guid LocalAppDataId = new("f1b32785-6fba-4fcf-9d55-7b8e7f157091"); + + /// FOLDERID_Pictures. + public static readonly Guid PicturesId = new("33e28130-4e1e-4676-835a-98395c3bc3bb"); + + /// %LOCALAPPDATA% (never synced by OneDrive). + public static string LocalAppData => GetPath(LocalAppDataId); + + /// The user's Pictures folder (may be redirected into OneDrive). + public static string Pictures => GetPath(PicturesId); + + /// The folder does not exist or is not available to this user. + public static string GetPath(Guid folderId) + { + var hr = SHGetKnownFolderPath(folderId, 0, 0, out var buffer); + try + { + Marshal.ThrowExceptionForHR(hr); + return Marshal.PtrToStringUni(buffer) ?? string.Empty; + } + finally + { + // The buffer must be freed whether or not the call succeeded. + Marshal.FreeCoTaskMem(buffer); + } + } + + [LibraryImport("shell32.dll")] + private static partial int SHGetKnownFolderPath(in Guid folderId, uint flags, nint token, out nint path); +} diff --git a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs new file mode 100644 index 00000000..b37a5a67 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs @@ -0,0 +1,48 @@ +using Microsoft.Win32; + +namespace Titano.Core.Windows.Shell; + +/// Folders synchronised by OneDrive for the current user (personal and work/school accounts). +public static class OneDriveFolders +{ + private const string AccountsKey = @"Software\Microsoft\OneDrive\Accounts"; + private static readonly string[] EnvironmentVariables = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]; + + /// + /// Sync roots from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder, + /// as full paths without a trailing separator, distinct (case-insensitive). + /// + public static IReadOnlyList SyncRoots() + { + var roots = new List(); + foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable)); + using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey); + if (accounts is not null) + { + foreach (var name in accounts.GetSubKeyNames()) + { + using var account = accounts.OpenSubKey(name); + Add(roots, account?.GetValue("UserFolder") as string); + } + } + return roots; + } + + /// The sync root that contains , or null. Both are expected to be full paths. + public static string? Containing(string path, IEnumerable syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root)); + + /// True when equals or lies below it (whole path segments, case-insensitive). + internal static bool IsUnder(string path, string root) + { + var trimmedRoot = root.TrimEnd('\\', '/'); + if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false; + return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/'; + } + + private static void Add(List roots, string? candidate) + { + if (string.IsNullOrWhiteSpace(candidate) || !Path.IsPathFullyQualified(candidate)) return; + var full = Path.GetFullPath(candidate).TrimEnd('\\', '/'); + if (!roots.Contains(full, StringComparer.OrdinalIgnoreCase)) roots.Add(full); + } +} diff --git a/src/Titano.Core.Windows/Shell/PortableMode.cs b/src/Titano.Core.Windows/Shell/PortableMode.cs new file mode 100644 index 00000000..2c438a37 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/PortableMode.cs @@ -0,0 +1,10 @@ +namespace Titano.Core.Windows.Shell; + +/// Portable mode (BRIEF §6.2): a portable.txt next to the executable keeps all data under .\data\. +public static class PortableMode +{ + public const string MarkerFileName = "portable.txt"; + public const string DataFolderName = "data"; + + public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName)); +} diff --git a/src/Titano.Core.Windows/Shell/ShellLauncher.cs b/src/Titano.Core.Windows/Shell/ShellLauncher.cs new file mode 100644 index 00000000..ecf9ed72 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/ShellLauncher.cs @@ -0,0 +1,132 @@ +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Shell; + +/// +/// The only shell verbs Titano may invoke (BRIEF §8.6): open for web and Microsoft Store links and +/// explore/select for revealing files. Callable from any thread: the work runs on an STA as shell +/// extensions require (inline on a UI thread, otherwise on a short-lived STA thread). +/// +public static partial class ShellLauncher +{ + private static readonly string[] AllowedSchemes = ["http", "https", "ms-windows-store"]; + + private const uint SEE_MASK_NOASYNC = 0x100; + private const uint SEE_MASK_FLAG_NO_UI = 0x400; + private const int SW_SHOWNORMAL = 1; + + /// True for absolute http, https and ms-windows-store URLs, the only links handed to the shell. + public static bool IsAllowedUrl(string url) => + Uri.TryCreate(url, UriKind.Absolute, out var uri) + && AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase); + + /// Opens the URL with ShellExecuteEx("open"); false when the shell could not open it. + /// The URL is not an absolute http, https or ms-windows-store URL. + public static bool OpenUrl(string url) + { + if (!IsAllowedUrl(url)) throw new ArgumentException("Only http, https and ms-windows-store URLs may be opened.", nameof(url)); + var canonical = new Uri(url, UriKind.Absolute).AbsoluteUri; + return RunOnSta(() => Execute("open", canonical)); + } + + /// + /// Shows a file selected in its Explorer folder (SHOpenFolderAndSelectItems) or opens a folder ("explore"). + /// False when the path does not exist or the shell failed. + /// + public static bool RevealInExplorer(string path) + { + var full = Path.GetFullPath(path); + if (Directory.Exists(full)) return RunOnSta(() => Execute("explore", full)); + return File.Exists(full) && RunOnSta(() => SelectInFolder(full)); + } + + private static unsafe bool Execute(string verb, string file) + { + fixed (char* verbPointer = verb) + fixed (char* filePointer = file) + { + var info = new ShellExecuteInfo + { + Size = (uint)sizeof(ShellExecuteInfo), + Mask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI, + Verb = (nint)verbPointer, + File = (nint)filePointer, + Show = SW_SHOWNORMAL, + }; + return ShellExecuteExW(ref info); + } + } + + private static bool SelectInFolder(string file) + { + if (SHParseDisplayName(file, 0, out var itemList, 0, out _) < 0) return false; + try + { + // With no child items the absolute ID list names the item to select; Explorer opens its parent. + return SHOpenFolderAndSelectItems(itemList, 0, 0, 0) >= 0; + } + finally + { + Marshal.FreeCoTaskMem(itemList); + } + } + + private static bool RunOnSta(Func action) + { + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) return action(); + var result = false; + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + result = action(); + } + catch (Exception ex) + { + failure = ExceptionDispatchInfo.Capture(ex); + } + }) + { + IsBackground = true, + Name = "Titano shell", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + failure?.Throw(); + return result; + } + + /// SHELLEXECUTEINFOW (112 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct ShellExecuteInfo + { + public uint Size; + public uint Mask; + public nint Window; + public nint Verb; + public nint File; + public nint Parameters; + public nint Directory; + public int Show; + public nint InstanceApp; + public nint ItemIdList; + public nint Class; + public nint ClassKey; + public uint HotKey; + public nint IconOrMonitor; + public nint Process; + } + + [LibraryImport("shell32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool ShellExecuteExW(ref ShellExecuteInfo info); + + [LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int SHParseDisplayName(string name, nint bindContext, out nint itemIdList, uint attributesIn, out uint attributesOut); + + [LibraryImport("shell32.dll")] + private static partial int SHOpenFolderAndSelectItems(nint folder, uint count, nint items, uint flags); +} diff --git a/src/Titano.Core.Windows/Shell/TaskbarProgress.cs b/src/Titano.Core.Windows/Shell/TaskbarProgress.cs new file mode 100644 index 00000000..d60d59e2 --- /dev/null +++ b/src/Titano.Core.Windows/Shell/TaskbarProgress.cs @@ -0,0 +1,84 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Shell; + +/// TBPFLAG: the taskbar button progress style. +public enum TaskbarProgressState +{ + None = 0x0, + Indeterminate = 0x1, + Normal = 0x2, + Error = 0x4, + Paused = 0x8, +} + +/// +/// Taskbar button progress through ITaskbarList3. The taskbar object is apartment-threaded: create, use and dispose +/// an instance on the UI thread that owns the window. Every call returns false (never throws) when the taskbar is +/// unavailable, the window handle is null or stale, or the shell rejects the call. +/// +public sealed class TaskbarProgress : IDisposable +{ + private static readonly Guid TaskbarListClsid = new("56fdf344-fd6d-11d0-958a-006097c9a090"); + private ITaskbarList3? _taskbar; + + public TaskbarProgress() + { + if (Win32Com.TryCreateInstance(TaskbarListClsid, typeof(ITaskbarList3).GUID, out var instance) >= 0 + && instance is ITaskbarList3 taskbar + && taskbar.HrInit() >= 0) + { + _taskbar = taskbar; + return; + } + Win32Com.Release(instance); + } + + /// False when no taskbar is available (e.g. a session without Explorer). + public bool IsAvailable => _taskbar is not null; + + public bool SetState(nint window, TaskbarProgressState state) => + _taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressState(window, state) >= 0; + + /// Sets the bar to / (switches to if no progress was shown). + public bool SetValue(nint window, ulong completed, ulong total) => + total > 0 && _taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressValue(window, Math.Min(completed, total), total) >= 0; + + public void Dispose() + { + Win32Com.Release(_taskbar); + _taskbar = null; + } +} + +/// ITaskbarList3 (ITaskbarList → ITaskbarList2 → ITaskbarList3), declared up to SetProgressState. +[ComImport] +[Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface ITaskbarList3 +{ + [PreserveSig] + int HrInit(); + + [PreserveSig] + int AddTab(nint window); + + [PreserveSig] + int DeleteTab(nint window); + + [PreserveSig] + int ActivateTab(nint window); + + [PreserveSig] + int SetActiveAlt(nint window); + + [PreserveSig] + int MarkFullscreenWindow(nint window, int fullscreen); + + [PreserveSig] + int SetProgressValue(nint window, ulong completed, ulong total); + + [PreserveSig] + int SetProgressState(nint window, TaskbarProgressState state); +} diff --git a/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs new file mode 100644 index 00000000..3be36314 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs @@ -0,0 +1,75 @@ +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Shell; + +public sealed class AppPathsTests(TestContext context) +{ + [Test] + public void PortableMarkerKeepsDataNextToTheExecutable() + { + var app = context.CreateTempDirectory("app"); + var local = context.CreateTempDirectory("local"); + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + + var paths = AppPaths.Resolve(app, local, []); + Assert.True(paths.IsPortable); + Assert.Equal(Path.Combine(app, "data"), paths.DataRoot); + Assert.Equal(Path.Combine(app, "data", "titano.db"), paths.DatabasePath); + Assert.False(paths.IsInSyncedFolder); + + paths.CreateDirectories(); + Assert.True(Directory.Exists(paths.LogsDirectory)); + Assert.True(Directory.Exists(paths.CacheDirectory)); + Assert.True(Directory.Exists(paths.ThumbnailsDirectory)); + } + + [Test] + public void InstalledModeUsesLocalAppData() + { + var app = context.CreateTempDirectory("app"); + var local = context.CreateTempDirectory("local"); + + var paths = AppPaths.Resolve(app, local, []); + Assert.False(paths.IsPortable); + Assert.Equal(Path.Combine(local, "Titano"), paths.DataRoot); + Assert.Equal(Path.Combine(local, "Titano", "titano.db"), paths.DatabasePath); + } + + [Test] + public void DataInsideOneDriveIsReportedAndRefused() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + + var paths = AppPaths.Resolve(app, context.CreateTempDirectory("local"), [oneDrive]); + Assert.True(paths.IsInSyncedFolder); + Assert.Equal(oneDrive, paths.SyncedFolder); + Assert.Throws(paths.CreateDirectories); + Assert.False(Directory.Exists(paths.DataRoot)); + } + + [Test] + public void SyncRootMatchingIsSegmentWise() + { + var root = Path.Combine(context.CreateTempDirectory(), "OneDrive"); + Assert.True(OneDriveFolders.IsUnder(root, root)); + Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar)); + Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root)); + Assert.False(OneDriveFolders.IsUnder(root + "Backup", root)); + Assert.Null(OneDriveFolders.Containing(root + "Backup", [root])); + } + + [Test] + [WindowsOnly] + public void ResolveChecksTheRealOneDriveRoots() + { + var app = context.CreateTempDirectory("app"); + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var paths = AppPaths.Resolve(app, KnownFolders.LocalAppData); + Assert.True(paths.IsPortable); + Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, OneDriveFolders.SyncRoots()), paths.SyncedFolder); + Assert.True(OneDriveFolders.SyncRoots().All(Path.IsPathFullyQualified)); + } +} diff --git a/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs b/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs new file mode 100644 index 00000000..e55a8539 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Shell/ShellTests.cs @@ -0,0 +1,57 @@ +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Shell; + +public sealed class ShellTests(TestContext context) +{ + private static readonly nint StaleWindow = 0x0BAD_F00D; + + [Theory] + [Case("https://apps.microsoft.com/detail/9nctdw2w1bh8")] + [Case("http://nas.local:8443/admin")] + [Case("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8")] + public void WebAndStoreUrlsAreAllowed(string url) => Assert.True(ShellLauncher.IsAllowedUrl(url)); + + [Theory] + [Case("file:///C:/Windows/System32/cmd.exe")] + [Case(@"C:\Windows\System32\cmd.exe")] + [Case(@"\\server\share\run.bat")] + [Case("javascript:alert(1)")] + [Case("mailto:someone@example.com")] + [Case("relative/page.html")] + [Case("")] + public void OtherTargetsAreRejected(string url) => Assert.False(ShellLauncher.IsAllowedUrl(url)); + + [Test] + public void OpenUrlRefusesRejectedTargetsBeforeTouchingTheShell() => + Assert.Throws(() => ShellLauncher.OpenUrl("file:///C:/Windows/System32/cmd.exe")); + + [Test] + public void RevealOfAMissingPathReturnsFalse() => + Assert.False(ShellLauncher.RevealInExplorer(Path.Combine(context.CreateTempDirectory(), "missing.jpg"))); + + [Test] + [WindowsOnly] + public void KnownFoldersMatchTheSystem() + { + Assert.Equal( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToUpperInvariant(), + KnownFolders.LocalAppData.ToUpperInvariant()); + Assert.True(Path.IsPathFullyQualified(KnownFolders.Pictures), KnownFolders.Pictures); + } + + [Test] + [WindowsOnly] + public void TaskbarCallsWithoutAValidWindowReturnFalse() + { + using var taskbar = new TaskbarProgress(); + Assert.False(taskbar.SetState(0, TaskbarProgressState.Normal)); + Assert.False(taskbar.SetValue(0, 1, 2)); + Assert.False(taskbar.SetState(StaleWindow, TaskbarProgressState.Indeterminate)); + Assert.False(taskbar.SetValue(StaleWindow, 1, 2)); + taskbar.Dispose(); + Assert.False(taskbar.IsAvailable); + Assert.False(taskbar.SetValue(StaleWindow, 1, 2)); + } +} From 3cbf72610e33e81b86b02ac3227eaca33b45c965 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:19 +0000 Subject: [PATCH 032/188] feat(windows): add WIC decoder provider and codec inventory WicDecoderProvider decodes through a pull chain (decoder, Fant scaler to MaxLongEdge, format converter) read in bounded row bands. Integer sources are requested as 64bppRGBA and linearised with the exact sRGB EOTF (Linear16); float/fixed sources as 128bppRGBAFloat (scRGB, already linear). The Exif orientation (photo policy, then raw IFD queries) is applied while de-interleaving instead of through IWICBitmapFlipRotator, which Microsoft documents as quadratic over scanline decoders. CodecInventory enumerates installed decoders (CreateComponentEnumerator), probes HEVC/AV1 decoders with MFTEnumEx and identifies the Raw Image Extension by package family, since it shares the in-box RAW codec's CLSID. It maps every ImageFileFormat to its decoder, native flag and the Store extensions (product ids, ms-windows-store links) that would unlock it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Codecs/CodecInventory.cs | 116 ++++++ .../Codecs/PackageProbe.cs | 22 ++ .../Codecs/StoreExtension.cs | 38 ++ .../Codecs/VideoDecoderProbe.cs | 66 ++++ .../Codecs/WicDecoderInfo.cs | 38 ++ src/Titano.Core.Windows/Wic/OrientationMap.cs | 27 ++ src/Titano.Core.Windows/Wic/WicComponents.cs | 78 ++++ .../Wic/WicDecoderProvider.cs | 222 +++++++++++ src/Titano.Core.Windows/Wic/WicFactory.cs | 27 ++ src/Titano.Core.Windows/Wic/WicGuids.cs | 26 ++ src/Titano.Core.Windows/Wic/WicInterfaces.cs | 354 ++++++++++++++++++ .../Codecs/CodecInventoryTests.cs | 145 +++++++ .../Wic/OrientationMapTests.cs | 67 ++++ .../Wic/WicDecoderProviderTests.cs | 163 ++++++++ .../Wic/WicTestImages.cs | 166 ++++++++ 15 files changed, 1555 insertions(+) create mode 100644 src/Titano.Core.Windows/Codecs/CodecInventory.cs create mode 100644 src/Titano.Core.Windows/Codecs/PackageProbe.cs create mode 100644 src/Titano.Core.Windows/Codecs/StoreExtension.cs create mode 100644 src/Titano.Core.Windows/Codecs/VideoDecoderProbe.cs create mode 100644 src/Titano.Core.Windows/Codecs/WicDecoderInfo.cs create mode 100644 src/Titano.Core.Windows/Wic/OrientationMap.cs create mode 100644 src/Titano.Core.Windows/Wic/WicComponents.cs create mode 100644 src/Titano.Core.Windows/Wic/WicDecoderProvider.cs create mode 100644 src/Titano.Core.Windows/Wic/WicFactory.cs create mode 100644 src/Titano.Core.Windows/Wic/WicGuids.cs create mode 100644 src/Titano.Core.Windows/Wic/WicInterfaces.cs create mode 100644 tests/Titano.Core.Windows.Tests/Codecs/CodecInventoryTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/Wic/OrientationMapTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/Wic/WicTestImages.cs diff --git a/src/Titano.Core.Windows/Codecs/CodecInventory.cs b/src/Titano.Core.Windows/Codecs/CodecInventory.cs new file mode 100644 index 00000000..37f953ab --- /dev/null +++ b/src/Titano.Core.Windows/Codecs/CodecInventory.cs @@ -0,0 +1,116 @@ +using Titano.Core.Imaging; +using Titano.Core.Windows.Wic; + +namespace Titano.Core.Windows.Codecs; + +/// How one image format decodes through WIC on this machine. +/// The format. +/// The WIC decoder that handles its extensions, if any (it may only reach previews, e.g. the in-box DNG decoder). +/// True when WIC delivers a full native decode (). +/// Store extensions whose installation would make the format native. +public sealed record FormatSupport(ImageFileFormat Format, WicDecoderInfo? Decoder, bool IsNative, IReadOnlyList MissingExtensions); + +/// +/// Which WIC decoders exist on this machine and what they mean per (BRIEF §8.1): +/// JPEG/PNG/TIFF/BMP/GIF/JPEG XR are built in; DNG and camera RAW count only through the Raw Image Extension +/// (the in-box DNG decoder reads just the embedded preview); HEIF needs the HEIF decoder plus an HEVC decoder, +/// AVIF an AVIF-capable decoder plus an AV1 decoder; WebP the WebP extension. Immutable snapshot; call +/// again (with refresh) after the user installs an extension. +/// +public sealed class CodecInventory +{ + /// The Raw Image Extension reuses the CLSID of the older in-box RAW codec, so its package identifies it. + internal const string RawImageExtensionPackageFamily = "Microsoft.RawImageExtension_8wekyb3d8bbwe"; + + private readonly Dictionary _formats; + + internal CodecInventory(IReadOnlyList decoders, bool hasHevcDecoder, bool hasAv1Decoder) + { + Decoders = decoders; + HasHevcDecoder = hasHevcDecoder; + HasAv1Decoder = hasAv1Decoder; + _formats = ImageFormatInfo.Known.ToDictionary(i => i.Format, Evaluate); + Formats = [.. _formats.Values]; + MissingExtensions = StoreExtension.All.Where(e => Formats.Any(f => f.MissingExtensions.Contains(e))).ToArray(); + } + + /// Installed WIC decoders, in WIC's enumeration order. + public IReadOnlyList Decoders { get; } + + /// An HEVC decoder MFT is present (HEVC Video Extensions or a vendor hardware decoder). + public bool HasHevcDecoder { get; } + + /// An AV1 decoder MFT is present (AV1 Video Extension or a vendor hardware decoder). + public bool HasAv1Decoder { get; } + + /// One entry per known format, in order. + public IReadOnlyList Formats { get; } + + /// Distinct Store extensions that would unlock at least one format, for the "Install" notice. + public IReadOnlyList MissingExtensions { get; } + + /// Enumerates WIC decoders and probes the HEVC/AV1 decoders. Call from any thread. + /// Make WIC re-read codec registrations (after an extension was installed). + public static CodecInventory Detect(bool refresh = false) + { + var rawExtensionInstalled = PackageProbe.IsInstalled(RawImageExtensionPackageFamily); + var decoders = WicComponents.EnumerateDecoders(refresh) + .Select(d => d with { Extension = Classify(d, rawExtensionInstalled) }) + .ToArray(); + return new CodecInventory(decoders, VideoDecoderProbe.HasDecoder(VideoDecoderProbe.Hevc), VideoDecoderProbe.HasDecoder(VideoDecoderProbe.Av1)); + } + + public FormatSupport For(ImageFileFormat format) => + _formats.TryGetValue(format, out var support) ? support : new FormatSupport(format, null, false, []); + + public bool IsNative(ImageFileFormat format) => For(format).IsNative; + + /// Which Microsoft Store extension installed a decoder, judged by its CLSID (and vendor for AVIF). + internal static StoreExtensionKind? Classify(WicDecoderInfo decoder, bool rawExtensionInstalled) + { + if (decoder.Clsid == WicGuids.RawDecoder) return rawExtensionInstalled ? StoreExtensionKind.RawImage : null; + if (decoder.Clsid == WicGuids.HeifDecoder) return StoreExtensionKind.HeifImage; + if (decoder.Clsid == WicGuids.WebpDecoder) return StoreExtensionKind.WebpImage; + var microsoft = decoder.Vendor == WicGuids.VendorMicrosoft || decoder.Vendor == WicGuids.VendorMicrosoftBuiltIn; + return microsoft && decoder.Handles("avif") ? StoreExtensionKind.Av1Video : null; + } + + private FormatSupport Evaluate(ImageFormatInfo info) + { + var handler = Decoders.FirstOrDefault(d => info.Extensions.Any(d.Handles)); + switch (info.Format) + { + case ImageFileFormat.Heif: + return new(info.Format, handler, handler is not null && HasHevcDecoder, + Missing((handler is null, StoreExtensionKind.HeifImage), (!HasHevcDecoder, StoreExtensionKind.HevcVideo))); + + case ImageFileFormat.Avif: + // AVIF is HEIF with AV1 payloads: the HEIF decoder reads it when no dedicated AVIF decoder is registered. + var avif = handler ?? Decoders.FirstOrDefault(d => d.Extension == StoreExtensionKind.HeifImage); + return new(info.Format, avif, avif is not null && HasAv1Decoder, + Missing((avif is null, StoreExtensionKind.HeifImage), (!HasAv1Decoder, StoreExtensionKind.Av1Video))); + + case ImageFileFormat.WebP: + return new(info.Format, handler, handler is not null, Missing((handler is null, StoreExtensionKind.WebpImage))); + } + + if (info.IsRaw) + { + var raw = Decoders.FirstOrDefault(d => d.Extension == StoreExtensionKind.RawImage && info.Extensions.Any(d.Handles)); + var extensionInstalled = Decoders.Any(d => d.Extension == StoreExtensionKind.RawImage); + return new(info.Format, raw ?? handler, raw is not null, Missing((!extensionInstalled, StoreExtensionKind.RawImage))); + } + + return new(info.Format, handler, handler is not null, []); + } + + private static StoreExtension[] Missing(params ReadOnlySpan<(bool IsMissing, StoreExtensionKind Kind)> requirements) + { + var missing = new List(requirements.Length); + foreach (var (isMissing, kind) in requirements) + { + if (isMissing) missing.Add(StoreExtension.Get(kind)); + } + return [.. missing]; + } +} diff --git a/src/Titano.Core.Windows/Codecs/PackageProbe.cs b/src/Titano.Core.Windows/Codecs/PackageProbe.cs new file mode 100644 index 00000000..c81c0df1 --- /dev/null +++ b/src/Titano.Core.Windows/Codecs/PackageProbe.cs @@ -0,0 +1,22 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Codecs; + +/// Checks whether a packaged (Store) app is registered for the current user. +internal static partial class PackageProbe +{ + private const int ERROR_SUCCESS = 0; + private const int ERROR_INSUFFICIENT_BUFFER = 122; + + /// True when at least one package of is installed for this user. + public static bool IsInstalled(string packageFamilyName) + { + uint count = 0, bufferLength = 0; + // With empty buffers the call reports how many packages exist (ERROR_INSUFFICIENT_BUFFER when any do). + var result = GetPackagesByPackageFamily(packageFamilyName, ref count, 0, ref bufferLength, 0); + return (result is ERROR_SUCCESS or ERROR_INSUFFICIENT_BUFFER) && count > 0; + } + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int GetPackagesByPackageFamily(string packageFamilyName, ref uint count, nint packageFullNames, ref uint bufferLength, nint buffer); +} diff --git a/src/Titano.Core.Windows/Codecs/StoreExtension.cs b/src/Titano.Core.Windows/Codecs/StoreExtension.cs new file mode 100644 index 00000000..abd2c340 --- /dev/null +++ b/src/Titano.Core.Windows/Codecs/StoreExtension.cs @@ -0,0 +1,38 @@ +using Titano.Core.Windows.Shell; + +namespace Titano.Core.Windows.Codecs; + +/// Free or paid Microsoft Store codec extensions that widen what WIC can decode (BRIEF §8.1). +public enum StoreExtensionKind +{ + RawImage, + HeifImage, + HevcVideo, + Av1Video, + WebpImage, +} + +/// A Microsoft Store codec extension: product id and the URIs that open its Store page. +public sealed record StoreExtension(StoreExtensionKind Kind, string ProductName, string ProductId) +{ + /// Catalogue in the order the UI lists missing extensions. + public static IReadOnlyList All { get; } = + [ + new(StoreExtensionKind.RawImage, "Raw Image Extension", "9NCTDW2W1BH8"), + new(StoreExtensionKind.HeifImage, "HEIF Image Extensions", "9PMMSR1CGPWG"), + new(StoreExtensionKind.HevcVideo, "HEVC Video Extensions", "9NMZLZ57R3T7"), + new(StoreExtensionKind.Av1Video, "AV1 Video Extension", "9MVZQVXJBQ9V"), + new(StoreExtensionKind.WebpImage, "WebP Image Extensions", "9PG2DK419DRG"), + ]; + + /// Store app deep link (ms-windows-store://pdp/?ProductId=…). + public Uri StoreUri => new($"ms-windows-store://pdp/?ProductId={ProductId}"); + + /// Web page of the same product, for systems without the Store app. + public Uri WebUri => new($"https://apps.microsoft.com/detail/{ProductId.ToLowerInvariant()}"); + + public static StoreExtension Get(StoreExtensionKind kind) => All.First(e => e.Kind == kind); + + /// Opens the Store page through the shell; false when the shell could not open it. + public bool OpenInStore() => ShellLauncher.OpenUrl(StoreUri.AbsoluteUri); +} diff --git a/src/Titano.Core.Windows/Codecs/VideoDecoderProbe.cs b/src/Titano.Core.Windows/Codecs/VideoDecoderProbe.cs new file mode 100644 index 00000000..b7ffc252 --- /dev/null +++ b/src/Titano.Core.Windows/Codecs/VideoDecoderProbe.cs @@ -0,0 +1,66 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Codecs; + +/// +/// Detects HEVC and AV1 decoders with MFTEnumEx, the check Microsoft documents for the codecs that HEIC and +/// AVIF decoding through WIC depend on (HEVC / AV1 Video Extensions or a vendor hardware decoder). +/// +internal static unsafe partial class VideoDecoderProbe +{ + /// MFVideoFormat_HEVC (FOURCC 'HEVC'). + public static readonly Guid Hevc = new("43564548-0000-0010-8000-00aa00389b71"); + + /// MFVideoFormat_AV1 (FOURCC 'AV01'). + public static readonly Guid Av1 = new("31305641-0000-0010-8000-00aa00389b71"); + + private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91"); + private static readonly Guid MediaTypeVideo = new("73646976-0000-0010-8000-00aa00389b71"); + + private const uint MF_VERSION = 0x00020070; + private const uint MFSTARTUP_LITE = 0x1; + private const uint MFT_ENUM_FLAG_SYNCMFT = 0x1, MFT_ENUM_FLAG_ASYNCMFT = 0x2, MFT_ENUM_FLAG_HARDWARE = 0x4, MFT_ENUM_FLAG_SORTANDFILTER = 0x40; + + /// True when at least one decoder MFT accepts the video . + public static bool HasDecoder(Guid subtype) + { + try + { + if (MFStartup(MF_VERSION, MFSTARTUP_LITE) < 0) return false; + try + { + var input = new MftRegisterTypeInfo { MajorType = MediaTypeVideo, Subtype = subtype }; + const uint flags = MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_ASYNCMFT | MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER; + if (MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var activates, out var count) < 0) return false; + for (var i = 0; i < count; i++) Marshal.Release(((nint*)activates)[i]); + Marshal.FreeCoTaskMem(activates); + return count > 0; + } + finally + { + MFShutdown(); + } + } + catch (DllNotFoundException) + { + // Windows "N" editions ship without Media Foundation unless the Media Feature Pack is installed. + return false; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct MftRegisterTypeInfo + { + public Guid MajorType; + public Guid Subtype; + } + + [LibraryImport("mfplat.dll")] + private static partial int MFStartup(uint version, uint flags); + + [LibraryImport("mfplat.dll")] + private static partial int MFShutdown(); + + [LibraryImport("mfplat.dll")] + private static partial int MFTEnumEx(Guid category, uint flags, MftRegisterTypeInfo* inputType, MftRegisterTypeInfo* outputType, out nint activates, out uint count); +} diff --git a/src/Titano.Core.Windows/Codecs/WicDecoderInfo.cs b/src/Titano.Core.Windows/Codecs/WicDecoderInfo.cs new file mode 100644 index 00000000..f2668154 --- /dev/null +++ b/src/Titano.Core.Windows/Codecs/WicDecoderInfo.cs @@ -0,0 +1,38 @@ +namespace Titano.Core.Windows.Codecs; + +/// One installed WIC decoder as registered on this machine. +/// Registered display name, e.g. "JPEG Decoder". +/// Decoder class id. +/// WIC container format GUID. +/// Vendor GUID (Microsoft built-in, Microsoft, or a third party). +/// Registered version string. +/// Lower-case extensions without the dot. +/// The Microsoft Store extension that installed it, if any. +public sealed record WicDecoderInfo( + string FriendlyName, + Guid Clsid, + Guid ContainerFormat, + Guid Vendor, + string Version, + IReadOnlyList FileExtensions, + StoreExtensionKind? Extension) +{ + /// True when the decoder registers (with or without the dot). + public bool Handles(string extension) + { + var bare = extension.TrimStart('.'); + foreach (var e in FileExtensions) + { + if (string.Equals(e, bare, StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + + /// Parses WIC's comma-separated extension list (".jpg,.jpeg") into bare lower-case names. + internal static IReadOnlyList ParseExtensions(string list) => + list.Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(e => e.TrimStart('.').ToLowerInvariant()) + .Where(e => e.Length > 0) + .Distinct() + .ToArray(); +} diff --git a/src/Titano.Core.Windows/Wic/OrientationMap.cs b/src/Titano.Core.Windows/Wic/OrientationMap.cs new file mode 100644 index 00000000..72ed1a08 --- /dev/null +++ b/src/Titano.Core.Windows/Wic/OrientationMap.cs @@ -0,0 +1,27 @@ +namespace Titano.Core.Windows.Wic; + +/// +/// Where each stored pixel (x, y) of a width×height image lands once Exif orientation 1–8 is applied, +/// as a linear index Origin + x·StepX + y·StepY into the row-major oriented image. Applying the orientation +/// while de-interleaving costs nothing extra, unlike a WIC flip-rotator over a scanline decoder. +/// +internal readonly record struct OrientationMap(int Width, int Height, int Origin, int StepX, int StepY) +{ + /// Orientations 5–8 swap width and height. + public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8; + + /// Map for a stored × image; unknown values act as 1. + public static OrientationMap Create(int orientation, int width, int height) => orientation switch + { + 2 => new(width, height, width - 1, -1, width), // mirror horizontal + 3 => new(width, height, (height * width) - 1, -1, -width), // rotate 180° + 4 => new(width, height, (height - 1) * width, 1, -width), // mirror vertical + 5 => new(height, width, 0, height, 1), // transpose + 6 => new(height, width, height - 1, height, -1), // rotate 90° clockwise + 7 => new(height, width, (width * height) - 1, -height, -1), // transverse + 8 => new(height, width, (width - 1) * height, -height, 1), // rotate 90° counter-clockwise + _ => new(width, height, 0, 1, width), + }; + + public int IndexOf(int x, int y) => Origin + (x * StepX) + (y * StepY); +} diff --git a/src/Titano.Core.Windows/Wic/WicComponents.cs b/src/Titano.Core.Windows/Wic/WicComponents.cs new file mode 100644 index 00000000..4d503f1d --- /dev/null +++ b/src/Titano.Core.Windows/Wic/WicComponents.cs @@ -0,0 +1,78 @@ +using System.Runtime.InteropServices; +using Titano.Core.Diagnostics; +using Titano.Core.Windows.Codecs; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Wic; + +/// Enumerates installed WIC decoders through IWICImagingFactory::CreateComponentEnumerator. +internal static class WicComponents +{ + private const uint ComponentDecoder = 0x1; + private const uint EnumerateRefresh = 0x1; + private const uint EnumerateUnsigned = 0x40000000; + + /// + /// Every enabled decoder, signed or not (third-party camera codecs are often unsigned and WIC still uses them). + /// makes WIC re-read the registrations, e.g. after a Store extension was installed. + /// + public static IReadOnlyList EnumerateDecoders(bool refresh) + { + Win32Com.EnsureInitialized(); + var decoders = new List(); + var enumerator = WicFactory.Instance.CreateComponentEnumerator(ComponentDecoder, EnumerateUnsigned | (refresh ? EnumerateRefresh : 0)); + try + { + while (enumerator.Next(1, out var unknown, out var fetched) == 0 && fetched == 1) + { + object? component = null; + try + { + component = Marshal.GetObjectForIUnknown(unknown); + if (component is IWICBitmapDecoderInfo info) decoders.Add(Read(info)); + } + catch (COMException ex) + { + Log.Warning("wic", "Skipped a WIC decoder whose registration could not be read", ex); + } + finally + { + Marshal.Release(unknown); + Win32Com.Release(component); + } + } + } + finally + { + Win32Com.Release(enumerator); + } + return decoders; + } + + /// Reads a component-info string through the "ask for the length, then fill" protocol. + public static unsafe string ReadString(WicStringGetter getter) + { + if (getter(0, null, out var length) < 0 || length <= 1) return string.Empty; + var buffer = new char[length]; + int hr; + fixed (char* p = buffer) + { + hr = getter(length, p, out length); + } + if (hr < 0) return string.Empty; + var text = buffer.AsSpan(0, (int)Math.Min(length, (uint)buffer.Length)); + var end = text.IndexOf('\0'); + return new string(end >= 0 ? text[..end] : text); + } + + // Lambdas call through the interface normally rather than binding delegates to COM methods. + private static unsafe WicDecoderInfo Read(IWICBitmapDecoderInfo info) => new( + FriendlyName: ReadString((uint capacity, char* buffer, out uint length) => info.GetFriendlyName(capacity, buffer, out length)), + Clsid: info.GetCLSID(), + ContainerFormat: info.GetContainerFormat(), + Vendor: info.GetVendorGUID(), + Version: ReadString((uint capacity, char* buffer, out uint length) => info.GetVersion(capacity, buffer, out length)), + FileExtensions: WicDecoderInfo.ParseExtensions( + ReadString((uint capacity, char* buffer, out uint length) => info.GetFileExtensions(capacity, buffer, out length))), + Extension: null); +} diff --git a/src/Titano.Core.Windows/Wic/WicDecoderProvider.cs b/src/Titano.Core.Windows/Wic/WicDecoderProvider.cs new file mode 100644 index 00000000..12034051 --- /dev/null +++ b/src/Titano.Core.Windows/Wic/WicDecoderProvider.cs @@ -0,0 +1,222 @@ +using System.Buffers; +using System.Runtime.InteropServices; +using Titano.Core.Imaging; +using Titano.Core.Windows.Codecs; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Wic; + +/// +/// Native decoding through the Windows Imaging Component (BRIEF §8.2 tier 1) for every format with an installed +/// WIC decoder (see ). Thread-safe: each call builds its own pull chain +/// (decoder → Fant scaler → format converter) on the calling thread, which joins the MTA if it has no apartment. +/// +/// +/// Pixels are requested as 64bppRGBA and linearised with the exact sRGB EOTF (): +/// WIC integer formats are sRGB-encoded, the 16-bit request keeps 16-bit PNG/TIFF precision, and the result matches +/// the managed decoders bit for bit, whereas WIC's own integer→float conversion uses its own gamma approximation. +/// Sources whose native format is floating or fixed point (scRGB: JPEG XR, HDR) are requested as 128bppRGBAFloat +/// and copied unchanged, keeping highlights above 1. Alpha is discarded. The Exif orientation is applied while +/// de-interleaving (). +/// +public sealed class WicDecoderProvider : IImageDecoderProvider +{ + private const int WINCODEC_ERR_COMPONENTNOTFOUND = unchecked((int)0x88982F50); + private const int WICBitmapInterpolationModeFant = 3; + private const int WICBitmapDitherTypeNone = 0; + private const int WICBitmapPaletteTypeCustom = 0; + private const uint NumericFixedPoint = 4, NumericFloat = 5; + private const int BandBytes = 4 << 20; + + /// The photo-policy query covers every WIC container; the raw paths catch decoders without the policy. + private static readonly string[] OrientationQueries = ["System.Photo.Orientation", "/app1/ifd/{ushort=274}", "/ifd/{ushort=274}"]; + + /// Codec snapshot deciding ; detected now when omitted. + public WicDecoderProvider(CodecInventory? inventory = null) => Inventory = inventory ?? CodecInventory.Detect(); + + public string Name => "wic"; + + public CodecInventory Inventory { get; } + + public DecodeTier? TierFor(ImageFileFormat format) => Inventory.IsNative(format) ? DecodeTier.Native : null; + + /// + /// Decodes the first frame. Returns null when WIC cannot natively decode this format here, when the request + /// forces the embedded preview, or when no installed decoder recognises the content. Corrupt files raise the + /// WIC ; unreadable files the matching . + /// + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + if (request.ForcePreview || TierFor(ImageFormatInfo.FromPath(request.Path).Format) is null) return null; + cancellationToken.ThrowIfCancellationRequested(); + + Win32Com.EnsureInitialized(); + var factory = WicFactory.Instance; + var stream = ShellStream.OpenRead(request.Path); + IWICBitmapDecoder? decoder = null; + IWICBitmapFrameDecode? frame = null; + IWICBitmapScaler? scaler = null; + IWICFormatConverter? converter = null; + try + { + var hr = factory.CreateDecoderFromStream(stream, 0, WicDecodeOptions.MetadataCacheOnDemand, out decoder); + if (hr == WINCODEC_ERR_COMPONENTNOTFOUND) return null; + Marshal.ThrowExceptionForHR(hr); + frame = decoder!.GetFrame(0); + frame.GetSize(out var width, out var height); + var orientation = request.ApplyOrientation ? ReadOrientation(frame) : 1; + + var (targetWidth, targetHeight) = TargetSize(width, height, request.MaxLongEdge); + IWICBitmapSource source = frame; + if (targetWidth != width || targetHeight != height) + { + scaler = factory.CreateBitmapScaler(); + scaler.Initialize(frame, targetWidth, targetHeight, WICBitmapInterpolationModeFant); + source = scaler; + } + + converter = factory.CreateFormatConverter(); + var sourceFormat = source.GetPixelFormat(); + var floating = IsFloatingPoint(factory, frame.GetPixelFormat()) && CanConvert(converter, sourceFormat, WicGuids.PixelFormat128bppRGBAFloat); + var targetFormat = floating ? WicGuids.PixelFormat128bppRGBAFloat : WicGuids.PixelFormat64bppRGBA; + converter.Initialize(source, ref targetFormat, WICBitmapDitherTypeNone, 0, 0.0, WICBitmapPaletteTypeCustom); + + var map = OrientationMap.Create(orientation, (int)targetWidth, (int)targetHeight); + var pixels = CopyToPlanes(converter, (int)targetWidth, (int)targetHeight, floating, map, cancellationToken); + var swap = OrientationMap.SwapsAxes(orientation); + return new DecodedImage(pixels, DecodeTier.Native, Name, (int)(swap ? height : width), (int)(swap ? width : height)); + } + finally + { + Win32Com.Release(converter); + Win32Com.Release(scaler); + Win32Com.Release(frame); + Win32Com.Release(decoder); + Marshal.Release(stream); + } + } + + /// Size after fitting the long edge into (never upscales; 0 = native). + internal static (uint Width, uint Height) TargetSize(uint width, uint height, int maxLongEdge) + { + var longEdge = Math.Max(width, height); + if (maxLongEdge <= 0 || longEdge <= (uint)maxLongEdge) return (width, height); + var scale = (double)maxLongEdge / longEdge; + return ((uint)Math.Max(1, Math.Round(width * scale)), (uint)Math.Max(1, Math.Round(height * scale))); + } + + private static int ReadOrientation(IWICBitmapFrameDecode frame) + { + if (frame.GetMetadataQueryReader(out var reader) < 0 || reader is null) return 1; + try + { + foreach (var query in OrientationQueries) + { + var value = default(PropVariant); + if (reader.GetMetadataByName(query, ref value) < 0) continue; + try + { + if (value.TryGetInt32(out var orientation) && orientation is >= 1 and <= 8) return orientation; + } + finally + { + PropVariant.Clear(ref value); + } + } + return 1; + } + finally + { + Win32Com.Release(reader); + } + } + + /// True for fixed- and floating-point (scRGB) pixel formats; unknown formats count as integer. + private static bool IsFloatingPoint(IWICImagingFactory factory, Guid pixelFormat) + { + IWICComponentInfo? info = null; + try + { + info = factory.CreateComponentInfo(ref pixelFormat); + return info is IWICPixelFormatInfo2 format && format.GetNumericRepresentation() is NumericFixedPoint or NumericFloat; + } + catch (COMException) + { + return false; + } + finally + { + Win32Com.Release(info); + } + } + + private static bool CanConvert(IWICFormatConverter converter, Guid from, Guid to) + { + converter.CanConvert(ref from, ref to, out var canConvert); + return canConvert != 0; + } + + /// Pulls the converted pixels in bands of rows (bounded memory) and writes oriented linear planes. + private static unsafe ImageBuffer CopyToPlanes(IWICBitmapSource source, int width, int height, bool floating, OrientationMap map, CancellationToken cancellationToken) + { + var stride = checked(width * (floating ? 16 : 8)); + var bandRows = Math.Clamp(BandBytes / stride, 1, height); + var image = new ImageBuffer(map.Width, map.Height, 3, clear: false); + var band = ArrayPool.Shared.Rent(checked(stride * bandRows)); + try + { + var r = image.Plane(0); + var g = image.Plane(1); + var b = image.Plane(2); + fixed (byte* bandPointer = band) + { + for (var top = 0; top < height; top += bandRows) + { + cancellationToken.ThrowIfCancellationRequested(); + var rows = Math.Min(bandRows, height - top); + var rect = new WicRect { X = 0, Y = top, Width = width, Height = rows }; + source.CopyPixels(ref rect, (uint)stride, (uint)(stride * rows), (nint)bandPointer); + for (var row = 0; row < rows; row++) + { + var line = new ReadOnlySpan(bandPointer + (row * stride), stride); + var index = map.IndexOf(0, top + row); + if (floating) WriteFloatRow(MemoryMarshal.Cast(line), index, map.StepX, r, g, b); + else WriteSrgb16Row(MemoryMarshal.Cast(line), index, map.StepX, r, g, b); + } + } + } + return image; + } + catch + { + image.Dispose(); + throw; + } + finally + { + ArrayPool.Shared.Return(band); + } + } + + private static void WriteSrgb16Row(ReadOnlySpan rgba, int index, int step, Span r, Span g, Span b) + { + for (var i = 0; i < rgba.Length; i += 4, index += step) + { + r[index] = ColorSpace.Linear16(rgba[i]); + g[index] = ColorSpace.Linear16(rgba[i + 1]); + b[index] = ColorSpace.Linear16(rgba[i + 2]); + } + } + + private static void WriteFloatRow(ReadOnlySpan rgba, int index, int step, Span r, Span g, Span b) + { + // scRGB can carry negative (out-of-gamut) components; the pipeline's range starts at 0. + for (var i = 0; i < rgba.Length; i += 4, index += step) + { + r[index] = MathF.Max(rgba[i], 0f); + g[index] = MathF.Max(rgba[i + 1], 0f); + b[index] = MathF.Max(rgba[i + 2], 0f); + } + } +} diff --git a/src/Titano.Core.Windows/Wic/WicFactory.cs b/src/Titano.Core.Windows/Wic/WicFactory.cs new file mode 100644 index 00000000..5cb04bde --- /dev/null +++ b/src/Titano.Core.Windows/Wic/WicFactory.cs @@ -0,0 +1,27 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Wic; + +/// Process-wide WIC imaging factory (free-threaded; safe to call from any thread). +internal static class WicFactory +{ + private static readonly Lazy Shared = new(Create); + + public static IWICImagingFactory Instance => Shared.Value; + + private static IWICImagingFactory Create() + { + // Create it in the MTA: a factory born on a UI thread's STA could make worker threads marshal every + // call into that apartment. + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + return Task.Run(Create).GetAwaiter().GetResult(); + + var iid = typeof(IWICImagingFactory).GUID; + var hr = Win32Com.TryCreateInstance(WicGuids.ImagingFactory2, iid, out var instance); + // WICImagingFactory2 is missing only on Windows 7 without the platform update. + if (hr == Win32Com.REGDB_E_CLASSNOTREG) hr = Win32Com.TryCreateInstance(WicGuids.ImagingFactory1, iid, out instance); + Marshal.ThrowExceptionForHR(hr); + return (IWICImagingFactory)instance!; + } +} diff --git a/src/Titano.Core.Windows/Wic/WicGuids.cs b/src/Titano.Core.Windows/Wic/WicGuids.cs new file mode 100644 index 00000000..3328ce04 --- /dev/null +++ b/src/Titano.Core.Windows/Wic/WicGuids.cs @@ -0,0 +1,26 @@ +namespace Titano.Core.Windows.Wic; + +/// Class, vendor and pixel-format identifiers from wincodec.h. +internal static class WicGuids +{ + public static readonly Guid ImagingFactory1 = new("cacaf262-9370-4615-a13b-9f5539da4c0a"); + public static readonly Guid ImagingFactory2 = new("317d06e8-5f24-433d-bdf7-79ce68d8abc2"); + + /// CLSID_WICRAWDecoder: the camera RAW decoder (Raw Image Extension; also the CLSID of the older in-box codec). + public static readonly Guid RawDecoder = new("41945702-8302-44a6-9445-ac98e8afa086"); + + /// CLSID_WICHeifDecoder (HEIF Image Extensions; decodes HEVC- and AV1-coded HEIF). + public static readonly Guid HeifDecoder = new("e9a4a80a-44fe-4de4-8971-7150b10a5199"); + + /// CLSID_WICWebpDecoder (WebP Image Extensions). + public static readonly Guid WebpDecoder = new("7693e886-51c9-4070-8419-9f70738ec8fa"); + + public static readonly Guid VendorMicrosoft = new("f0e749ca-edef-4589-a73a-ee0e626a2a2b"); + public static readonly Guid VendorMicrosoftBuiltIn = new("257a30fd-06b6-462b-aea4-63f70b86e533"); + + /// 16-bit unsigned RGBA, sRGB-encoded like every WIC integer format. + public static readonly Guid PixelFormat64bppRGBA = new("6fddc324-4e03-4bfe-b185-3d77768dc916"); + + /// 32-bit float RGBA, scRGB (linear light, Rec.709 primaries) like every WIC float format. + public static readonly Guid PixelFormat128bppRGBAFloat = new("6fddc324-4e03-4bfe-b185-3d77768dc919"); +} diff --git a/src/Titano.Core.Windows/Wic/WicInterfaces.cs b/src/Titano.Core.Windows/Wic/WicInterfaces.cs new file mode 100644 index 00000000..86e4668d --- /dev/null +++ b/src/Titano.Core.Windows/Wic/WicInterfaces.cs @@ -0,0 +1,354 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Wic; + +// Windows Imaging Component interfaces, vtable order as in wincodec.h / objidl.h. +// [ComImport] interfaces do not inherit vtable slots from their C# base, so every derived interface +// redeclares the base methods (with `new`) in their native order before its own. Interfaces are declared +// up to the last slot Titano calls (a vtable prefix is valid); intermediate slots Titano never calls keep +// their native shape with pointer-sized placeholders for interfaces it does not model. Methods whose +// failure is an expected outcome use [PreserveSig]; the others throw COMException on a failed HRESULT. + +/// WICDecodeOptions. +internal enum WicDecodeOptions +{ + MetadataCacheOnDemand = 0, + MetadataCacheOnLoad = 1, +} + +/// WICRect. +[StructLayout(LayoutKind.Sequential)] +internal struct WicRect +{ + public int X; + public int Y; + public int Width; + public int Height; +} + +[ComImport] +[Guid("ec5ec8a9-c395-4314-9c77-54d7a935ff70")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICImagingFactory +{ + [PreserveSig] + int CreateDecoderFromFilename(nint fileName, nint vendor, uint desiredAccess, WicDecodeOptions options, out nint decoder); + + [PreserveSig] + int CreateDecoderFromStream(nint stream, nint vendor, WicDecodeOptions options, out IWICBitmapDecoder? decoder); + + [PreserveSig] + int CreateDecoderFromFileHandle(nint file, nint vendor, WicDecodeOptions options, out nint decoder); + + IWICComponentInfo CreateComponentInfo(ref Guid clsid); + + [PreserveSig] + int CreateDecoder(ref Guid containerFormat, nint vendor, out nint decoder); + + /// Returns an owned IWICBitmapEncoder pointer (used by the tests to synthesise JPEG fixtures). + [PreserveSig] + int CreateEncoder(ref Guid containerFormat, nint vendor, out nint encoder); + + [PreserveSig] + int CreatePalette(out nint palette); + + IWICFormatConverter CreateFormatConverter(); + + IWICBitmapScaler CreateBitmapScaler(); + + [PreserveSig] + int CreateBitmapClipper(out nint clipper); + + [PreserveSig] + int CreateBitmapFlipRotator(out nint flipRotator); + + [PreserveSig] + int CreateStream(out nint stream); + + [PreserveSig] + int CreateColorContext(out nint colorContext); + + [PreserveSig] + int CreateColorTransformer(out nint colorTransform); + + [PreserveSig] + int CreateBitmap(uint width, uint height, ref Guid pixelFormat, int cacheOption, out nint bitmap); + + [PreserveSig] + int CreateBitmapFromSource(nint source, int cacheOption, out nint bitmap); + + [PreserveSig] + int CreateBitmapFromSourceRect(nint source, uint x, uint y, uint width, uint height, out nint bitmap); + + [PreserveSig] + int CreateBitmapFromMemory(uint width, uint height, ref Guid pixelFormat, uint stride, uint bufferSize, nint buffer, out nint bitmap); + + [PreserveSig] + int CreateBitmapFromHBITMAP(nint bitmapHandle, nint paletteHandle, int alphaOption, out nint bitmap); + + [PreserveSig] + int CreateBitmapFromHICON(nint iconHandle, out nint bitmap); + + IEnumUnknown CreateComponentEnumerator(uint componentTypes, uint options); +} + +[ComImport] +[Guid("00000100-0000-0000-c000-000000000046")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IEnumUnknown +{ + /// S_OK when items were fetched, S_FALSE at the end. + [PreserveSig] + int Next(uint count, out nint element, out uint fetched); +} + +[ComImport] +[Guid("9edde9e7-8dee-47ea-99df-e6faf2ed44bf")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapDecoder +{ + [PreserveSig] + int QueryCapability(nint stream, out uint capability); + + [PreserveSig] + int Initialize(nint stream, WicDecodeOptions options); + + Guid GetContainerFormat(); + + [PreserveSig] + int GetDecoderInfo(out nint decoderInfo); + + [PreserveSig] + int CopyPalette(nint palette); + + [PreserveSig] + int GetMetadataQueryReader(out nint reader); + + [PreserveSig] + int GetPreview(out nint preview); + + [PreserveSig] + int GetColorContexts(uint count, nint colorContexts, out uint actualCount); + + [PreserveSig] + int GetThumbnail(out nint thumbnail); + + uint GetFrameCount(); + + IWICBitmapFrameDecode GetFrame(uint index); +} + +[ComImport] +[Guid("00000120-a8f2-4877-ba0a-fd2b6645fb94")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapSource +{ + void GetSize(out uint width, out uint height); + + Guid GetPixelFormat(); + + void GetResolution(out double dpiX, out double dpiY); + + [PreserveSig] + int CopyPalette(nint palette); + + void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer); +} + +[ComImport] +[Guid("3b16811b-6a43-4ec9-a813-3d930c13b940")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapFrameDecode : IWICBitmapSource +{ + new void GetSize(out uint width, out uint height); + + new Guid GetPixelFormat(); + + new void GetResolution(out double dpiX, out double dpiY); + + [PreserveSig] + new int CopyPalette(nint palette); + + new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer); + + /// Fails (e.g. WINCODEC_ERR_UNSUPPORTEDOPERATION) for formats without metadata. + [PreserveSig] + int GetMetadataQueryReader(out IWICMetadataQueryReader? reader); +} + +[ComImport] +[Guid("00000301-a8f2-4877-ba0a-fd2b6645fb94")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICFormatConverter : IWICBitmapSource +{ + new void GetSize(out uint width, out uint height); + + new Guid GetPixelFormat(); + + new void GetResolution(out double dpiX, out double dpiY); + + [PreserveSig] + new int CopyPalette(nint palette); + + new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer); + + void Initialize(IWICBitmapSource source, ref Guid destinationFormat, int dither, nint palette, double alphaThresholdPercent, int paletteTranslate); + + void CanConvert(ref Guid sourceFormat, ref Guid destinationFormat, out int canConvert); +} + +[ComImport] +[Guid("00000302-a8f2-4877-ba0a-fd2b6645fb94")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapScaler : IWICBitmapSource +{ + new void GetSize(out uint width, out uint height); + + new Guid GetPixelFormat(); + + new void GetResolution(out double dpiX, out double dpiY); + + [PreserveSig] + new int CopyPalette(nint palette); + + new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer); + + void Initialize(IWICBitmapSource source, uint width, uint height, int interpolationMode); +} + +[ComImport] +[Guid("30989668-e1c9-4597-b395-458eedb808df")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICMetadataQueryReader +{ + Guid GetContainerFormat(); + + [PreserveSig] + int GetLocation(uint capacity, nint buffer, out uint length); + + /// Fails with WINCODEC_ERR_PROPERTYNOTFOUND when the query matches nothing. + [PreserveSig] + int GetMetadataByName([MarshalAs(UnmanagedType.LPWStr)] string name, ref PropVariant value); +} + +/// String getters of the component-info family: capacity 0 + null buffer returns the required length. +internal unsafe delegate int WicStringGetter(uint capacity, char* buffer, out uint length); + +[ComImport] +[Guid("23bc3f0a-698b-4357-886b-f24d50671334")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal unsafe interface IWICComponentInfo +{ + uint GetComponentType(); + + Guid GetCLSID(); + + uint GetSigningStatus(); + + [PreserveSig] + int GetAuthor(uint capacity, char* buffer, out uint length); + + Guid GetVendorGUID(); + + [PreserveSig] + int GetVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + int GetSpecVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + int GetFriendlyName(uint capacity, char* buffer, out uint length); +} + +/// IWICPixelFormatInfo2 (IWICComponentInfo → IWICPixelFormatInfo → IWICPixelFormatInfo2). +[ComImport] +[Guid("a9db33a2-af5f-43c7-b679-74f5984b5aa4")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal unsafe interface IWICPixelFormatInfo2 : IWICComponentInfo +{ + new uint GetComponentType(); + + new Guid GetCLSID(); + + new uint GetSigningStatus(); + + [PreserveSig] + new int GetAuthor(uint capacity, char* buffer, out uint length); + + new Guid GetVendorGUID(); + + [PreserveSig] + new int GetVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + new int GetSpecVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + new int GetFriendlyName(uint capacity, char* buffer, out uint length); + + Guid GetFormatGUID(); + + [PreserveSig] + int GetColorContext(out nint colorContext); + + uint GetBitsPerPixel(); + + uint GetChannelCount(); + + [PreserveSig] + int GetChannelMask(uint channel, uint maskSize, nint mask, out uint actualSize); + + void SupportsTransparency(out int supportsTransparency); + + /// WICPixelFormatNumericRepresentation: 2 unsigned integer, 4 fixed point, 5 float. + uint GetNumericRepresentation(); +} + +/// IWICBitmapDecoderInfo (IWICComponentInfo → IWICBitmapCodecInfo → IWICBitmapDecoderInfo). +[ComImport] +[Guid("d8cd007f-d08f-4191-9bfc-236ea7f0e4b5")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal unsafe interface IWICBitmapDecoderInfo : IWICComponentInfo +{ + new uint GetComponentType(); + + new Guid GetCLSID(); + + new uint GetSigningStatus(); + + [PreserveSig] + new int GetAuthor(uint capacity, char* buffer, out uint length); + + new Guid GetVendorGUID(); + + [PreserveSig] + new int GetVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + new int GetSpecVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + new int GetFriendlyName(uint capacity, char* buffer, out uint length); + + Guid GetContainerFormat(); + + [PreserveSig] + int GetPixelFormats(uint count, nint pixelFormats, out uint actualCount); + + [PreserveSig] + int GetColorManagementVersion(uint capacity, char* buffer, out uint length); + + [PreserveSig] + int GetDeviceManufacturer(uint capacity, char* buffer, out uint length); + + [PreserveSig] + int GetDeviceModels(uint capacity, char* buffer, out uint length); + + [PreserveSig] + int GetMimeTypes(uint capacity, char* buffer, out uint length); + + /// Comma-separated list such as ".jpg,.jpeg,.jpe,.jfif". + [PreserveSig] + int GetFileExtensions(uint capacity, char* buffer, out uint length); +} diff --git a/tests/Titano.Core.Windows.Tests/Codecs/CodecInventoryTests.cs b/tests/Titano.Core.Windows.Tests/Codecs/CodecInventoryTests.cs new file mode 100644 index 00000000..2f750eba --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Codecs/CodecInventoryTests.cs @@ -0,0 +1,145 @@ +using Titano.Core.Imaging; +using Titano.Core.Windows.Codecs; +using Titano.Core.Windows.Wic; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Codecs; + +public sealed class CodecInventoryTests +{ + private static readonly WicDecoderInfo Jpeg = Decoder("JPEG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".jpeg,.jpe,.jpg,.jfif,.exif"); + private static readonly WicDecoderInfo InBoxDng = Decoder("DNG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".dng"); + private static readonly WicDecoderInfo Raw = Decoder("Microsoft Raw Image Decoder", WicGuids.RawDecoder, WicGuids.VendorMicrosoft, ".arw,.cr2,.cr3,.dng,.nef,.raf"); + private static readonly WicDecoderInfo Heif = Decoder("HEIF Decoder", WicGuids.HeifDecoder, WicGuids.VendorMicrosoft, ".heic,.heif,.hif"); + private static readonly WicDecoderInfo Webp = Decoder("WebP Decoder", WicGuids.WebpDecoder, WicGuids.VendorMicrosoft, ".webp"); + + [Test] + [WindowsOnly] + public void DetectFindsTheBuiltInDecoders() + { + var inventory = CodecInventory.Detect(); + Assert.NotEmpty(inventory.Decoders); + foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff }) + { + var support = inventory.For(format); + Assert.True(support.IsNative, $"{format} should decode natively through WIC"); + var decoder = Assert.NotNull(support.Decoder); + Assert.False(string.IsNullOrWhiteSpace(decoder.FriendlyName), $"{format} decoder has no name"); + Assert.NotEqual(Guid.Empty, decoder.ContainerFormat); + Assert.Empty(support.MissingExtensions); + } + Assert.Equal(ImageFormatInfo.Known.Count, inventory.Formats.Count); + } + + [Test] + public void RawNeedsTheRawImageExtension() + { + var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: false)]); + var dng = inventory.For(ImageFileFormat.Dng); + Assert.False(dng.IsNative); + Assert.Equal("DNG Decoder", dng.Decoder?.FriendlyName); + Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.RawImage)], dng.MissingExtensions); + Assert.False(inventory.IsNative(ImageFileFormat.Cr3)); + Assert.Contains(StoreExtension.Get(StoreExtensionKind.RawImage), inventory.MissingExtensions); + } + + [Test] + public void RawIsNativeThroughTheExtension() + { + var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: true)]); + Assert.True(inventory.IsNative(ImageFileFormat.Dng)); + Assert.Equal(StoreExtensionKind.RawImage, inventory.For(ImageFileFormat.Dng).Decoder?.Extension); + Assert.True(inventory.IsNative(ImageFileFormat.Cr3)); + // Installed but without this extension registered: nothing to install, still not native. + var gpr = inventory.For(ImageFileFormat.Gpr); + Assert.False(gpr.IsNative); + Assert.Empty(gpr.MissingExtensions); + } + + [Test] + public void HeifNeedsAnHevcDecoder() + { + var withoutHevc = Inventory([Jpeg, Classified(Heif)]).For(ImageFileFormat.Heif); + Assert.False(withoutHevc.IsNative); + Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.HevcVideo)], withoutHevc.MissingExtensions); + + Assert.True(Inventory([Jpeg, Classified(Heif)], hevc: true).IsNative(ImageFileFormat.Heif)); + + var nothing = Inventory([Jpeg]).For(ImageFileFormat.Heif); + Assert.SequenceEqual( + [StoreExtension.Get(StoreExtensionKind.HeifImage), StoreExtension.Get(StoreExtensionKind.HevcVideo)], + nothing.MissingExtensions); + } + + [Test] + public void AvifUsesTheHeifDecoderWithAnAv1Decoder() + { + var withoutAv1 = Inventory([Classified(Heif)], hevc: true).For(ImageFileFormat.Avif); + Assert.False(withoutAv1.IsNative); + Assert.Equal("HEIF Decoder", withoutAv1.Decoder?.FriendlyName); + Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.Av1Video)], withoutAv1.MissingExtensions); + + Assert.True(Inventory([Classified(Heif)], av1: true).IsNative(ImageFileFormat.Avif)); + } + + [Test] + public void WebpNeedsTheWebpExtension() + { + Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.WebpImage)], Inventory([Jpeg]).For(ImageFileFormat.WebP).MissingExtensions); + Assert.True(Inventory([Jpeg, Classified(Webp)]).IsNative(ImageFileFormat.WebP)); + } + + [Test] + public void BuiltInFormatsNeverAskForExtensions() + { + var inventory = Inventory([Jpeg]); + Assert.True(inventory.IsNative(ImageFileFormat.Jpeg)); + Assert.False(inventory.IsNative(ImageFileFormat.Png)); + Assert.Empty(inventory.For(ImageFileFormat.Png).MissingExtensions); + Assert.False(inventory.IsNative(ImageFileFormat.Unknown)); + } + + [Test] + public void ClassificationUsesClsidPackageAndVendor() + { + Assert.Null(CodecInventory.Classify(Raw, rawExtensionInstalled: false)); + Assert.Equal(StoreExtensionKind.RawImage, CodecInventory.Classify(Raw, rawExtensionInstalled: true)); + Assert.Equal(StoreExtensionKind.HeifImage, CodecInventory.Classify(Heif, false)); + Assert.Equal(StoreExtensionKind.WebpImage, CodecInventory.Classify(Webp, false)); + var avif = Decoder("AVIF Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoft, ".avif"); + Assert.Equal(StoreExtensionKind.Av1Video, CodecInventory.Classify(avif, false)); + var thirdParty = Decoder("Other AVIF", Guid.NewGuid(), Guid.NewGuid(), ".avif"); + Assert.Null(CodecInventory.Classify(thirdParty, false)); + Assert.Null(CodecInventory.Classify(Jpeg, false)); + } + + [Test] + public void StoreLinksUseTheProductIds() + { + Assert.Equal(5, StoreExtension.All.Count); + var raw = StoreExtension.Get(StoreExtensionKind.RawImage); + Assert.Equal("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8", raw.StoreUri.AbsoluteUri); + Assert.Equal("https://apps.microsoft.com/detail/9nctdw2w1bh8", raw.WebUri.AbsoluteUri); + Assert.Equal("9PMMSR1CGPWG", StoreExtension.Get(StoreExtensionKind.HeifImage).ProductId); + Assert.Equal("9NMZLZ57R3T7", StoreExtension.Get(StoreExtensionKind.HevcVideo).ProductId); + Assert.Equal("9MVZQVXJBQ9V", StoreExtension.Get(StoreExtensionKind.Av1Video).ProductId); + Assert.Equal("9PG2DK419DRG", StoreExtension.Get(StoreExtensionKind.WebpImage).ProductId); + } + + [Test] + public void ExtensionListsAreNormalised() + { + Assert.SequenceEqual(["jpg", "jpeg", "jfif"], WicDecoderInfo.ParseExtensions(".JPG, .jpeg;.jfif,,.jpg")); + Assert.True(Jpeg.Handles(".JPG")); + Assert.True(Jpeg.Handles("jfif")); + Assert.False(Jpeg.Handles("png")); + } + + private static CodecInventory Inventory(WicDecoderInfo[] decoders, bool hevc = false, bool av1 = false) => new(decoders, hevc, av1); + + private static WicDecoderInfo Classified(WicDecoderInfo decoder, bool rawExtensionInstalled = false) => + decoder with { Extension = CodecInventory.Classify(decoder, rawExtensionInstalled) }; + + private static WicDecoderInfo Decoder(string name, Guid clsid, Guid vendor, string extensions) => + new(name, clsid, Guid.NewGuid(), vendor, "1.0", WicDecoderInfo.ParseExtensions(extensions), null); +} diff --git a/tests/Titano.Core.Windows.Tests/Wic/OrientationMapTests.cs b/tests/Titano.Core.Windows.Tests/Wic/OrientationMapTests.cs new file mode 100644 index 00000000..cd3fb86c --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Wic/OrientationMapTests.cs @@ -0,0 +1,67 @@ +using Titano.Core.Windows.Wic; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Wic; + +public sealed class OrientationMapTests +{ + [Theory] + [Case(1)] + [Case(2)] + [Case(3)] + [Case(4)] + [Case(5)] + [Case(6)] + [Case(7)] + [Case(8)] + public void MatchesTheExifDefinition(int orientation) + { + const int width = 5, height = 3; + var map = OrientationMap.Create(orientation, width, height); + var swapped = OrientationMap.SwapsAxes(orientation); + Assert.Equal(swapped ? height : width, map.Width); + Assert.Equal(swapped ? width : height, map.Height); + + var seen = new HashSet(); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var (dx, dy) = Reference(orientation, x, y, width, height); + Assert.Equal((dy * map.Width) + dx, map.IndexOf(x, y), $"orientation {orientation}, pixel ({x},{y})"); + seen.Add(map.IndexOf(x, y)); + } + } + Assert.Equal(width * height, seen.Count); + } + + [Test] + public void UnknownValuesActAsIdentity() => Assert.Equal(OrientationMap.Create(1, 4, 2), OrientationMap.Create(0, 4, 2)); + + [Theory] + [Case(4000u, 3000u, 1920, 1920u, 1440u)] + [Case(400u, 100u, 100, 100u, 25u)] + [Case(3000u, 4000u, 1000, 750u, 1000u)] + [Case(640u, 480u, 0, 640u, 480u)] + [Case(640u, 480u, 2000, 640u, 480u)] + [Case(2u, 1000u, 10, 1u, 10u)] + public void TargetSizeFitsTheLongEdge(uint width, uint height, int maxLongEdge, uint expectedWidth, uint expectedHeight) + { + var (w, h) = WicDecoderProvider.TargetSize(width, height, maxLongEdge); + Assert.Equal(expectedWidth, w); + Assert.Equal(expectedHeight, h); + } + + /// Displayed position of stored pixel (x, y), straight from the Exif 2.3 orientation table. + private static (int X, int Y) Reference(int orientation, int x, int y, int w, int h) => orientation switch + { + 2 => (w - 1 - x, y), + 3 => (w - 1 - x, h - 1 - y), + 4 => (x, h - 1 - y), + 5 => (y, x), + 6 => (h - 1 - y, x), + 7 => (h - 1 - y, w - 1 - x), + 8 => (y, w - 1 - x), + _ => (x, y), + }; +} diff --git a/tests/Titano.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs b/tests/Titano.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs new file mode 100644 index 00000000..4dfec12b --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Wic/WicDecoderProviderTests.cs @@ -0,0 +1,163 @@ +using Titano.Core.Imaging; +using Titano.Core.Windows.Wic; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Wic; + +[WindowsOnly] +public sealed class WicDecoderProviderTests(TestContext context) +{ + private static readonly Lazy SharedProvider = new(() => new WicDecoderProvider()); + private static readonly double MidGrey = ColorSpace.SrgbToLinear(128 / 255.0); + + private static WicDecoderProvider Provider => SharedProvider.Value; + + [Test] + public void BuiltInFormatsAreNative() + { + Assert.Equal("wic", Provider.Name); + foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff, ImageFileFormat.Bmp, ImageFileFormat.Gif }) + Assert.Equal(DecodeTier.Native, Provider.TierFor(format), format.ToString()); + Assert.Null(Provider.TierFor(ImageFileFormat.Unknown)); + } + + [Test] + public void PngMidGreyDecodesToLinearLight() + { + var path = Path.Combine(context.CreateTempDirectory(), "grey.png"); + WicTestImages.WriteRgbPng(path, 64, 48, (_, _) => (128, 128, 128)); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + Assert.Equal(DecodeTier.Native, image.Tier); + Assert.Equal("wic", image.Decoder); + Assert.Equal(64, image.Pixels.Width); + Assert.Equal(48, image.Pixels.Height); + Assert.Equal(3, image.Pixels.Channels); + Assert.Equal(64, image.SourceWidth); + Assert.Equal(48, image.SourceHeight); + AssertUniform(image.Pixels, MidGrey, 1e-3); + } + + [Test] + public void PngChannelsKeepTheirOrder() + { + var path = Path.Combine(context.CreateTempDirectory(), "red-blue.png"); + WicTestImages.WriteRgbPng(path, 32, 16, (x, _) => x < 16 ? ((byte)255, (byte)0, (byte)0) : ((byte)0, (byte)0, (byte)255)); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + var p = image.Pixels; + Assert.Approximately(1.0, p[0, 4, 8], 1e-4); + Assert.Approximately(0.0, p[1, 4, 8], 1e-4); + Assert.Approximately(0.0, p[2, 4, 8], 1e-4); + Assert.Approximately(0.0, p[0, 28, 8], 1e-4); + Assert.Approximately(1.0, p[2, 28, 8], 1e-4); + } + + [Test] + public void SixteenBitPngKeepsPrecision() + { + var path = Path.Combine(context.CreateTempDirectory(), "grey16.png"); + WicTestImages.WriteGray16Png(path, 8, 8, 0x8000); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + AssertUniform(image.Pixels, ColorSpace.Linear16(0x8000), 1e-4); + } + + [Test] + public void JpegMidGreyDecodesToLinearLight() + { + var path = Path.Combine(context.CreateTempDirectory(), "grey.jpg"); + WicTestImages.WriteGrayJpeg(path, 64, 48, (_, _) => 128); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + Assert.Equal(64, image.Pixels.Width); + Assert.Equal(48, image.Pixels.Height); + AssertUniform(image.Pixels, MidGrey, 1e-3); + } + + [Test] + public void ScalingToMaxLongEdgeKeepsAspect() + { + var path = Path.Combine(context.CreateTempDirectory(), "wide.png"); + WicTestImages.WriteRgbPng(path, 400, 100, (_, _) => (128, 128, 128)); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, MaxLongEdge: 100))); + Assert.Equal(100, image.Pixels.Width); + Assert.Equal(25, image.Pixels.Height); + Assert.Equal(400, image.SourceWidth); + Assert.Equal(100, image.SourceHeight); + AssertUniform(image.Pixels, MidGrey, 2e-3); + } + + [Test] + public void Orientation6RotatesClockwise() + { + // Stored 64×32 with a white 16×16 block at the top-left; displayed 32×64 with the block at the top-right. + var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg"); + WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + Assert.Equal(32, image.Pixels.Width); + Assert.Equal(64, image.Pixels.Height); + Assert.Equal(32, image.SourceWidth); + Assert.Equal(64, image.SourceHeight); + Assert.Greater(image.Pixels[1, 24, 8], 0.8); + Assert.Less(image.Pixels[1, 8, 8], 0.05); + Assert.Less(image.Pixels[1, 24, 40], 0.05); + } + + [Test] + public void OrientationIsIgnoredWhenNotRequested() + { + var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg"); + WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, ApplyOrientation: false))); + Assert.Equal(64, image.Pixels.Width); + Assert.Equal(32, image.Pixels.Height); + Assert.Greater(image.Pixels[1, 8, 8], 0.8); + } + + [Test] + public void DecodesAFileAnotherProcessHasOpenForWriting() + { + var path = Path.Combine(context.CreateTempDirectory(), "busy.png"); + WicTestImages.WriteRgbPng(path, 16, 16, (_, _) => (128, 128, 128)); + using var writer = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); + + using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path))); + Assert.Equal(16, image.Pixels.Width); + } + + [Test] + public void UnrecognisedContentReturnsNull() + { + var path = Path.Combine(context.CreateTempDirectory(), "noise.png"); + File.WriteAllBytes(path, Enumerable.Range(0, 4096).Select(i => (byte)(i * 37)).ToArray()); + Assert.Null(Provider.Decode(new DecodeRequest(path))); + } + + [Test] + public void MissingFileThrowsFileNotFound() + { + var path = Path.Combine(context.CreateTempDirectory(), "missing.png"); + Assert.Throws(() => Provider.Decode(new DecodeRequest(path))); + } + + [Test] + public void ForcedPreviewIsLeftToOtherProviders() => + Assert.Null(Provider.Decode(new DecodeRequest(Path.Combine(context.CreateTempDirectory(), "any.jpg"), ForcePreview: true))); + + private static void AssertUniform(ImageBuffer image, double expected, double tolerance) + { + for (var c = 0; c < image.Channels; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) + { + if (Math.Abs(plane[i] - expected) > tolerance) + Assert.Fail($"channel {c} pixel {i}: expected {expected:F5} ± {tolerance}, actual {plane[i]:F5}"); + } + } + } +} diff --git a/tests/Titano.Core.Windows.Tests/Wic/WicTestImages.cs b/tests/Titano.Core.Windows.Tests/Wic/WicTestImages.cs new file mode 100644 index 00000000..7ec07c53 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Wic/WicTestImages.cs @@ -0,0 +1,166 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using Titano.Core.Codecs.Png; +using Titano.Core.Windows.Interop; +using Titano.Core.Windows.Wic; + +namespace Titano.Core.Windows.Tests.Wic; + +/// Synthetic fixtures: PNG through the managed encoder, JPEG through WIC's own encoder. +internal static unsafe partial class WicTestImages +{ + private static readonly Guid JpegContainer = new("19e4a5aa-5662-4fc5-a0c0-1758028e1057"); + private static readonly Guid PixelFormat8bppGray = new("6fddc324-4e03-4bfe-b185-3d77768dc908"); + + private const uint STGM_WRITE = 0x1, STGM_SHARE_EXCLUSIVE = 0x10, STGM_CREATE = 0x1000; + private const uint FILE_ATTRIBUTE_NORMAL = 0x80; + private const int WICBitmapEncoderNoCache = 2; + + public static void WriteRgbPng(string path, int width, int height, Func pixel) + { + var data = new byte[width * height * 3]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var (r, g, b) = pixel(x, y); + var i = ((y * width) + x) * 3; + data[i] = r; + data[i + 1] = g; + data[i + 2] = b; + } + } + File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Rgb)); + } + + public static void WriteGray16Png(string path, int width, int height, ushort value) + { + var data = new byte[width * height * 2]; + for (var i = 0; i < data.Length; i += 2) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(i), value); + File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Gray, bitDepth: 16)); + } + + /// Grayscale baseline JPEG from WIC's encoder; optionally tagged with an Exif orientation. + public static void WriteGrayJpeg(string path, int width, int height, Func gray, int? exifOrientation = null) + { + var pixels = new byte[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) pixels[(y * width) + x] = gray(x, y); + } + + var container = JpegContainer; + Marshal.ThrowExceptionForHR(WicFactory.Instance.CreateEncoder(ref container, 0, out var encoderPointer)); + IWICBitmapEncoder encoder; + try + { + encoder = (IWICBitmapEncoder)Marshal.GetObjectForIUnknown(encoderPointer); + } + finally + { + Marshal.Release(encoderPointer); + } + + Marshal.ThrowExceptionForHR(SHCreateStreamOnFileEx(path, STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, FILE_ATTRIBUTE_NORMAL, 1, 0, out var stream)); + IWICBitmapFrameEncode? frame = null; + nint options = 0; + try + { + encoder.Initialize(stream, WICBitmapEncoderNoCache); + encoder.CreateNewFrame(out frame, out options); + frame.Initialize(options); + frame.SetSize((uint)width, (uint)height); + var format = PixelFormat8bppGray; + frame.SetPixelFormat(ref format); + if (format != PixelFormat8bppGray) throw new InvalidOperationException("The WIC JPEG encoder did not accept 8bppGray."); + fixed (byte* p = pixels) frame.WritePixels((uint)height, (uint)width, (uint)pixels.Length, (nint)p); + frame.Commit(); + encoder.Commit(); + } + finally + { + Win32Com.Release(frame); + if (options != 0) Marshal.Release(options); + Win32Com.Release(encoder); + Marshal.Release(stream); + } + + if (exifOrientation is { } orientation) InsertExifOrientation(path, orientation); + } + + /// Adds an APP1 Exif segment holding only IFD0 Orientation (after APP0 when present, as cameras do). + private static void InsertExifOrientation(string path, int orientation) + { + var jpeg = File.ReadAllBytes(path); + byte[] tiff = + [ + (byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0, // little-endian header, IFD0 at offset 8 + 1, 0, // one entry + 0x12, 0x01, 3, 0, 1, 0, 0, 0, (byte)orientation, 0, 0, 0, // 0x0112 Orientation, SHORT, count 1 + 0, 0, 0, 0, // no next IFD + ]; + var insertAt = 2; + if (jpeg[2] == 0xFF && jpeg[3] == 0xE0) insertAt = 4 + BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(4)); + var segmentLength = 2 + 6 + tiff.Length; + using var output = new MemoryStream(); + output.Write(jpeg, 0, insertAt); + output.Write([0xFF, 0xE1, (byte)(segmentLength >> 8), (byte)segmentLength]); + output.Write("Exif\0\0"u8); + output.Write(tiff); + output.Write(jpeg, insertAt, jpeg.Length - insertAt); + File.WriteAllBytes(path, output.ToArray()); + } + + [LibraryImport("shlwapi.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream); +} + +[ComImport] +[Guid("00000103-a8f2-4877-ba0a-fd2b6645fb94")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapEncoder +{ + void Initialize(nint stream, int cacheOption); + + Guid GetContainerFormat(); + + void GetEncoderInfo(out nint encoderInfo); + + void SetColorContexts(uint count, nint colorContexts); + + void SetPalette(nint palette); + + void SetThumbnail(nint thumbnail); + + void SetPreview(nint preview); + + void CreateNewFrame(out IWICBitmapFrameEncode frame, out nint encoderOptions); + + void Commit(); +} + +[ComImport] +[Guid("00000105-a8f2-4877-ba0a-fd2b6645fb94")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IWICBitmapFrameEncode +{ + void Initialize(nint encoderOptions); + + void SetSize(uint width, uint height); + + void SetResolution(double dpiX, double dpiY); + + void SetPixelFormat(ref Guid pixelFormat); + + void SetColorContexts(uint count, nint colorContexts); + + void SetPalette(nint palette); + + void SetThumbnail(nint thumbnail); + + void WritePixels(uint lineCount, uint stride, uint bufferSize, nint pixels); + + void WriteSource(nint source, nint rect); + + void Commit(); +} From 113637d707eafb021b45a5d8740ebbfd31b96839 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:26 +0000 Subject: [PATCH 033/188] feat(windows): add removable volume watcher, ejector and format dialog VolumeInfo reads label, file system, serial, capacity, drive type and DCIM presence (no "insert disk" prompts) and exposes the card identity {serial:X8}-{label}-{capacity}. RemovableVolumeWatcher runs a hidden top-level window on its own message loop for WM_DEVICECHANGE volume unit masks (message-only windows receive no broadcasts) plus a 3 s DriveInfo poll, diffing snapshots so each change is raised once. VolumeEjector locks (with retries), dismounts, allows removal and ejects; FormatDialog shows SHFormatDrive with quick format preselected and refuses the system drive. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Devices/FormatDialog.cs | 57 +++ .../Devices/RemovableVolumeWatcher.cs | 346 ++++++++++++++++++ .../Devices/VolumeEjector.cs | 76 ++++ src/Titano.Core.Windows/Devices/VolumeInfo.cs | 92 +++++ .../Devices/VolumeNative.cs | 54 +++ .../Devices/VolumeTests.cs | 98 +++++ 6 files changed, 723 insertions(+) create mode 100644 src/Titano.Core.Windows/Devices/FormatDialog.cs create mode 100644 src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs create mode 100644 src/Titano.Core.Windows/Devices/VolumeEjector.cs create mode 100644 src/Titano.Core.Windows/Devices/VolumeInfo.cs create mode 100644 src/Titano.Core.Windows/Devices/VolumeNative.cs create mode 100644 tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs diff --git a/src/Titano.Core.Windows/Devices/FormatDialog.cs b/src/Titano.Core.Windows/Devices/FormatDialog.cs new file mode 100644 index 00000000..7d91dec1 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/FormatDialog.cs @@ -0,0 +1,57 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Devices; + +/// Outcome of the Windows format dialog. +public enum FormatDialogResult +{ + /// The user formatted the volume. + Formatted, + + /// The user closed the dialog without formatting. + Cancelled, + + /// Windows reported that the drive cannot be formatted. + NotFormattable, + + /// The last format attempt failed. + Failed, +} + +/// +/// The Windows "Format" dialog (SHFormatDrive), the only way Titano formats a card (BRIEF §8.6): the user confirms +/// and starts the format in the OS dialog, quick format preselected. +/// +public static partial class FormatDialog +{ + private const uint SHFMT_ID_DEFAULT = 0xFFFF; + private const uint SHFMT_OPT_QUICK = 0x0; // no SHFMT_OPT_FULL: "Quick Format" stays checked + private const uint SHFMT_ERROR = 0xFFFFFFFF; + private const uint SHFMT_CANCEL = 0xFFFFFFFE; + private const uint SHFMT_NOFORMAT = 0xFFFFFFFD; + + /// Shows the modal dialog for . Call on the UI thread that owns . + /// No owner window (the dialog requires one). + /// Not a drive letter. + /// The drive holds the running Windows installation. + public static FormatDialogResult Show(nint ownerWindow, char driveLetter) + { + if (ownerWindow == 0) throw new ArgumentException("The format dialog needs an owner window.", nameof(ownerWindow)); + var letter = char.ToUpperInvariant(driveLetter); + if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z."); + var systemRoot = Path.GetPathRoot(Environment.SystemDirectory); + if (!string.IsNullOrEmpty(systemRoot) && char.ToUpperInvariant(systemRoot[0]) == letter) + throw new InvalidOperationException("The Windows system drive cannot be formatted."); + + return SHFormatDrive(ownerWindow, (uint)(letter - 'A'), SHFMT_ID_DEFAULT, SHFMT_OPT_QUICK) switch + { + SHFMT_CANCEL => FormatDialogResult.Cancelled, + SHFMT_NOFORMAT => FormatDialogResult.NotFormattable, + SHFMT_ERROR => FormatDialogResult.Failed, + _ => FormatDialogResult.Formatted, + }; + } + + [LibraryImport("shell32.dll")] + private static partial uint SHFormatDrive(nint ownerWindow, uint drive, uint formatId, uint options); +} diff --git a/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs b/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs new file mode 100644 index 00000000..d87091d0 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs @@ -0,0 +1,346 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using Titano.Core.Diagnostics; + +namespace Titano.Core.Windows.Devices; + +/// Event data for a volume that appeared or disappeared. +public sealed class VolumeEventArgs(VolumeInfo volume) : EventArgs +{ + public VolumeInfo Volume { get; } = volume; +} + +/// +/// Detects cards and other import candidates (BRIEF §13): removable volumes, plus fixed volumes that hold a DCIM +/// folder. A hidden window on a dedicated message-loop thread receives WM_DEVICECHANGE +/// (DBT_DEVICEARRIVAL / DBT_DEVICEREMOVECOMPLETE with DEV_BROADCAST_VOLUME unit masks) and a 3-second +/// poll on the same thread catches anything the broadcast missed. Both paths diff against +/// the last snapshot, so each change is reported exactly once. Events are raised on the watcher thread. +/// +/// +/// The window is top-level but never shown, not message-only (HWND_MESSAGE): Windows broadcasts volume arrival +/// and removal only to top-level windows, and message-only windows receive no broadcasts. +/// +public sealed unsafe partial class RemovableVolumeWatcher : IDisposable +{ + private const string WindowClassName = "Titano.RemovableVolumeWatcher"; + private const uint PollIntervalMilliseconds = 3000; + private const nuint PollTimerId = 1; + + private const uint WM_DESTROY = 0x0002; + private const uint WM_CLOSE = 0x0010; + private const uint WM_TIMER = 0x0113; + private const uint WM_DEVICECHANGE = 0x0219; + private const nint DBT_DEVICEARRIVAL = 0x8000; + private const nint DBT_DEVICEREMOVECOMPLETE = 0x8004; + private const uint DBT_DEVTYP_VOLUME = 0x2; + private const uint WS_EX_TOOLWINDOW = 0x80; + private const int GWLP_USERDATA = -21; + private const int ERROR_CLASS_ALREADY_EXISTS = 1410; + + private static readonly Lock ClassGate = new(); + private static bool s_classRegistered; + + private readonly Dictionary _known = new(StringComparer.OrdinalIgnoreCase); + private readonly Lock _gate = new(); + private Thread? _thread; + private nint _window; + private GCHandle _self; + private int _disposed; + + /// A candidate volume was inserted or became ready. + public event EventHandler? VolumeArrived; + + /// A known volume was removed (or its media was swapped; the new one then arrives). + public event EventHandler? VolumeRemoved; + + /// Candidate volumes currently present (populated by , without events). + public IReadOnlyList Volumes + { + get + { + lock (_gate) return [.. _known.Values.OrderBy(v => v.RootPath, StringComparer.OrdinalIgnoreCase)]; + } + } + + /// True for volumes the import UI lists: removable media, or fixed media with a DCIM folder. + public static bool IsCandidate(VolumeInfo volume) => + volume.DriveType == VolumeDriveType.Removable || (volume.DriveType == VolumeDriveType.Fixed && volume.HasDcim); + + /// Takes the initial snapshot and starts watching; returns once the window exists. + /// The hidden window could not be created. + public void Start() + { + ObjectDisposedException.ThrowIf(_disposed != 0, this); + if (_thread is not null) throw new InvalidOperationException("The watcher is already running."); + + using var ready = new ManualResetEventSlim(); + Win32Exception? failure = null; + var thread = new Thread(() => + { + try + { + _window = CreateHiddenWindow(); + Rescan(raiseEvents: false); + } + catch (Win32Exception ex) + { + failure = ex; + } + finally + { + ready.Set(); + } + if (failure is null) RunMessageLoop(); + }) + { + IsBackground = true, + Name = "Titano volume watcher", + }; + thread.Start(); + ready.Wait(); + if (failure is not null) + { + thread.Join(); + throw failure; + } + _thread = thread; + } + + /// Stops watching and waits for the watcher thread (unless called from one of its event handlers). + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (_window != 0) PostMessageW(_window, WM_CLOSE, 0, 0); + if (_thread is { } thread && thread != Thread.CurrentThread) thread.Join(); + } + + private nint CreateHiddenWindow() + { + var instance = GetModuleHandleW(null); + RegisterWindowClass(instance); + var window = CreateWindowExW(WS_EX_TOOLWINDOW, WindowClassName, WindowClassName, 0, 0, 0, 0, 0, 0, 0, instance, 0); + if (window == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + _self = GCHandle.Alloc(this); + SetWindowLongPtrW(window, GWLP_USERDATA, GCHandle.ToIntPtr(_self)); + if (SetTimer(window, PollTimerId, PollIntervalMilliseconds, 0) == 0) + Log.Warning("devices", $"SetTimer failed (error {Marshal.GetLastPInvokeError()}); relying on WM_DEVICECHANGE only."); + return window; + } + + private static void RegisterWindowClass(nint instance) + { + lock (ClassGate) + { + if (s_classRegistered) return; + fixed (char* className = WindowClassName) + { + var windowClass = new WindowClass + { + Size = (uint)sizeof(WindowClass), + WindowProcedure = (nint)(delegate* unmanaged)&WindowProcedure, + Instance = instance, + ClassName = className, + }; + if (RegisterClassExW(&windowClass) == 0 && Marshal.GetLastPInvokeError() != ERROR_CLASS_ALREADY_EXISTS) + throw new Win32Exception(Marshal.GetLastPInvokeError()); + } + s_classRegistered = true; + } + } + + private void RunMessageLoop() + { + try + { + while (GetMessageW(out var message, 0, 0, 0) > 0) + { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + finally + { + // Normally a no-op (WM_QUIT follows WM_DESTROY); after a GetMessage failure it guarantees that no + // callback can reach the handle once it is freed. + DestroyWindow(_window); + _self.Free(); + } + } + + [UnmanagedCallersOnly] + private static nint WindowProcedure(nint window, uint message, nint wParam, nint lParam) + { + try + { + var handle = GetWindowLongPtrW(window, GWLP_USERDATA); + if (handle != 0 && GCHandle.FromIntPtr(handle).Target is RemovableVolumeWatcher watcher) + { + switch (message) + { + case WM_DEVICECHANGE when (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) && lParam != 0: + var header = (DeviceBroadcastVolume*)lParam; + if (header->DeviceType == DBT_DEVTYP_VOLUME) watcher.Refresh(header->UnitMask); + return 1; + case WM_TIMER when (nuint)wParam == PollTimerId: + watcher.Rescan(raiseEvents: true); + return 0; + case WM_CLOSE: + KillTimer(window, PollTimerId); + DestroyWindow(window); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + } + } + } + catch (Exception ex) + { + // Nothing may unwind through a native callback. + Log.Error("devices", "Volume watcher message handling failed", ex); + } + return DefWindowProcW(window, message, wParam, lParam); + } + + /// Re-reads the drive letters named by a DEV_BROADCAST_VOLUME unit mask (bit 0 = A:). + private void Refresh(uint unitMask) + { + for (var bit = 0; bit < 26; bit++) + { + if ((unitMask & (1u << bit)) == 0) continue; + var root = $"{(char)('A' + bit)}:\\"; + Update(root, Read(root), raiseEvents: true); + } + } + + /// Full poll: every local drive letter plus every previously known root. + private void Rescan(bool raiseEvents) + { + var roots = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var drive in DriveInfo.GetDrives()) + { + if (drive.DriveType is DriveType.Fixed or DriveType.Removable) roots.Add(drive.Name); + } + lock (_gate) roots.UnionWith(_known.Keys); + foreach (var root in roots) Update(root, Read(root), raiseEvents); + } + + private static VolumeInfo? Read(string root) => VolumeInfo.TryRead(root) is { } volume && IsCandidate(volume) ? volume : null; + + private void Update(string root, VolumeInfo? current, bool raiseEvents) + { + VolumeInfo? previous; + lock (_gate) + { + _known.TryGetValue(root, out previous); + if (current is null) _known.Remove(root); + else _known[root] = current; + } + if (!raiseEvents) return; + var sameVolume = previous is not null && current is not null && previous.Identity == current.Identity; + if (previous is not null && !sameVolume) Raise(VolumeRemoved, previous); + if (current is not null && !sameVolume) Raise(VolumeArrived, current); + } + + private void Raise(EventHandler? handler, VolumeInfo volume) + { + try + { + handler?.Invoke(this, new VolumeEventArgs(volume)); + } + catch (Exception ex) + { + Log.Error("devices", $"A volume event handler failed for {volume.RootPath}", ex); + } + } + + /// DEV_BROADCAST_VOLUME (the header's first three fields, then the unit mask and flags). + [StructLayout(LayoutKind.Sequential)] + private struct DeviceBroadcastVolume + { + public uint Size; + public uint DeviceType; + public uint Reserved; + public uint UnitMask; + public ushort Flags; + } + + /// WNDCLASSEXW (80 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct WindowClass + { + public uint Size; + public uint Style; + public nint WindowProcedure; + public int ClassExtraBytes; + public int WindowExtraBytes; + public nint Instance; + public nint Icon; + public nint Cursor; + public nint Background; + public char* MenuName; + public char* ClassName; + public nint SmallIcon; + } + + /// MSG (48 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct Message + { + public nint Window; + public uint Id; + public nint WParam; + public nint LParam; + public uint Time; + public int X; + public int Y; + public uint Private; + } + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial nint GetModuleHandleW(string? moduleName); + + [LibraryImport("user32.dll", SetLastError = true)] + private static partial ushort RegisterClassExW(WindowClass* windowClass); + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + private static partial nint CreateWindowExW(uint exStyle, string className, string windowName, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, nint parameter); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DestroyWindow(nint window); + + [LibraryImport("user32.dll")] + private static partial nint DefWindowProcW(nint window, uint message, nint wParam, nint lParam); + + [LibraryImport("user32.dll")] + private static partial int GetMessageW(out Message message, nint window, uint filterMin, uint filterMax); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool TranslateMessage(Message* message); + + [LibraryImport("user32.dll")] + private static partial nint DispatchMessageW(Message* message); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool PostMessageW(nint window, uint message, nint wParam, nint lParam); + + [LibraryImport("user32.dll")] + private static partial void PostQuitMessage(int exitCode); + + [LibraryImport("user32.dll", SetLastError = true)] + private static partial nuint SetTimer(nint window, nuint id, uint elapse, nint timerProcedure); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool KillTimer(nint window, nuint id); + + [LibraryImport("user32.dll")] + private static partial nint SetWindowLongPtrW(nint window, int index, nint value); + + [LibraryImport("user32.dll")] + private static partial nint GetWindowLongPtrW(nint window, int index); +} diff --git a/src/Titano.Core.Windows/Devices/VolumeEjector.cs b/src/Titano.Core.Windows/Devices/VolumeEjector.cs new file mode 100644 index 00000000..0dfb1d1b --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeEjector.cs @@ -0,0 +1,76 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Titano.Core.Windows.Devices; + +/// Outcome of . +public enum EjectResult +{ + /// The volume was dismounted and the media ejected; the card can be removed. + Ejected, + + /// Another process holds files open on the volume; nothing was changed. + InUse, + + /// The drive is not a removable-media drive (fixed, network, unknown or no such letter). + NotRemovable, + + /// Windows refused to open, dismount or eject the volume. + Failed, +} + +/// +/// Safe card removal (BRIEF §12.4): open \\.\X:, FSCTL_LOCK_VOLUME (retried while other handles close), +/// FSCTL_DISMOUNT_VOLUME, IOCTL_STORAGE_MEDIA_REMOVAL (allow), IOCTL_STORAGE_EJECT_MEDIA. Blocks for up to about +/// two seconds while retrying the lock; call it off the UI thread. +/// +public static unsafe class VolumeEjector +{ + private const uint DRIVE_REMOVABLE = 2; + private const uint DRIVE_CDROM = 5; + private const int LockAttempts = 5; + private static readonly TimeSpan LockRetryDelay = TimeSpan.FromMilliseconds(500); + + public static EjectResult Eject(char driveLetter) + { + var letter = char.ToUpperInvariant(driveLetter); + if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z."); + if (VolumeNative.GetDriveType($"{letter}:\\") is not (DRIVE_REMOVABLE or DRIVE_CDROM)) return EjectResult.NotRemovable; + + using var volume = VolumeNative.CreateFile( + $@"\\.\{letter}:", + VolumeNative.GENERIC_READ | VolumeNative.GENERIC_WRITE, + VolumeNative.FILE_SHARE_READ | VolumeNative.FILE_SHARE_WRITE, + 0, + VolumeNative.OPEN_EXISTING, + 0, + 0); + if (volume.IsInvalid) return EjectResult.Failed; + if (!Lock(volume)) return EjectResult.InUse; + if (!Control(volume, VolumeNative.FSCTL_DISMOUNT_VOLUME)) return EjectResult.Failed; + if (!AllowRemoval(volume)) return EjectResult.Failed; + // Closing the handle afterwards releases the lock. + return Control(volume, VolumeNative.IOCTL_STORAGE_EJECT_MEDIA) ? EjectResult.Ejected : EjectResult.Failed; + } + + private static bool Lock(SafeFileHandle volume) + { + for (var attempt = 1; attempt <= LockAttempts; attempt++) + { + if (Control(volume, VolumeNative.FSCTL_LOCK_VOLUME)) return true; + if (attempt < LockAttempts) Thread.Sleep(LockRetryDelay); + } + return false; + } + + /// Clears any media-removal lock; readers that do not implement the request count as unlocked. + private static bool AllowRemoval(SafeFileHandle volume) + { + byte preventMediaRemoval = 0; + if (VolumeNative.DeviceIoControl(volume, VolumeNative.IOCTL_STORAGE_MEDIA_REMOVAL, &preventMediaRemoval, sizeof(byte), null, 0, out _, 0)) return true; + return Marshal.GetLastPInvokeError() is VolumeNative.ERROR_INVALID_FUNCTION or VolumeNative.ERROR_NOT_SUPPORTED; + } + + private static bool Control(SafeFileHandle volume, uint code) => + VolumeNative.DeviceIoControl(volume, code, null, 0, null, 0, out _, 0); +} diff --git a/src/Titano.Core.Windows/Devices/VolumeInfo.cs b/src/Titano.Core.Windows/Devices/VolumeInfo.cs new file mode 100644 index 00000000..38b016dc --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeInfo.cs @@ -0,0 +1,92 @@ +using System.Globalization; + +namespace Titano.Core.Windows.Devices; + +/// GetDriveTypeW results. +public enum VolumeDriveType +{ + Unknown = 0, + NoRootDirectory = 1, + Removable = 2, + Fixed = 3, + Remote = 4, + CdRom = 5, + RamDisk = 6, +} + +/// A mounted volume with the facts card import needs (BRIEF §12.4, §13). +/// Root with trailing separator, e.g. E:\. +/// Volume label (may be empty). +/// File system name, e.g. exFAT. +/// Volume serial number assigned at format time. +/// Capacity in bytes. +/// Free bytes available to the current user. +/// Drive type reported by Windows. +/// A DCIM folder exists at the root (camera card). +public sealed record VolumeInfo( + string RootPath, + string Label, + string FileSystem, + uint SerialNumber, + long TotalBytes, + long FreeBytes, + VolumeDriveType DriveType, + bool HasDcim) +{ + private const int MaxPath = 261; + + public char DriveLetter => char.ToUpperInvariant(RootPath[0]); + + /// Card identity {serial:X8}-{label}-{capacity} (BRIEF §13); stable across readers and drive letters. + public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}"); + + /// Reads a volume; null when the root does not exist or holds no media (empty card reader). + public static unsafe VolumeInfo? TryRead(string rootPath) + { + var root = NormalizeRoot(rootPath); + var driveType = (VolumeDriveType)VolumeNative.GetDriveType(root); + if (driveType is VolumeDriveType.Unknown or VolumeDriveType.NoRootDirectory) return null; + + VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode); + try + { + var label = stackalloc char[MaxPath]; + var fileSystem = stackalloc char[MaxPath]; + if (!VolumeNative.GetVolumeInformation(root, label, MaxPath, out var serial, out _, out _, fileSystem, MaxPath)) return null; + if (!VolumeNative.GetDiskFreeSpaceEx(root, out var free, out var total, out _)) return null; + return new VolumeInfo( + root, + new string(label), + new string(fileSystem), + serial, + (long)total, + (long)free, + driveType, + Directory.Exists(Path.Combine(root, "DCIM"))); + } + finally + { + VolumeNative.SetThreadErrorMode(previousMode, out _); + } + } + + /// Every ready fixed or removable volume, enumerated through (network and optical drives are skipped). + public static IReadOnlyList ListLocal() + { + var volumes = new List(); + foreach (var drive in DriveInfo.GetDrives()) + { + if (drive.DriveType is not (System.IO.DriveType.Fixed or System.IO.DriveType.Removable)) continue; + if (TryRead(drive.Name) is { } volume) volumes.Add(volume); + } + return volumes; + } + + /// "e:", "E:\" or "E:\DCIM" → "E:\". + internal static string NormalizeRoot(string path) + { + var root = Path.GetPathRoot(path); + if (string.IsNullOrEmpty(root)) throw new ArgumentException("The path has no root.", nameof(path)); + return root.EndsWith('\\') ? root.ToUpperInvariant() : root.ToUpperInvariant() + "\\"; + } +} diff --git a/src/Titano.Core.Windows/Devices/VolumeNative.cs b/src/Titano.Core.Windows/Devices/VolumeNative.cs new file mode 100644 index 00000000..58a261d2 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeNative.cs @@ -0,0 +1,54 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Titano.Core.Windows.Devices; + +/// kernel32 volume and device-control entry points used by the Devices helpers. +internal static unsafe partial class VolumeNative +{ + public const uint GENERIC_READ = 0x80000000; + public const uint GENERIC_WRITE = 0x40000000; + public const uint FILE_SHARE_READ = 0x1; + public const uint FILE_SHARE_WRITE = 0x2; + public const uint OPEN_EXISTING = 3; + public const uint SEM_FAILCRITICALERRORS = 0x1; + + public const uint FSCTL_LOCK_VOLUME = 0x00090018; + public const uint FSCTL_DISMOUNT_VOLUME = 0x00090020; + public const uint IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804; + public const uint IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808; + + public const int ERROR_INVALID_FUNCTION = 1; + public const int ERROR_NOT_SUPPORTED = 50; + + [LibraryImport("kernel32.dll", EntryPoint = "GetDriveTypeW", StringMarshalling = StringMarshalling.Utf16)] + public static partial uint GetDriveType(string rootPath); + + [LibraryImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetVolumeInformation( + string rootPath, + char* volumeName, + uint volumeNameSize, + out uint serialNumber, + out uint maximumComponentLength, + out uint fileSystemFlags, + char* fileSystemName, + uint fileSystemNameSize); + + [LibraryImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceExW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetDiskFreeSpaceEx(string directory, out ulong freeBytesAvailable, out ulong totalBytes, out ulong totalFreeBytes); + + /// Per-thread error mode; SEM_FAILCRITICALERRORS stops "insert a disk" dialogs on empty card readers. + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool SetThreadErrorMode(uint newMode, out uint oldMode); + + [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + public static partial SafeFileHandle CreateFile(string fileName, uint desiredAccess, uint shareMode, nint securityAttributes, uint creationDisposition, uint flagsAndAttributes, nint templateFile); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DeviceIoControl(SafeFileHandle device, uint controlCode, void* inBuffer, uint inBufferSize, void* outBuffer, uint outBufferSize, out uint bytesReturned, nint overlapped); +} diff --git a/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs b/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs new file mode 100644 index 00000000..039dd40c --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs @@ -0,0 +1,98 @@ +using System.Text.RegularExpressions; +using Titano.Core.Windows.Devices; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Devices; + +public sealed class VolumeTests +{ + [Test] + [WindowsOnly] + public void ListingIncludesTheSystemDriveWithItsSerial() + { + var systemRoot = Path.GetPathRoot(Environment.SystemDirectory)!; + var volumes = VolumeInfo.ListLocal(); + var system = volumes.FirstOrDefault(v => string.Equals(v.RootPath, systemRoot, StringComparison.OrdinalIgnoreCase)); + if (system is null) Assert.Fail($"{systemRoot} missing from [{string.Join(", ", volumes.Select(v => v.RootPath))}]"); + Assert.NotEqual(0u, system!.SerialNumber); + Assert.Greater(system.TotalBytes, 0); + Assert.InRange(system.FreeBytes, 0, system.TotalBytes); + Assert.Equal(VolumeDriveType.Fixed, system.DriveType); + Assert.False(string.IsNullOrEmpty(system.FileSystem)); + Assert.True(Regex.IsMatch(system.Identity, "^[0-9A-F]{8}-.*-[0-9]+$"), system.Identity); + } + + [Test] + [WindowsOnly] + public void MissingDriveLetterReadsAsNull() + { + var used = DriveInfo.GetDrives().Select(d => char.ToUpperInvariant(d.Name[0])).ToHashSet(); + var free = Enumerable.Range('D', 23).Select(c => (char)c).Where(c => !used.Contains(c)).ToArray(); + if (free.Length == 0) TestContext.Skip("Every drive letter is in use."); + Assert.Null(VolumeInfo.TryRead($"{free[^1]}:\\")); + } + + [Test] + [WindowsOnly] + public void RootsAreNormalised() + { + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot("e:")); + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"E:\")); + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"e:\DCIM\100CANON")); + } + + [Test] + public void IdentityFollowsTheBriefFormat() + { + var card = new VolumeInfo(@"E:\", "EOS_DIGITAL", "exFAT", 0x3F2A9C11, 127_865_454_592, 1_000, VolumeDriveType.Removable, true); + Assert.Equal("3F2A9C11-EOS_DIGITAL-127865454592", card.Identity); + Assert.Equal('E', card.DriveLetter); + Assert.Equal("0000000A--1024", (card with { SerialNumber = 10, Label = "", TotalBytes = 1024 }).Identity); + } + + [Test] + public void CandidatesAreRemovableOrCameraVolumes() + { + var card = new VolumeInfo(@"E:\", "", "exFAT", 1, 1, 1, VolumeDriveType.Removable, false); + Assert.True(RemovableVolumeWatcher.IsCandidate(card)); + Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed })); + Assert.True(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed, HasDcim = true })); + Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Remote, HasDcim = true })); + } + + [Test] + [WindowsOnly] + [Timeout(30_000)] + public void WatcherStartsAndStops() + { + using var watcher = new RemovableVolumeWatcher(); + watcher.Start(); + Assert.True(watcher.Volumes.All(RemovableVolumeWatcher.IsCandidate)); + Assert.Throws(watcher.Start); + watcher.Dispose(); + Assert.Throws(watcher.Start); + } + + [Test] + [WindowsOnly] + public void EjectRefusesTheSystemDrive() + { + var letter = Path.GetPathRoot(Environment.SystemDirectory)![0]; + Assert.Equal(EjectResult.NotRemovable, VolumeEjector.Eject(letter)); + } + + [Test] + public void EjectRejectsNonLetters() => Assert.Throws(() => VolumeEjector.Eject('1')); + + [Test] + public void FormatDialogNeedsAnOwnerWindow() => Assert.Throws(() => FormatDialog.Show(0, 'E')); + + [Test] + [WindowsOnly] + public void FormatDialogRefusesTheSystemDrive() + { + var letter = Path.GetPathRoot(Environment.SystemDirectory)![0]; + // The guard runs before the dialog, so any non-null owner handle exercises it without showing UI. + Assert.Throws(() => FormatDialog.Show(1, letter)); + } +} From 6f765aafbc1d98d92e60fb64d419a0346d06fcf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:40 +0000 Subject: [PATCH 034/188] feat(windows): add DPAPI token protection Dpapi.Protect/Unprotect wrap CryptProtectData/CryptUnprotectData in the current-user scope with optional entropy and no UI; decrypted native buffers are zeroed before LocalFree. String helpers return Base64 for JSON settings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core.Windows/Security/Dpapi.cs | 111 ++++++++++++++++++ .../Security/DpapiTests.cs | 48 ++++++++ 2 files changed, 159 insertions(+) create mode 100644 src/Titano.Core.Windows/Security/Dpapi.cs create mode 100644 tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs diff --git a/src/Titano.Core.Windows/Security/Dpapi.cs b/src/Titano.Core.Windows/Security/Dpapi.cs new file mode 100644 index 00000000..3b0b4589 --- /dev/null +++ b/src/Titano.Core.Windows/Security/Dpapi.cs @@ -0,0 +1,111 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Core.Windows.Security; + +/// +/// Windows Data Protection API in the current-user scope (BRIEF §15): secrets such as server tokens are encrypted +/// with a key derived from the user's logon credentials, so only the same Windows user can decrypt them. +/// Optional entropy binds a secret to a purpose (it must be supplied again to decrypt). +/// +public static unsafe partial class Dpapi +{ + private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1; + + /// Encryption failed. + public static byte[] Protect(ReadOnlySpan plaintext, ReadOnlySpan entropy = default) + { + // An empty span pins to null, but the API wants a valid pointer even for zero bytes. + byte empty = 0; + fixed (byte* input = plaintext) + fixed (byte* salt = entropy) + { + var inputBlob = new DataBlob { Size = (uint)plaintext.Length, Data = input == null ? &empty : input }; + var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt }; + DataBlob output = default; + if (!CryptProtectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) + throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage()); + return TakeOutput(output, clear: false); + } + } + + /// The data was protected by another user, tampered with, or the entropy differs. + public static byte[] Unprotect(ReadOnlySpan protectedData, ReadOnlySpan entropy = default) + { + byte empty = 0; + fixed (byte* input = protectedData) + fixed (byte* salt = entropy) + { + var inputBlob = new DataBlob { Size = (uint)protectedData.Length, Data = input == null ? &empty : input }; + var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt }; + DataBlob output = default; + if (!CryptUnprotectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) + throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage()); + return TakeOutput(output, clear: true); + } + } + + /// Protects a UTF-8 string and returns Base64, convenient for JSON settings. + public static string ProtectString(string value, ReadOnlySpan entropy = default) + { + var bytes = Encoding.UTF8.GetBytes(value); + try + { + return Convert.ToBase64String(Protect(bytes, entropy)); + } + finally + { + CryptographicOperations.ZeroMemory(bytes); + } + } + + /// Reverses . + /// The text is not Base64. + /// The data cannot be decrypted by this user with this entropy. + public static string UnprotectString(string protectedBase64, ReadOnlySpan entropy = default) + { + var bytes = Unprotect(Convert.FromBase64String(protectedBase64), entropy); + try + { + return Encoding.UTF8.GetString(bytes); + } + finally + { + CryptographicOperations.ZeroMemory(bytes); + } + } + + private static byte[] TakeOutput(DataBlob output, bool clear) + { + try + { + var native = new Span(output.Data, (int)output.Size); + var result = native.ToArray(); + if (clear) CryptographicOperations.ZeroMemory(native); + return result; + } + finally + { + LocalFree((nint)output.Data); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public uint Size; + public byte* Data; + } + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptProtectData(DataBlob* dataIn, char* description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut); + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptUnprotectData(DataBlob* dataIn, char** description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut); + + [LibraryImport("kernel32.dll")] + private static partial nint LocalFree(nint memory); +} diff --git a/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs b/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs new file mode 100644 index 00000000..eed58197 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs @@ -0,0 +1,48 @@ +using System.Security.Cryptography; +using System.Text; +using Titano.Core.Windows.Security; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Security; + +[WindowsOnly] +public sealed class DpapiTests +{ + private static readonly byte[] Secret = Encoding.UTF8.GetBytes("titano-refresh-token-0123456789"); + + [Test] + public void RoundTripsBytes() + { + var protectedData = Dpapi.Protect(Secret); + Assert.False(protectedData.AsSpan().SequenceEqual(Secret), "ciphertext equals plaintext"); + Assert.Greater(protectedData.Length, Secret.Length); + Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData)); + } + + [Test] + public void EntropyMustMatch() + { + var entropy = "Titano.Uploader.Token"u8.ToArray(); + var protectedData = Dpapi.Protect(Secret, entropy); + Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData, entropy)); + Assert.Throws(() => Dpapi.Unprotect(protectedData, "other"u8)); + Assert.Throws(() => Dpapi.Unprotect(protectedData)); + } + + [Test] + public void TamperedDataIsRejected() + { + var protectedData = Dpapi.Protect(Secret); + protectedData[^1] ^= 0x5A; + Assert.Throws(() => Dpapi.Unprotect(protectedData)); + } + + [Test] + public void RoundTripsStringsAndEmptyValues() + { + var stored = Dpapi.ProtectString("päss wörd ✓"); + Assert.Equal("päss wörd ✓", Dpapi.UnprotectString(stored)); + Assert.Equal(string.Empty, Dpapi.UnprotectString(Dpapi.ProtectString(string.Empty))); + Assert.Empty(Dpapi.Unprotect(Dpapi.Protect([]))); + } +} From 598433773e8320c186ec7a4c2d235b89b2027edb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:40 +0000 Subject: [PATCH 035/188] feat(windows): add DWM window chrome and system theme watcher DwmWindow sets dark mode (attribute 20, 19 on older Windows 10), Mica/none backdrop, corner preference and caption/border colours, returning false for null or stale windows and unsupported builds. SystemTheme reads AppsUseLightTheme and the accent colour (DWM AccentColor, else DwmGetColorizationColor); SystemThemeWatcher raises Changed from a RegNotifyChangeKeyValue thread when either value actually changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core.Windows/Window/DwmWindow.cs | 66 +++++++++++++ src/Titano.Core.Windows/Window/RgbColor.cs | 16 ++++ src/Titano.Core.Windows/Window/SystemTheme.cs | 37 ++++++++ .../Window/SystemThemeWatcher.cs | 95 +++++++++++++++++++ .../Window/WindowTests.cs | 52 ++++++++++ 5 files changed, 266 insertions(+) create mode 100644 src/Titano.Core.Windows/Window/DwmWindow.cs create mode 100644 src/Titano.Core.Windows/Window/RgbColor.cs create mode 100644 src/Titano.Core.Windows/Window/SystemTheme.cs create mode 100644 src/Titano.Core.Windows/Window/SystemThemeWatcher.cs create mode 100644 tests/Titano.Core.Windows.Tests/Window/WindowTests.cs diff --git a/src/Titano.Core.Windows/Window/DwmWindow.cs b/src/Titano.Core.Windows/Window/DwmWindow.cs new file mode 100644 index 00000000..a3de3229 --- /dev/null +++ b/src/Titano.Core.Windows/Window/DwmWindow.cs @@ -0,0 +1,66 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Window; + +/// DWMWA_SYSTEMBACKDROP_TYPE values (Windows 11 22H2+). +public enum SystemBackdrop +{ + Auto = 0, + None = 1, + Mica = 2, + Acrylic = 3, + MicaAlt = 4, +} + +/// DWMWA_WINDOW_CORNER_PREFERENCE values (Windows 11+). +public enum WindowCornerPreference +{ + Default = 0, + DoNotRound = 1, + Round = 2, + RoundSmall = 3, +} + +/// +/// Window chrome through DwmSetWindowAttribute (BRIEF §2.1). Every helper returns false, without throwing, when the +/// handle is null or stale or this Windows build does not support the attribute, so callers need no version checks. +/// +public static partial class DwmWindow +{ + private const uint DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19; + private const uint DWMWA_USE_IMMERSIVE_DARK_MODE = 20; + private const uint DWMWA_WINDOW_CORNER_PREFERENCE = 33; + private const uint DWMWA_BORDER_COLOR = 34; + private const uint DWMWA_CAPTION_COLOR = 35; + private const uint DWMWA_SYSTEMBACKDROP_TYPE = 38; + private const uint DWMWA_COLOR_DEFAULT = 0xFFFFFFFF; + + /// Dark title bar (attribute 20; 19 on Windows 10 1809–1909). + public static bool SetDarkMode(nint window, bool enabled) + { + if (!Win32Window.Exists(window)) return false; + var value = enabled ? 1 : 0; + return Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE, value) || Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, value); + } + + public static bool SetBackdrop(nint window, SystemBackdrop backdrop) => + Win32Window.Exists(window) && Set(window, DWMWA_SYSTEMBACKDROP_TYPE, (int)backdrop); + + public static bool SetCornerPreference(nint window, WindowCornerPreference preference) => + Win32Window.Exists(window) && Set(window, DWMWA_WINDOW_CORNER_PREFERENCE, (int)preference); + + /// Title bar colour; null restores the system default. + public static bool SetCaptionColor(nint window, RgbColor? color) => + Win32Window.Exists(window) && Set(window, DWMWA_CAPTION_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT))); + + /// Window border colour; null restores the system default. + public static bool SetBorderColor(nint window, RgbColor? color) => + Win32Window.Exists(window) && Set(window, DWMWA_BORDER_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT))); + + private static unsafe bool Set(nint window, uint attribute, int value) => + DwmSetWindowAttribute(window, attribute, &value, sizeof(int)) >= 0; + + [LibraryImport("dwmapi.dll")] + private static unsafe partial int DwmSetWindowAttribute(nint window, uint attribute, void* value, uint size); +} diff --git a/src/Titano.Core.Windows/Window/RgbColor.cs b/src/Titano.Core.Windows/Window/RgbColor.cs new file mode 100644 index 00000000..5dc12f39 --- /dev/null +++ b/src/Titano.Core.Windows/Window/RgbColor.cs @@ -0,0 +1,16 @@ +namespace Titano.Core.Windows.Window; + +/// An opaque 8-bit sRGB colour, as used by DWM window chrome and the system accent. +public readonly record struct RgbColor(byte R, byte G, byte B) +{ + /// Win32 COLORREF layout 0x00BBGGRR. + internal uint ToColorRef() => R | ((uint)G << 8) | ((uint)B << 16); + + /// From 0xAABBGGRR (COLORREF with alpha, as stored in the registry's AccentColor). + internal static RgbColor FromAbgr(uint value) => new((byte)value, (byte)(value >> 8), (byte)(value >> 16)); + + /// From 0xAARRGGBB (DwmGetColorizationColor). + internal static RgbColor FromArgb(uint value) => new((byte)(value >> 16), (byte)(value >> 8), (byte)value); + + public override string ToString() => $"#{R:X2}{G:X2}{B:X2}"; +} diff --git a/src/Titano.Core.Windows/Window/SystemTheme.cs b/src/Titano.Core.Windows/Window/SystemTheme.cs new file mode 100644 index 00000000..fc8f388e --- /dev/null +++ b/src/Titano.Core.Windows/Window/SystemTheme.cs @@ -0,0 +1,37 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32; + +namespace Titano.Core.Windows.Window; + +/// The user's light/dark app mode and accent colour, read on demand (see for changes). +public static partial class SystemTheme +{ + internal const string PersonalizeKey = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; + internal const string DwmKey = @"Software\Microsoft\Windows\DWM"; + + /// HKCU …\Themes\Personalize\AppsUseLightTheme; true when absent (the Windows default). + public static bool AppsUseLightTheme + { + get + { + using var key = Registry.CurrentUser.OpenSubKey(PersonalizeKey); + return key?.GetValue("AppsUseLightTheme") is not int value || value != 0; + } + } + + /// The accent colour: HKCU …\DWM\AccentColor, else DwmGetColorizationColor; null when neither is available. + public static RgbColor? AccentColor + { + get + { + using (var key = Registry.CurrentUser.OpenSubKey(DwmKey)) + { + if (key?.GetValue("AccentColor") is int abgr) return RgbColor.FromAbgr(unchecked((uint)abgr)); + } + return DwmGetColorizationColor(out var argb, out _) >= 0 ? RgbColor.FromArgb(argb) : null; + } + } + + [LibraryImport("dwmapi.dll")] + private static partial int DwmGetColorizationColor(out uint colorization, out int opaqueBlend); +} diff --git a/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs b/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs new file mode 100644 index 00000000..b04ae165 --- /dev/null +++ b/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs @@ -0,0 +1,95 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using Titano.Core.Diagnostics; + +namespace Titano.Core.Windows.Window; + +/// +/// Raises when the app light/dark mode or the accent colour changes, using +/// RegNotifyChangeKeyValue on a dedicated background thread (the registration lives as long as that thread). +/// Handlers run on that thread; marshal to the UI dispatcher. +/// +public sealed partial class SystemThemeWatcher : IDisposable +{ + private const uint REG_NOTIFY_CHANGE_LAST_SET = 0x4; + + private readonly ManualResetEvent _stop = new(false); + private readonly Thread _thread; + private int _disposed; + + public SystemThemeWatcher() + { + _thread = new Thread(Run) { IsBackground = true, Name = "Titano theme watcher" }; + _thread.Start(); + } + + /// Raised once per effective change of or . + public event EventHandler? Changed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _stop.Set(); + // From a Changed handler the loop is still running on this thread and will observe the stop signal itself. + if (_thread == Thread.CurrentThread) return; + _thread.Join(); + _stop.Dispose(); + } + + private void Run() + { + using var personalize = Registry.CurrentUser.OpenSubKey(SystemTheme.PersonalizeKey); + using var dwm = Registry.CurrentUser.OpenSubKey(SystemTheme.DwmKey); + var keys = new[] { personalize, dwm }.OfType().ToArray(); + var signals = keys.Select(_ => new AutoResetEvent(false)).ToArray(); + try + { + for (var i = 0; i < keys.Length; i++) Arm(keys[i], signals[i]); + WaitHandle[] handles = [_stop, .. signals]; + var last = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor); + while (true) + { + var index = WaitHandle.WaitAny(handles); + if (index == 0) return; + // Re-arm before reading so a change landing in between still signals. + Arm(keys[index - 1], signals[index - 1]); + var now = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor); + if (now == last) continue; + last = now; + RaiseChanged(); + } + } + finally + { + foreach (var signal in signals) signal.Dispose(); + } + } + + private static void Arm(RegistryKey key, AutoResetEvent signal) + { + var result = RegNotifyChangeKeyValue(key.Handle, false, REG_NOTIFY_CHANGE_LAST_SET, signal.SafeWaitHandle, true); + if (result != 0) Log.Warning("theme", $"RegNotifyChangeKeyValue failed for {key.Name} (error {result})."); + } + + private void RaiseChanged() + { + try + { + Changed?.Invoke(this, EventArgs.Empty); + } + catch (Exception ex) + { + // An exception escaping this thread would terminate the process. + Log.Error("theme", "A theme Changed handler failed", ex); + } + } + + [LibraryImport("advapi32.dll")] + private static partial int RegNotifyChangeKeyValue( + SafeRegistryHandle key, + [MarshalAs(UnmanagedType.Bool)] bool watchSubtree, + uint notifyFilter, + SafeWaitHandle eventHandle, + [MarshalAs(UnmanagedType.Bool)] bool asynchronous); +} diff --git a/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs b/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs new file mode 100644 index 00000000..e6d0cd8b --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs @@ -0,0 +1,52 @@ +using Titano.Core.Windows.Window; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Window; + +public sealed class WindowTests +{ + private static readonly nint StaleWindow = 0x0BAD_F00D; + + [Test] + [WindowsOnly] + public void DwmCallsWithoutAValidWindowReturnFalse() + { + foreach (var window in new[] { (nint)0, StaleWindow }) + { + Assert.False(DwmWindow.SetDarkMode(window, true)); + Assert.False(DwmWindow.SetBackdrop(window, SystemBackdrop.Mica)); + Assert.False(DwmWindow.SetCornerPreference(window, WindowCornerPreference.Round)); + Assert.False(DwmWindow.SetCaptionColor(window, new RgbColor(0x20, 0x20, 0x20))); + Assert.False(DwmWindow.SetBorderColor(window, null)); + } + } + + [Test] + [WindowsOnly] + public void SystemThemeReadsWithoutThrowing() + { + Assert.DoesNotThrow(() => _ = SystemTheme.AppsUseLightTheme); + Assert.DoesNotThrow(() => _ = SystemTheme.AccentColor); + } + + [Test] + [WindowsOnly] + [Timeout(30_000)] + public void ThemeWatcherStartsAndStops() + { + var watcher = new SystemThemeWatcher(); + watcher.Changed += (_, _) => { }; + watcher.Dispose(); + watcher.Dispose(); + } + + [Test] + public void ColoursConvertBetweenWin32Layouts() + { + var accent = RgbColor.FromAbgr(0xFFD77800); + Assert.Equal(new RgbColor(0x00, 0x78, 0xD7), accent); + Assert.Equal("#0078D7", accent.ToString()); + Assert.Equal(0x00D77800u, accent.ToColorRef()); + Assert.Equal(accent, RgbColor.FromArgb(0xFF0078D7)); + } +} From e9cd17624c4677db8a36a6137ef656491dd48b50 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:46:40 +0000 Subject: [PATCH 036/188] feat(windows): add sleep blocker for long jobs SleepBlocker requests ES_CONTINUOUS | ES_SYSTEM_REQUIRED (optionally the display) from a dedicated thread, because the execution state belongs to the calling thread; disposing from any thread clears it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core.Windows/Power/SleepBlocker.cs | 55 +++++++++++++++++++ .../Power/SleepBlockerTests.cs | 27 +++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/Titano.Core.Windows/Power/SleepBlocker.cs create mode 100644 tests/Titano.Core.Windows.Tests/Power/SleepBlockerTests.cs diff --git a/src/Titano.Core.Windows/Power/SleepBlocker.cs b/src/Titano.Core.Windows/Power/SleepBlocker.cs new file mode 100644 index 00000000..13bc07f2 --- /dev/null +++ b/src/Titano.Core.Windows/Power/SleepBlocker.cs @@ -0,0 +1,55 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Power; + +/// +/// Keeps the system (and optionally the display) awake during a long job: SetThreadExecutionState with +/// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, cleared again on . The execution state belongs to the +/// calling thread, so each blocker owns a small dedicated thread; this keeps the request valid even when an async +/// job is disposed on a different pool thread than the one that started it. +/// +public sealed partial class SleepBlocker : IDisposable +{ + private const uint ES_SYSTEM_REQUIRED = 0x1; + private const uint ES_DISPLAY_REQUIRED = 0x2; + private const uint ES_CONTINUOUS = 0x80000000; + + private readonly ManualResetEventSlim _release = new(); + private readonly Thread _owner; + private int _disposed; + + /// Also keep the display on (e.g. while a preview plays). + public SleepBlocker(bool keepDisplayOn = false) + { + var flags = ES_CONTINUOUS | ES_SYSTEM_REQUIRED | (keepDisplayOn ? ES_DISPLAY_REQUIRED : 0); + using var applied = new ManualResetEventSlim(); + _owner = new Thread(() => + { + IsActive = SetThreadExecutionState(flags) != 0; + applied.Set(); + _release.Wait(); + SetThreadExecutionState(ES_CONTINUOUS); + }) + { + IsBackground = true, + Name = "Titano sleep blocker", + }; + _owner.Start(); + applied.Wait(); + } + + /// False when Windows rejected the request. + public bool IsActive { get; private set; } + + /// Restores normal sleep behaviour. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _release.Set(); + _owner.Join(); + _release.Dispose(); + } + + [LibraryImport("kernel32.dll")] + private static partial uint SetThreadExecutionState(uint flags); +} diff --git a/tests/Titano.Core.Windows.Tests/Power/SleepBlockerTests.cs b/tests/Titano.Core.Windows.Tests/Power/SleepBlockerTests.cs new file mode 100644 index 00000000..7de06e67 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Power/SleepBlockerTests.cs @@ -0,0 +1,27 @@ +using Titano.Core.Windows.Power; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Power; + +[WindowsOnly] +public sealed class SleepBlockerTests +{ + [Test] + [Timeout(10_000)] + public async Task BlocksUntilDisposedFromAnyThread() + { + var blocker = new SleepBlocker(); + Assert.True(blocker.IsActive); + // Disposing on another pool thread must still clear the request made by the owner thread. + await Task.Run(blocker.Dispose); + blocker.Dispose(); + } + + [Test] + [Timeout(10_000)] + public void DisplayVariantWorks() + { + using var blocker = new SleepBlocker(keepDisplayOn: true); + Assert.True(blocker.IsActive); + } +} From 016a06d147098aaba13bcb587ae19a8d317e8484 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:47:44 +0000 Subject: [PATCH 037/188] feat(codecs): add PNG decoder and ImageBuffer PNG encoding Every colour type and bit depth (1/2/4/8/16), PLTE + tRNS (palette alpha and colour keys), Adam7, all five filters, zlib via ZLibStream; CRC mismatches and truncated data are tolerated with warnings. PngEncoder gains an additive ImageBuffer overload (8/16-bit sRGB with sRGB chunk) and the Palette colour type for decoding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Png/PngDecoder.cs | 359 +++++++++++++++++++++ src/Titano.Core/Codecs/Png/PngEncoder.cs | 35 +- tests/Titano.Core.Tests/Codecs/PngTests.cs | 278 ++++++++++++++++ 3 files changed, 671 insertions(+), 1 deletion(-) create mode 100644 src/Titano.Core/Codecs/Png/PngDecoder.cs create mode 100644 tests/Titano.Core.Tests/Codecs/PngTests.cs diff --git a/src/Titano.Core/Codecs/Png/PngDecoder.cs b/src/Titano.Core/Codecs/Png/PngDecoder.cs new file mode 100644 index 00000000..72d74a2e --- /dev/null +++ b/src/Titano.Core/Codecs/Png/PngDecoder.cs @@ -0,0 +1,359 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Hashing; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Png; + +/// IHDR facts of a PNG stream. +public sealed record PngInfo(int Width, int Height, int BitDepth, PngColorType ColorType, bool Interlaced); + +/// Decoded PNG pixels: interleaved, top-down, palette and tRNS expanded. +public sealed class PngImage +{ + internal PngImage(PngInfo info, int channels, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList warnings) + { + Info = info; + Channels = channels; + Pixels8 = pixels8; + Pixels16 = pixels16; + Warnings = warnings; + } + + public PngInfo Info { get; } + public int Width => Info.Width; + public int Height => Info.Height; + + /// 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA (palette → RGB/RGBA; tRNS adds alpha). + public int Channels { get; } + + /// 8 (; 1/2/4-bit gray is scaled to 0..255) or 16 (). + public int BitDepth => Pixels16 is null ? 8 : 16; + + public byte[]? Pixels8 { get; } + public ushort[]? Pixels16 { get; } + + /// Recoverable problems (CRC mismatches, truncated or corrupt image data, unknown critical chunks). + public IReadOnlyList Warnings { get; } +} + +/// +/// PNG decoder: every colour type and bit depth (1/2/4/8/16), PLTE + tRNS, Adam7, all five filters, zlib through +/// . CRC mismatches are tolerated with a warning; damaged image data yields the rows decoded so +/// far plus a warning. Ancillary colour chunks (gAMA, iCCP, cHRM) are ignored: samples are taken as sRGB. +/// +public static class PngDecoder +{ + private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + private static readonly (int X, int Y, int Dx, int Dy)[] Adam7 = + [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]; + + public static PngInfo ReadInfo(ReadOnlySpan data) + { + if (data.Length < 33 || !data.StartsWith(Signature) || !data.Slice(12, 4).SequenceEqual("IHDR"u8)) + throw new InvalidDataException("PNG: missing signature or IHDR"); + return ParseHeader(data.Slice(16, 13)); + } + + /// Upper bound on width × height, checked before allocation. + public static PngImage Decode(ReadOnlySpan data, long maxPixels = 1L << 28) + { + var info = ReadInfo(data); + if ((long)info.Width * info.Height > maxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit"); + var warnings = new List(); + byte[]? palette = null; + byte[]? trns = null; + using var idat = new MemoryStream(); + var pos = 8; + var ended = false; + while (pos + 8 <= data.Length) + { + var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]); + var type = data.Slice(pos + 4, 4); + if (length > int.MaxValue || pos + 12 + (long)length > data.Length) + { + warnings.Add("PNG: truncated chunk"); + break; + } + var body = data.Slice(pos + 8, (int)length); + var crc = BinaryPrimitives.ReadUInt32BigEndian(data[(pos + 8 + (int)length)..]); + if (Crc32.Compute(data.Slice(pos + 4, 4 + (int)length)) != crc) warnings.Add($"PNG: CRC mismatch in {Name(type)}"); + pos += 12 + (int)length; + if (type.SequenceEqual("IDAT"u8)) + { + idat.Write(body); + } + else if (type.SequenceEqual("PLTE"u8)) + { + if (body.Length % 3 != 0 || body.Length > 768 || body.Length == 0) throw new InvalidDataException("PNG: bad PLTE"); + palette = body.ToArray(); + } + else if (type.SequenceEqual("tRNS"u8)) + { + trns = body.ToArray(); + } + else if (type.SequenceEqual("IEND"u8)) + { + ended = true; + break; + } + else if (!type.SequenceEqual("IHDR"u8) && (type[0] & 0x20) == 0) + { + warnings.Add($"PNG: unknown critical chunk {Name(type)} ignored"); + } + } + if (!ended) warnings.Add("PNG: missing IEND"); + if (idat.Length == 0) throw new InvalidDataException("PNG: no image data"); + if (info.ColorType == PngColorType.Palette && palette is null) throw new InvalidDataException("PNG: palette image without PLTE"); + + var layout = Layout.For(info, palette, trns); + idat.Position = 0; + using var z = new ZLibStream(idat, CompressionMode.Decompress); + return layout.Sixteen ? Decode16(info, layout, z, warnings) : Decode8(info, layout, z, warnings); + } + + /// Decodes into a linear-light buffer (samples are sRGB-encoded; alpha stays linear). + /// Return gray as three identical channels. + /// Keep alpha as a fourth channel (gray is then expanded). + public static ImageBuffer DecodeToLinear(ReadOnlySpan data, bool expandGray = false, bool keepAlpha = false) + { + var image = Decode(data); + var gray = image.Channels <= 2; + var hasAlpha = image.Channels is 2 or 4; + var output = keepAlpha && hasAlpha ? 4 : gray && !expandGray ? 1 : 3; + return image.Pixels8 is { } p8 + ? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Channels, outputChannels: output) + : PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Channels, outputChannels: output); + } + + private static string Name(ReadOnlySpan type) => string.Create(4, type.ToArray(), (s, t) => + { + for (var i = 0; i < 4; i++) s[i] = t[i] is >= 32 and < 127 ? (char)t[i] : '?'; + }); + + private static PngInfo ParseHeader(ReadOnlySpan h) + { + var width = BinaryPrimitives.ReadUInt32BigEndian(h); + var height = BinaryPrimitives.ReadUInt32BigEndian(h[4..]); + int depth = h[8], type = h[9]; + if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) throw new InvalidDataException("PNG: bad dimensions"); + var valid = type switch + { + 0 => depth is 1 or 2 or 4 or 8 or 16, + 3 => depth is 1 or 2 or 4 or 8, + 2 or 4 or 6 => depth is 8 or 16, + _ => false, + }; + if (!valid) throw new InvalidDataException($"PNG: invalid colour type {type} / bit depth {depth}"); + if (h[10] != 0 || h[11] != 0 || h[12] > 1) throw new InvalidDataException("PNG: unsupported compression, filter or interlace method"); + return new PngInfo((int)width, (int)height, depth, (PngColorType)type, h[12] == 1); + } + + /// Sample geometry of the stored scanlines and of the expanded output. + private sealed class Layout + { + public int SourceChannels, BitsPerPixel, BytesPerPixel, OutChannels; + public bool Sixteen; + public byte[]? Palette; + public byte[]? PaletteAlpha; + + /// tRNS colour key in source sample units (gray: 1 value, RGB: 3), or null. + public int[]? Key; + + public static Layout For(PngInfo info, byte[]? palette, byte[]? trns) + { + var l = new Layout + { + SourceChannels = info.ColorType switch + { + PngColorType.Gray or PngColorType.Palette => 1, + PngColorType.GrayAlpha => 2, + PngColorType.Rgb => 3, + _ => 4, + }, + Sixteen = info.BitDepth == 16, + }; + l.BitsPerPixel = l.SourceChannels * info.BitDepth; + l.BytesPerPixel = Math.Max(1, l.BitsPerPixel / 8); + l.OutChannels = l.SourceChannels; + switch (info.ColorType) + { + case PngColorType.Palette: + l.Palette = palette; + l.OutChannels = 3; + if (trns is { Length: > 0 }) + { + l.PaletteAlpha = new byte[256]; + Array.Fill(l.PaletteAlpha, (byte)255); + trns.AsSpan(0, Math.Min(trns.Length, 256)).CopyTo(l.PaletteAlpha); + l.OutChannels = 4; + } + break; + case PngColorType.Gray when trns is { Length: >= 2 }: + l.Key = [trns[0] << 8 | trns[1]]; + l.OutChannels = 2; + break; + case PngColorType.Rgb when trns is { Length: >= 6 }: + l.Key = [trns[0] << 8 | trns[1], trns[2] << 8 | trns[3], trns[4] << 8 | trns[5]]; + l.OutChannels = 4; + break; + } + return l; + } + } + + private static PngImage Decode8(PngInfo info, Layout l, Stream z, List warnings) + { + var pixels = new byte[checked((long)info.Width * info.Height * l.OutChannels)]; + var row = new byte[info.Width * l.OutChannels]; + Inflate(info, l, z, warnings, (raw, y, x0, dx, count) => + { + Expand8(raw, info.BitDepth, count, l, row); + for (int i = 0, x = x0; i < count; i++, x += dx) + { + row.AsSpan(i * l.OutChannels, l.OutChannels).CopyTo(pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels))); + } + }); + return new PngImage(info, l.OutChannels, pixels, null, warnings); + } + + private static PngImage Decode16(PngInfo info, Layout l, Stream z, List warnings) + { + var pixels = new ushort[checked((long)info.Width * info.Height * l.OutChannels)]; + Inflate(info, l, z, warnings, (raw, y, x0, dx, count) => + { + for (int i = 0, x = x0; i < count; i++, x += dx) + { + var dst = pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels), l.OutChannels); + var transparent = l.Key is not null; + for (var c = 0; c < l.SourceChannels; c++) + { + dst[c] = BinaryPrimitives.ReadUInt16BigEndian(raw[((i * l.SourceChannels + c) * 2)..]); + if (l.Key is not null && dst[c] != l.Key[c]) transparent = false; + } + if (l.Key is not null) dst[l.SourceChannels] = transparent ? (ushort)0 : ushort.MaxValue; + } + }); + return new PngImage(info, l.OutChannels, null, pixels, warnings); + } + + private delegate void RowHandler(ReadOnlySpan raw, int y, int x0, int dx, int count); + + /// Streams every (pass,) row out of zlib, unfilters it and hands the raw samples to . + private static void Inflate(PngInfo info, Layout l, Stream z, List warnings, RowHandler handle) + { + var passes = info.Interlaced ? Adam7 : [(0, 0, 1, 1)]; + var maxRow = (int)(((long)info.Width * l.BitsPerPixel + 7) / 8); + var line = new byte[maxRow + 1]; + var prior = new byte[maxRow]; + try + { + foreach (var (px, py, dx, dy) in passes) + { + if (px >= info.Width || py >= info.Height) continue; + var count = (info.Width - px + dx - 1) / dx; + var rowBytes = (int)(((long)count * l.BitsPerPixel + 7) / 8); + Array.Clear(prior); + for (var y = py; y < info.Height; y += dy) + { + var buffer = line.AsSpan(0, rowBytes + 1); + if (z.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) < buffer.Length) + { + warnings.Add("PNG: image data truncated"); + return; + } + if (buffer[0] > 4) + { + warnings.Add($"PNG: invalid filter type {buffer[0]}"); + return; + } + var row = buffer[1..]; + Unfilter(buffer[0], row, prior.AsSpan(0, rowBytes), l.BytesPerPixel); + handle(row, y, px, dx, count); + row.CopyTo(prior); + } + } + } + catch (InvalidDataException ex) + { + warnings.Add("PNG: corrupt image data: " + ex.Message); + } + } + + private static void Unfilter(int filter, Span row, ReadOnlySpan prior, int bpp) + { + switch (filter) + { + case 1: + for (var i = bpp; i < row.Length; i++) row[i] += row[i - bpp]; + break; + case 2: + for (var i = 0; i < row.Length; i++) row[i] += prior[i]; + break; + case 3: + for (var i = 0; i < bpp && i < row.Length; i++) row[i] += (byte)(prior[i] >> 1); + for (var i = bpp; i < row.Length; i++) row[i] += (byte)((row[i - bpp] + prior[i]) >> 1); + break; + case 4: + for (var i = 0; i < bpp && i < row.Length; i++) row[i] += prior[i]; + for (var i = bpp; i < row.Length; i++) row[i] += (byte)PngEncoder.Paeth(row[i - bpp], prior[i], prior[i - bpp]); + break; + } + } + + /// Expands one row of ≤ 8-bit samples (sub-byte gray, palette, tRNS key) to 8-bit output channels. + private static void Expand8(ReadOnlySpan raw, int depth, int count, Layout l, Span dst) + { + var oc = l.OutChannels; + if (depth == 8 && l.Palette is null && l.Key is null) + { + raw[..(count * oc)].CopyTo(dst); + return; + } + if (depth == 8 && l.Key is not null) + { + var sc = l.SourceChannels; + for (var i = 0; i < count; i++) + { + var opaque = false; + for (var c = 0; c < sc; c++) + { + var v = raw[i * sc + c]; + dst[i * oc + c] = v; + if (v != l.Key[c]) opaque = true; + } + dst[i * oc + sc] = opaque ? (byte)255 : (byte)0; + } + return; + } + // Sub-byte or palette: one sample per pixel, MSB first. + var mask = (1 << depth) - 1; + var scale = l.Palette is null ? 255 / mask : 1; + for (var i = 0; i < count; i++) + { + var bit = i * depth; + var v = (raw[bit >> 3] >> (8 - depth - (bit & 7))) & mask; + if (l.Palette is { } pal) + { + var o = dst.Slice(i * oc, oc); + if (3 * v + 2 < pal.Length) + { + o[0] = pal[3 * v]; + o[1] = pal[3 * v + 1]; + o[2] = pal[3 * v + 2]; + } + else + { + o[..3].Clear(); // out-of-range index: black, as libpng + } + if (oc == 4) o[3] = l.PaletteAlpha![v]; + } + else + { + dst[i * oc] = (byte)(v * scale); + if (l.Key is not null) dst[i * oc + 1] = v == l.Key[0] ? (byte)0 : (byte)255; + } + } + } +} diff --git a/src/Titano.Core/Codecs/Png/PngEncoder.cs b/src/Titano.Core/Codecs/Png/PngEncoder.cs index 6c9273fc..3fc68112 100644 --- a/src/Titano.Core/Codecs/Png/PngEncoder.cs +++ b/src/Titano.Core/Codecs/Png/PngEncoder.cs @@ -1,14 +1,16 @@ using System.Buffers.Binary; using System.IO.Compression; using Titano.Core.Hashing; +using Titano.Core.Imaging; namespace Titano.Core.Codecs.Png; -/// PNG colour types written by . +/// PNG colour types ( is decoded but never written by ). public enum PngColorType : byte { Gray = 0, Rgb = 2, + Palette = 3, GrayAlpha = 4, Rgba = 6, } @@ -29,6 +31,7 @@ public static class PngEncoder public static void Encode(Stream output, ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null) { if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth)); + if (colorType == PngColorType.Palette) throw new ArgumentException("Palette images are not written", nameof(colorType)); var channels = colorType switch { PngColorType.Gray => 1, @@ -60,6 +63,36 @@ public static class PngEncoder WriteChunk(output, "IEND", []); } + /// Encodes a linear-light buffer as sRGB-encoded PNG (1 channel → gray, 3 → RGB, 4 → RGBA with linear + /// alpha) and tags it with an sRGB chunk. + /// 8 or 16 bits per sample. + public static byte[] Encode(ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize) + { + using var ms = new MemoryStream(); + Encode(ms, image, bitDepth, level); + return ms.ToArray(); + } + + public static void Encode(Stream output, ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null) + { + if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth)); + var channels = image.Channels; + var colorType = channels switch { 1 => PngColorType.Gray, 3 => PngColorType.Rgb, _ => PngColorType.Rgba }; + byte[] pixels; + if (bitDepth == 8) + { + pixels = PixelConvert.ToInterleaved8(image, channels); + } + else + { + var words = PixelConvert.ToInterleaved16(image, channels); + pixels = new byte[words.Length * 2]; + for (var i = 0; i < words.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(pixels.AsSpan(2 * i), words[i]); + } + IEnumerable<(string Type, byte[] Data)> chunks = [("sRGB", [0]), .. extraChunks ?? []]; + Encode(output, pixels, image.Width, image.Height, colorType, bitDepth, level, chunks); + } + /// Filters every row (adaptive, minimum sum of absolute differences) and deflates the result. public static byte[] Compress(ReadOnlySpan pixels, int height, int stride, int bpp, CompressionLevel level) { diff --git a/tests/Titano.Core.Tests/Codecs/PngTests.cs b/tests/Titano.Core.Tests/Codecs/PngTests.cs new file mode 100644 index 00000000..636902a4 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/PngTests.cs @@ -0,0 +1,278 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Codecs.Png; +using Titano.Core.Imaging; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +public sealed class PngTests(TestContext context) +{ + [Theory] + [Case("png/adam7.png", false)] + [Case("png/rgb16.png", true)] + [Case("png/adam7-16.png", true)] + public void RgbFixturesMatchSource(string name, bool sixteen) + { + var image = PngDecoder.Decode(Fixture(name)); + Assert.Equal(3, image.Channels); + Assert.Empty(image.Warnings); + if (sixteen) Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, image.Pixels16!); + else Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Bytes, image.Pixels8!); + } + + [Theory] + [Case("gray1", 1)] + [Case("gray2", 1)] + [Case("gray4", 1)] + [Case("gray8", 1)] + [Case("graya", 2)] + [Case("palette4", 3)] + [Case("palette-adam7", 3)] + [Case("palette-trns", 4)] + [Case("rgba", 4)] + public void LibpngFixturesMatchReference(string name, int channels) + { + var image = PngDecoder.Decode(Fixture($"png/{name}.png")); + var reference = ReadPnm(Fixture($"png/{name}.pam")); + Assert.Equal(channels, image.Channels); + Assert.Empty(image.Warnings); + var pixels = image.Pixels8!; + for (var i = 0; i < image.Width * image.Height; i++) + { + for (var c = 0; c < channels; c++) + { + // ImageMagick expands gray to RGB in PAM; compare against its first channel. + var refChannel = reference.Channels == channels ? c : c == channels - 1 && channels == 2 ? reference.Channels - 1 : 0; + if (pixels[i * channels + c] != reference.Samples[i * reference.Channels + refChannel]) + Assert.Fail($"{name}: pixel {i} channel {c}: {pixels[i * channels + c]} vs {reference.Samples[i * reference.Channels + refChannel]}"); + } + } + } + + [Theory] + [Case(PngColorType.Gray, 8)] + [Case(PngColorType.Gray, 16)] + [Case(PngColorType.GrayAlpha, 8)] + [Case(PngColorType.GrayAlpha, 16)] + [Case(PngColorType.Rgb, 8)] + [Case(PngColorType.Rgb, 16)] + [Case(PngColorType.Rgba, 8)] + [Case(PngColorType.Rgba, 16)] + public void EncoderRoundTrips(PngColorType type, int depth) + { + const int w = 37, h = 21; + var channels = type switch { PngColorType.Gray => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 }; + var bytes = new byte[w * h * channels * depth / 8]; + new Random(depth * 10 + channels).NextBytes(bytes.AsSpan(bytes.Length / 2)); + for (var i = 0; i < bytes.Length / 2; i++) bytes[i] = (byte)(i * 7); + var image = PngDecoder.Decode(PngEncoder.Encode(bytes, w, h, type, depth)); + Assert.Equal(channels, image.Channels); + if (depth == 8) + { + Assert.SequenceEqual(bytes, image.Pixels8!); + } + else + { + var words = new ushort[bytes.Length / 2]; + for (var i = 0; i < words.Length; i++) words[i] = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2 * i)); + Assert.SequenceEqual(words, image.Pixels16!); + } + } + + [Theory] + [Case(0)] + [Case(1)] + [Case(2)] + [Case(3)] + [Case(4)] + public void EveryFilterTypeDecodes(int filter) + { + const int w = 23, h = 9; + var rgb = TestCard(w, h); + var png = RawPng(w, h, PngColorType.Rgb, 8, rgb, filter); + Assert.SequenceEqual(rgb, PngDecoder.Decode(png).Pixels8!); + var rgba16 = new byte[w * h * 8]; + new Random(filter).NextBytes(rgba16); + var wide = PngDecoder.Decode(RawPng(w, h, PngColorType.Rgba, 16, rgba16, filter, interlaced: true)); + Assert.Equal((ushort)(rgba16[8 * 5] << 8 | rgba16[8 * 5 + 1]), wide.Pixels16![4 * 5]); + } + + [Theory] + [Case(1)] + [Case(2)] + [Case(4)] + public void SubBytePaletteWithTransparency(int depth) + { + const int w = 13, h = 7; + var colours = 1 << depth; + var indices = new byte[w * h]; + for (var i = 0; i < indices.Length; i++) indices[i] = (byte)(i * 5 % colours); + var packed = Pack(indices, w, h, depth); + var plte = new byte[colours * 3]; + for (var i = 0; i < plte.Length; i++) plte[i] = (byte)(i * 37); + var trns = new byte[] { 0, 128 }; + var png = RawPng(w, h, PngColorType.Palette, depth, packed, 4, interlaced: depth == 2, ("PLTE", plte), ("tRNS", trns)); + var image = PngDecoder.Decode(png); + Assert.Equal(4, image.Channels); + for (var i = 0; i < indices.Length; i++) + { + int idx = indices[i]; + Assert.Equal(plte[3 * idx + 1], image.Pixels8![4 * i + 1]); + Assert.Equal(idx < trns.Length ? trns[idx] : (byte)255, image.Pixels8[4 * i + 3]); + } + } + + [Test] + public void ColourKeyTransparency() + { + var gray = PngDecoder.Decode(RawPng(4, 1, PngColorType.Gray, 4, [0x0F, 0x3F], 0, false, ("tRNS", [0, 3]))); + Assert.SequenceEqual(new byte[] { 0, 255, 255, 255, 51, 0, 255, 255 }, gray.Pixels8!); + var rgb16 = new byte[12]; + rgb16[1] = 9; + var keyed = PngDecoder.Decode(RawPng(2, 1, PngColorType.Rgb, 16, rgb16, 1, false, ("tRNS", [0, 0, 0, 0, 0, 0]))); + Assert.Equal(4, keyed.Channels); + Assert.Equal(ushort.MaxValue, keyed.Pixels16![3]); + Assert.Equal((ushort)0, keyed.Pixels16[7]); + } + + [Test] + public void CrcMismatchIsToleratedWithWarning() + { + var png = PngEncoder.Encode(TestCard(8, 8), 8, 8, PngColorType.Rgb); + png[^13] ^= 0xFF; // last byte of the IDAT CRC (IEND is the final 12 bytes) + var image = PngDecoder.Decode(png); + Assert.SequenceEqual(TestCard(8, 8), image.Pixels8!); + Assert.Contains("CRC", string.Join(";", image.Warnings)); + } + + [Test] + public void ImageBufferRoundTripsAtSixteenBits() + { + using var image = new ImageBuffer(33, 17, 4); + for (var c = 0; c < 4; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 1) % 97) / 96f; + } + var png = PngEncoder.Encode(image, 16); + Assert.True(png.AsSpan().IndexOf("sRGB"u8) > 0, "sRGB chunk"); + using var back = PngDecoder.DecodeToLinear(png, keepAlpha: true); + Assert.Equal(4, back.Channels); + for (var i = 0; i < image.Data.Length; i += 13) Assert.Approximately(image.Data[i], back.Data[i], 2e-4); + using var eight = PngDecoder.DecodeToLinear(PngEncoder.Encode(image)); + Assert.Equal(3, eight.Channels); + Assert.Approximately(image[1, 5, 5], eight[1, 5, 5], 0.01); + } + + [Theory] + [Case("png/adam7.png")] + [Case("png/palette-trns.png")] + [Case("png/gray2.png")] + [Case("png/adam7-16.png")] + public void FuzzedInputOnlyThrowsInvalidData(string name) + { + int ok = 0, rejected = 0; + foreach (var input in Corruptions(Fixture(name), 150, seed: name.Length)) + { + try + { + var image = PngDecoder.Decode(input); + Assert.True(image.Width > 0); + ok++; + } + catch (InvalidDataException) + { + rejected++; + } + } + context.Log($"{name}: {ok} decoded, {rejected} rejected"); + } + + [Test] + public void StructuralErrorsAreRejected() + { + Assert.Throws(() => PngDecoder.Decode([])); + Assert.Throws(() => PngDecoder.Decode(Fixture("jpeg/b420.jpg"))); + var palette = Fixture("png/palette4.png"); + var plte = palette.AsSpan().IndexOf("PLTE"u8); + palette[plte] = (byte)'X'; // drop the palette (and make an unknown critical chunk) + Assert.Throws(() => PngDecoder.Decode(palette)); + Assert.Throws(() => PngEncoder.Encode(new byte[4], 2, 2, PngColorType.Palette)); + } + + /// Builds a PNG with every row filtered by (test-side writer). + private static byte[] RawPng(int w, int h, PngColorType type, int depth, byte[] rows, int filter, bool interlaced = false, params (string Type, byte[] Data)[] chunks) + { + var channels = type switch { PngColorType.Gray or PngColorType.Palette => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 }; + var bits = channels * depth; + var bpp = Math.Max(1, bits / 8); + var stride = (w * bits + 7) / 8; + var passes = interlaced + ? new[] { (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2) } + : [(0, 0, 1, 1)]; + using var raw = new MemoryStream(); + foreach (var (px, py, dx, dy) in passes) + { + if (px >= w || py >= h) continue; + var count = (w - px + dx - 1) / dx; + var rowBytes = (count * bits + 7) / 8; + var prev = new byte[rowBytes]; + for (var y = py; y < h; y += dy) + { + // Gather this pass's pixels (bit-exact copy of their samples). + var row = new byte[rowBytes]; + for (int i = 0, x = px; i < count; i++, x += dx) + { + for (var b = 0; b < bits; b++) + { + var src = y * stride * 8 + x * bits + b; + if ((rows[src >> 3] >> (7 - (src & 7)) & 1) != 0) row[(i * bits + b) >> 3] |= (byte)(0x80 >> ((i * bits + b) & 7)); + } + } + raw.WriteByte((byte)filter); + for (var i = 0; i < rowBytes; i++) + { + int a = i >= bpp ? row[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0; + var predicted = filter switch { 0 => 0, 1 => a, 2 => b, 3 => (a + b) >> 1, _ => PngEncoder.Paeth(a, b, c) }; + raw.WriteByte((byte)(row[i] - predicted)); + } + prev = row; + } + } + using var z = new MemoryStream(); + using (var deflate = new ZLibStream(z, CompressionLevel.Fastest, leaveOpen: true)) deflate.Write(raw.ToArray()); + using var png = new MemoryStream(); + png.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + var ihdr = new byte[13]; + BinaryPrimitives.WriteInt32BigEndian(ihdr, w); + BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), h); + ihdr[8] = (byte)depth; + ihdr[9] = (byte)type; + ihdr[12] = (byte)(interlaced ? 1 : 0); + PngEncoder.WriteChunk(png, "IHDR", ihdr); + foreach (var (t, d) in chunks) PngEncoder.WriteChunk(png, t, d); + var compressed = z.ToArray(); + var half = compressed.Length / 2; + PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(0, half)); + PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(half)); + PngEncoder.WriteChunk(png, "IEND", []); + return png.ToArray(); + } + + private static byte[] Pack(byte[] values, int w, int h, int depth) + { + var stride = (w * depth + 7) / 8; + var packed = new byte[stride * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var bit = x * depth; + packed[y * stride + (bit >> 3)] |= (byte)(values[y * w + x] << (8 - depth - (bit & 7))); + } + } + return packed; + } +} From 2d67e0a3bafe3d65966b8e56b6c1cf5d02733111 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:49:28 +0000 Subject: [PATCH 038/188] docs: record Windows interop decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index b1074064..236d3f8e 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -24,3 +24,9 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Release notes are generated by `Titano.Tools changelog` from `git log` piped on stdin. | Tool spawning git | Keeps the tool free of external process calls. | | 2026-10-02 | CI `dotnet format` gate checks whitespace formatting. | Full style/analyzer verification | Analyzer rules already fail the build (warnings as errors); style preferences stay suggestions. | | 2026-10-02 | Test runner exits 0 for a project with no tests and 2 when a filter matches nothing. | Always 2 | Empty projects during bootstrap are not failures; mistyped filters are. | +| 2026-10-02 | COM via `[ComImport]` + explicit `ReleaseComObject`; flat APIs via `LibraryImport`. | `[GeneratedComInterface]` | Deterministic release keeps files unlocked; the apps are not trimmed. | +| 2026-10-02 | WIC decodes to 64bppRGBA and linearises with the exact sRGB LUT (128bpp float only for float sources). | Always 128bppPRGBAFloat | WIC's integer→float gamma is not the exact sRGB curve and premultiplication darkens edges. | +| 2026-10-02 | Exif orientation is applied in managed code while de-interleaving. | `IWICBitmapFlipRotator` | Microsoft documents quadratic behaviour of the flip-rotator over scanline decoders. | +| 2026-10-02 | Volume watcher uses a hidden top-level tool window plus 3 s polling. | Message-only window | Message-only windows do not receive broadcast WM_DEVICECHANGE. | +| 2026-10-02 | Camera RAW is "native" via WIC only when the Raw Image Extension package is installed. | Decoder CLSID alone | The in-box RAW codec shares the CLSID but only reads embedded previews. | +| 2026-10-02 | HEVC/AV1 decoder presence is detected with `MFTEnumEx`. | Store package names | Also covers OEM and hardware decoders. | From 71c0113f5fdce5c7045bb37ddb8195b8dea62463 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:49:30 +0000 Subject: [PATCH 039/188] feat(gif): add animated GIF encoder with variance-split palettes, dithering and frame differencing Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Gif/GifEncoder.cs | 394 ++++++++++++++++++ src/Titano.Core/Codecs/Gif/GifLzw.cs | 104 +++++ src/Titano.Core/Codecs/Gif/GifPalette.cs | 216 ++++++++++ .../Video/GifEncoderTests.cs | 255 ++++++++++++ .../Titano.Core.Tests/Video/GifTestDecoder.cs | 197 +++++++++ 5 files changed, 1166 insertions(+) create mode 100644 src/Titano.Core/Codecs/Gif/GifEncoder.cs create mode 100644 src/Titano.Core/Codecs/Gif/GifLzw.cs create mode 100644 src/Titano.Core/Codecs/Gif/GifPalette.cs create mode 100644 tests/Titano.Core.Tests/Video/GifEncoderTests.cs create mode 100644 tests/Titano.Core.Tests/Video/GifTestDecoder.cs diff --git a/src/Titano.Core/Codecs/Gif/GifEncoder.cs b/src/Titano.Core/Codecs/Gif/GifEncoder.cs new file mode 100644 index 00000000..fa754467 --- /dev/null +++ b/src/Titano.Core/Codecs/Gif/GifEncoder.cs @@ -0,0 +1,394 @@ +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Gif; + +/// Where GIF frames take their colours from. +public enum GifPaletteMode +{ + /// One palette for the whole animation, built from the first frames (or supplied). + Global, + + /// A palette per frame, built from that frame. + Local, +} + +/// Options of . +public sealed record GifEncoderOptions +{ + /// NETSCAPE2.0 loop count: 0 loops forever; null plays once (no loop extension). + public int? LoopCount { get; init; } = 0; + + /// Serpentine Floyd–Steinberg error diffusion. + public bool Dither { get; init; } = true; + + /// Unchanged pixels become transparent and frames are cropped to the changed area. + public bool FrameDifferencing { get; init; } = true; + + /// Largest per-channel difference (8-bit) between a pixel and its value when last drawn that still counts as unchanged. + public int DifferenceThreshold { get; init; } = 2; + + public GifPaletteMode PaletteMode { get; init; } = GifPaletteMode.Global; + + /// Frames buffered to build the global palette when is not supplied. + public int PaletteSampleFrames { get; init; } = 8; + + /// Optional global palette as RGB triples (see ). + public byte[]? Palette { get; init; } + + /// Colours per palette, 2–256 (one is reserved for transparency when differencing). + public int MaxColors { get; init; } = 256; +} + +/// +/// Animated GIF89a encoder. Frames arrive one by one as linear-light s (converted to +/// 8-bit sRGB) or 8-bit sRGB RGB bytes, with durations in 90 kHz ticks. Delays are rounded on the cumulative +/// timeline so the total duration is exact to the centisecond; identical frames merge into one longer frame. +/// The output stream is not disposed. +/// +public sealed class GifEncoder +{ + private const string LogCategory = "GifEncoder"; + private const int PaletteSamples = 1 << 18; + + private readonly Stream _output; + private readonly int _width; + private readonly int _height; + private readonly GifEncoderOptions _options; + private readonly List<(byte[] Rgb, long Duration)> _sampling = []; + private byte[]? _globalPalette; + private GifPalette.Map? _globalMap; + private byte[]? _canvas; + private byte[]? _drawn; + private PendingFrame? _pending; + private long _time; + private bool _headerWritten; + private bool _warnedShortDelay; + private bool _completed; + + public GifEncoder(Stream output, int width, int height, GifEncoderOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + if (width is <= 0 or > ushort.MaxValue || height is <= 0 or > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(width), "GIF sizes are 1–65535"); + _options = options ?? new GifEncoderOptions(); + if (_options.MaxColors is < 2 or > 256) throw new ArgumentOutOfRangeException(nameof(options), "MaxColors must be 2–256"); + if (_options.Palette is { } p && (p.Length % 3 != 0 || p.Length / 3 > PaletteBudget || p.Length == 0)) + throw new ArgumentException("Palette must hold 1 to MaxColors (minus the transparent slot) RGB triples", nameof(options)); + _output = output; + _width = width; + _height = height; + if (_options.PaletteMode == GifPaletteMode.Global && _options.Palette is { } palette) SetGlobalPalette(palette); + } + + /// Frames written to the file so far (identical consecutive frames count once). + public int FrameCount { get; private set; } + + /// Builds a palette (RGB triples) from sample frames, e.g. spread across a sequence. + public static byte[] BuildPalette(IEnumerable frames, int maxColors = 255) + { + using var ms = new MemoryStream(); + foreach (var frame in frames) ms.Write(Subsample(ToRgb(frame), frame.Width * frame.Height, PaletteSamples / 8)); + return GifPalette.Build(ms.ToArray(), maxColors); + } + + /// Adds a linear-light frame (alpha ignored) shown for ticks. + public void AddFrame(ImageBuffer frame, long duration90k) + { + if (frame.Width != _width || frame.Height != _height) throw new ArgumentException("Frame size differs from the animation size", nameof(frame)); + AddRgb(ToRgb(frame), duration90k); + } + + /// Adds an interleaved 8-bit sRGB frame. + public void AddFrame(ReadOnlySpan rgb24, long duration90k) + { + if (rgb24.Length != _width * _height * 3) throw new ArgumentException("Expected width × height × 3 bytes", nameof(rgb24)); + AddRgb(rgb24.ToArray(), duration90k); + } + + /// Writes the remaining frames and the trailer. + public void Complete() + { + if (_completed) throw new InvalidOperationException("The encoder is already complete"); + if (_globalMap is null && _options.PaletteMode == GifPaletteMode.Global) FlushSampling(); + if (!_headerWritten) throw new InvalidOperationException("No frames were added"); + Emit(_time); + _output.WriteByte(0x3B); + _output.Flush(); + _completed = true; + } + + private int PaletteBudget => _options.FrameDifferencing ? _options.MaxColors - 1 : _options.MaxColors; + + private void AddRgb(byte[] rgb, long duration) + { + if (_completed) throw new InvalidOperationException("The encoder is complete"); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration); + if (_options.PaletteMode == GifPaletteMode.Global && _globalMap is null) + { + _sampling.Add((rgb, duration)); + if (_sampling.Count >= Math.Max(1, _options.PaletteSampleFrames)) FlushSampling(); + return; + } + EncodeFrame(rgb, duration); + } + + private void FlushSampling() + { + if (_sampling.Count == 0) return; + using var ms = new MemoryStream(); + foreach (var (rgb, _) in _sampling) ms.Write(Subsample(rgb, _width * _height, PaletteSamples / _sampling.Count)); + SetGlobalPalette(GifPalette.Build(ms.ToArray(), PaletteBudget)); + foreach (var (rgb, duration) in _sampling) EncodeFrame(rgb, duration); + _sampling.Clear(); + } + + private void SetGlobalPalette(byte[] palette) + { + _globalPalette = palette; + _globalMap = new GifPalette.Map(palette); + } + + private sealed record PendingFrame(long Start, int Left, int Top, int Width, int Height, byte[]? LocalPalette, int Transparent, byte[] Indices, int TableBits); + + private void EncodeFrame(byte[] rgb, long duration) + { + byte[] palette; + GifPalette.Map map; + if (_options.PaletteMode == GifPaletteMode.Local) + { + palette = GifPalette.Build(Subsample(rgb, _width * _height, PaletteSamples), PaletteBudget); + map = new GifPalette.Map(palette); + } + else + { + palette = _globalPalette!; + map = _globalMap!; + } + var colors = palette.Length / 3; + var differencing = _options.FrameDifferencing && _canvas is not null; + var transparent = _options.FrameDifferencing ? colors : -1; + + var indices = new byte[_width * _height]; + var changed = Quantize(rgb, palette, map, indices, differencing); + var (left, top, right, bottom) = differencing ? Bounds(changed) : (0, 0, _width - 1, _height - 1); + if (right < left) + { + // Nothing visible changed: the previous frame simply stays longer. + _time += duration; + return; + } + + _canvas ??= new byte[_width * _height * 3]; + var w = right - left + 1; + var h = bottom - top + 1; + var cropped = new byte[w * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var i = (top + y) * _width + left + x; + if (differencing && !changed[i]) + { + cropped[y * w + x] = (byte)transparent; + continue; + } + var index = indices[i]; + cropped[y * w + x] = index; + _canvas[i * 3] = palette[index * 3]; + _canvas[i * 3 + 1] = palette[index * 3 + 1]; + _canvas[i * 3 + 2] = palette[index * 3 + 2]; + } + } + + if (!_headerWritten) WriteHeader(); + Emit(_time); + var tableBits = TableBits(colors + (transparent >= 0 ? 1 : 0)); + _pending = new PendingFrame(_time, left, top, w, h, _options.PaletteMode == GifPaletteMode.Local ? palette : null, + differencing ? transparent : -1, cropped, tableBits); + _time += duration; + } + + /// + /// Maps the frame to palette indices with optional serpentine Floyd–Steinberg diffusion. With a previous canvas, + /// pixels whose source stays within the threshold of the source they were last drawn from keep the displayed + /// colour and pass no error on, so static areas keep their dither pattern while other regions change. + /// + private bool[] Quantize(byte[] rgb, byte[] palette, GifPalette.Map map, byte[] indices, bool differencing) + { + var changed = new bool[_width * _height]; + _drawn ??= new byte[rgb.Length]; + var dither = _options.Dither; + var threshold = _options.DifferenceThreshold; + var current = new float[(_width + 2) * 3]; + var next = new float[(_width + 2) * 3]; + for (var y = 0; y < _height; y++) + { + var reverse = dither && (y & 1) == 1; + var step = reverse ? -1 : 1; + for (var n = 0; n < _width; n++) + { + var x = reverse ? _width - 1 - n : n; + var i = y * _width + x; + var p = i * 3; + if (differencing + && Math.Abs(rgb[p] - _drawn[p]) <= threshold && Math.Abs(rgb[p + 1] - _drawn[p + 1]) <= threshold && Math.Abs(rgb[p + 2] - _drawn[p + 2]) <= threshold) + { + continue; + } + var e = (x + 1) * 3; + var r = Math.Clamp(rgb[p] + current[e], 0f, 255f); + var g = Math.Clamp(rgb[p + 1] + current[e + 1], 0f, 255f); + var b = Math.Clamp(rgb[p + 2] + current[e + 2], 0f, 255f); + var index = map.Nearest((int)(r + 0.5f), (int)(g + 0.5f), (int)(b + 0.5f)); + int outR = palette[index * 3], outG = palette[index * 3 + 1], outB = palette[index * 3 + 2]; + indices[i] = (byte)index; + changed[i] = !differencing || outR != _canvas![p] || outG != _canvas[p + 1] || outB != _canvas[p + 2]; + _drawn[p] = rgb[p]; + _drawn[p + 1] = rgb[p + 1]; + _drawn[p + 2] = rgb[p + 2]; + if (!dither) continue; + var er = r - outR; + var eg = g - outG; + var eb = b - outB; + var ahead = e + step * 3; + var behind = e - step * 3; + current[ahead] += er * (7 / 16f); + current[ahead + 1] += eg * (7 / 16f); + current[ahead + 2] += eb * (7 / 16f); + next[behind] += er * (3 / 16f); + next[behind + 1] += eg * (3 / 16f); + next[behind + 2] += eb * (3 / 16f); + next[e] += er * (5 / 16f); + next[e + 1] += eg * (5 / 16f); + next[e + 2] += eb * (5 / 16f); + next[ahead] += er * (1 / 16f); + next[ahead + 1] += eg * (1 / 16f); + next[ahead + 2] += eb * (1 / 16f); + } + (current, next) = (next, current); + Array.Clear(next); + } + return changed; + } + + private (int Left, int Top, int Right, int Bottom) Bounds(bool[] changed) + { + int left = _width, top = _height, right = -1, bottom = -1; + for (var y = 0; y < _height; y++) + { + for (var x = 0; x < _width; x++) + { + if (!changed[y * _width + x]) continue; + left = Math.Min(left, x); + right = Math.Max(right, x); + top = Math.Min(top, y); + bottom = y; + } + } + return (left, top, right, bottom); + } + + private void WriteHeader() + { + _output.Write("GIF89a"u8); + Span screen = stackalloc byte[7]; + screen[0] = (byte)_width; + screen[1] = (byte)(_width >> 8); + screen[2] = (byte)_height; + screen[3] = (byte)(_height >> 8); + var globalBits = 0; + if (_globalPalette is not null) + { + globalBits = TableBits(_globalPalette.Length / 3 + (_options.FrameDifferencing ? 1 : 0)); + screen[4] = (byte)(0x80 | 0x70 | (globalBits - 1)); + } + _output.Write(screen); + if (_globalPalette is not null) WriteColorTable(_globalPalette, globalBits); + if (_options.LoopCount is { } loops) + { + _output.Write([0x21, 0xFF, 0x0B]); + _output.Write("NETSCAPE2.0"u8); + _output.Write([0x03, 0x01, (byte)loops, (byte)(loops >> 8), 0x00]); + } + _headerWritten = true; + } + + /// Writes the pending frame with the delay up to (cumulative rounding keeps the total exact). + private void Emit(long end) + { + if (_pending is not { } frame) return; + var delay = (int)(Centiseconds(end) - Centiseconds(frame.Start)); + if (delay > ushort.MaxValue) + { + Log.Warning(LogCategory, "Frame delay above 655 s clamped"); + delay = ushort.MaxValue; + } + if (delay < 2 && !_warnedShortDelay) + { + Log.Warning(LogCategory, "Frame delays below 2 cs are slowed down by most viewers"); + _warnedShortDelay = true; + } + + Span gce = [0x21, 0xF9, 0x04, (byte)(1 << 2 | (frame.Transparent >= 0 ? 1 : 0)), (byte)delay, (byte)(delay >> 8), (byte)Math.Max(frame.Transparent, 0), 0x00]; + _output.Write(gce); + Span descriptor = + [ + 0x2C, (byte)frame.Left, (byte)(frame.Left >> 8), (byte)frame.Top, (byte)(frame.Top >> 8), + (byte)frame.Width, (byte)(frame.Width >> 8), (byte)frame.Height, (byte)(frame.Height >> 8), + frame.LocalPalette is null ? (byte)0 : (byte)(0x80 | (frame.TableBits - 1)), + ]; + _output.Write(descriptor); + if (frame.LocalPalette is not null) WriteColorTable(frame.LocalPalette, frame.TableBits); + GifLzw.Encode(frame.Indices, Math.Max(2, frame.TableBits), _output); + FrameCount++; + _pending = null; + } + + private void WriteColorTable(byte[] palette, int bits) + { + var table = new byte[3 << bits]; + palette.CopyTo(table, 0); + _output.Write(table); + } + + private static long Centiseconds(long ticks90k) => (ticks90k + 450) / 900; + + /// Colour table size exponent (1–8) holding entries. + private static int TableBits(int entries) + { + var bits = 1; + while (1 << bits < entries) bits++; + return bits; + } + + private static byte[] ToRgb(ImageBuffer frame) + { + var n = frame.Width * frame.Height; + var rgb = new byte[n * 3]; + var r = frame.Plane(0); + var g = frame.Channels >= 3 ? frame.Plane(1) : r; + var b = frame.Channels >= 3 ? frame.Plane(2) : r; + for (var i = 0; i < n; i++) + { + rgb[i * 3] = ColorSpace.Encode8(r[i]); + rgb[i * 3 + 1] = ColorSpace.Encode8(g[i]); + rgb[i * 3 + 2] = ColorSpace.Encode8(b[i]); + } + return rgb; + } + + /// Every n-th pixel so at most about pixels feed the palette (deterministic). + private static byte[] Subsample(byte[] rgb, int pixels, int budget) + { + var stride = Math.Max(1, pixels / Math.Max(budget, 4096)); + if (stride == 1) return rgb; + var result = new byte[(pixels + stride - 1) / stride * 3]; + for (int i = 0, o = 0; i < pixels; i += stride, o += 3) + { + result[o] = rgb[i * 3]; + result[o + 1] = rgb[i * 3 + 1]; + result[o + 2] = rgb[i * 3 + 2]; + } + return result; + } +} diff --git a/src/Titano.Core/Codecs/Gif/GifLzw.cs b/src/Titano.Core/Codecs/Gif/GifLzw.cs new file mode 100644 index 00000000..38fba552 --- /dev/null +++ b/src/Titano.Core/Codecs/Gif/GifLzw.cs @@ -0,0 +1,104 @@ +namespace Titano.Core.Codecs.Gif; + +/// GIF variable-length LZW encoder (GIF89a appendix F): clear/end codes, 12-bit cap, 255-byte sub-blocks. +internal static class GifLzw +{ + private const int MaxCode = 4096; + private const int TableSize = 8192; // power of two > MaxCode for open addressing + + /// Writes the LZW minimum code size, the data sub-blocks and the block terminator. + public static void Encode(ReadOnlySpan indices, int minCodeSize, Stream output) + { + output.WriteByte((byte)minCodeSize); + var writer = new BlockWriter(output); + var clear = 1 << minCodeSize; + var end = clear + 1; + var keys = new int[TableSize]; + var codes = new short[TableSize]; + Array.Fill(keys, -1); + var next = end + 1; + var codeSize = minCodeSize + 1; + writer.Write(clear, codeSize); + if (indices.IsEmpty) + { + writer.Write(end, codeSize); + writer.Finish(); + return; + } + + int prefix = indices[0]; + for (var i = 1; i < indices.Length; i++) + { + int k = indices[i]; + var key = prefix << 8 | k; + var slot = (int)(((uint)key * 0x9E3779B1u) >> 19); // 13 bits: 0..TableSize-1 + while (keys[slot] != -1 && keys[slot] != key) slot = (slot + 1) & (TableSize - 1); + if (keys[slot] == key) + { + prefix = codes[slot]; + continue; + } + writer.Write(prefix, codeSize); + if (next == MaxCode) + { + // Table full: restart the dictionary (the clear code is still written at 12 bits). + writer.Write(clear, codeSize); + Array.Fill(keys, -1); + next = end + 1; + codeSize = minCodeSize + 1; + } + else + { + if (next >= 1 << codeSize) codeSize++; + keys[slot] = key; + codes[slot] = (short)next++; + } + prefix = k; + } + writer.Write(prefix, codeSize); + writer.Write(end, codeSize); + writer.Finish(); + } + + /// Packs codes LSB-first into sub-blocks of at most 255 bytes. + private sealed class BlockWriter(Stream output) + { + private readonly byte[] _block = new byte[256]; + private int _length; + private ulong _bits; + private int _count; + + public void Write(int code, int size) + { + _bits |= (ulong)code << _count; + _count += size; + while (_count >= 8) + { + Put((byte)_bits); + _bits >>= 8; + _count -= 8; + } + } + + public void Finish() + { + if (_count > 0) Put((byte)_bits); + Flush(); + output.WriteByte(0); + } + + private void Put(byte b) + { + _block[1 + _length++] = b; + if (_length == 255) Flush(); + } + + private void Flush() + { + if (_length == 0) return; + _block[0] = (byte)_length; + output.Write(_block, 0, _length + 1); + _length = 0; + } + } +} diff --git a/src/Titano.Core/Codecs/Gif/GifPalette.cs b/src/Titano.Core/Codecs/Gif/GifPalette.cs new file mode 100644 index 00000000..d6f29823 --- /dev/null +++ b/src/Titano.Core/Codecs/Gif/GifPalette.cs @@ -0,0 +1,216 @@ +namespace Titano.Core.Codecs.Gif; + +/// Palette construction (exact or median cut) and nearest-colour mapping for GIF frames. +internal static class GifPalette +{ + private const int WeightR = 2, WeightG = 4, WeightB = 3; + + /// + /// Builds at most colours (RGB triples) from interleaved RGB samples: the exact set when + /// it is small enough, otherwise median cut over a 5-bit-per-channel histogram where, as in Wu's quantiser, the box + /// with the largest squared error is split at the position that minimises the summed error of both halves. + /// + public static byte[] Build(ReadOnlySpan rgb, int maxColors) + { + var distinct = new HashSet(); + for (var i = 0; i + 2 < rgb.Length && distinct.Count <= maxColors; i += 3) distinct.Add(rgb[i] << 16 | rgb[i + 1] << 8 | rgb[i + 2]); + if (distinct.Count <= maxColors) + { + var exact = distinct.Order().ToArray(); + var palette = new byte[exact.Length * 3]; + for (var i = 0; i < exact.Length; i++) + { + palette[i * 3] = (byte)(exact[i] >> 16); + palette[i * 3 + 1] = (byte)(exact[i] >> 8); + palette[i * 3 + 2] = (byte)exact[i]; + } + return palette; + } + return MedianCut(rgb, maxColors); + } + + /// Population moments of a set of histogram bins. + private struct Moments + { + public long N, R, G, B, Squares; + + public void Add(in Moments m) + { + N += m.N; + R += m.R; + G += m.G; + B += m.B; + Squares += m.Squares; + } + + public readonly Moments Minus(in Moments m) => new() { N = N - m.N, R = R - m.R, G = G - m.G, B = B - m.B, Squares = Squares - m.Squares }; + + /// Sum of squared distances to the mean colour. + public readonly double Error => N == 0 ? 0 : Squares - ((double)R * R + (double)G * G + (double)B * B) / N; + } + + private readonly record struct Box(int Start, int End, Moments Moments); + + private static byte[] MedianCut(ReadOnlySpan rgb, int maxColors) + { + var bins = new Moments[1 << 15]; + for (var i = 0; i + 2 < rgb.Length; i += 3) + { + int r = rgb[i], g = rgb[i + 1], b = rgb[i + 2]; + ref var m = ref bins[(r >> 3) << 10 | (g >> 3) << 5 | (b >> 3)]; + m.N++; + m.R += r; + m.G += g; + m.B += b; + m.Squares += r * r + g * g + b * b; + } + var used = new List(); + var total = default(Moments); + for (var b = 0; b < bins.Length; b++) + { + if (bins[b].N == 0) continue; + used.Add(b); + total.Add(bins[b]); + } + var order = used.ToArray(); + var keys = new int[order.Length]; + var boxes = new List { new(0, order.Length, total) }; + + while (boxes.Count < maxColors) + { + var pick = -1; + double worst = 0; + for (var i = 0; i < boxes.Count; i++) + { + if (boxes[i].End - boxes[i].Start > 1 && boxes[i].Moments.Error > worst) + { + worst = boxes[i].Moments.Error; + pick = i; + } + } + if (pick < 0) break; + var box = boxes[pick]; + var (axis, split, left) = BestSplit(order, keys, bins, box); + var shift = 10 - axis * 5; + for (var i = box.Start; i < box.End; i++) keys[i] = (order[i] >> shift) & 31; + Array.Sort(keys, order, box.Start, box.End - box.Start); + boxes[pick] = new Box(box.Start, split, left); + boxes.Add(new Box(split, box.End, box.Moments.Minus(left))); + } + + var palette = new byte[boxes.Count * 3]; + for (var p = 0; p < boxes.Count; p++) + { + var m = boxes[p].Moments; + palette[p * 3] = (byte)((m.R + m.N / 2) / m.N); + palette[p * 3 + 1] = (byte)((m.G + m.N / 2) / m.N); + palette[p * 3 + 2] = (byte)((m.B + m.N / 2) / m.N); + } + return palette; + } + + /// Tries each axis; returns the cut (first index of the right half) with the least summed error. + private static (int Axis, int Split, Moments Left) BestSplit(int[] order, int[] keys, Moments[] bins, Box box) + { + (int Axis, int Split, Moments Left) best = (0, box.Start + 1, bins[order[box.Start]]); + var bestError = double.MaxValue; + for (var axis = 0; axis < 3; axis++) + { + var shift = 10 - axis * 5; + for (var i = box.Start; i < box.End; i++) keys[i] = (order[i] >> shift) & 31; + Array.Sort(keys, order, box.Start, box.End - box.Start); + var left = default(Moments); + for (var i = box.Start; i < box.End - 1; i++) + { + left.Add(bins[order[i]]); + if (keys[i] == keys[i + 1]) continue; // cut only between distinct coordinates + var error = left.Error + box.Moments.Minus(left).Error; + if (error < bestError) + { + bestError = error; + best = (axis, i + 1, left); + } + } + } + return best; + } + + /// Nearest palette entry (weighted RGB distance) with a green-sorted pruned search and a colour cache. + public sealed class Map + { + private readonly byte[] _palette; + private readonly int[] _order; + private readonly int[] _green; + private readonly int[] _cacheKey = new int[1 << 16]; + private readonly byte[] _cacheValue = new byte[1 << 16]; + + public Map(byte[] palette) + { + _palette = palette; + var n = palette.Length / 3; + _order = new int[n]; + _green = new int[n]; + for (var i = 0; i < n; i++) + { + _order[i] = i; + _green[i] = palette[i * 3 + 1]; + } + Array.Sort(_green, _order); + } + + public int Nearest(int r, int g, int b) + { + var color = r << 16 | g << 8 | b; + var slot = (int)(((uint)color * 0x9E3779B1u) >> 16); + if (_cacheKey[slot] == color + 1) return _cacheValue[slot]; + + var best = int.MaxValue; + var bestIndex = 0; + var up = LowerBound(g); + var down = up - 1; + while (up < _green.Length || down >= 0) + { + if (up < _green.Length) + { + var dg = _green[up] - g; + if (WeightG * dg * dg >= best) up = _green.Length; + else Consider(_order[up++], r, g, b, ref best, ref bestIndex); + } + if (down >= 0) + { + var dg = g - _green[down]; + if (WeightG * dg * dg >= best) down = -1; + else Consider(_order[down--], r, g, b, ref best, ref bestIndex); + } + } + _cacheKey[slot] = color + 1; + _cacheValue[slot] = (byte)bestIndex; + return bestIndex; + } + + private void Consider(int index, int r, int g, int b, ref int best, ref int bestIndex) + { + var dr = _palette[index * 3] - r; + var dg = _palette[index * 3 + 1] - g; + var db = _palette[index * 3 + 2] - b; + var d = WeightR * dr * dr + WeightG * dg * dg + WeightB * db * db; + if (d < best) + { + best = d; + bestIndex = index; + } + } + + private int LowerBound(int g) + { + int lo = 0, hi = _green.Length; + while (lo < hi) + { + var mid = (lo + hi) >> 1; + if (_green[mid] < g) lo = mid + 1; + else hi = mid; + } + return lo; + } + } +} diff --git a/tests/Titano.Core.Tests/Video/GifEncoderTests.cs b/tests/Titano.Core.Tests/Video/GifEncoderTests.cs new file mode 100644 index 00000000..4ac317cc --- /dev/null +++ b/tests/Titano.Core.Tests/Video/GifEncoderTests.cs @@ -0,0 +1,255 @@ +using Titano.Core.Codecs.Gif; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class GifEncoderTests(TestContext context) +{ + private const int W = 64, H = 48; + private const long Frame30 = 3000; // 1/30 s in 90 kHz ticks + + [Test] + public void SmoothFramesRoundTripWithinPaletteError() + { + var frames = Enumerable.Range(0, 4).Select(i => Smooth(i * 3)).ToList(); + var plain = Encode(frames, new GifEncoderOptions { Dither = false }); + var dithered = Encode(frames, new GifEncoderOptions()); + Assert.Equal(4, plain.Frames.Count); + Assert.True(plain.GlobalTable); + for (var f = 0; f < frames.Count; f++) + { + var (mean, max) = Error(frames[f], plain.Frames[f].Canvas); + Assert.Less(mean, 6.0, $"frame {f} mean error"); + Assert.Less(max, 40, $"frame {f} max error"); + context.Log($"frame {f}: plain {mean:0.00}/{max}, dithered tiles {TileError(frames[f], dithered.Frames[f].Canvas):0.00}"); + // Dithering trades per-pixel error for accurate local averages. + Assert.Less(TileError(frames[f], dithered.Frames[f].Canvas), 2.0, $"frame {f} 4×4 average error"); + } + } + + /// Mean absolute difference of 4×4 tile averages. + private static double TileError(byte[] rgb, byte[] rgba) + { + double sum = 0; + var tiles = 0; + for (var ty = 0; ty < H / 4; ty++) + { + for (var tx = 0; tx < W / 4; tx++) + { + for (var c = 0; c < 3; c++) + { + double a = 0, b = 0; + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 4; x++) + { + var i = (ty * 4 + y) * W + tx * 4 + x; + a += rgb[i * 3 + c]; + b += rgba[i * 4 + c]; + } + } + sum += Math.Abs(a - b) / 16; + tiles++; + } + } + } + return sum / tiles; + } + + [Test] + public void ExactColoursReproduceExactly() + { + var palette = RandomColours(120, 5); + var frames = Enumerable.Range(0, 3).Select(i => Blocks(palette, i)).ToList(); + var gif = Encode(frames, new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 }); + for (var f = 0; f < frames.Count; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas)); + } + + [Test] + public void DelaysFollowTheCumulativeTimelineAndLoopIsWritten() + { + var frames = Enumerable.Range(0, 10).Select(i => Blocks(RandomColours(8, i), i)).ToList(); + var gif = Encode(frames, new GifEncoderOptions()); + Assert.Equal(0, gif.LoopCount); + Assert.SequenceEqual([3, 4, 3, 3, 4, 3, 3, 4, 3, 3], gif.Frames.Select(f => f.DelayCs)); + Assert.Equal(33, gif.Frames.Sum(f => f.DelayCs)); + + Assert.Equal(5, Encode(frames, new GifEncoderOptions { LoopCount = 5 }).LoopCount); + Assert.Null(Encode(frames, new GifEncoderOptions { LoopCount = null }).LoopCount); + } + + [Test] + public void DifferencingCropsToTheChangedAreaAndKeepsTheRest() + { + var palette = RandomColours(64, 9); + var a = Blocks(palette, 0); + var b = (byte[])a.Clone(); + for (var y = 7; y < 11; y++) + { + for (var x = 10; x < 15; x++) + { + var i = (y * W + x) * 3; + b[i] = (byte)(255 - b[i]); + b[i + 1] = (byte)(255 - b[i + 1]); + } + } + var gif = Encode([a, b], new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 }); + Assert.Equal(2, gif.Frames.Count); + var second = gif.Frames[1]; + Assert.Equal((10, 7, 5, 4), (second.Left, second.Top, second.Width, second.Height)); + Assert.True(second.Transparent); + Assert.Equal(1, second.Disposal); + Assert.Equal(1, gif.Frames[0].Disposal); + Assert.False(gif.Frames[0].Transparent); + Assert.Equal((0.0, 0), Error(b, second.Canvas)); + } + + [Test] + public void IdenticalFramesMergeIntoOneLongerFrame() + { + var palette = RandomColours(16, 2); + var a = Blocks(palette, 0); + var b = Blocks(palette, 1); + var gif = Encode([a, a, a, b], new GifEncoderOptions { Dither = false }); + Assert.Equal(2, gif.Frames.Count); + Assert.Equal(10, gif.Frames[0].DelayCs); + Assert.Equal(3, gif.Frames[1].DelayCs); + } + + [Test] + public void LocalPalettesFollowEachFrame() + { + var reds = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)(55 + i), (byte)(i / 4), (byte)0 }).ToArray(); + var blues = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)0, (byte)(i / 4), (byte)(55 + i) }).ToArray(); + var frames = new List { Blocks(reds, 0), Blocks(blues, 0) }; + var gif = Encode(frames, new GifEncoderOptions { PaletteMode = GifPaletteMode.Local, Dither = false, DifferenceThreshold = 0 }); + Assert.False(gif.GlobalTable); + Assert.True(gif.Frames.All(f => f.LocalTable)); + for (var f = 0; f < 2; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas)); + } + + [Test] + public void LzwSurvivesDictionaryResets() + { + // 200×200 pixels of random indices fill the 4096-entry dictionary many times over. + const int size = 200; + var palette = RandomColours(200, 4); + var rng = new Random(8); + var rgb = new byte[size * size * 3]; + for (var i = 0; i < size * size; i++) + { + var c = rng.Next(200); + rgb[i * 3] = palette[c * 3]; + rgb[i * 3 + 1] = palette[c * 3 + 1]; + rgb[i * 3 + 2] = palette[c * 3 + 2]; + } + using var ms = new MemoryStream(); + var encoder = new GifEncoder(ms, size, size, new GifEncoderOptions { Dither = false, FrameDifferencing = false }); + encoder.AddFrame(rgb, Frame30); + encoder.Complete(); + var gif = GifTestDecoder.Decode(ms.ToArray()); + Assert.Equal((0.0, 0), Error(rgb, gif.Frames[0].Canvas)); + } + + [Test] + public void LinearImageBuffersAreEncodedAsSrgb() + { + var palette = RandomColours(30, 6); + var rgb = Blocks(palette, 3); + using var image = new ImageBuffer(W, H); + for (var i = 0; i < W * H; i++) + { + for (var c = 0; c < 3; c++) image.Plane(c)[i] = ColorSpace.Linear8(rgb[i * 3 + c]); + } + using var ms = new MemoryStream(); + var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Dither = false }); + encoder.AddFrame(image, Frame30); + encoder.Complete(); + Assert.Equal(1, encoder.FrameCount); + Assert.Equal((0.0, 0), Error(rgb, GifTestDecoder.Decode(ms.ToArray()).Frames[0].Canvas)); + } + + [Test] + public void SuppliedPaletteIsUsedAsGlobalTable() + { + using var image = new ImageBuffer(W, H); + image.Plane(0).Fill(0.5f); + var palette = GifEncoder.BuildPalette([image], 4); + Assert.Equal(3, palette.Length); + using var ms = new MemoryStream(); + var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Palette = palette }); + encoder.AddFrame(image, Frame30); + encoder.Complete(); + var gif = GifTestDecoder.Decode(ms.ToArray()); + Assert.True(gif.GlobalTable); + Assert.Equal(ColorSpace.Encode8(0.5f), gif.Frames[0].Canvas[0]); + } + + private static GifTestDecoder Encode(List frames, GifEncoderOptions options) + { + using var ms = new MemoryStream(); + var encoder = new GifEncoder(ms, W, H, options); + foreach (var f in frames) encoder.AddFrame(f, Frame30); + encoder.Complete(); + return GifTestDecoder.Decode(ms.ToArray()); + } + + private static (double Mean, int Max) Error(byte[] rgb, byte[] rgba) + { + long sum = 0; + var max = 0; + for (var i = 0; i < rgb.Length / 3; i++) + { + for (var c = 0; c < 3; c++) + { + var d = Math.Abs(rgb[i * 3 + c] - rgba[i * 4 + c]); + sum += d; + max = Math.Max(max, d); + } + } + return (sum / (double)rgb.Length, max); + } + + private static byte[] Smooth(int shift) + { + var rgb = new byte[W * H * 3]; + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + var i = (y * W + x) * 3; + rgb[i] = (byte)((x + shift) * 255 / (W + 12)); + rgb[i + 1] = (byte)(y * 255 / H); + rgb[i + 2] = (byte)(128 + 100 * Math.Sin((x + y + shift) * 0.1)); + } + } + return rgb; + } + + private static byte[] RandomColours(int count, int seed) + { + var bytes = new byte[count * 3]; + new Random(seed).NextBytes(bytes); + return bytes; + } + + /// 4×4 blocks coloured from , pattern varying with . + private static byte[] Blocks(byte[] palette, int variant) + { + var colours = palette.Length / 3; + var rgb = new byte[W * H * 3]; + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + var c = ((x / 4) * 7 + (y / 4) * 13 + variant * 5) % colours; + var i = (y * W + x) * 3; + rgb[i] = palette[c * 3]; + rgb[i + 1] = palette[c * 3 + 1]; + rgb[i + 2] = palette[c * 3 + 2]; + } + } + return rgb; + } +} diff --git a/tests/Titano.Core.Tests/Video/GifTestDecoder.cs b/tests/Titano.Core.Tests/Video/GifTestDecoder.cs new file mode 100644 index 00000000..1283fae6 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/GifTestDecoder.cs @@ -0,0 +1,197 @@ +using System.Text; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +/// Minimal GIF89a decoder used to verify GifEncoder output (composition with disposal 0–3). +internal sealed class GifTestDecoder +{ + public sealed record Frame(byte[] Canvas, int DelayCs, int Left, int Top, int Width, int Height, int Disposal, bool Transparent, bool LocalTable); + + public int Width { get; private set; } + public int Height { get; private set; } + public bool GlobalTable { get; private set; } + public int? LoopCount { get; private set; } + public List Frames { get; } = []; + + public static GifTestDecoder Decode(byte[] data) + { + var gif = new GifTestDecoder(); + Assert.Equal("GIF89a", Encoding.ASCII.GetString(data, 0, 6)); + gif.Width = data[6] | data[7] << 8; + gif.Height = data[8] | data[9] << 8; + var pos = 13; + byte[]? global = null; + if ((data[10] & 0x80) != 0) + { + gif.GlobalTable = true; + var size = 3 << ((data[10] & 7) + 1); + global = data.AsSpan(pos, size).ToArray(); + pos += size; + } + var canvas = new byte[gif.Width * gif.Height * 4]; + int delay = 0, disposal = 0, transparentIndex = -1; + while (true) + { + var block = data[pos++]; + if (block == 0x3B) break; + if (block == 0x21) + { + var label = data[pos++]; + if (label == 0xF9) + { + Assert.Equal((byte)4, data[pos]); + disposal = (data[pos + 1] >> 2) & 7; + transparentIndex = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1; + delay = data[pos + 2] | data[pos + 3] << 8; + pos += 6; + } + else if (label == 0xFF && Encoding.ASCII.GetString(data, pos + 1, 11) == "NETSCAPE2.0") + { + gif.LoopCount = data[pos + 14] | data[pos + 15] << 8; + pos += 12; + pos = SkipSubBlocks(data, pos); + } + else + { + pos = SkipSubBlocks(data, pos); + } + continue; + } + Assert.Equal((byte)0x2C, block); + var left = data[pos] | data[pos + 1] << 8; + var top = data[pos + 2] | data[pos + 3] << 8; + var w = data[pos + 4] | data[pos + 5] << 8; + var h = data[pos + 6] | data[pos + 7] << 8; + var packed = data[pos + 8]; + pos += 9; + var table = global; + var local = (packed & 0x80) != 0; + if (local) + { + var size = 3 << ((packed & 7) + 1); + table = data.AsSpan(pos, size).ToArray(); + pos += size; + } + Assert.False((packed & 0x40) != 0, "interlaced frames are not produced"); + Assert.True(left + w <= gif.Width && top + h <= gif.Height, "frame inside the logical screen"); + var minCode = data[pos++]; + using var lzw = new MemoryStream(); + while (data[pos] != 0) + { + lzw.Write(data, pos + 1, data[pos]); + pos += data[pos] + 1; + } + pos++; + var indices = DecodeLzw(lzw.ToArray(), minCode, w * h); + var saved = disposal == 3 ? (byte[])canvas.Clone() : null; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var index = indices[y * w + x]; + if (index == transparentIndex) continue; + var o = ((top + y) * gif.Width + left + x) * 4; + canvas[o] = table![index * 3]; + canvas[o + 1] = table[index * 3 + 1]; + canvas[o + 2] = table[index * 3 + 2]; + canvas[o + 3] = 255; + } + } + gif.Frames.Add(new Frame((byte[])canvas.Clone(), delay, left, top, w, h, disposal, transparentIndex >= 0, local)); + if (disposal == 2) + { + for (var y = 0; y < h; y++) canvas.AsSpan(((top + y) * gif.Width + left) * 4, w * 4).Clear(); + } + else if (disposal == 3) + { + canvas = saved!; + } + delay = 0; + disposal = 0; + transparentIndex = -1; + } + return gif; + } + + private static int SkipSubBlocks(byte[] data, int pos) + { + while (data[pos] != 0) pos += data[pos] + 1; + return pos + 1; + } + + private static byte[] DecodeLzw(byte[] data, int minCode, int pixels) + { + var output = new List(pixels); + var prefix = new short[4096]; + var suffix = new byte[4096]; + var stack = new byte[4097]; + var clear = 1 << minCode; + var end = clear + 1; + var codeSize = minCode + 1; + var next = end + 1; + var old = -1; + long bits = 0; + var count = 0; + var pos = 0; + while (true) + { + while (count < codeSize && pos < data.Length) + { + bits |= (long)data[pos++] << count; + count += 8; + } + Assert.True(count >= codeSize, "LZW data ended before the end code"); + var code = (int)(bits & ((1 << codeSize) - 1)); + bits >>= codeSize; + count -= codeSize; + if (code == clear) + { + codeSize = minCode + 1; + next = end + 1; + old = -1; + continue; + } + if (code == end) break; + if (old == -1) + { + Assert.True(code < clear, "first code after clear is a literal"); + output.Add((byte)code); + old = code; + continue; + } + Assert.True(code <= next, $"LZW code {code} beyond the table ({next})"); + var depth = 0; + var c = code; + if (code == next) + { + stack[depth++] = First(old, prefix, suffix, clear); + c = old; + } + while (c >= clear) + { + stack[depth++] = suffix[c]; + c = prefix[c]; + } + stack[depth++] = (byte)c; + var firstByte = (byte)c; + for (var i = depth - 1; i >= 0; i--) output.Add(stack[i]); + if (next < 4096) + { + prefix[next] = (short)old; + suffix[next] = firstByte; + next++; + if (next == 1 << codeSize && codeSize < 12) codeSize++; + } + old = code; + } + Assert.Equal(pixels, output.Count); + return [.. output]; + } + + private static byte First(int code, short[] prefix, byte[] suffix, int clear) + { + while (code >= clear) code = prefix[code]; + return (byte)code; + } +} From 14567ecac34449d67458e26927ad246f4f25b899 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:50:31 +0000 Subject: [PATCH 040/188] test(data): cover sessions, SQLite binding and PostgreSQL wire client Shared session tests run on SQLite and PostgreSQL (types, nulls, placeholders, transactions, constraint errors, COPY/bulk escaping, cancellation). PostgreSQL tests cover SCRAM/MD5/cleartext/trust auth, TLS, result decoding, bytea, LISTEN/NOTIFY, error mapping, pooling and broken-connection recovery, and the statement cache. In-memory SQLite now pools shared-cache connections and retries SQLITE_LOCKED. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Sqlite/SqliteDatabase.cs | 6 +- src/Titano.Data/Sqlite/SqliteSession.cs | 47 +-- .../Core/ValueConversionTests.cs | 87 ++++++ .../Infrastructure/DatabaseTest.cs | 104 +++++++ .../Postgres/PgProtocolUnitTests.cs | 106 +++++++ .../Titano.Data.Tests/Postgres/PgWireTests.cs | 272 ++++++++++++++++++ .../Sessions/SessionTests.cs | 260 +++++++++++++++++ .../Sqlite/SqliteBindingTests.cs | 155 ++++++++++ 8 files changed, 1015 insertions(+), 22 deletions(-) create mode 100644 tests/Titano.Data.Tests/Core/ValueConversionTests.cs create mode 100644 tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs create mode 100644 tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs create mode 100644 tests/Titano.Data.Tests/Postgres/PgWireTests.cs create mode 100644 tests/Titano.Data.Tests/Sessions/SessionTests.cs create mode 100644 tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs diff --git a/src/Titano.Data/Sqlite/SqliteDatabase.cs b/src/Titano.Data/Sqlite/SqliteDatabase.cs index eb64e302..2387a4d3 100644 --- a/src/Titano.Data/Sqlite/SqliteDatabase.cs +++ b/src/Titano.Data/Sqlite/SqliteDatabase.cs @@ -26,7 +26,8 @@ internal sealed record SqliteSettings(string DataSource, int PoolSize) /// /// SQLite through the system library (BRIEF §6.2). Up to Pool Size connections serve concurrent /// readers (WAL); writes are serialised in-process by one async write lock, so writers wait in a queue instead -/// of spinning on SQLITE_BUSY. In-memory databases use a single shared-cache connection. +/// of spinning on SQLITE_BUSY. An in-memory database is a shared-cache URI that lives while the pool holds a +/// connection; its table locks (SQLITE_LOCKED) are retried by the sessions. /// public sealed class SqliteDatabase : IDatabase { @@ -51,7 +52,6 @@ public sealed class SqliteDatabase : IDatabase if (_memory) { _filename = $"file:titano-{Guid.NewGuid():N}?mode=memory&cache=shared"; - _maxConnections = 1; } else { @@ -59,8 +59,8 @@ public sealed class SqliteDatabase : IDatabase var directory = System.IO.Path.GetDirectoryName(Path); if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); _filename = Path; - _maxConnections = settings.PoolSize; } + _maxConnections = settings.PoolSize; _slots = new SemaphoreSlim(_maxConnections, _maxConnections); } diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs index eeee6552..472a3155 100644 --- a/src/Titano.Data/Sqlite/SqliteSession.cs +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -35,7 +35,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co } using var interrupt = RegisterInterrupt(cancellationToken); var before = connection.TotalChanges; - while (await StepAsync(statement, _transaction is null, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + while (await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) { } // sqlite3_changes keeps the last DML count across DDL; only trust it when this statement changed rows. @@ -64,10 +64,10 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co } using var interrupt = RegisterInterrupt(cancellationToken); DbColumns? columns = null; - var retry = _transaction is null; - while (await StepAsync(statement, retry, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + var canRestart = true; + while (await StepAsync(statement, canRestart, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) { - retry = false; // restarting after rows were yielded would repeat them + canRestart = false; // restarting after rows were yielded would repeat them columns ??= statement.ReadColumns(); yield return statement.ReadRow(columns); cancellationToken.ThrowIfCancellationRequested(); @@ -108,7 +108,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); try { - await RunAsync("BEGIN IMMEDIATE", retryBusy: true, cancellationToken).ConfigureAwait(false); + await RunAsync("BEGIN IMMEDIATE", cancellationToken).ConfigureAwait(false); } catch { @@ -188,7 +188,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co if (_transaction != transaction) return; try { - await RunAsync(commit ? "COMMIT" : "ROLLBACK", retryBusy: commit, cancellationToken).ConfigureAwait(false); + await RunAsync(commit ? "COMMIT" : "ROLLBACK", cancellationToken).ConfigureAwait(false); } finally { @@ -225,7 +225,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co try { for (var i = 0; i < rowCount * columns.Count; i++) statement.BindValue(i + 1, buffer[i]); - await StepAsync(statement, retryBusy: false, cancellationToken).ConfigureAwait(false); + await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false); } finally { @@ -248,12 +248,12 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co return sb.ToString(); } - private async Task RunAsync(string sql, bool retryBusy, CancellationToken cancellationToken) + private async Task RunAsync(string sql, CancellationToken cancellationToken) { var statement = connection.Rent(sql); try { - await StepAsync(statement, retryBusy, cancellationToken).ConfigureAwait(false); + await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false); } finally { @@ -261,23 +261,32 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co } } - private async ValueTask StepAsync(SqliteStatement statement, bool retryBusy, CancellationToken cancellationToken) + /// + /// Steps once. While (no row returned yet) a statement stopped by a lock is + /// rewound and retried: SQLITE_LOCKED (shared-cache table locks, which busy_timeout does not cover) for up to + /// the busy timeout, SQLITE_BUSY (another process; busy_timeout already waited) a few times outside transactions. + /// + private async ValueTask StepAsync(SqliteStatement statement, bool canRestart, CancellationToken cancellationToken) { - for (var attempt = 0; ; attempt++) + var waitedMs = 0; + var busyRetries = 0; + while (true) { var rc = statement.Step(); if (rc is SQLITE_ROW or SQLITE_DONE) return rc; var primary = rc & 0xFF; if (primary == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) throw new OperationCanceledException(cancellationToken); - if (retryBusy && primary is SQLITE_BUSY or SQLITE_LOCKED && attempt < MaxBusyRetries) - { - // busy_timeout already waited; another process holds the lock for long. Back off and restart. - statement.Rewind(); - await Task.Delay(50 * (attempt + 1) + Random.Shared.Next(50), cancellationToken).ConfigureAwait(false); - continue; - } - throw connection.Error(rc); + int delayMs; + if (canRestart && primary == SQLITE_LOCKED && waitedMs < SqliteDatabase.BusyTimeoutMs) + delayMs = Math.Min(50, 1 + waitedMs / 10); + else if (canRestart && primary == SQLITE_BUSY && _transaction is null && busyRetries++ < MaxBusyRetries) + delayMs = 50 * busyRetries + Random.Shared.Next(50); + else + throw connection.Error(rc); + statement.Rewind(); + await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); + waitedMs += delayMs; } } diff --git a/tests/Titano.Data.Tests/Core/ValueConversionTests.cs b/tests/Titano.Data.Tests/Core/ValueConversionTests.cs new file mode 100644 index 00000000..d480a998 --- /dev/null +++ b/tests/Titano.Data.Tests/Core/ValueConversionTests.cs @@ -0,0 +1,87 @@ +using Titano.Testing; + +namespace Titano.Data.Tests.Core; + +/// Dialect-independent value handling: parameter normalisation, row conversions, text forms. +public sealed class ValueConversionTests +{ + private static DbRow Row(params object?[] values) => + new(new DbColumns(values.Select((_, i) => "c" + i).ToArray()), values); + + [Test] + public void ParametersKeepTheirTypeEvenWhenNull() + { + Assert.Equal(DbValueType.Uuid, ((DbParam)(Guid?)null).Type); + Assert.Equal(DbValueType.LocalDateTime, ((DbParam)(DateTime?)null).Type); + Assert.Equal(DbValueType.Auto, DbParam.Null.Type); + Assert.Equal(DbValueType.Int64, new DbParam(DayOfWeek.Friday).Type); + Assert.Equal(5L, new DbParam(DayOfWeek.Friday).Value); + Assert.Equal(DbValueType.Timestamp, ((DbParam)new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Type); + Assert.Equal(DbValueType.LocalDateTime, ((DbParam)new DateTime(2020, 1, 1)).Type); + Assert.Equal(3, new DbParam((short)3).Value); + Assert.Throws(() => new DbParam(new object())); + } + + [Test] + public void RowGettersConvertBetweenProviderForms() + { + var guid = Guid.CreateVersion7(); + var row = Row(42L, "0190a8b4-5c4e-7a1b-9c3d-0123456789ab", "2026-09-28T16:30:15.123456Z", "2024-02-29T23:59:58.500000", 1L, 3.0, guid, null); + Assert.Equal(42, row.GetInt32(0)); + Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(1)); + Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(2)); + Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(3)); + Assert.True(row.GetBool(4)); + Assert.Equal(3L, row.GetInt64(5)); + Assert.Equal(guid.ToString(), row.GetString(6)); + Assert.Null(row.GetInt32OrNull(7)); + Assert.Equal(DayOfWeek.Wednesday, row.Get(5)); + Assert.Equal(42, row.Get(0)); + Assert.Null(row.Get(7)); + Assert.Equal(1, row.GetOrdinal("C1")); + Assert.Throws(() => row.GetGuid(0)); + Assert.Throws(() => Row(long.MaxValue).GetInt32(0)); + Assert.Throws(() => row.GetOrdinal("missing")); + } + + [Theory] + [Case("2026-09-28 18:30:15.5+02", "2026-09-28T16:30:15.5000000+00:00")] + [Case("2026-09-28 18:30:15+05:30", "2026-09-28T13:00:15.0000000+00:00")] + [Case("2026-09-28T18:30:15.1234567Z", "2026-09-28T18:30:15.1234567+00:00")] + [Case("2026-09-28T18:30:15.12345678Z", "2026-09-28T18:30:15.1234567+00:00")] + [Case("2026-09-28 18:30", "2026-09-28T18:30:00.0000000+00:00")] + [Case("2026-09-28", "2026-09-28T00:00:00.0000000+00:00")] + [Case("1999-12-31 23:00:00-01", "2000-01-01T00:00:00.0000000+00:00")] + public void ParsesTimestampTextForms(string text, string expected) => + Assert.Equal(expected, TextValues.ParseTimestamp(text).ToString("O")); + + [Theory] + [Case("2026-02-30")] + [Case("2026-09-28 25:00:00")] + [Case("26-09-28")] + [Case("2026-09-28T10:00:00.Z")] + [Case("2026-09-28T10:00:00+1")] + public void RejectsMalformedTimestamps(string text) => + Assert.Throws(() => TextValues.ParseTimestamp(text)); + + [Test] + public void StoredTextFormsSortChronologically() + { + var a = new DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero); + var values = new[] { a, a.AddTicks(10), a.AddSeconds(1), a.AddYears(-1), a.AddMilliseconds(999) }; + var sorted = values.Select(TextValues.FormatTimestamp).OrderBy(s => s, StringComparer.Ordinal).ToList(); + Assert.SequenceEqual(values.OrderBy(v => v).Select(TextValues.FormatTimestamp), sorted); + Assert.Equal("2026-01-01T09:00:00.000001Z", TextValues.FormatTimestamp(a.AddTicks(10))); + } + + [Test] + public void BuildsUpsertsAndPatterns() + { + Assert.Equal( + "INSERT INTO t (a, b, c) VALUES ($1, $2, $3) ON CONFLICT (a) DO UPDATE SET b = excluded.b, c = excluded.c", + SqlDialect.Upsert("t", ["a", "b", "c"], 1)); + Assert.Equal("INSERT INTO t (a, b) VALUES ($1, $2) ON CONFLICT (a, b) DO NOTHING", SqlDialect.Upsert("t", ["a", "b"], 2)); + Assert.Equal("%50\\%\\_off\\\\%", SqlDialect.ContainsPattern("50%_off\\")); + Assert.Equal("\"we\"\"ird\"", SqlDialect.QuoteIdentifier("we\"ird")); + } +} diff --git a/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs b/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs new file mode 100644 index 00000000..cb2a015f --- /dev/null +++ b/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs @@ -0,0 +1,104 @@ +using Titano.Data.Postgres; +using Titano.Testing; + +namespace Titano.Data.Tests.Infrastructure; + +/// Engine a dialect-parameterised test class runs against. +public enum Backend +{ + SqliteMemory, + SqliteFile, + Postgres, +} + +/// +/// The PostgreSQL server named by TITANO_TEST_PG. Every test gets its own schema (selected through +/// Search Path), so classes run in parallel without seeing each other's tables. +/// +internal static class PgTestServer +{ + public const string Variable = "TITANO_TEST_PG"; + + private static readonly Lazy Admin = new(() => + new PostgresDatabase(PostgresSettings.Parse(ConnectionString) with { MaxPoolSize = 4 })); + + public static string ConnectionString => + Environment.GetEnvironmentVariable(Variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{Variable} not set"); + + /// A connection string for another role (MD5, cleartext, trust tests), or a skip when not configured. + public static string Optional(string variable) => + Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set"); + + public static async Task CreateSchemaAsync(CancellationToken cancellationToken) + { + var name = "titano_t_" + Guid.NewGuid().ToString("N")[..16]; + await using var session = await Admin.Value.OpenAsync(cancellationToken); + await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", cancellationToken); + return name; + } + + public static async Task DropSchemaAsync(string name) + { + await using var session = await Admin.Value.OpenAsync(CancellationToken.None); + await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {name} CASCADE", CancellationToken.None); + } + + public static string With(string connectionString, string extra) => connectionString.TrimEnd(';', ' ') + ";" + extra; +} + +/// +/// Base of tests that run against a fresh database per test: an in-memory or temporary-file SQLite database, or +/// a private schema on the PostgreSQL test server. Everything opened through it is disposed after the test. +/// +public abstract class DatabaseTest(TestContext context) : IAsyncDisposable +{ + private readonly List _owned = []; + private readonly List _schemas = []; + + protected TestContext Context => context; + + protected CancellationToken Ct => context.Cancellation; + + protected abstract Backend Backend { get; } + + protected Dialect Dialect => Backend == Backend.Postgres ? Dialect.Postgres : Dialect.Sqlite; + + /// Picks the DDL/SQL variant of the current dialect. + protected string ForDialect(string sqlite, string postgres) => Dialect == Dialect.Postgres ? postgres : sqlite; + + /// Options for a new empty database; forces a SQLite file (pooled readers). + protected async Task NewOptionsAsync(bool multiConnection = false, string? extraPostgres = null) + { + switch (Backend) + { + case Backend.SqliteMemory when !multiConnection: + return DatabaseOptions.SqliteInMemory(); + case Backend.SqliteMemory or Backend.SqliteFile: + return DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "titano.db")); + default: + var schema = await PgTestServer.CreateSchemaAsync(Ct); + _schemas.Add(schema); + var cs = PgTestServer.With(PgTestServer.ConnectionString, $"Search Path={schema};Maximum Pool Size=12"); + return DatabaseOptions.Postgres(extraPostgres is null ? cs : PgTestServer.With(cs, extraPostgres)); + } + } + + /// Opens a bare database (no migrations). + protected async Task OpenDatabaseAsync(bool multiConnection = false) + { + var database = DatabaseFactory.Open(await NewOptionsAsync(multiConnection)); + return Own(database); + } + + protected T Own(T disposable) where T : IAsyncDisposable + { + _owned.Add(disposable); + return disposable; + } + + public async ValueTask DisposeAsync() + { + for (var i = _owned.Count - 1; i >= 0; i--) await _owned[i].DisposeAsync(); + foreach (var schema in _schemas) await PgTestServer.DropSchemaAsync(schema); + } +} diff --git a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs new file mode 100644 index 00000000..5e1ac58d --- /dev/null +++ b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs @@ -0,0 +1,106 @@ +using System.Buffers; +using System.Text; +using Titano.Data.Postgres; +using Titano.Testing; + +namespace Titano.Data.Tests.Postgres; + +/// Protocol pieces that need no server. +public sealed class PgProtocolUnitTests +{ + [Test] + public void ScramMatchesTheRfc7677Example() + { + var scram = new ScramSha256("pencil", "user", "rOprNGfwEbeRWgbNEkqO"); + Assert.Equal("n,,n=user,r=rOprNGfwEbeRWgbNEkqO", Encoding.UTF8.GetString(scram.ClientFirstMessage())); + var final = scram.ClientFinalMessage(Encoding.UTF8.GetBytes( + "r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096")); + Assert.Equal( + "c=biws,r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,p=dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ=", + Encoding.UTF8.GetString(final)); + scram.VerifyServerFinal("v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="u8); + Assert.Throws(() => scram.VerifyServerFinal("v=AAAA"u8)); + } + + [Test] + public void ScramRejectsANonceTheClientDidNotStart() + { + var scram = new ScramSha256("pencil", "user", "abc"); + scram.ClientFirstMessage(); + Assert.Throws( + () => scram.ClientFinalMessage("r=xyz123,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096"u8)); + } + + [Theory] + [Case("plain-ascii", "plain-ascii")] + [Case("I\u00ADX", "IX")] + [Case("a\u00A0b", "a b")] + [Case("\u2168", "IX")] + [Case("\u00AA", "a")] + [Case("bell\u0007", "bell\u0007")] + [Case("x\u00ADy\u0007", "x\u00ADy\u0007")] + public void SaslPrepMapsNormalisesAndFallsBack(string input, string expected) => + Assert.Equal(expected, ScramSha256.SaslPrep(input)); + + [Test] + public void Md5ResponseMatchesPostgresFormula() => + Assert.Equal("md534d7feefdad153ddeacb423a9893b99e", PgMd5.Response("titano_md5", "md5-pw", [1, 2, 3, 4])); + + [Test] + public void CopyTextEscapesSpecialsAndEncodesValues() + { + var buffer = new ArrayBufferWriter(); + foreach (var value in new object?[] { "a\tb\nc\rd\\e ✓", null, new byte[] { 0, 0xAB }, true, 42L, Guid.Empty, new DateTime(2020, 1, 2, 3, 4, 5), 2.5f }) + { + PgTypes.WriteCopyValue(value, buffer); + buffer.Write("|"u8); + } + Assert.Equal( + "a\\tb\\nc\\rd\\\\e ✓|\\N|\\\\x00ab|t|42|00000000-0000-0000-0000-000000000000|2020-01-02T03:04:05.000000|2.5|", + Encoding.UTF8.GetString(buffer.WrittenSpan)); + } + + [Test] + public void DecodesByteaInHexAndEscapeFormats() + { + Assert.BytesEqual(new byte[] { 0xDE, 0xAD }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdead"u8)); + Assert.BytesEqual(new byte[] { (byte)'a', 0, (byte)'\\', 0xFF }, (byte[])PgTypes.Decode(PgTypes.Bytea, "a\\000\\\\\\377"u8)); + } + + [Theory] + [Case("SELECT 1", true)] + [Case(" -- comment\n /* block */ select * from t", true)] + [Case("VALUES (1)", true)] + [Case("SHOW TimeZone", true)] + [Case("SELECTED", false)] + [Case("UPDATE t SET a = 1", false)] + [Case("WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x", false)] + public void RecognisesRepeatableReads(string sql, bool expected) => + Assert.Equal(expected, PostgresSession.IsReadOnlyQuery(sql)); + + [Test] + public void ParsesConnectionStrings() + { + var s = PostgresSettings.Parse("Host=db.local; Port=6543; Username=me; Password='p;w''d'; SslMode=verify-full; Maximum Pool Size=7; Search Path=s1"); + Assert.Equal("db.local", s.Host); + Assert.Equal(6543, s.Port); + Assert.Equal("me", s.Database); + Assert.Equal("p;w'd", s.Password); + Assert.Equal(SslMode.VerifyFull, s.SslMode); + Assert.Equal(7, s.MaxPoolSize); + Assert.Equal("s1", s.SearchPath); + Assert.Equal("titano-server", s.ApplicationName); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;SslMode=allowish")); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;Pasword=typo")); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;Minimum Pool Size=5;Maximum Pool Size=2")); + } + + [Test] + public void InfersTheDialectFromTheConnectionString() + { + Assert.Equal(Dialect.Postgres, DatabaseOptions.Parse("Server=x;User Id=u").Dialect); + Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse("Data Source=/tmp/a.db").Dialect); + Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse(@"C:\Users\me\titano.db").Dialect); + Assert.Throws(() => DatabaseOptions.Parse("Foo=bar")); + } +} diff --git a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs new file mode 100644 index 00000000..4e7ebfba --- /dev/null +++ b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs @@ -0,0 +1,272 @@ +using System.Diagnostics; +using System.Security.Authentication; +using Titano.Data.Postgres; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Postgres; + +/// Protocol-level tests against a live server (TITANO_TEST_PG; optional TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST). +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PgWireTests(TestContext context) : DatabaseTest(context) +{ + protected override Backend Backend => Backend.Postgres; + + private async Task OpenAsync(string? extra = null) => + (PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra))); + + private async Task AuthenticateAsync(string connectionString) + { + var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString))); + await using var session = await database.OpenAsync(Ct); + return (await session.ScalarAsync("SELECT current_user", [], Ct))!; + } + + [Test] + public async Task ScramSha256Login() + { + var settings = PostgresSettings.Parse(PgTestServer.ConnectionString); + Assert.Equal(settings.Username, await AuthenticateAsync(PgTestServer.ConnectionString)); + } + + [Test] + public async Task Md5Login() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_MD5"))); + + [Test] + public async Task CleartextLogin() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_CLEARTEXT"))); + + [Test] + public async Task TrustLogin() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_TRUST"))); + + [Test] + public async Task WrongPasswordIsRejected() + { + var wrong = PgTestServer.With(PgTestServer.ConnectionString, "Password=definitely-wrong"); + var error = await Assert.ThrowsAsync(() => AuthenticateAsync(wrong)); + Assert.Equal("28P01", error.SqlState); + Assert.Equal("FATAL", error.Severity); + } + + [Test] + public async Task TlsIsNegotiatedWhenRequired() + { + PostgresDatabase database; + try + { + database = await OpenAsync("SslMode=Require"); + await using var probe = await database.OpenAsync(Ct); + } + catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal)) + { + TestContext.Skip("server has no TLS"); + return; + } + await using var session = await database.OpenAsync(Ct); + Assert.True(await session.ScalarAsync("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct)); + + var plain = await OpenAsync("SslMode=Disable"); + await using var plainSession = await plain.OpenAsync(Ct); + Assert.False(await plainSession.ScalarAsync("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct)); + } + + [Test] + public async Task VerifyFullRejectsAnUntrustedCertificate() + { + var database = await OpenAsync("SslMode=VerifyFull"); + try + { + await using var session = await database.OpenAsync(Ct); + Assert.Fail("A self-signed server certificate must not pass verify-full."); + } + catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal)) + { + TestContext.Skip("server has no TLS"); + } + catch (AuthenticationException) + { + } + } + + [Test] + public async Task DecodesEveryMappedResultType() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + var row = await session.QuerySingleAsync( + "SELECT 'txt'::text, 'vc'::varchar(5), 'bp'::bpchar(4), 7::int2, -8::int4, 9000000000::int8, 1.5::float4, " + + "-2.25::float8, 'Infinity'::float8, true, '\\x00ff10'::bytea, '2026-09-28 18:30:15.123456+02'::timestamptz, " + + "'2024-02-29 23:59:58.5'::timestamp, '2026-01-31'::date, '0190a8b4-5c4e-7a1b-9c3d-0123456789ab'::uuid, " + + "'{\"k\": 1}'::json, '{\"k\": [true]}'::jsonb, 12345678901234567890.123::numeric, NULL::int4", [], Ct); + Assert.Equal("txt", row.GetString(0)); + Assert.Equal("vc", row.GetString(1)); + Assert.Equal("bp ", row.GetString(2)); + Assert.Equal(7, row.GetInt32(3)); + Assert.Equal(-8, row.GetInt32(4)); + Assert.Equal(9000000000L, row.GetInt64(5)); + Assert.Equal(1.5, row.GetDouble(6)); + Assert.Equal(-2.25, row.GetDouble(7)); + Assert.Equal(double.PositiveInfinity, row.GetDouble(8)); + Assert.True(row.GetBool(9)); + Assert.BytesEqual(new byte[] { 0, 0xFF, 0x10 }, row.GetBytes(10)); + Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(11)); + Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(12)); + Assert.Equal(new DateTime(2026, 1, 31), row.GetDateTime(13)); + Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(14)); + Assert.Equal("{\"k\": 1}", row.GetString(15)); + Assert.Equal("{\"k\": [true]}", row.GetString(16)); + Assert.Equal("12345678901234567890.123", row.GetString(17)); + Assert.True(row.IsNull(18)); + } + + [Test] + public async Task ByteaTravelsInBinary() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE blobs (id integer PRIMARY KEY, data bytea)", Ct); + var all = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray(); + var large = new byte[1 << 20]; + new Random(7).NextBytes(large); + await session.ExecuteAsync("INSERT INTO blobs VALUES ($1, $2), ($3, $4), ($5, $6)", [1, all, 2, large, 3, Array.Empty()], Ct); + var readAll = await session.ScalarAsync("SELECT data FROM blobs WHERE id = 1", [], Ct); + var readLarge = await session.ScalarAsync("SELECT data FROM blobs WHERE id = 2", [], Ct); + Assert.BytesEqual(all, readAll); + Assert.BytesEqual(large, readLarge); + Assert.Equal(0, (await session.ScalarAsync("SELECT data FROM blobs WHERE id = 3", [], Ct))!.Length); + Assert.Equal(1L << 20, await session.ScalarAsync("SELECT length(data) FROM blobs WHERE id = $1", [2], Ct)); + } + + [Test] + public async Task ListenReceivesNotifications() + { + var database = await OpenAsync(); + var listener = Own(await database.CreateListenerAsync(Ct)); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + listener.Notification += (_, n) => received.TrySetResult(n); + await listener.ListenAsync("titano_jobs", Ct); + + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteAsync("SELECT pg_notify($1, $2)", ["titano_jobs", "wake ✓"], Ct); + + var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct); + Assert.Equal("titano_jobs", notification.Channel); + Assert.Equal("wake ✓", notification.Payload); + await listener.UnlistenAsync("titano_jobs", Ct); + await Assert.ThrowsAsync(() => listener.ListenAsync("", Ct)); + await listener.ListenAsync("still_usable", Ct); + } + + [Test] + public async Task ServerErrorsMapToTypedExceptions() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE u (id integer PRIMARY KEY, code text CONSTRAINT u_code_key UNIQUE)", Ct); + await session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [1, "a"], Ct); + var unique = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [2, "a"], Ct)); + Assert.Equal("23505", unique.SqlState); + Assert.Equal("ERROR", unique.Severity); + Assert.Equal("u_code_key", unique.ConstraintName); + Assert.Equal("u", unique.TableName); + Assert.NotNull(unique.Detail); + Assert.True(unique.IsUniqueViolation); + + var syntax = await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT * FROM u WHER id = 1", [], Ct)); + Assert.Equal("42601", syntax.SqlState); + Assert.Equal(22, syntax.Position); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + + [Test] + public async Task CommitOfAnAbortedTransactionThrows() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE a (id integer PRIMARY KEY)", Ct); + var tx = await session.BeginAsync(Ct); + await session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct); + await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct)); + await Assert.ThrowsAsync(() => tx.CommitAsync(Ct)); + Assert.False(session.InTransaction); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM a", [], Ct)); + } + + [Test] + public async Task PoolReusesConnectionsAndHandsOutDistinctOnesConcurrently() + { + var database = await OpenAsync("Maximum Pool Size=3;Timeout=2"); + int first; + await using (var s = await database.OpenAsync(Ct)) first = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + await using (var s = await database.OpenAsync(Ct)) Assert.Equal(first, await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct)); + + var sessions = new List(); + for (var i = 0; i < 3; i++) sessions.Add(await database.OpenAsync(Ct)); + var pids = new HashSet(); + foreach (var s in sessions) pids.Add(await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct)); + Assert.Equal(3, pids.Count); + var watch = Stopwatch.StartNew(); + await Assert.ThrowsAsync(() => database.OpenAsync(Ct)); + Assert.InRange(watch.Elapsed.TotalSeconds, 1.5, 5); + foreach (var s in sessions) await s.DisposeAsync(); + } + + [Test] + public async Task ReadsRecoverFromATerminatedBackend() + { + var database = await OpenAsync("Maximum Pool Size=2"); + int victim; + await using (var s = await database.OpenAsync(Ct)) victim = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + + var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString))); + await using (var k = await killer.OpenAsync(Ct)) + Assert.True(await k.ScalarAsync("SELECT pg_terminate_backend($1)", [victim], Ct)); + await Task.Delay(200, Ct); + + await using (var s = await database.OpenAsync(Ct)) + { + var pid = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + Assert.NotEqual(victim, pid); + Assert.Equal(2, await s.ScalarAsync("SELECT 1 + 1", [], Ct)); + } + } + + [Test] + public async Task WritesOnABrokenConnectionFailWithoutRetry() + { + var database = await OpenAsync("Maximum Pool Size=1"); + await using var session = await database.OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE w (id integer)", Ct); + var pid = await session.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString))); + await using (var k = await killer.OpenAsync(Ct)) await k.ExecuteAsync("SELECT pg_terminate_backend($1)", [pid], Ct); + await Task.Delay(200, Ct); + var error = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO w VALUES ($1)", [1], Ct)); + Assert.True(error.IsTransient); + } + + [Test] + public async Task StatementCacheEvictsAndSurvivesSchemaChanges() + { + await using var session = await (await OpenAsync("Statement Cache Size=2")).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE c (a integer); INSERT INTO c VALUES (1)", Ct); + for (var i = 0; i < 5; i++) Assert.Equal(i, await session.ScalarAsync($"SELECT {i} + 0 * $1", [i], Ct)); + // Evicted statements are closed with the next command: the cache size plus the counting statement remain. + Assert.LessOrEqual(await session.ScalarAsync("SELECT count(*) FROM pg_prepared_statements", [], Ct), 3); + + var first = await session.QuerySingleAsync("SELECT * FROM c", [], Ct); + Assert.Equal(1, first.FieldCount); + await session.ExecuteScriptAsync("ALTER TABLE c ADD COLUMN b text DEFAULT 'x'", Ct); + var second = await session.QuerySingleAsync("SELECT * FROM c", [], Ct); + Assert.Equal(2, second.FieldCount); + Assert.Equal("x", second.GetString("b")); + } + + [Test] + public async Task NoticesAndScriptsDoNotDisturbTheSession() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("DO $$ BEGIN RAISE NOTICE 'hello from the server'; END $$; CREATE TABLE n (id integer)", Ct); + Assert.Equal(1, await session.ExecuteAsync("INSERT INTO n VALUES ($1)", [1], Ct)); + await Assert.ThrowsAsync(() => session.ExecuteScriptAsync("SELECT 1; SELECT * FROM missing_table; SELECT 2", Ct)); + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM n", [], Ct)); + } +} diff --git a/tests/Titano.Data.Tests/Sessions/SessionTests.cs b/tests/Titano.Data.Tests/Sessions/SessionTests.cs new file mode 100644 index 00000000..72b7706b --- /dev/null +++ b/tests/Titano.Data.Tests/Sessions/SessionTests.cs @@ -0,0 +1,260 @@ +using System.Diagnostics; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Sessions; + +/// Behaviour every must share, run once per dialect. +public abstract class SessionTests(TestContext context) : DatabaseTest(context) +{ + private string AllTypesTable => ForDialect( + "CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT, i INTEGER, l INTEGER, d REAL, b INTEGER, g TEXT, ts TEXT, ldt TEXT, bytes BLOB, j TEXT)", + "CREATE TABLE t (id integer PRIMARY KEY, s text, i integer, l bigint, d double precision, b boolean, g uuid, ts timestamptz, ldt timestamp, bytes bytea, j jsonb)"); + + [Test] + public async Task ParametersRoundTripEveryType() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(AllTypesTable, Ct); + var guid = Guid.CreateVersion7(); + var instant = new DateTimeOffset(2026, 9, 28, 18, 30, 15, 123, TimeSpan.FromHours(2)).AddTicks(4560); + var wallClock = new DateTime(2024, 2, 29, 23, 59, 58, 999).AddTicks(9990); + byte[] bytes = [0, 1, 2, 0x7F, 0x80, 0xFE, 0xFF, (byte)'\\', (byte)'\t']; + var text = "Città \"quoted\" 'single' \\ back\ttab\nnewline 🎞️ 時間"; + await session.ExecuteAsync( + "INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + [1, text, int.MinValue, long.MaxValue, Math.PI, true, guid, instant, wallClock, bytes, DbParam.Json("{\"a\": [1, 2]}")], + Ct); + + var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t WHERE id = $1", [1], Ct); + Assert.Equal(text, row.GetString(0)); + Assert.Equal(int.MinValue, row.GetInt32(1)); + Assert.Equal(long.MaxValue, row.GetInt64(2)); + Assert.Equal(Math.PI, row.GetDouble(3)); + Assert.True(row.GetBool(4)); + Assert.Equal(guid, row.GetGuid(5)); + Assert.Equal(instant, row.GetDateTimeOffset(6)); + Assert.Equal(TimeSpan.Zero, row.GetDateTimeOffset(6).Offset); + Assert.Equal(wallClock, row.GetDateTime(7)); + Assert.Equal(DateTimeKind.Unspecified, row.GetDateTime(7).Kind); + Assert.BytesEqual(bytes, row.GetBytes(8)); + Assert.Equal("{\"a\": [1, 2]}", row.GetString(9)); + Assert.Equal(text, row.GetString("S")); + } + + [Test] + public async Task TypedNullsRoundTrip() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(AllTypesTable, Ct); + await session.ExecuteAsync( + "INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + [1, (string?)null, (int?)null, (long?)null, (double?)null, (bool?)null, (Guid?)null, (DateTimeOffset?)null, (DateTime?)null, (byte[]?)null, DbParam.Json(null)], + Ct); + var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t", [], Ct); + for (var i = 0; i < row.FieldCount; i++) Assert.True(row.IsNull(i), $"column {row.GetName(i)} should be NULL"); + Assert.Null(row.GetGuidOrNull(5)); + Assert.Null(row.GetDateTimeOffsetOrNull(6)); + Assert.Throws(() => row.GetInt32(1)); + } + + [Test] + public async Task PlaceholdersBindByNumberNotByOrder() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + var row = await session.QuerySingleAsync("SELECT $2 AS b, $1 AS a, $2 AS b2", [10, "x"], Ct); + Assert.Equal("x", row.GetString("b")); + Assert.Equal(10, row.GetInt32("a")); + Assert.Equal("x", row.GetString(2)); + } + + [Test] + public async Task ExecuteReportsChangedRowsOnly() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + Assert.Equal(0, await session.ExecuteAsync("CREATE TABLE n (id integer PRIMARY KEY, v integer)", [], Ct)); + for (var i = 0; i < 5; i++) await session.ExecuteAsync("INSERT INTO n (id, v) VALUES ($1, $2)", [i, i % 2], Ct); + Assert.Equal(3, await session.ExecuteAsync("UPDATE n SET v = 7 WHERE v = $1", [0], Ct)); + Assert.Equal(0, await session.ExecuteAsync("CREATE INDEX ix_n ON n (v)", [], Ct)); + Assert.Equal(2, await session.ExecuteAsync("DELETE FROM n WHERE v = $1", [1], Ct)); + Assert.Equal(3L, await session.ScalarAsync("SELECT count(*) FROM n", [], Ct)); + } + + [Test] + public async Task TransactionsCommitRollBackAndRollBackOnDispose() + { + var database = await OpenDatabaseAsync(); + await using var session = await database.OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct); + + await using (var tx = await session.BeginAsync(Ct)) + { + Assert.True(session.InTransaction); + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct); + await tx.CommitAsync(Ct); + } + Assert.False(session.InTransaction); + + await using (var tx = await session.BeginAsync(Ct)) + { + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct); + await tx.RollbackAsync(Ct); + } + await using (await session.BeginAsync(Ct)) + { + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [3], Ct); + await Assert.ThrowsAsync(() => session.BeginAsync(Ct)); + } + + await using var other = await database.OpenAsync(Ct); + Assert.Equal(1L, await other.ScalarAsync("SELECT count(*) FROM x", [], Ct)); + Assert.Equal(1, await other.ScalarAsync("SELECT max(id) FROM x", [], Ct)); + } + + [Test] + public async Task SessionDisposedInsideTransactionRollsBack() + { + var database = await OpenDatabaseAsync(); + await using (var setup = await database.OpenAsync(Ct)) + await setup.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct); + var session = await database.OpenAsync(Ct); + await session.BeginAsync(Ct); + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct); + await session.DisposeAsync(); + + await using var check = await database.OpenAsync(Ct); + Assert.Equal(0L, await check.ScalarAsync("SELECT count(*) FROM x", [], Ct)); + await check.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct); + } + + [Test] + public async Task ConstraintViolationsAreTyped() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync( + "CREATE TABLE p (id integer PRIMARY KEY, code text NOT NULL UNIQUE); " + + "CREATE TABLE c (id integer PRIMARY KEY, p_id integer NOT NULL REFERENCES p(id))", Ct); + await session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "a"], Ct); + + var unique = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [2, "a"], Ct)); + Assert.True(unique.IsUniqueViolation); + var primary = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "b"], Ct)); + Assert.True(primary.IsUniqueViolation); + var foreign = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO c (id, p_id) VALUES ($1, $2)", [1, 99], Ct)); + Assert.True(foreign.IsForeignKeyViolation); + + // The session stays usable after errors. + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM p", [], Ct)); + } + + [Test] + public async Task BulkInsertKeepsSpecialCharactersAndNulls() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(ForDialect( + "CREATE TABLE b (id INTEGER PRIMARY KEY, s TEXT, bytes BLOB, ts TEXT, ldt TEXT, d REAL, g TEXT, f INTEGER)", + "CREATE TABLE b (id integer PRIMARY KEY, s text, bytes bytea, ts timestamptz, ldt timestamp, d double precision, g uuid, f boolean)"), Ct); + string?[] texts = + [ + "tab\there", "new\nline", "carriage\rreturn", "back\\slash", "\\N", "", null, "unicode ✓ ñ 漢字 🎉", + "mixed \\t\t\\n\n end\\", "trailing tab\t", "x", + ]; + var instant = new DateTimeOffset(2025, 1, 2, 3, 4, 5, TimeSpan.Zero); + var rows = texts.Select((s, i) => new object?[] + { + i, s, i % 3 == 0 ? null : new byte[] { (byte)i, (byte)'\\', (byte)'\n', 0 }, instant.AddDays(i), + new DateTime(2020, 1, 1).AddHours(i), i / 3.0, Guid.CreateVersion7(), i % 2 == 0, + }).ToList(); + + var inserted = await session.BulkInsertAsync("b", ["id", "s", "bytes", "ts", "ldt", "d", "g", "f"], rows.ToAsyncEnumerable(), Ct); + Assert.Equal(texts.Length, (int)inserted); + + var read = await session.QueryListAsync("SELECT id, s, bytes, ts, ldt, d, g, f FROM b ORDER BY id", [], r => r, Ct); + Assert.Equal(texts.Length, read.Count); + for (var i = 0; i < texts.Length; i++) + { + var r = read[i]; + Assert.Equal(texts[i], r.GetStringOrNull(1), $"row {i}"); + if (rows[i][2] is byte[] expected) Assert.BytesEqual(expected, r.GetBytes(2)); + else Assert.True(r.IsNull(2)); + Assert.Equal(instant.AddDays(i), r.GetDateTimeOffset(3)); + Assert.Equal(new DateTime(2020, 1, 1).AddHours(i), r.GetDateTime(4)); + Assert.Equal(i / 3.0, r.GetDouble(5)); + Assert.Equal((Guid)rows[i][6]!, r.GetGuid(6)); + Assert.Equal(i % 2 == 0, r.GetBool(7)); + } + } + + [Test] + public async Task FailingBulkProducerLeavesTableUntouched() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE b (id integer PRIMARY KEY)", Ct); + async IAsyncEnumerable Rows() + { + for (var i = 0; i < 1000; i++) + { + if (i == 700) throw new InvalidDataException("producer failed"); + yield return [i]; + await Task.Yield(); + } + } + await Assert.ThrowsAsync(() => session.BulkInsertAsync("b", ["id"], Rows(), Ct)); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM b", [], Ct)); + } + + [Test] + public async Task AbandonedQueryLeavesSessionUsable() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE q (id integer PRIMARY KEY)", Ct); + await session.BulkInsertAsync("q", ["id"], Enumerable.Range(0, 2000).Select(i => new object?[] { i }).ToAsyncEnumerable(), Ct); + await foreach (var row in session.QueryAsync("SELECT id FROM q ORDER BY id", [], Ct)) + { + Assert.Equal(0, row.GetInt32(0)); + break; + } + Assert.Equal(1999, await session.ScalarAsync("SELECT max(id) FROM q", [], Ct)); + Assert.Equal(2000L, await session.ScalarAsync("SELECT count(*) FROM q", [], Ct)); + } + + [Test] + public async Task SingleRowHelpersEnforceCardinality() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE s (id integer PRIMARY KEY); INSERT INTO s (id) VALUES (1); INSERT INTO s (id) VALUES (2)", Ct); + Assert.Null(await session.QuerySingleOrDefaultAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + await Assert.ThrowsAsync(() => session.QuerySingleAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + await Assert.ThrowsAsync(() => session.QuerySingleOrDefaultAsync("SELECT id FROM s", [], Ct)); + Assert.Equal(0, await session.ScalarAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + Assert.Null(await session.ScalarAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + Assert.Equal("2", await session.ScalarAsync("SELECT max(id) FROM s", [], Ct)); + } + + [Test] + public async Task CancellationStopsALongQueryQuickly() + { + var database = await OpenDatabaseAsync(); + await using var session = await database.OpenAsync(Ct); + var sql = ForDialect( + "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", + "SELECT pg_sleep(10)"); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); + cts.CancelAfter(300); + var watch = Stopwatch.StartNew(); + await Assert.ThrowsAsync(() => session.ExecuteAsync(sql, [], cts.Token)); + Assert.Less(watch.Elapsed.TotalSeconds, 2.0, "cancellation latency"); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } +} + +public sealed class SqliteSessionTests(TestContext context) : SessionTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresSessionTests(TestContext context) : SessionTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs new file mode 100644 index 00000000..65942b0b --- /dev/null +++ b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs @@ -0,0 +1,155 @@ +using Titano.Data.Sqlite; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Sqlite; + +public sealed class SqliteBindingTests(TestContext context) : DatabaseTest(context) +{ + protected override Backend Backend => Backend.SqliteFile; + + [Test] + public void SystemLibraryIsRecentEnough() + { + var parts = SqliteDatabase.LibraryVersion.Split('.').Select(int.Parse).ToArray(); + Assert.True(parts[0] > 3 || (parts[0] == 3 && parts[1] >= 31), $"SQLite {SqliteDatabase.LibraryVersion}"); + } + + [Test] + public async Task ConnectionsUseTheBriefPragmas() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + Assert.Equal("wal", await session.ScalarAsync("PRAGMA journal_mode", [], Ct)); + Assert.Equal(1L, await session.ScalarAsync("PRAGMA synchronous", [], Ct)); + Assert.Equal(1L, await session.ScalarAsync("PRAGMA foreign_keys", [], Ct)); + Assert.Equal(2L, await session.ScalarAsync("PRAGMA temp_store", [], Ct)); + Assert.Equal(-65536L, await session.ScalarAsync("PRAGMA cache_size", [], Ct)); + Assert.Equal(268435456L, await session.ScalarAsync("PRAGMA mmap_size", [], Ct)); + } + + [Test] + public async Task RejectsScriptsAndWrongParameterCounts() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT 1; SELECT 2", [], Ct)); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT $1, $2", [1], Ct)); + Assert.Equal(1, await session.ScalarAsync("SELECT 1 -- trailing comment", [], Ct)); + var error = await Assert.ThrowsAsync(() => session.ExecuteAsync("SELEC 1", [], Ct)); + Assert.Equal(1, error.ResultCode); + } + + [Test] + public async Task WritersFromManySessionsAreSerialised() + { + var database = await OpenDatabaseAsync(multiConnection: true); + await using (var setup = await database.OpenAsync(Ct)) + await setup.ExecuteScriptAsync("CREATE TABLE counter (id INTEGER PRIMARY KEY, n INTEGER NOT NULL); INSERT INTO counter VALUES (1, 0)", Ct); + + await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(async () => + { + for (var i = 0; i < 25; i++) + { + await using var session = await database.OpenAsync(Ct); + await using var tx = await session.BeginAsync(Ct); + var n = await session.ScalarAsync("SELECT n FROM counter WHERE id = 1", [], Ct); + await session.ExecuteAsync("UPDATE counter SET n = $1 WHERE id = 1", [n + 1], Ct); + await tx.CommitAsync(Ct); + } + }))); + + await using var check = await database.OpenAsync(Ct); + Assert.Equal(200L, await check.ScalarAsync("SELECT n FROM counter", [], Ct)); + } + + [Test] + public async Task ReadersSeeTheLastCommitWhileAWriterIsOpen() + { + var database = await OpenDatabaseAsync(multiConnection: true); + await using var writer = await database.OpenAsync(Ct); + await writer.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1)", Ct); + await using var tx = await writer.BeginAsync(Ct); + await writer.ExecuteAsync("INSERT INTO r VALUES ($1)", [2], Ct); + + await using var reader = await database.OpenAsync(Ct); + Assert.Equal(1L, await reader.ScalarAsync("SELECT count(*) FROM r", [], Ct)); + await tx.CommitAsync(Ct); + Assert.Equal(2L, await reader.ScalarAsync("SELECT count(*) FROM r", [], Ct)); + } + + [Test] + public async Task SameStatementCanRunNestedOnOneSession() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1); INSERT INTO r VALUES (2)", Ct); + var pairs = 0; + await foreach (var outer in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct)) + { + await foreach (var inner in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct)) + { + pairs++; + Assert.True(inner.GetInt32(0) is 1 or 2 && outer.GetInt32(0) is 1 or 2); + } + } + Assert.Equal(4, pairs); + } + + [Test] + public async Task BackupKeepsTheThreeNewestAndRestoreBringsDataBack() + { + var path = Path.Combine(Context.CreateTempDirectory(), "titano.db"); + var backups = Context.CreateTempDirectory(); + var database = (SqliteDatabase)Own(DatabaseFactory.Open(DatabaseOptions.Sqlite(path))); + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteScriptAsync("CREATE TABLE b (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO b VALUES (1, 'original')", Ct); + + var first = await database.BackupAsync(backups, cancellationToken: Ct); + Assert.FileExists(first); + for (var i = 0; i < 4; i++) await database.BackupAsync(backups, cancellationToken: Ct); + var kept = Directory.GetFiles(backups).OrderBy(f => f, StringComparer.Ordinal).ToList(); + Assert.Equal(3, kept.Count); + Assert.DoesNotContain(first, kept); + + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteAsync("UPDATE b SET v = $1", ["changed"], Ct); + await database.RestoreAsync(kept[^1], Ct); + + await using (var session = await database.OpenAsync(Ct)) + Assert.Equal("original", await session.ScalarAsync("SELECT v FROM b WHERE id = 1", [], Ct)); + } + + [Test] + public async Task RestoreRefusesAFileThatIsNotADatabase() + { + var database = (SqliteDatabase)await OpenDatabaseAsync(); + var bogus = Path.Combine(Context.CreateTempDirectory(), "bogus.db"); + await File.WriteAllTextAsync(bogus, "not a database, just text that is long enough to have a header", Ct); + await Assert.ThrowsAsync(() => database.RestoreAsync(bogus, Ct)); + await using var session = await database.OpenAsync(Ct); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + + [Test] + public async Task InMemoryDatabasesAreIsolated() + { + var a = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory())); + var b = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory())); + await using (var s = await a.OpenAsync(Ct)) await s.ExecuteScriptAsync("CREATE TABLE only_a (id INTEGER)", Ct); + await using var sb = await b.OpenAsync(Ct); + Assert.Equal(0L, await sb.ScalarAsync("SELECT count(*) FROM sqlite_master WHERE name = 'only_a'", [], Ct)); + await Assert.ThrowsAsync(() => ((SqliteDatabase)a).RestoreAsync("x.db", Ct)); + } +} + +public sealed class SqliteSqlTextTests +{ + [Theory] + [Case("SELECT $1", "SELECT ?1")] + [Case("SELECT $2, $1, $12", "SELECT ?2, ?1, ?12")] + [Case("SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = $5", "SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = ?5")] + [Case("SELECT 'it''s $1' || $1", "SELECT 'it''s $1' || ?1")] + [Case("SELECT $1 -- $2\n, $3 /* $4 */", "SELECT ?1 -- $2\n, ?3 /* $4 */")] + [Case("SELECT a$1 FROM t", "SELECT a$1 FROM t")] + [Case("SELECT 'unterminated $1", "SELECT 'unterminated $1")] + public void TranslatesPlaceholdersOutsideLiterals(string sql, string expected) => + Assert.Equal(expected, SqliteSqlText.TranslatePlaceholders(sql)); +} From 04f31e7f436ebd19bb18ea3e6bc93663ba44ce3a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:37 +0000 Subject: [PATCH 041/188] feat(apng): add APNG encoder with frame differencing and exact delays Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Apng/ApngEncoder.cs | 246 ++++++++++++++++++ .../Video/ApngEncoderTests.cs | 221 ++++++++++++++++ 2 files changed, 467 insertions(+) create mode 100644 src/Titano.Core/Codecs/Apng/ApngEncoder.cs create mode 100644 tests/Titano.Core.Tests/Video/ApngEncoderTests.cs diff --git a/src/Titano.Core/Codecs/Apng/ApngEncoder.cs b/src/Titano.Core/Codecs/Apng/ApngEncoder.cs new file mode 100644 index 00000000..5047d90a --- /dev/null +++ b/src/Titano.Core/Codecs/Apng/ApngEncoder.cs @@ -0,0 +1,246 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Codecs.Png; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Apng; + +/// Options of . +public sealed record ApngEncoderOptions +{ + /// Write RGBA (alpha taken from 4-channel buffers); otherwise RGB. + public bool Alpha { get; init; } + + /// acTL num_plays: 0 loops forever. + public int LoopCount { get; init; } + + /// Crop frames to the changed area (blend OVER with transparent unchanged pixels when possible). + public bool FrameDifferencing { get; init; } = true; + + public CompressionLevel CompressionLevel { get; init; } = CompressionLevel.Optimal; +} + +/// +/// Animated PNG encoder (8-bit RGB/RGBA): acTL/fcTL/IDAT/fdAT with one shared sequence counter; the first frame is +/// the default image. Delays are exact fractions of the 90 kHz durations when they fit 16 bits, otherwise rounded on +/// the cumulative timeline. Identical consecutive frames merge. The output must be seekable (acTL is patched at the +/// end) and is not disposed. +/// +public sealed class ApngEncoder +{ + private const int TimeScale = 90_000; + private const byte DisposeNone = 0; + private const byte BlendSource = 0, BlendOver = 1; + + private readonly Stream _output; + private readonly int _width; + private readonly int _height; + private readonly int _bpp; + private readonly ApngEncoderOptions _options; + private readonly long _actlOffset; + private byte[]? _canvas; + private Pending? _pending; + private long _time; + private uint _sequence; + private bool _completed; + + public ApngEncoder(Stream output, int width, int height, ApngEncoderOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + if (!output.CanSeek || !output.CanWrite) throw new ArgumentException("The output stream must be writable and seekable", nameof(output)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + _options = options ?? new ApngEncoderOptions(); + ArgumentOutOfRangeException.ThrowIfNegative(_options.LoopCount, nameof(options)); + _output = output; + _width = width; + _height = height; + _bpp = _options.Alpha ? 4 : 3; + + output.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + Span ihdr = stackalloc byte[13]; + BinaryPrimitives.WriteInt32BigEndian(ihdr, width); + BinaryPrimitives.WriteInt32BigEndian(ihdr[4..], height); + ihdr[8] = 8; + ihdr[9] = (byte)(_options.Alpha ? PngColorType.Rgba : PngColorType.Rgb); + PngEncoder.WriteChunk(output, "IHDR", ihdr); + _actlOffset = output.Position; + WriteAnimationControl(0); + } + + /// Frames written so far (merged identical frames count once). + public int FrameCount { get; private set; } + + /// Adds a linear-light frame shown for ticks. + public void AddFrame(ImageBuffer frame, long duration90k) + { + if (frame.Width != _width || frame.Height != _height) throw new ArgumentException("Frame size differs from the animation size", nameof(frame)); + var n = _width * _height; + var pixels = new byte[n * _bpp]; + var r = frame.Plane(0); + var g = frame.Channels >= 3 ? frame.Plane(1) : r; + var b = frame.Channels >= 3 ? frame.Plane(2) : r; + var a = frame.Channels == 4 ? frame.Plane(3) : default; + for (var i = 0; i < n; i++) + { + var o = i * _bpp; + pixels[o] = ColorSpace.Encode8(r[i]); + pixels[o + 1] = ColorSpace.Encode8(g[i]); + pixels[o + 2] = ColorSpace.Encode8(b[i]); + if (_bpp == 4) pixels[o + 3] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[i], 0f, 1f) * 255f + 0.5f); + } + AddPixels(pixels, duration90k); + } + + /// Adds interleaved 8-bit sRGB pixels (RGB, or RGBA when ). + public void AddFrame(ReadOnlySpan pixels, long duration90k) + { + if (pixels.Length != _width * _height * _bpp) throw new ArgumentException($"Expected width × height × {_bpp} bytes", nameof(pixels)); + AddPixels(pixels.ToArray(), duration90k); + } + + /// Writes the last frame and IEND, then patches the frame count. + public void Complete() + { + if (_completed) throw new InvalidOperationException("The encoder is already complete"); + if (_pending is null) throw new InvalidOperationException("No frames were added"); + Emit(_time); + PngEncoder.WriteChunk(_output, "IEND", []); + var end = _output.Position; + _output.Position = _actlOffset; + WriteAnimationControl(FrameCount); + _output.Position = end; + _output.Flush(); + _completed = true; + } + + private sealed record Pending(long Start, int X, int Y, int Width, int Height, byte Blend, byte[] Data); + + private void AddPixels(byte[] pixels, long duration) + { + if (_completed) throw new InvalidOperationException("The encoder is complete"); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration); + int x = 0, y = 0, w = _width, h = _height; + var blend = BlendSource; + var region = pixels; + if (_canvas is not null && _options.FrameDifferencing) + { + (x, y, w, h) = ChangedArea(pixels, _canvas); + if (w == 0) + { + _time += duration; // identical frame: the previous one stays longer + return; + } + region = Crop(pixels, x, y, w, h, out var opaque); + if (_bpp == 4 && opaque) + { + // Unchanged pixels become fully transparent and OVER keeps what is displayed beneath them. + for (var row = 0; row < h; row++) + { + for (var col = 0; col < w; col++) + { + var c = ((y + row) * _width + x + col) * 4; + if (pixels.AsSpan(c, 4).SequenceEqual(_canvas.AsSpan(c, 4))) region.AsSpan((row * w + col) * 4, 4).Clear(); + } + } + blend = BlendOver; + } + } + _canvas = pixels; + var data = PngEncoder.Compress(region, h, w * _bpp, _bpp, _options.CompressionLevel); + Emit(_time); + _pending = new Pending(_time, x, y, w, h, blend, data); + _time += duration; + } + + private (int X, int Y, int Width, int Height) ChangedArea(byte[] pixels, byte[] canvas) + { + int left = _width, top = _height, right = -1, bottom = -1; + for (var y = 0; y < _height; y++) + { + var row = y * _width * _bpp; + for (var x = 0; x < _width; x++) + { + var o = row + x * _bpp; + if (pixels.AsSpan(o, _bpp).SequenceEqual(canvas.AsSpan(o, _bpp))) continue; + left = Math.Min(left, x); + right = Math.Max(right, x); + top = Math.Min(top, y); + bottom = y; + } + } + return right < 0 ? (0, 0, 0, 0) : (left, top, right - left + 1, bottom - top + 1); + } + + private byte[] Crop(byte[] pixels, int x, int y, int w, int h, out bool opaque) + { + var region = new byte[w * h * _bpp]; + opaque = true; + for (var row = 0; row < h; row++) pixels.AsSpan(((y + row) * _width + x) * _bpp, w * _bpp).CopyTo(region.AsSpan(row * w * _bpp)); + if (_bpp == 4) + { + for (var i = 3; i < region.Length && opaque; i += 4) opaque = region[i] == 255; + } + return region; + } + + private void Emit(long end) + { + if (_pending is not { } frame) return; + var (num, den) = Delay(frame.Start, end); + Span fctl = stackalloc byte[26]; + BinaryPrimitives.WriteUInt32BigEndian(fctl, _sequence++); + BinaryPrimitives.WriteInt32BigEndian(fctl[4..], frame.Width); + BinaryPrimitives.WriteInt32BigEndian(fctl[8..], frame.Height); + BinaryPrimitives.WriteInt32BigEndian(fctl[12..], frame.X); + BinaryPrimitives.WriteInt32BigEndian(fctl[16..], frame.Y); + BinaryPrimitives.WriteUInt16BigEndian(fctl[20..], num); + BinaryPrimitives.WriteUInt16BigEndian(fctl[22..], den); + fctl[24] = DisposeNone; + fctl[25] = frame.Blend; + PngEncoder.WriteChunk(_output, "fcTL", fctl); + if (FrameCount == 0) + { + PngEncoder.WriteChunk(_output, "IDAT", frame.Data); + } + else + { + var fdat = new byte[4 + frame.Data.Length]; + BinaryPrimitives.WriteUInt32BigEndian(fdat, _sequence++); + frame.Data.CopyTo(fdat, 4); + PngEncoder.WriteChunk(_output, "fdAT", fdat); + } + FrameCount++; + _pending = null; + } + + /// Exact reduced fraction of a second when it fits 16 bits; otherwise the cumulative timeline rounded to 1/1000 … 1 s. + private static (ushort Num, ushort Den) Delay(long start, long end) + { + var duration = end - start; + var g = Gcd(duration, TimeScale); + if (duration / g <= ushort.MaxValue && TimeScale / g <= ushort.MaxValue) return ((ushort)(duration / g), (ushort)(TimeScale / g)); + foreach (var den in (ReadOnlySpan)[1000, 100, 10, 1]) + { + var num = Rounded(end, den) - Rounded(start, den); + if (num <= ushort.MaxValue) return ((ushort)num, (ushort)den); + } + return (ushort.MaxValue, 1); + + static long Rounded(long ticks, int den) => (ticks * den + TimeScale / 2) / TimeScale; + } + + private static long Gcd(long a, long b) + { + while (b != 0) (a, b) = (b, a % b); + return a; + } + + private void WriteAnimationControl(int frames) + { + Span actl = stackalloc byte[8]; + BinaryPrimitives.WriteInt32BigEndian(actl, frames); + BinaryPrimitives.WriteInt32BigEndian(actl[4..], _options.LoopCount); + PngEncoder.WriteChunk(_output, "acTL", actl); + } +} diff --git a/tests/Titano.Core.Tests/Video/ApngEncoderTests.cs b/tests/Titano.Core.Tests/Video/ApngEncoderTests.cs new file mode 100644 index 00000000..db4eba39 --- /dev/null +++ b/tests/Titano.Core.Tests/Video/ApngEncoderTests.cs @@ -0,0 +1,221 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using Titano.Core.Codecs.Apng; +using Titano.Core.Hashing; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Video; + +public sealed class ApngEncoderTests +{ + private const int W = 40, H = 30; + + [Test] + public void ChunkOrderSequenceNumbersAndCrcsAreValid() + { + var frames = Enumerable.Range(0, 5).Select(i => Pattern(i, 3)).ToList(); + var bytes = Encode(frames, new ApngEncoderOptions(), 3000); + var chunks = Chunks(bytes); + Assert.SequenceEqual( + ["IHDR", "acTL", "fcTL", "IDAT", "fcTL", "fdAT", "fcTL", "fdAT", "fcTL", "fdAT", "fcTL", "fdAT", "IEND"], + chunks.Select(c => c.Type)); + var actl = chunks[1].Data; + Assert.Equal(5, BinaryPrimitives.ReadInt32BigEndian(actl)); + Assert.Equal(0, BinaryPrimitives.ReadInt32BigEndian(actl.AsSpan(4))); + var sequence = chunks.Where(c => c.Type is "fcTL" or "fdAT").Select(c => BinaryPrimitives.ReadUInt32BigEndian(c.Data)).ToList(); + Assert.SequenceEqual(Enumerable.Range(0, sequence.Count).Select(i => (uint)i), sequence); + var first = chunks[2].Data; + Assert.Equal((W, H, 0, 0), (BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(4)), BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(8)), + BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(12)), BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(16)))); + Assert.Equal((1, 30), Delay(first)); + } + + [Test] + public void FirstFrameIsTheDefaultImageAndAllFramesComposeExactly() + { + var frames = new List { Pattern(0, 3), Pattern(0, 3), Pattern(1, 3) }; + // Frame 3 changes only a small block of frame 2. + var last = (byte[])frames[2].Clone(); + for (var y = 5; y < 9; y++) + { + for (var x = 20; x < 26; x++) last[(y * W + x) * 3] ^= 0xFF; + } + frames.Add(last); + var bytes = Encode(frames, new ApngEncoderOptions(), 1500); + var decoded = Decode(bytes, 3); + Assert.Equal(3, decoded.Count); // the duplicate merged into the first frame + Assert.BytesEqual(frames[0], decoded[0].Canvas); + Assert.BytesEqual(frames[2], decoded[1].Canvas); + Assert.BytesEqual(frames[3], decoded[2].Canvas); + Assert.Equal((1, 30), decoded[0].Delay); + Assert.Equal((20, 5, 6, 4), decoded[2].Rect); + Assert.Equal(0, decoded[2].Blend); // RGB output always uses SOURCE + } + + [Test] + public void RgbaDifferencingUsesOverWithTransparentUnchangedPixels() + { + var a = Pattern(2, 4); + var b = (byte[])a.Clone(); + b[(10 * W + 10) * 4] ^= 0x80; + b[(12 * W + 14) * 4 + 1] ^= 0x80; + var bytes = Encode([a, b], new ApngEncoderOptions { Alpha = true }, 3000); + var decoded = Decode(bytes, 4); + Assert.Equal(2, decoded.Count); + Assert.Equal(1, decoded[1].Blend); + Assert.Equal((10, 10, 5, 3), decoded[1].Rect); + Assert.BytesEqual(b, decoded[1].Canvas); + } + + [Theory] + [Case(3003L, 1001, 30000)] + [Case(90000L * 30, 30, 1)] + [Case(3001L, 33, 1000)] + public void DelaysAreExactFractionsOrCumulativelyRounded(long duration, int num, int den) + { + var bytes = Encode([Pattern(0, 3), Pattern(1, 3)], new ApngEncoderOptions(), duration); + var fctl = Chunks(bytes).Where(c => c.Type == "fcTL").ToList(); + Assert.Equal((num, den), Delay(fctl[0].Data)); + } + + [Test] + public void LinearBuffersAreEncodedAsSrgb() + { + using var image = new ImageBuffer(W, H, 4); + image.Plane(0).Fill(ColorSpace.Linear8(200)); + image.Plane(1).Fill(ColorSpace.Linear8(100)); + image.Plane(3).Fill(0.5f); + using var ms = new MemoryStream(); + var encoder = new ApngEncoder(ms, W, H, new ApngEncoderOptions { Alpha = true, LoopCount = 2 }); + encoder.AddFrame(image, 9000); + encoder.Complete(); + var decoded = Decode(ms.ToArray(), 4); + Assert.SequenceEqual(new byte[] { 200, 100, 0, 128 }, decoded[0].Canvas.Take(4)); + Assert.Equal(2, BinaryPrimitives.ReadInt32BigEndian(Chunks(ms.ToArray())[1].Data.AsSpan(4))); + } + + private static byte[] Encode(List frames, ApngEncoderOptions options, long duration) + { + using var ms = new MemoryStream(); + var encoder = new ApngEncoder(ms, W, H, options); + foreach (var f in frames) encoder.AddFrame(f, duration); + encoder.Complete(); + return ms.ToArray(); + } + + private static (int, int) Delay(byte[] fctl) => + (BinaryPrimitives.ReadUInt16BigEndian(fctl.AsSpan(20)), BinaryPrimitives.ReadUInt16BigEndian(fctl.AsSpan(22))); + + private sealed record Chunk(string Type, byte[] Data); + + /// Splits the PNG into chunks, checking the signature, lengths and every CRC. + private static List Chunks(byte[] png) + { + Assert.BytesEqual([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], png.AsSpan(0, 8)); + var list = new List(); + var pos = 8; + while (pos < png.Length) + { + var length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(pos)); + var type = Encoding.ASCII.GetString(png, pos + 4, 4); + Assert.Equal(BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), Crc32.Compute(png.AsSpan(pos + 4, length + 4)), $"CRC of {type}"); + list.Add(new Chunk(type, png.AsSpan(pos + 8, length).ToArray())); + pos += 12 + length; + } + Assert.Equal(png.Length, pos); + return list; + } + + private sealed record Frame(byte[] Canvas, (int, int) Delay, (int X, int Y, int W, int H) Rect, int Blend); + + /// Inflates, unfilters and composites every frame (dispose NONE, blend SOURCE/OVER with binary alpha). + private static List Decode(byte[] png, int bpp) + { + var chunks = Chunks(png); + var canvas = new byte[W * H * bpp]; + var frames = new List(); + for (var i = 0; i < chunks.Count; i++) + { + if (chunks[i].Type != "fcTL") continue; + var f = chunks[i].Data; + int w = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(4)), h = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(8)); + int x = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(12)), y = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(16)); + Assert.Equal((byte)0, f[24]); + var data = chunks[i + 1].Type == "IDAT" ? chunks[i + 1].Data : chunks[i + 1].Data[4..]; + var pixels = Unfilter(Inflate(data), w, h, bpp); + for (var row = 0; row < h; row++) + { + for (var col = 0; col < w; col++) + { + var s = (row * w + col) * bpp; + var d = ((y + row) * W + x + col) * bpp; + if (f[25] == 1 && bpp == 4 && pixels[s + 3] == 0) continue; + pixels.AsSpan(s, bpp).CopyTo(canvas.AsSpan(d)); + } + } + frames.Add(new Frame((byte[])canvas.Clone(), Delay(f), (x, y, w, h), f[25])); + } + return frames; + } + + private static byte[] Inflate(byte[] zlib) + { + using var z = new ZLibStream(new MemoryStream(zlib), CompressionMode.Decompress); + using var ms = new MemoryStream(); + z.CopyTo(ms); + return ms.ToArray(); + } + + private static byte[] Unfilter(byte[] filtered, int w, int h, int bpp) + { + var stride = w * bpp; + Assert.Equal((stride + 1) * h, filtered.Length); + var output = new byte[stride * h]; + for (var y = 0; y < h; y++) + { + var filter = filtered[y * (stride + 1)]; + for (var i = 0; i < stride; i++) + { + int raw = filtered[y * (stride + 1) + 1 + i]; + int a = i >= bpp ? output[y * stride + i - bpp] : 0; + int b = y > 0 ? output[(y - 1) * stride + i] : 0; + int c = i >= bpp && y > 0 ? output[(y - 1) * stride + i - bpp] : 0; + output[y * stride + i] = (byte)(filter switch + { + 0 => raw, + 1 => raw + a, + 2 => raw + b, + 3 => raw + ((a + b) >> 1), + _ => raw + Paeth(a, b, c), + }); + } + } + return output; + } + + private static int Paeth(int a, int b, int c) + { + var p = a + b - c; + int pa = Math.Abs(p - a), pb = Math.Abs(p - b), pc = Math.Abs(p - c); + return pa <= pb && pa <= pc ? a : pb <= pc ? b : c; + } + + private static byte[] Pattern(int variant, int bpp) + { + var pixels = new byte[W * H * bpp]; + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + var o = (y * W + x) * bpp; + pixels[o] = (byte)(x * 6 + variant * 40); + pixels[o + 1] = (byte)(y * 8); + pixels[o + 2] = (byte)((x ^ y) * 4 + variant); + if (bpp == 4) pixels[o + 3] = 255; + } + } + return pixels; + } +} From 40870e12dc1fc50d87f645ea5897d2bb59840a3b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 042/188] feat(analysis): add frame statistics, colour temperature and exposure processor FrameStatistics: trimmed log2-luminance mean (fine weighted histogram), 256-bin log histogram, clip fractions, channel means, CCT, Laplacian variance sharpness, Immerkaer noise, mask-weighted region statistics, black/white/duplicate helpers. ColorTemperature: McCamy seed refined to the nearest Krystek Planckian-locus point with a |Duv| <= 0.02 check. ExposureProcessor: SIMD EV/white-balance/region gains and hue-preserving highlight soft clip. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/AnalysisImage.cs | 51 ++++ src/Titano.Core/Analysis/ColorTemperature.cs | 118 ++++++++ src/Titano.Core/Analysis/ExposureProcessor.cs | 149 ++++++++++ src/Titano.Core/Analysis/FrameStatistics.cs | 268 ++++++++++++++++++ .../Analysis/ExposureProcessorTests.cs | 116 ++++++++ 5 files changed, 702 insertions(+) create mode 100644 src/Titano.Core/Analysis/AnalysisImage.cs create mode 100644 src/Titano.Core/Analysis/ColorTemperature.cs create mode 100644 src/Titano.Core/Analysis/ExposureProcessor.cs create mode 100644 src/Titano.Core/Analysis/FrameStatistics.cs create mode 100644 tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs diff --git a/src/Titano.Core/Analysis/AnalysisImage.cs b/src/Titano.Core/Analysis/AnalysisImage.cs new file mode 100644 index 00000000..ffbb24e9 --- /dev/null +++ b/src/Titano.Core/Analysis/AnalysisImage.cs @@ -0,0 +1,51 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Builds the reduced-size images that analysis passes measure. +public static class AnalysisImage +{ + /// + /// Area-average (box) downscale by the smallest integer factor that brings the long edge to at most + /// . Exact for flat fields; trailing rows/columns that do not fill a block are + /// dropped. Returns a copy when no reduction is needed. + /// + public static ImageBuffer Downscale(ImageBuffer source, int maxLongEdge) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentOutOfRangeException.ThrowIfLessThan(maxLongEdge, 1); + var factor = (Math.Max(source.Width, source.Height) + maxLongEdge - 1) / maxLongEdge; + if (factor <= 1) return source.Clone(); + var fx = Math.Min(factor, source.Width); + var fy = Math.Min(factor, source.Height); + var width = source.Width / fx; + var height = source.Height / fy; + var result = new ImageBuffer(width, height, source.Channels, clear: false); + var scale = 1f / (fx * fy); + + void Row(int index) + { + var c = index / height; + var y = index % height; + var target = result.Row(c, y); + target.Clear(); + for (var dy = 0; dy < fy; dy++) + { + var src = source.Row(c, y * fy + dy); + for (var x = 0; x < width; x++) + { + var block = src.Slice(x * fx, fx); + var sum = 0f; + foreach (var v in block) sum += v; + target[x] += sum; + } + } + foreach (ref var v in target) v *= scale; + } + + var rows = height * source.Channels; + if ((long)source.PlaneLength * source.Channels >= 1 << 20) Parallel.For(0, rows, Row); + else for (var i = 0; i < rows; i++) Row(i); + return result; + } +} diff --git a/src/Titano.Core/Analysis/ColorTemperature.cs b/src/Titano.Core/Analysis/ColorTemperature.cs new file mode 100644 index 00000000..ff446f2e --- /dev/null +++ b/src/Titano.Core/Analysis/ColorTemperature.cs @@ -0,0 +1,118 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Correlated colour temperature of a near-Planckian colour. +/// CCT: temperature of the nearest Planckian-locus point in CIE 1960 uv. +/// McCamy's cubic estimate the search started from. +/// Signed uv distance from the locus (positive towards green). +public readonly record struct ColorTemperatureEstimate(double Kelvin, double McCamyKelvin, double Duv); + +/// +/// Colour temperature from chromaticity: McCamy (1992) cubic as the starting point, refined to the closest point +/// of the Planckian locus (Krystek 1985 rational approximation, 1000–15000 K) in CIE 1960 uv. Colours farther than +/// from the locus have no meaningful CCT and are rejected. +/// +public static class ColorTemperature +{ + /// Validity limit on |Duv| (ANSI C78.377 uses ±0.02 as the edge of "white" light). + public const double MaxDuv = 0.02; + + public const double MinKelvin = 1000; + public const double MaxKelvin = 15000; + + /// McCamy's cubic CCT approximation from CIE 1931 xy (epicentre 0.3320, 0.1858). + public static double McCamy(Chromaticity xy) + { + var n = (xy.X - 0.3320) / (0.1858 - xy.Y); + return ((449 * n + 3525) * n + 6823.3) * n + 5520.33; + } + + /// Planckian locus in CIE 1960 uv (Krystek 1985; |Δu|, |Δv| < 1e-4 over 1000–15000 K). + public static (double U, double V) PlanckianUv(double kelvin) + { + var t = kelvin; + var u = (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * t * t) / (1 + 8.42420235e-4 * t + 7.08145163e-7 * t * t); + var v = (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * t * t) / (1 - 2.89741816e-5 * t + 1.61456053e-7 * t * t); + return (u, v); + } + + public static Chromaticity PlanckianChromaticity(double kelvin) + { + var (u, v) = PlanckianUv(kelvin); + return Chromaticity.FromUv1960(u, v); + } + + /// Linear Rec.709 RGB of a Planckian radiator's chromaticity, scaled to luminance 1. + public static Vector3D PlanckianRgb(double kelvin) => Matrix3.XyzToRec709 * PlanckianChromaticity(kelvin).ToXyz(); + + /// Estimate from a chromaticity; null outside the locus range or beyond . + public static ColorTemperatureEstimate? Estimate(Chromaticity xy) + { + if (!double.IsFinite(xy.X) || !double.IsFinite(xy.Y) || !(xy.Y > 0)) return null; + var mcCamy = McCamy(xy); + if (!(mcCamy >= MinKelvin && mcCamy <= MaxKelvin)) return null; + + var (u, v) = xy.ToUv1960(); + // Golden-section search in mireds (the locus is far more uniform in 1/T) around the McCamy seed. + var seed = 1e6 / mcCamy; + double lo = Math.Max(1e6 / MaxKelvin, seed - 40), hi = Math.Min(1e6 / MinKelvin, seed + 40); + const double ratio = 0.6180339887498949; + var a = hi - ratio * (hi - lo); + var b = lo + ratio * (hi - lo); + double fa = Distance2(u, v, a), fb = Distance2(u, v, b); + while (hi - lo > 1e-7) + { + if (fa <= fb) + { + hi = b; + b = a; + fb = fa; + a = hi - ratio * (hi - lo); + fa = Distance2(u, v, a); + } + else + { + lo = a; + a = b; + fa = fb; + b = lo + ratio * (hi - lo); + fb = Distance2(u, v, b); + } + } + var kelvin = 1e6 / (0.5 * (lo + hi)); + var duv = SignedDistance(u, v, kelvin); + if (!(Math.Abs(duv) <= MaxDuv)) return null; + return new ColorTemperatureEstimate(kelvin, mcCamy, duv); + } + + /// Estimate from mean linear Rec.709 RGB; null for non-positive or off-locus colours. + public static ColorTemperatureEstimate? Estimate(double red, double green, double blue) + { + if (!(red > 0 && green > 0 && blue > 0) || !double.IsFinite(red + green + blue)) return null; + return Estimate(Chromaticity.FromXyz(Matrix3.Rec709ToXyz * new Vector3D(red, green, blue))); + } + + private static double Distance2(double u, double v, double mired) + { + var (pu, pv) = PlanckianUv(1e6 / mired); + return (u - pu) * (u - pu) + (v - pv) * (v - pv); + } + + /// Distance to the locus point at , signed by the side of the locus normal + /// that points to larger v (the green side). + private static double SignedDistance(double u, double v, double kelvin) + { + var (pu, pv) = PlanckianUv(kelvin); + var (qu, qv) = PlanckianUv(kelvin * 1.001); + // Normal to the locus tangent, oriented towards +v. + double nu = pv - qv, nv = qu - pu; + if (nv < 0) + { + nu = -nu; + nv = -nv; + } + var distance = Math.Sqrt((u - pu) * (u - pu) + (v - pv) * (v - pv)); + return (u - pu) * nu + (v - pv) * nv >= 0 ? distance : -distance; + } +} diff --git a/src/Titano.Core/Analysis/ExposureProcessor.cs b/src/Titano.Core/Analysis/ExposureProcessor.cs new file mode 100644 index 00000000..06b1b7f7 --- /dev/null +++ b/src/Titano.Core/Analysis/ExposureProcessor.cs @@ -0,0 +1,149 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Per-channel multiplicative gains in linear light (white balance). +public readonly record struct ChannelGains(double Red, double Green, double Blue) +{ + public static ChannelGains Identity { get; } = new(1, 1, 1); +} + +/// +/// Applies per-frame corrections to linear-light images in place: an EV gain, white-balance channel gains, sky/land +/// gains blended through a soft mask, and an optional hue-preserving highlight soft clip. Vectorised with +/// ; large images are split across cores. A fourth (alpha) channel is left untouched. +/// +public static class ExposureProcessor +{ + private const int ParallelThreshold = 1 << 20; + private const int Chunk = 1 << 16; + + /// When set (0 < knee < 1), values above the knee roll off smoothly towards 1. + public static void Apply(ImageBuffer image, double ev, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + var factors = Factors(image, ev, gains); + var knee = Knee(softClipKnee); + ForChunks(image.PlaneLength, (start, length) => + { + for (var c = 0; c < factors.Length; c++) Scale(image.Plane(c).Slice(start, length), factors[c]); + if (knee is { } k && image.Channels >= 3) SoftClip(image, start, length, k); + }); + } + + /// + /// Sky/land correction: per pixel the gain is 2^landEv + m·(2^skyEv − 2^landEv) with m the sky weight, i.e. + /// gains blend linearly across the feathered transition. + /// + public static void ApplyRegion(ImageBuffer image, ReadOnlyMemory skyMask, double skyEv, double landEv, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + if (skyMask.Length != image.PlaneLength) throw new ArgumentException("Mask must have one weight per pixel.", nameof(skyMask)); + if (!double.IsFinite(skyEv)) throw new ArgumentOutOfRangeException(nameof(skyEv)); + var land = Factors(image, landEv, gains); + var sky = Factors(image, skyEv, gains); + var knee = Knee(softClipKnee); + ForChunks(image.PlaneLength, (start, length) => + { + var m = skyMask.Span.Slice(start, length); + for (var c = 0; c < land.Length; c++) Blend(image.Plane(c).Slice(start, length), m, land[c], sky[c] - land[c]); + if (knee is { } k && image.Channels >= 3) SoftClip(image, start, length, k); + }); + } + + /// Scalar reference of the soft clip: identity up to the knee, then knee + e/(1 + e/(1 − knee)) with + /// e = value − knee, which is C¹ at the knee and approaches 1 asymptotically. + public static float SoftClip(float value, float knee) + { + if (!(value > knee)) return value; + var excess = value - knee; + return knee + excess / (1 + excess / (1 - knee)); + } + + private static float[] Factors(ImageBuffer image, double ev, ChannelGains? gains) + { + if (!double.IsFinite(ev)) throw new ArgumentOutOfRangeException(nameof(ev)); + var scale = Math.Pow(2, ev); + if (image.Channels == 1) return [(float)scale]; + var g = gains ?? ChannelGains.Identity; + if (!(g.Red > 0 && g.Green > 0 && g.Blue > 0) || !double.IsFinite(g.Red + g.Green + g.Blue)) + throw new ArgumentOutOfRangeException(nameof(gains), "Gains must be positive and finite."); + return [(float)(scale * g.Red), (float)(scale * g.Green), (float)(scale * g.Blue)]; + } + + private static float? Knee(double? knee) + { + if (knee is not { } k) return null; + if (!(k > 0 && k < 1)) throw new ArgumentOutOfRangeException(nameof(knee), "Knee must lie in (0, 1)."); + return (float)k; + } + + private static void ForChunks(int length, Action body) + { + if (length < ParallelThreshold) + { + body(0, length); + return; + } + var chunks = (length + Chunk - 1) / Chunk; + Parallel.For(0, chunks, i => + { + var start = i * Chunk; + body(start, Math.Min(Chunk, length - start)); + }); + } + + private static void Scale(Span data, float factor) + { + var vectors = MemoryMarshal.Cast>(data); + var f = new Vector(factor); + for (var i = 0; i < vectors.Length; i++) vectors[i] *= f; + for (var i = vectors.Length * Vector.Count; i < data.Length; i++) data[i] *= factor; + } + + private static void Blend(Span data, ReadOnlySpan mask, float baseFactor, float delta) + { + var vectors = MemoryMarshal.Cast>(data); + var masks = MemoryMarshal.Cast>(mask); + var b = new Vector(baseFactor); + var d = new Vector(delta); + for (var i = 0; i < vectors.Length; i++) vectors[i] *= b + masks[i] * d; + for (var i = vectors.Length * Vector.Count; i < data.Length; i++) data[i] *= baseFactor + mask[i] * delta; + } + + /// Compresses the largest channel with and scales all three + /// channels by the same ratio, so hue and saturation are kept. + private static void SoftClip(ImageBuffer image, int start, int length, float knee) + { + var r = image.Plane(0).Slice(start, length); + var g = image.Plane(1).Slice(start, length); + var b = image.Plane(2).Slice(start, length); + var vr = MemoryMarshal.Cast>(r); + var vg = MemoryMarshal.Cast>(g); + var vb = MemoryMarshal.Cast>(b); + var k = new Vector(knee); + var inverseRange = new Vector(1 / (1 - knee)); + for (var i = 0; i < vr.Length; i++) + { + var m = Vector.Max(vr[i], Vector.Max(vg[i], vb[i])); + if (!Vector.GreaterThanAny(m, k)) continue; + var excess = m - k; + var ratio = (k + excess / (Vector.One + excess * inverseRange)) / m; + var s = Vector.ConditionalSelect(Vector.GreaterThan(m, k), ratio, Vector.One); + vr[i] *= s; + vg[i] *= s; + vb[i] *= s; + } + for (var i = vr.Length * Vector.Count; i < length; i++) + { + var m = MathF.Max(r[i], MathF.Max(g[i], b[i])); + if (!(m > knee)) continue; + var s = SoftClip(m, knee) / m; + r[i] *= s; + g[i] *= s; + b[i] *= s; + } + } +} diff --git a/src/Titano.Core/Analysis/FrameStatistics.cs b/src/Titano.Core/Analysis/FrameStatistics.cs new file mode 100644 index 00000000..e817906d --- /dev/null +++ b/src/Titano.Core/Analysis/FrameStatistics.cs @@ -0,0 +1,268 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Thresholds for . +public sealed record FrameStatisticsOptions +{ + public static FrameStatisticsOptions Default { get; } = new(); + + /// Weight fraction trimmed from the dark end of the log-luminance distribution. + public double TrimLow { get; init; } = 0.02; + + /// Weight fraction trimmed from the bright end. + public double TrimHigh { get; init; } = 0.02; + + /// A pixel is crushed when every channel is below this linear level (1/1024 ≈ −10 EV). + public double ClipLowLevel { get; init; } = 1.0 / 1024; + + /// A pixel is clipped when any channel reaches this fraction of . + public double ClipHighFraction { get; init; } = 0.98; + + public double WhiteLevel { get; init; } = 1.0; +} + +/// +/// Per-frame (or per-region) measurements of the deep analysis (BRIEF §10.2), taken in one pass over a +/// downscaled linear-light image (see ) plus one 3×3 neighbourhood pass. +/// +public sealed record FrameStatistics +{ + public const int HistogramBins = 256; + + /// Lower edge of the log-luminance histogram, in EV relative to linear 1.0. + public const double HistogramMinEv = -14; + + /// Upper edge of the log-luminance histogram, in EV relative to linear 1.0. + public const double HistogramMaxEv = 2; + + public int Width { get; init; } + public int Height { get; init; } + + /// Total sample weight: pixel count, or the mask sum for region statistics. + public double Weight { get; init; } + + /// Mean of log2 luminance after trimming both tails (luminance floored at 2⁻¹⁴). + public double MeanLogLuminance { get; init; } + + /// Weight fraction per bin of log2 luminance over [−14, +2) EV; sums to 1. + public double[] Histogram { get; init; } = []; + + public double ClipLowFraction { get; init; } + public double ClipHighFraction { get; init; } + public double MeanRed { get; init; } + public double MeanGreen { get; init; } + public double MeanBlue { get; init; } + + /// Correlated colour temperature of the mean colour; null when it is not near-Planckian. + public ColorTemperatureEstimate? ColorTemperature { get; init; } + + /// Variance of the 4-neighbour Laplacian of sRGB-encoded luminance (focus/blur measure). + public double Sharpness { get; init; } + + /// Noise standard deviation of sRGB-encoded luminance, Immerkær (1996) fast estimator. + public double Noise { get; init; } + + /// Nearly every pixel is crushed (lens cap, missed exposure). + public bool IsBlack(double fraction = 0.95) => ClipLowFraction >= fraction; + + /// Nearly every pixel is clipped (blown exposure). + public bool IsWhite(double fraction = 0.95) => ClipHighFraction >= fraction; + + /// + /// True when two frames have practically identical statistics (histogram, level, colour, detail, noise): a + /// cheap duplicate test before any pixel or hash comparison. + /// + public static bool AreLikelyDuplicates(FrameStatistics a, FrameStatistics b, double tolerance = 1e-6) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + if (a.Width != b.Width || a.Height != b.Height || a.Histogram.Length != b.Histogram.Length) return false; + static bool Close(double x, double y, double tolerance) => Math.Abs(x - y) <= tolerance * (1 + Math.Abs(x) + Math.Abs(y)); + return Close(a.MeanLogLuminance, b.MeanLogLuminance, tolerance) + && Statistics.ChiSquareDistance(a.Histogram, b.Histogram) <= tolerance + && Close(a.MeanRed, b.MeanRed, tolerance) + && Close(a.MeanGreen, b.MeanGreen, tolerance) + && Close(a.MeanBlue, b.MeanBlue, tolerance) + && Close(a.Sharpness, b.Sharpness, tolerance) + && Close(a.Noise, b.Noise, tolerance); + } + + /// Measures an image, optionally weighted by a per-pixel in [0, 1]. + public static FrameStatistics Measure(ImageBuffer image, ReadOnlySpan mask = default, FrameStatisticsOptions? options = null) + { + ArgumentNullException.ThrowIfNull(image); + options ??= FrameStatisticsOptions.Default; + ValidateMask(image, mask); + var n = image.PlaneLength; + var r = image.Plane(0); + var g = image.Channels >= 3 ? image.Plane(1) : r; + var b = image.Channels >= 3 ? image.Plane(2) : r; + var low = (float)options.ClipLowLevel; + var high = (float)(options.ClipHighFraction * options.WhiteLevel); + + var histogram = new LogHistogram(); + var encoded = new float[n]; + double weight = 0, clipLow = 0, clipHigh = 0, sumR = 0, sumG = 0, sumB = 0; + for (var i = 0; i < n; i++) + { + var w = mask.IsEmpty ? 1f : mask[i]; + var y = ColorSpace.Luminance(r[i], g[i], b[i]); + encoded[i] = ColorSpace.EncodeFast(y); + if (!(w > 0)) continue; + weight += w; + histogram.Add(y, w); + var max = MathF.Max(r[i], MathF.Max(g[i], b[i])); + if (max < low) clipLow += w; + if (max >= high) clipHigh += w; + sumR += w * r[i]; + sumG += w * g[i]; + sumB += w * b[i]; + } + + var (sharpness, noise) = Detail(encoded, image.Width, image.Height, mask); + var inverse = weight > 0 ? 1 / weight : double.NaN; + var meanR = sumR * inverse; + var meanG = sumG * inverse; + var meanB = sumB * inverse; + return new FrameStatistics + { + Width = image.Width, + Height = image.Height, + Weight = weight, + MeanLogLuminance = histogram.TrimmedMean(options.TrimLow, options.TrimHigh), + Histogram = histogram.Coarse(HistogramBins), + ClipLowFraction = clipLow * inverse, + ClipHighFraction = clipHigh * inverse, + MeanRed = meanR, + MeanGreen = meanG, + MeanBlue = meanB, + ColorTemperature = image.Channels >= 3 ? Analysis.ColorTemperature.Estimate(meanR, meanG, meanB) : null, + Sharpness = sharpness, + Noise = noise, + }; + } + + /// Only the trimmed mean of log2 luminance (the deflicker signal), optionally mask-weighted. + public static double MeasureLogLuminance(ImageBuffer image, ReadOnlySpan mask = default, double trimLow = 0.02, double trimHigh = 0.02) + { + ArgumentNullException.ThrowIfNull(image); + ValidateMask(image, mask); + var r = image.Plane(0); + var g = image.Channels >= 3 ? image.Plane(1) : r; + var b = image.Channels >= 3 ? image.Plane(2) : r; + var histogram = new LogHistogram(); + for (var i = 0; i < r.Length; i++) + { + var w = mask.IsEmpty ? 1f : mask[i]; + if (w > 0) histogram.Add(ColorSpace.Luminance(r[i], g[i], b[i]), w); + } + return histogram.TrimmedMean(trimLow, trimHigh); + } + + private static void ValidateMask(ImageBuffer image, ReadOnlySpan mask) + { + if (!mask.IsEmpty && mask.Length != image.PlaneLength) + throw new ArgumentException("Mask must have one weight per pixel.", nameof(mask)); + } + + /// Laplacian variance and Immerkær noise σ over interior pixels, weighted by the mask at the centre. + private static (double Sharpness, double Noise) Detail(float[] e, int width, int height, ReadOnlySpan mask) + { + if (width < 3 || height < 3) return (0, 0); + double sw = 0, sl = 0, sl2 = 0, sn = 0; + for (var y = 1; y < height - 1; y++) + { + var row = y * width; + for (var x = 1; x < width - 1; x++) + { + var i = row + x; + var w = mask.IsEmpty ? 1f : mask[i]; + if (!(w > 0)) continue; + double up = e[i - width], down = e[i + width], left = e[i - 1], right = e[i + 1], c = e[i]; + var laplacian = up + down + left + right - 4 * c; + var immerkaer = e[i - width - 1] + e[i - width + 1] + e[i + width - 1] + e[i + width + 1] + - 2 * (up + down + left + right) + 4 * c; + sw += w; + sl += w * laplacian; + sl2 += w * laplacian * laplacian; + sn += w * Math.Abs(immerkaer); + } + } + if (!(sw > 0)) return (0, 0); + var mean = sl / sw; + return (Math.Max(0, sl2 / sw - mean * mean), Math.Sqrt(Math.PI / 2) / 6 * sn / sw); + } + + /// + /// Weighted histogram of log2 luminance with 1/256 EV bins over [−14, +2) that also keeps the weighted sum of + /// the exact log values per bin, so trimmed means are exact except for the one partially trimmed bin per tail. + /// + private sealed class LogHistogram + { + private const int BinsPerEv = 256; + private const int Count = (int)(HistogramMaxEv - HistogramMinEv) * BinsPerEv; + private readonly double[] _weight = new double[Count]; + private readonly double[] _sum = new double[Count]; + + public void Add(float luminance, float weight) + { + var log = luminance > 6.1035156e-05f ? Math.Log2(luminance) : HistogramMinEv; + var bin = (int)((log - HistogramMinEv) * BinsPerEv); + bin = Math.Clamp(bin, 0, Count - 1); + _weight[bin] += weight; + _sum[bin] += weight * log; + } + + public double TrimmedMean(double trimLow, double trimHigh) + { + if (!(trimLow >= 0 && trimHigh >= 0 && trimLow + trimHigh < 1)) + throw new ArgumentOutOfRangeException(nameof(trimLow), "Trim fractions must be ≥ 0 and sum below 1."); + double total = 0; + foreach (var w in _weight) total += w; + if (!(total > 0)) return double.NaN; + var kept = (double[])_weight.Clone(); + var remaining = trimLow * total; + for (var i = 0; i < Count && remaining > 0; i++) + { + var take = Math.Min(kept[i], remaining); + kept[i] -= take; + remaining -= take; + } + remaining = trimHigh * total; + for (var i = Count - 1; i >= 0 && remaining > 0; i--) + { + var take = Math.Min(kept[i], remaining); + kept[i] -= take; + remaining -= take; + } + double keptWeight = 0, keptSum = 0; + for (var i = 0; i < Count; i++) + { + if (!(kept[i] > 0)) continue; + keptWeight += kept[i]; + keptSum += _sum[i] * (kept[i] / _weight[i]); + } + return keptWeight > 0 ? keptSum / keptWeight : double.NaN; + } + + /// Normalised coarse histogram (bins must divide the fine bin count). + public double[] Coarse(int bins) + { + var result = new double[bins]; + var group = Count / bins; + double total = 0; + for (var i = 0; i < Count; i++) + { + result[i / group] += _weight[i]; + total += _weight[i]; + } + if (total > 0) + { + for (var i = 0; i < bins; i++) result[i] /= total; + } + return result; + } + } +} diff --git a/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs b/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs new file mode 100644 index 00000000..a4ad4bdc --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs @@ -0,0 +1,116 @@ +using Titano.Core.Analysis; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class ExposureProcessorTests +{ + // 37 × 5 = 185 pixels: not a multiple of any vector width, so the scalar tail runs too. + private static ImageBuffer Ramp(int width = 37, int height = 5, int channels = 3) + { + var image = new ImageBuffer(width, height, channels); + var data = image.Data; + for (var i = 0; i < data.Length; i++) data[i] = 0.001f * (i % 997); + return image; + } + + [Test] + public void EvAndChannelGainsMultiply() + { + using var image = Ramp(); + using var original = image.Clone(); + ExposureProcessor.Apply(image, 1, new ChannelGains(1.5, 1, 0.5)); + float[] factors = [3, 2, 1]; + for (var c = 0; c < 3; c++) + { + for (var i = 0; i < image.PlaneLength; i++) + Assert.Approximately(factors[c] * original.Plane(c)[i], image.Plane(c)[i], 1e-6); + } + Assert.Throws(() => ExposureProcessor.Apply(image, double.NaN)); + Assert.Throws(() => ExposureProcessor.Apply(image, 0, new ChannelGains(0, 1, 1))); + } + + [Test] + public void SingleChannelAndAlphaAreHandled() + { + using var grey = Ramp(channels: 1); + using var greyOriginal = grey.Clone(); + ExposureProcessor.Apply(grey, -1, new ChannelGains(4, 4, 4)); + Assert.Approximately(0.5 * greyOriginal.Plane(0)[100], grey.Plane(0)[100], 1e-7); + + using var rgba = Ramp(channels: 4); + using var rgbaOriginal = rgba.Clone(); + ExposureProcessor.Apply(rgba, 2); + Assert.SequenceEqual(rgbaOriginal.Plane(3).ToArray(), rgba.Plane(3).ToArray()); + Assert.Approximately(4 * rgbaOriginal.Plane(2)[50], rgba.Plane(2)[50], 1e-6); + } + + [Test] + public void RegionGainsBlendThroughTheMask() + { + using var image = new ImageBuffer(37, 5, 3); + image.Data.Fill(0.1f); + var mask = new float[image.PlaneLength]; + for (var i = 0; i < mask.Length; i++) mask[i] = (i % 3) * 0.5f; + ExposureProcessor.ApplyRegion(image, mask, skyEv: 1, landEv: -1); + for (var i = 0; i < mask.Length; i++) + { + var expected = 0.1 * (0.5 + mask[i] * (2 - 0.5)); + Assert.Approximately(expected, image.Plane(1)[i], 1e-7); + } + Assert.Throws(() => ExposureProcessor.ApplyRegion(image, new float[3], 0, 0)); + } + + [Test] + public void SoftClipIsSmoothBoundedAndKeepsHue() + { + const float knee = 0.8f; + Assert.Equal(0.5f, ExposureProcessor.SoftClip(0.5f, knee)); + Assert.Approximately(knee, ExposureProcessor.SoftClip(knee + 1e-6f, knee), 1e-5); + var values = Enumerable.Range(0, 400).Select(i => (double)ExposureProcessor.SoftClip(i * 0.05f, knee)).ToList(); + Assert.Monotonic(values); + Assert.Less(values.Max(), 1); + // Slope 1 at the knee (C¹): the secant over h above it is 1 / (1 + h / (1 − knee)). + var slope = (ExposureProcessor.SoftClip(knee + 1e-3f, knee) - knee) / 1e-3f; + Assert.Approximately(1 / (1 + 1e-3 / (1 - knee)), slope, 1e-3); + + using var image = new ImageBuffer(37, 5, 3); + for (var i = 0; i < image.PlaneLength; i++) + { + image.Plane(0)[i] = 0.02f * i; + image.Plane(1)[i] = 0.01f * i; + image.Plane(2)[i] = 0.005f * i; + } + ExposureProcessor.Apply(image, 0, softClipKnee: knee); + for (var i = 1; i < image.PlaneLength; i++) + { + var r = image.Plane(0)[i]; + Assert.LessOrEqual(r, 1); + Assert.Approximately(2, r / image.Plane(1)[i], 1e-4); + Assert.Approximately(2, image.Plane(1)[i] / image.Plane(2)[i], 1e-4); + Assert.Approximately(ExposureProcessor.SoftClip(0.02f * i, knee), r, 1e-5); + } + } + + [Test] + public void LargeImagesTakeTheParallelPathWithTheSameResult() + { + using var image = new ImageBuffer(1100, 1000, 3); + var data = image.Data; + for (var i = 0; i < data.Length; i++) data[i] = (i % 1000) * 0.0012f; + using var expected = image.Clone(); + ExposureProcessor.Apply(image, 0.5, softClipKnee: 0.9); + var gain = (float)Math.Pow(2, 0.5); + foreach (var index in new[] { 0, 12345, 777_777, 1_099_999 }) + { + var r = expected.Plane(0)[index] * gain; + var g = expected.Plane(1)[index] * gain; + var b = expected.Plane(2)[index] * gain; + var m = Math.Max(r, Math.Max(g, b)); + var s = m > 0.9f ? ExposureProcessor.SoftClip(m, 0.9f) / m : 1; + Assert.Approximately(r * s, image.Plane(0)[index], 1e-5); + Assert.Approximately(b * s, image.Plane(2)[index], 1e-5); + } + } +} From 3b3d7b7f6b5f9180d0d507e629df4ecc5a1fb5b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 043/188] feat(analysis): add metadata light analyzer with findings Cadence, jitter, gaps and sessions (small sessions merge), timestamp sanity (duplicates, out-of-order frames, clock jumps incl. DST), EV series and exposure steps, camera/lens identity, resolution and orientation consistency, and NOAA day phases from GPS. Findings carry stable resource keys plus positional arguments. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/Finding.cs | 38 ++ .../Analysis/LightAnalysisReport.cs | 135 ++++++ src/Titano.Core/Analysis/LightAnalyzer.cs | 390 ++++++++++++++++++ src/Titano.Core/Analysis/LightFrame.cs | 84 ++++ 4 files changed, 647 insertions(+) create mode 100644 src/Titano.Core/Analysis/Finding.cs create mode 100644 src/Titano.Core/Analysis/LightAnalysisReport.cs create mode 100644 src/Titano.Core/Analysis/LightAnalyzer.cs create mode 100644 src/Titano.Core/Analysis/LightFrame.cs diff --git a/src/Titano.Core/Analysis/Finding.cs b/src/Titano.Core/Analysis/Finding.cs new file mode 100644 index 00000000..217208d6 --- /dev/null +++ b/src/Titano.Core/Analysis/Finding.cs @@ -0,0 +1,38 @@ +namespace Titano.Core.Analysis; + +public enum FindingSeverity +{ + Info, + Warning, + Error, +} + +/// +/// One explainable analysis result. is a stable resource key (e.g. Advisor.Finding.Gaps) +/// whose localised text is a composite format filled with (Loc.L(Key, Arguments)). +/// +/// Indices of the frames concerned (capped at ). +public sealed record Finding(string Key, FindingSeverity Severity, object[] Arguments, IReadOnlyList Frames) +{ + public const int MaxFrames = 256; +} + +/// Resource keys of the findings produced by the analysis modules. +public static class FindingKeys +{ + public const string NoTimestamps = "Advisor.Finding.NoTimestamps"; + public const string Gaps = "Advisor.Finding.Gaps"; + public const string Sessions = "Advisor.Finding.Sessions"; + public const string IrregularInterval = "Advisor.Finding.IrregularInterval"; + public const string DuplicateTimestamps = "Advisor.Finding.DuplicateTimestamps"; + public const string NonMonotonicTimestamps = "Advisor.Finding.NonMonotonicTimestamps"; + public const string ClockJumps = "Advisor.Finding.ClockJumps"; + public const string ExposureSteps = "Advisor.Finding.ExposureSteps"; + public const string MissingExposure = "Advisor.Finding.MissingExposure"; + public const string CameraChanged = "Advisor.Finding.CameraChanged"; + public const string LensChanged = "Advisor.Finding.LensChanged"; + public const string MixedResolution = "Advisor.Finding.MixedResolution"; + public const string MixedOrientation = "Advisor.Finding.MixedOrientation"; + public const string TimeZoneEstimated = "Advisor.Finding.TimeZoneEstimated"; + public const string DayNightTransition = "Advisor.Finding.DayNightTransition"; +} diff --git a/src/Titano.Core/Analysis/LightAnalysisReport.cs b/src/Titano.Core/Analysis/LightAnalysisReport.cs new file mode 100644 index 00000000..501ca433 --- /dev/null +++ b/src/Titano.Core/Analysis/LightAnalysisReport.cs @@ -0,0 +1,135 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record LightAnalysisOptions +{ + public static LightAnalysisOptions Default { get; } = new(); + + /// A pause at least this long starts a new capture session. + public double SessionGapMinutes { get; init; } = 45; + + /// Sessions with fewer frames merge into the previous session (the first into the next). + public int MinimumSessionFrames { get; init; } = 8; + + /// An interval longer than this multiple of the median interval is a gap. + public double GapFactor { get; init; } = 3; + + /// Relative shutter-time or f-number change treated as a deliberate setting change. + public double ExposureTolerance { get; init; } = 0.01; + + /// Interval jitter (MAD) above this fraction of the median interval is reported. + public double IrregularIntervalFraction { get; init; } = 0.1; +} + +/// How the interval leading into a frame was classified. +public enum IntervalKind +{ + Regular, + + /// Longer than × the median interval. + Gap, + + /// At least . + SessionBreak, + + /// Same capture time as the previous frame. + Duplicate, + + /// Small step backwards in time (frames out of order). + NonMonotonic, + + /// Camera clock change: a backward step longer than the gap threshold, or a step exactly one hour off + /// the cadence (daylight-saving change). + ClockJump, +} + +/// The interval between the previous timed frame and frame . +public readonly record struct FrameInterval(int Index, double Seconds, IntervalKind Kind); + +/// A run of frames shot without a pause of or more. +public sealed record CaptureSession(int StartIndex, int EndIndex, DateTime? Start, DateTime? End) +{ + public int FrameCount => EndIndex - StartIndex + 1; +} + +[Flags] +public enum ExposureChange +{ + None = 0, + Shutter = 1, + Aperture = 2, + Iso = 4, +} + +/// A change of exposure settings between frame − 1 and . +public sealed record ExposureStep(int Index, ExposureChange Changes, double EvBefore, double EvAfter) +{ + /// Camera EV change; the pixels brighten by − stops. + public double DeltaEv => EvAfter - EvBefore; +} + +public enum IdentityKind +{ + Camera, + Lens, +} + +/// The camera body or lens differs from the previous frame that recorded one. +public sealed record IdentityChange(int Index, IdentityKind Kind, string? Before, string After); + +/// Result of the metadata-only light analysis (BRIEF §10.1). Frame indices are positions in the input list. +public sealed record LightAnalysisReport +{ + public int FrameCount { get; init; } + public int TimedFrameCount { get; init; } + + /// Median of the positive intervals shorter than the session gap, in seconds. + public double? MedianIntervalSeconds { get; init; } + + /// Median absolute deviation of the regular intervals, in seconds. + public double? JitterSeconds { get; init; } + + public DateTime? FirstCapture { get; init; } + public DateTime? LastCapture { get; init; } + + /// Capture duration on the clock-corrected timeline (clock jumps count as one median interval). + public TimeSpan CaptureSpan { get; init; } + + /// Camera clock per frame with clock jumps and backward steps removed; null for untimed frames. + public DateTime?[] AdjustedTimes { get; init; } = []; + + /// Every interval between consecutive timed frames. + public IReadOnlyList Intervals { get; init; } = []; + + /// Intervals classified as or . + public IReadOnlyList Gaps { get; init; } = []; + + /// Duplicate, non-monotonic and clock-jump intervals. + public IReadOnlyList TimestampIssues { get; init; } = []; + + public IReadOnlyList Sessions { get; init; } = []; + + /// EV at ISO 100 per frame; null when shutter time or f-number is missing. + public double?[] ExposureValues { get; init; } = []; + + public IReadOnlyList ExposureSteps { get; init; } = []; + + /// Median number of frames between consecutive exposure steps (null with fewer than two steps). + public double? TypicalStepDistance { get; init; } + + public IReadOnlyList IdentityChanges { get; init; } = []; + + /// Most common oriented size, null when no frame records its size. + public (int Width, int Height)? DominantSize { get; init; } + + public IReadOnlyList ResolutionOutliers { get; init; } = []; + public int DominantOrientation { get; init; } = 1; + public IReadOnlyList OrientationOutliers { get; init; } = []; + + /// Light condition per frame from GPS position and capture time; all null without GPS. + public DayPhase?[] DayPhases { get; init; } = []; + + public IReadOnlyList Findings { get; init; } = []; +} diff --git a/src/Titano.Core/Analysis/LightAnalyzer.cs b/src/Titano.Core/Analysis/LightAnalyzer.cs new file mode 100644 index 00000000..0fc5dc9b --- /dev/null +++ b/src/Titano.Core/Analysis/LightAnalyzer.cs @@ -0,0 +1,390 @@ +using Titano.Core.Mathematics; +using Titano.Core.Model; + +namespace Titano.Core.Analysis; + +/// +/// Metadata-only sequence analysis run at import/scan (BRIEF §10.1): cadence, gaps and sessions, timestamp +/// sanity, exposure series and steps, camera/lens identity, size and orientation consistency, and day phases +/// from GPS. Linear in the number of frames apart from two medians; deterministic. +/// +public static class LightAnalyzer +{ + private const double SameTimeSeconds = 0.001; + private const double Hour = 3600; + + public static LightAnalysisReport Analyze(IReadOnlyList frames, LightAnalysisOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + var light = new LightFrame[frames.Count]; + for (var i = 0; i < light.Length; i++) light[i] = LightFrame.From(frames[i]); + return Analyze(light, options); + } + + public static LightAnalysisReport Analyze(IReadOnlyList frames, LightAnalysisOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + options ??= LightAnalysisOptions.Default; + if (!(options.GapFactor > 1)) throw new ArgumentOutOfRangeException(nameof(options), "GapFactor must exceed 1."); + var findings = new List(); + var timing = AnalyzeTiming(frames, options, findings); + var exposure = AnalyzeExposure(frames, options, findings); + var identity = AnalyzeIdentity(frames, findings); + var (dominantSize, sizeOutliers, orientation, orientationOutliers) = AnalyzeGeometry(frames, findings); + var phases = AnalyzeDayPhases(frames, timing.Adjusted, findings); + + return new LightAnalysisReport + { + FrameCount = frames.Count, + TimedFrameCount = timing.TimedCount, + MedianIntervalSeconds = timing.Median, + JitterSeconds = timing.Jitter, + FirstCapture = timing.First, + LastCapture = timing.Last, + CaptureSpan = timing.Span, + AdjustedTimes = timing.Adjusted, + Intervals = timing.Intervals, + Gaps = timing.Intervals.Where(i => i.Kind is IntervalKind.Gap or IntervalKind.SessionBreak).ToList(), + TimestampIssues = timing.Intervals.Where(i => i.Kind is IntervalKind.Duplicate or IntervalKind.NonMonotonic or IntervalKind.ClockJump).ToList(), + Sessions = timing.Sessions, + ExposureValues = exposure.Values, + ExposureSteps = exposure.Steps, + TypicalStepDistance = exposure.TypicalDistance, + IdentityChanges = identity, + DominantSize = dominantSize, + ResolutionOutliers = sizeOutliers, + DominantOrientation = orientation, + OrientationOutliers = orientationOutliers, + DayPhases = phases, + Findings = findings, + }; + } + + private sealed record Timing( + int TimedCount, + double? Median, + double? Jitter, + DateTime? First, + DateTime? Last, + TimeSpan Span, + DateTime?[] Adjusted, + List Intervals, + List Sessions); + + private static Timing AnalyzeTiming(IReadOnlyList frames, LightAnalysisOptions options, List findings) + { + var n = frames.Count; + var sessionGap = options.SessionGapMinutes * 60; + var raw = new List<(int Index, double Seconds)>(); + int? previous = null; + var timedCount = 0; + for (var i = 0; i < n; i++) + { + if (frames[i].CapturedAt is not { } t) continue; + timedCount++; + if (previous is { } p) raw.Add((i, (t - frames[p].CapturedAt!.Value).TotalSeconds)); + previous = i; + } + if (timedCount < 2 && n >= 2) + findings.Add(new Finding(FindingKeys.NoTimestamps, FindingSeverity.Warning, [timedCount, n], [])); + + var cadence = raw.Where(d => d.Seconds > SameTimeSeconds && d.Seconds < sessionGap).Select(d => d.Seconds).ToArray(); + if (cadence.Length == 0) cadence = raw.Where(d => d.Seconds > SameTimeSeconds).Select(d => d.Seconds).ToArray(); + double? median = cadence.Length > 0 ? Statistics.Median(cadence) : null; + double? jitter = null; + if (median is { } m) + { + var regular = raw.Where(d => d.Seconds > SameTimeSeconds && d.Seconds <= options.GapFactor * m).Select(d => d.Seconds).ToArray(); + jitter = regular.Length > 0 ? Statistics.MedianAbsoluteDeviation(regular) : 0; + } + var tolerance = median is { } med ? Math.Max(2, Math.Max(3 * Statistics.MadToSigma * (jitter ?? 0), 0.05 * med)) : 0; + + var intervals = new List(raw.Count); + foreach (var (index, seconds) in raw) + intervals.Add(new FrameInterval(index, seconds, Classify(seconds, median, tolerance, sessionGap, options.GapFactor))); + + // Clock-corrected timeline: jumps count as one cadence step, backward steps as none. + var adjusted = new DateTime?[n]; + var first = -1; + var last = -1; + for (var i = 0; i < n; i++) + { + if (frames[i].CapturedAt is null) continue; + if (first < 0) first = i; + last = i; + } + if (first >= 0) adjusted[first] = frames[first].CapturedAt; + var previousTimed = first; + foreach (var interval in intervals) + { + var advance = interval.Kind switch + { + IntervalKind.ClockJump => median ?? 0, + IntervalKind.Duplicate or IntervalKind.NonMonotonic => 0, + _ => interval.Seconds, + }; + adjusted[interval.Index] = adjusted[previousTimed]!.Value.AddSeconds(advance); + previousTimed = interval.Index; + } + var span = first >= 0 ? adjusted[last]!.Value - adjusted[first]!.Value : TimeSpan.Zero; + + var sessions = BuildSessions(frames, intervals, options.MinimumSessionFrames); + ReportTiming(intervals, sessions, median, jitter, options, findings); + return new Timing(timedCount, median, jitter, first >= 0 ? frames[first].CapturedAt : null, last >= 0 ? frames[last].CapturedAt : null, + span, adjusted, intervals, sessions); + } + + private static IntervalKind Classify(double seconds, double? median, double tolerance, double sessionGap, double gapFactor) + { + if (Math.Abs(seconds) < SameTimeSeconds) return IntervalKind.Duplicate; + if (median is not { } m) return seconds < 0 ? IntervalKind.NonMonotonic : IntervalKind.Regular; + // A daylight-saving change shifts the clock by exactly one hour while the cadence continues. Longer + // whole-hour pauses are left alone: scheduled intervalometer breaks look the same. + var hours = Math.Round((seconds - m) / Hour); + var hourAligned = Math.Abs(hours) == 1 && m < Hour / 2 && Math.Abs(seconds - m - hours * Hour) <= tolerance; + if (seconds < 0) return hourAligned || -seconds > gapFactor * m ? IntervalKind.ClockJump : IntervalKind.NonMonotonic; + if (hourAligned) return IntervalKind.ClockJump; + if (seconds >= sessionGap) return IntervalKind.SessionBreak; + return seconds > gapFactor * m ? IntervalKind.Gap : IntervalKind.Regular; + } + + private static List BuildSessions(IReadOnlyList frames, List intervals, int minimumFrames) + { + var n = frames.Count; + var ranges = new List<(int Start, int End)>(); + if (n == 0) return []; + var start = 0; + foreach (var interval in intervals) + { + if (interval.Kind != IntervalKind.SessionBreak) continue; + ranges.Add((start, interval.Index - 1)); + start = interval.Index; + } + ranges.Add((start, n - 1)); + + for (var i = 0; i < ranges.Count && ranges.Count > 1;) + { + if (ranges[i].End - ranges[i].Start + 1 >= minimumFrames) + { + i++; + continue; + } + if (i > 0) + { + ranges[i - 1] = (ranges[i - 1].Start, ranges[i].End); + ranges.RemoveAt(i); + } + else + { + ranges[1] = (ranges[0].Start, ranges[1].End); + ranges.RemoveAt(0); + } + } + + var sessions = new List(ranges.Count); + foreach (var (s, e) in ranges) + { + DateTime? first = null, last = null; + for (var i = s; i <= e; i++) + { + if (frames[i].CapturedAt is not { } t) continue; + first ??= t; + last = t; + } + sessions.Add(new CaptureSession(s, e, first, last)); + } + return sessions; + } + + private static void ReportTiming(List intervals, List sessions, double? median, double? jitter, LightAnalysisOptions options, List findings) + { + var gaps = intervals.Where(i => i.Kind is IntervalKind.Gap or IntervalKind.SessionBreak).ToList(); + if (gaps.Count > 0) + findings.Add(new Finding(FindingKeys.Gaps, FindingSeverity.Warning, [gaps.Count, gaps.Max(g => g.Seconds)], Indices(gaps))); + if (sessions.Count > 1) + findings.Add(new Finding(FindingKeys.Sessions, FindingSeverity.Info, [sessions.Count], Cap(sessions.Select(s => s.StartIndex)))); + if (median is { } m && jitter is { } j && j > options.IrregularIntervalFraction * m) + findings.Add(new Finding(FindingKeys.IrregularInterval, FindingSeverity.Info, [j, m], [])); + AddIssue(intervals, IntervalKind.Duplicate, FindingKeys.DuplicateTimestamps, findings); + AddIssue(intervals, IntervalKind.NonMonotonic, FindingKeys.NonMonotonicTimestamps, findings); + var jumps = intervals.Where(i => i.Kind == IntervalKind.ClockJump).ToList(); + if (jumps.Count > 0) + { + var largest = jumps.MaxBy(i => Math.Abs(i.Seconds - (median ?? 0))); + findings.Add(new Finding(FindingKeys.ClockJumps, FindingSeverity.Warning, [jumps.Count, largest.Seconds - (median ?? 0)], Indices(jumps))); + } + } + + private static void AddIssue(List intervals, IntervalKind kind, string key, List findings) + { + var issues = intervals.Where(i => i.Kind == kind).ToList(); + if (issues.Count > 0) findings.Add(new Finding(key, FindingSeverity.Warning, [issues.Count], Indices(issues))); + } + + private sealed record Exposure(double?[] Values, List Steps, double? TypicalDistance); + + private static Exposure AnalyzeExposure(IReadOnlyList frames, LightAnalysisOptions options, List findings) + { + var n = frames.Count; + var values = new double?[n]; + var steps = new List(); + var missing = new List(); + var logTolerance = Math.Log(1 + options.ExposureTolerance); + var previous = -1; + for (var i = 0; i < n; i++) + { + var f = frames[i]; + values[i] = f.ExposureValue; + if (values[i] is null) + { + missing.Add(i); + continue; + } + if (previous >= 0) + { + var p = frames[previous]; + var changes = ExposureChange.None; + if (Math.Abs(Math.Log(f.ExposureTime!.Value / p.ExposureTime!.Value)) > logTolerance) changes |= ExposureChange.Shutter; + if (Math.Abs(Math.Log(f.FNumber!.Value / p.FNumber!.Value)) > logTolerance) changes |= ExposureChange.Aperture; + if ((f.Iso ?? 100) != (p.Iso ?? 100)) changes |= ExposureChange.Iso; + if (changes != ExposureChange.None) steps.Add(new ExposureStep(i, changes, values[previous]!.Value, values[i]!.Value)); + } + previous = i; + } + + double? typical = null; + if (steps.Count >= 2) + { + var distances = new double[steps.Count - 1]; + for (var i = 1; i < steps.Count; i++) distances[i - 1] = steps[i].Index - steps[i - 1].Index; + typical = Statistics.Median(distances); + } + if (steps.Count > 0) + { + var total = steps.Sum(s => s.DeltaEv); + findings.Add(new Finding(FindingKeys.ExposureSteps, FindingSeverity.Info, [steps.Count, typical ?? 0, total], Cap(steps.Select(s => s.Index)))); + } + if (missing.Count > 0 && n > 0) + findings.Add(new Finding(FindingKeys.MissingExposure, FindingSeverity.Info, [missing.Count], Cap(missing))); + return new Exposure(values, steps, typical); + } + + private static List AnalyzeIdentity(IReadOnlyList frames, List findings) + { + var changes = new List(); + string? camera = null, lens = null; + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + var body = Join(f.CameraMake, f.CameraModel, f.CameraSerial); + if (body is not null) + { + if (camera is not null && !string.Equals(camera, body, StringComparison.Ordinal)) + changes.Add(new IdentityChange(i, IdentityKind.Camera, camera, body)); + camera = body; + } + var l = string.IsNullOrWhiteSpace(f.Lens) ? null : f.Lens.Trim(); + if (l is not null) + { + if (lens is not null && !string.Equals(lens, l, StringComparison.Ordinal)) + changes.Add(new IdentityChange(i, IdentityKind.Lens, lens, l)); + lens = l; + } + } + var bodyChanges = changes.Where(c => c.Kind == IdentityKind.Camera).Select(c => c.Index).ToList(); + if (bodyChanges.Count > 0) findings.Add(new Finding(FindingKeys.CameraChanged, FindingSeverity.Warning, [bodyChanges.Count], Cap(bodyChanges))); + var lensChanges = changes.Where(c => c.Kind == IdentityKind.Lens).Select(c => c.Index).ToList(); + if (lensChanges.Count > 0) findings.Add(new Finding(FindingKeys.LensChanged, FindingSeverity.Warning, [lensChanges.Count], Cap(lensChanges))); + return changes; + } + + private static string? Join(params string?[] parts) + { + var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!.Trim()).ToArray(); + return present.Length == 0 ? null : string.Join(' ', present); + } + + private static ((int, int)? Size, List SizeOutliers, int Orientation, List OrientationOutliers) AnalyzeGeometry(IReadOnlyList frames, List findings) + { + var sizes = new Dictionary<(int, int), int>(); + var orientations = new Dictionary(); + foreach (var f in frames) + { + if (f.Width > 0 && f.Height > 0) sizes[f.OrientedSize] = sizes.GetValueOrDefault(f.OrientedSize) + 1; + orientations[f.Orientation] = orientations.GetValueOrDefault(f.Orientation) + 1; + } + // Dictionaries preserve first-insertion order here (no removals), so ties go to the first value seen. + (int, int)? dominant = sizes.Count > 0 ? sizes.MaxBy(kv => kv.Value).Key : null; + var orientation = orientations.Count > 0 ? orientations.MaxBy(kv => kv.Value).Key : 1; + var sizeOutliers = new List(); + var orientationOutliers = new List(); + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + if (dominant is { } d && f.Width > 0 && f.Height > 0 && f.OrientedSize != d) sizeOutliers.Add(i); + if (f.Orientation != orientation) orientationOutliers.Add(i); + } + if (sizeOutliers.Count > 0 && dominant is { } ds) + findings.Add(new Finding(FindingKeys.MixedResolution, FindingSeverity.Warning, [sizeOutliers.Count, ds.Item1, ds.Item2], Cap(sizeOutliers))); + if (orientationOutliers.Count > 0) + findings.Add(new Finding(FindingKeys.MixedOrientation, FindingSeverity.Warning, [orientationOutliers.Count], Cap(orientationOutliers))); + return (dominant, sizeOutliers, orientation, orientationOutliers); + } + + private static DayPhase?[] AnalyzeDayPhases(IReadOnlyList frames, DateTime?[] adjusted, List findings) + { + var n = frames.Count; + var phases = new DayPhase?[n]; + (double Lat, double Lon)? fallback = null; + int? sequenceOffset = null; + foreach (var f in frames) + { + fallback ??= Location(f); + sequenceOffset ??= Offset(f); + } + if (fallback is not { } site) return phases; + if (sequenceOffset is null) + { + // No recorded offset: assume the nominal zone of the longitude. + sequenceOffset = (int)Math.Round(site.Lon / 15) * 60; + findings.Add(new Finding(FindingKeys.TimeZoneEstimated, FindingSeverity.Info, [sequenceOffset.Value], [])); + } + + int day = 0, twilight = 0, night = 0; + for (var i = 0; i < n; i++) + { + if (adjusted[i] is not { } local) continue; + var (lat, lon) = Location(frames[i]) ?? site; + var utc = DateTime.SpecifyKind(local.AddMinutes(-(Offset(frames[i]) ?? sequenceOffset.Value)), DateTimeKind.Utc); + var phase = SolarPosition.Phase(utc, lat, lon); + phases[i] = phase; + switch (phase) + { + case DayPhase.Day or DayPhase.GoldenHour: day++; break; + case DayPhase.Night or DayPhase.AstronomicalTwilight: night++; break; + default: twilight++; break; + } + } + if (day > 0 && night > 0) + findings.Add(new Finding(FindingKeys.DayNightTransition, FindingSeverity.Info, [day, twilight, night], [])); + return phases; + } + + private static (double, double)? Location(LightFrame f) => + f.Latitude is { } lat && f.Longitude is { } lon && lat is >= -90 and <= 90 && lon is >= -180 and <= 180 && (lat != 0 || lon != 0) + ? (lat, lon) + : null; + + /// Recorded UTC offset, else the camera-clock minus GPS-time difference rounded to 15 minutes. + private static int? Offset(LightFrame f) + { + if (f.UtcOffsetMinutes is { } recorded) return recorded; + if (f.CapturedAt is not { } local || f.GpsUtc is not { } gps) return null; + var minutes = (local - gps).TotalMinutes; + return Math.Abs(minutes) <= 14 * 60 ? (int)Math.Round(minutes / 15) * 15 : null; + } + + private static List Indices(List intervals) => Cap(intervals.Select(i => i.Index)); + + private static List Cap(IEnumerable indices) => indices.Take(Finding.MaxFrames).ToList(); +} diff --git a/src/Titano.Core/Analysis/LightFrame.cs b/src/Titano.Core/Analysis/LightFrame.cs new file mode 100644 index 00000000..40529c0f --- /dev/null +++ b/src/Titano.Core/Analysis/LightFrame.cs @@ -0,0 +1,84 @@ +using Titano.Core.Metadata; +using Titano.Core.Model; + +namespace Titano.Core.Analysis; + +/// The metadata the light analysis needs from one frame (BRIEF §10.1). +public sealed record LightFrame +{ + public int Index { get; init; } + + /// Camera wall-clock capture time (unspecified kind). + public DateTime? CapturedAt { get; init; } + + /// UTC offset of in minutes, when recorded. + public int? UtcOffsetMinutes { get; init; } + + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? ExposureBias { get; init; } + public int Width { get; init; } + public int Height { get; init; } + public int Orientation { get; init; } = 1; + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? Lens { get; init; } + public double? Latitude { get; init; } + public double? Longitude { get; init; } + + /// GPS (satellite) UTC time stamp, used to infer the camera clock's UTC offset. + public DateTime? GpsUtc { get; init; } + + /// Exposure value at ISO 100: log2(N²/t) − log2(ISO/100). + public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0 + ? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso is > 0 ? Iso.Value : 100) / 100.0) + : null; + + /// Width and height after Exif orientations 5–8 (90° rotations). + public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height); + + public static LightFrame From(Frame frame) + { + ArgumentNullException.ThrowIfNull(frame); + return new LightFrame + { + Index = frame.Index, + CapturedAt = frame.CapturedAt, + UtcOffsetMinutes = frame.UtcOffsetMinutes, + ExposureTime = frame.ExposureTime, + FNumber = frame.FNumber, + Iso = frame.Iso, + ExposureBias = frame.ExposureBias, + Width = frame.Width, + Height = frame.Height, + Orientation = frame.Orientation, + }; + } + + public static LightFrame From(FrameMetadata metadata, int index) + { + ArgumentNullException.ThrowIfNull(metadata); + return new LightFrame + { + Index = index, + CapturedAt = metadata.CapturedAt, + UtcOffsetMinutes = metadata.UtcOffsetMinutes, + ExposureTime = metadata.ExposureTime, + FNumber = metadata.FNumber, + Iso = metadata.Iso, + ExposureBias = metadata.ExposureBias, + Width = metadata.Width, + Height = metadata.Height, + Orientation = metadata.Orientation, + CameraMake = metadata.Make, + CameraModel = metadata.Model, + CameraSerial = metadata.BodySerial, + Lens = metadata.LensModel, + Latitude = metadata.Gps?.Latitude, + Longitude = metadata.Gps?.Longitude, + GpsUtc = metadata.Gps?.UtcTimestamp, + }; + } +} From 353143b953f438588f58d5e328d3e2c09a620338 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 044/188] feat(diagnostics): add deterministic synthetic sequence generator Known-answer fixtures: brightness ramp, seeded global/sky/land flicker, metadata and pixel exposure steps, horizon split, colour temperature drift and white-balance jitter, star field, black/white/duplicate frames, gaps and clock shifts. Covers frame statistics (CCT against exact blackbody chromaticities) and the light analyzer with it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Synthetic/SyntheticSequence.cs | 374 ++++++++++++++++++ .../Analysis/AnalysisFixtures.cs | 59 +++ .../Analysis/FrameStatisticsTests.cs | 197 +++++++++ .../Analysis/LightAnalyzerTests.cs | 196 +++++++++ .../Analysis/SyntheticSequenceTests.cs | 80 ++++ 5 files changed, 906 insertions(+) create mode 100644 src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs create mode 100644 tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs create mode 100644 tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs create mode 100644 tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs create mode 100644 tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs diff --git a/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs b/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs new file mode 100644 index 00000000..53a02c98 --- /dev/null +++ b/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs @@ -0,0 +1,374 @@ +using Titano.Core.Analysis; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Model; + +namespace Titano.Core.Diagnostics.Synthetic; + +/// A deliberate exposure change written to the metadata from frame on; when +/// is false the pixels ignore it (e.g. a setting the camera did not apply). +/// Camera EV change (positive = less light; the pixels darken by this many stops). +public sealed record SyntheticExposureStep(int Index, double DeltaEv, ExposureChange Change = ExposureChange.Shutter, bool Received = true); + +/// Seconds added to the capture clock from frame on (pauses, clock jumps). +public sealed record SyntheticTimeShift(int Index, double Seconds); + +/// Recipe of a synthetic sequence; every field has a neutral default. +public sealed record SyntheticSequenceOptions +{ + public int Width { get; init; } = 96; + public int Height { get; init; } = 64; + public int FrameCount { get; init; } = 120; + public int Seed { get; init; } = 1; + + /// Camera wall-clock time of the first frame. + public DateTime Start { get; init; } = new(2024, 6, 21, 19, 0, 0); + + public int? UtcOffsetMinutes { get; init; } = 120; + public double IntervalSeconds { get; init; } = 10; + + /// Uniform ± jitter of each capture time, in seconds. + public double IntervalJitterSeconds { get; init; } + + public IReadOnlyList TimeShifts { get; init; } = []; + + /// Scene brightness (EV) at the first and last frame; linear ramp in between. + public double StartEv { get; init; } + + public double EndEv { get; init; } + + /// Global flicker amplitude in EV: uniform in ±amplitude, or a sinusoid when a period is set. + public double FlickerEv { get; init; } + + /// Period of sinusoidal flicker in frames; 0 = random flicker. + public double FlickerPeriodFrames { get; init; } + + /// Extra independent uniform flicker of the sky region, in ±EV. + public double SkyFlickerEv { get; init; } + + /// Extra independent uniform flicker of the land region, in ±EV. + public double LandFlickerEv { get; init; } + + public IReadOnlyList ExposureSteps { get; init; } = []; + + /// Horizon row at the centre column as a fraction of the height (sky above). + public double HorizonFraction { get; init; } = 0.45; + + /// Horizon slope in rows per column. + public double HorizonTilt { get; init; } + + /// Amplitude in rows of one sine period of horizon undulation across the width. + public double HorizonWave { get; init; } + + /// Linear luminance of the sky (at the horizon) and of the average land pixel at 0 EV. + public double SkyLevel { get; init; } = 0.25; + + public double LandLevel { get; init; } = 0.05; + + /// Night sky: dark background with point stars instead of a bright gradient. + public bool StarField { get; init; } + + public int StarCount { get; init; } = 40; + + /// Correlated colour temperature of the light at the first and last frame (linear in mireds). + public double StartKelvin { get; init; } = 5500; + + public double EndKelvin { get; init; } = 5500; + + /// Uniform ± per-frame jitter of log2(R/G) and log2(B/G). + public double WhiteBalanceJitter { get; init; } + + /// Additive Gaussian sensor noise (linear units) on every channel. + public double NoiseSigma { get; init; } + + public IReadOnlyList BlackFrames { get; init; } = []; + public IReadOnlyList WhiteFrames { get; init; } = []; + + /// Frames that repeat the previous frame exactly (pixels, capture time and settings). + public IReadOnlyList DuplicateFrames { get; init; } = []; + + public double BaseExposureTime { get; init; } = 1.0 / 100; + public double BaseFNumber { get; init; } = 8; + public int BaseIso { get; init; } = 100; + public string CameraMake { get; init; } = "Titano"; + public string CameraModel { get; init; } = "Synthetic"; + public string Lens { get; init; } = "Synthetic 24mm"; + public double? Latitude { get; init; } + public double? Longitude { get; init; } +} + +/// +/// Deterministic synthetic time-lapse with known answers (the analysis self-test fixture): a scene-brightness +/// ramp, seeded flicker (global and per region), exposure steps in metadata and pixels, a sky/land split along a +/// horizon, colour-temperature drift, an optional star field, and black/white/duplicate frames. Pixels are linear +/// light: base(x, y) · 2^(scene + exposure + flicker + regionFlicker) · rgb(kelvin) with rgb at luminance 1, +/// so log-luminance shifts equal the truth series exactly. +/// +public sealed class SyntheticSequence +{ + private readonly int[] _source; + + private SyntheticSequence(SyntheticSequenceOptions options) + { + Options = options; + var n = options.FrameCount; + var random = new Random(options.Seed); + _source = new int[n]; + SceneEv = new double[n]; + FlickerEv = new double[n]; + SkyFlickerEv = new double[n]; + LandFlickerEv = new double[n]; + ExposureOffsetEv = new double[n]; + Kelvin = new double[n]; + RedJitter = new double[n]; + BlueJitter = new double[n]; + var phase = random.NextDouble() * 2 * Math.PI; + for (var i = 0; i < n; i++) + { + var t = n > 1 ? (double)i / (n - 1) : 0; + SceneEv[i] = options.StartEv + (options.EndEv - options.StartEv) * t; + FlickerEv[i] = options.FlickerPeriodFrames > 0 + ? options.FlickerEv * Math.Sin(2 * Math.PI * i / options.FlickerPeriodFrames + phase) + : options.FlickerEv * (2 * random.NextDouble() - 1); + SkyFlickerEv[i] = options.SkyFlickerEv * (2 * random.NextDouble() - 1); + LandFlickerEv[i] = options.LandFlickerEv * (2 * random.NextDouble() - 1); + Kelvin[i] = 1e6 / (1e6 / options.StartKelvin + (1e6 / options.EndKelvin - 1e6 / options.StartKelvin) * t); + RedJitter[i] = options.WhiteBalanceJitter * (2 * random.NextDouble() - 1); + BlueJitter[i] = options.WhiteBalanceJitter * (2 * random.NextDouble() - 1); + } + + var frames = new Frame[n]; + var metadata = new FrameMetadata[n]; + var sequenceId = DeterministicGuid(options.Seed, -1); + double exposureTime = options.BaseExposureTime, fNumber = options.BaseFNumber, pixelOffset = 0; + var iso = options.BaseIso; + var timeShift = 0.0; + var duplicates = new HashSet(options.DuplicateFrames); + for (var i = 0; i < n; i++) + { + foreach (var shift in options.TimeShifts) + { + if (shift.Index == i) timeShift += shift.Seconds; + } + foreach (var step in options.ExposureSteps) + { + if (step.Index != i) continue; + var before = Ev(exposureTime, fNumber, iso); + switch (step.Change) + { + case ExposureChange.Aperture: fNumber *= Math.Pow(2, step.DeltaEv / 2); break; + case ExposureChange.Iso: iso = (int)Math.Round(iso * Math.Pow(2, -step.DeltaEv)); break; + default: exposureTime *= Math.Pow(2, -step.DeltaEv); break; + } + if (step.Received) pixelOffset -= Ev(exposureTime, fNumber, iso) - before; + } + ExposureOffsetEv[i] = pixelOffset; + var jitter = options.IntervalJitterSeconds * (2 * random.NextDouble() - 1); + var captured = options.Start.AddSeconds(i * options.IntervalSeconds + jitter + timeShift); + _source[i] = i; + if (duplicates.Contains(i) && i > 0) + { + _source[i] = _source[i - 1]; + captured = metadata[i - 1].CapturedAt!.Value; + CopyTruth(i, i - 1); + } + var exposure = duplicates.Contains(i) && i > 0 ? metadata[i - 1] : null; + metadata[i] = new FrameMetadata + { + Format = ImageFileFormat.Tiff, + Make = options.CameraMake, + Model = options.CameraModel, + LensModel = options.Lens, + CapturedAt = captured, + UtcOffsetMinutes = options.UtcOffsetMinutes, + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = exposure?.ExposureTime ?? exposureTime, + FNumber = exposure?.FNumber ?? fNumber, + Iso = exposure?.Iso ?? iso, + Width = options.Width, + Height = options.Height, + Gps = options.Latitude is { } lat && options.Longitude is { } lon ? new GpsPosition(lat, lon, null, null) : null, + }; + var name = $"IMG_{i + 1:D4}.tif"; + frames[i] = new Frame + { + Id = DeterministicGuid(options.Seed, i), + SequenceId = sequenceId, + Index = i, + RelativePath = "synthetic/" + name, + FileName = name, + CapturedAt = captured, + UtcOffsetMinutes = options.UtcOffsetMinutes, + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = metadata[i].ExposureTime, + FNumber = metadata[i].FNumber, + Iso = metadata[i].Iso, + Width = options.Width, + Height = options.Height, + Format = ImageFileFormat.Tiff, + }; + } + Frames = frames; + Metadata = metadata; + } + + public SyntheticSequenceOptions Options { get; } + public IReadOnlyList Frames { get; } + public IReadOnlyList Metadata { get; } + + /// True scene brightness per frame (EV): the ramp. + public double[] SceneEv { get; } + + /// Global flicker per frame (EV). + public double[] FlickerEv { get; } + + public double[] SkyFlickerEv { get; } + public double[] LandFlickerEv { get; } + + /// Luminance offset of the received exposure steps (EV). + public double[] ExposureOffsetEv { get; } + + public double[] Kelvin { get; } + + /// Per-frame white-balance jitter of log2(R/G) and log2(B/G). + public double[] RedJitter { get; } + + public double[] BlueJitter { get; } + + public int Count => Options.FrameCount; + + public bool IsBlack(int index) => Options.BlackFrames.Contains(_source[index]); + + public bool IsWhite(int index) => Options.WhiteFrames.Contains(_source[index]); + + /// Light-analysis input of every frame (with camera, lens and GPS). + public IReadOnlyList LightFrames() => Metadata.Select((m, i) => LightFrame.From(m, i)).ToList(); + + /// Horizon position (rows from the top edge) at column centre . + public double HorizonRow(double x) + { + var o = Options; + var centre = o.Width / 2.0; + return o.HorizonFraction * o.Height + o.HorizonTilt * (x - centre) + o.HorizonWave * Math.Sin(2 * Math.PI * x / o.Width); + } + + public bool IsSky(int x, int y) => y + 0.5 < HorizonRow(x + 0.5); + + public static SyntheticSequence Create(SyntheticSequenceOptions options) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentOutOfRangeException.ThrowIfLessThan(options.Width, 4); + ArgumentOutOfRangeException.ThrowIfLessThan(options.Height, 4); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.FrameCount); + return new SyntheticSequence(options); + } + + /// Renders frame (linear RGB); identical calls give identical pixels. + public ImageBuffer Render(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + var o = Options; + var source = _source[index]; + var image = new ImageBuffer(o.Width, o.Height, 3); + if (IsWhite(index)) + { + image.Data.Fill(1f); + return image; + } + if (IsBlack(index)) return image; + + var colour = ColourOf(source); + var common = SceneEv[source] + ExposureOffsetEv[source] + FlickerEv[source]; + var skyGain = Math.Pow(2, common + SkyFlickerEv[source]); + var landGain = Math.Pow(2, common + LandFlickerEv[source]); + var noise = o.NoiseSigma > 0 ? new Random(unchecked(o.Seed * 7919 + source * 104729)) : null; + var r = image.Plane(0); + var g = image.Plane(1); + var b = image.Plane(2); + for (var y = 0; y < o.Height; y++) + { + for (var x = 0; x < o.Width; x++) + { + var horizon = HorizonRow(x + 0.5); + double value; + if (y + 0.5 < horizon) + { + value = skyGain * (o.StarField + ? StarOrBackground(x, y) + : o.SkyLevel * (0.7 + 0.3 * Math.Clamp((y + 0.5) / Math.Max(1, horizon), 0, 1))); + } + else + { + value = landGain * o.LandLevel * (o.StarField ? 1.0 / 32 : 1) * (0.5 + Hash(x, y, o.Seed)); + } + var i = y * o.Width + x; + r[i] = (float)(value * colour.Red + Noise(noise)); + g[i] = (float)(value * colour.Green + Noise(noise)); + b[i] = (float)(value * colour.Blue + Noise(noise)); + } + } + return image; + } + + private double StarOrBackground(int x, int y) + { + var o = Options; + var star = Hash(x, y, o.Seed + 1); + var density = (double)o.StarCount / (o.Width * o.Height * o.HorizonFraction); + return star < density ? 0.25 + 0.75 * Hash(y, x, o.Seed + 2) : 1.0 / 2048; + } + + private double Noise(Random? random) + { + if (random is null) return 0; + // Box–Muller transform of two uniform deviates. + var u = 1 - random.NextDouble(); + var v = random.NextDouble(); + return Options.NoiseSigma * Math.Sqrt(-2 * Math.Log(u)) * Math.Cos(2 * Math.PI * v); + } + + /// Linear Rec.709 colour of the frame's light at luminance 1, with the white-balance jitter applied. + private ChannelGains ColourOf(int index) + { + var rgb = ColorTemperature.PlanckianRgb(Kelvin[index]); + var red = rgb.X * Math.Pow(2, RedJitter[index]); + var blue = rgb.Z * Math.Pow(2, BlueJitter[index]); + var luminance = ColorSpace.LumaR * red + ColorSpace.LumaG * rgb.Y + ColorSpace.LumaB * blue; + return new ChannelGains(red / luminance, rgb.Y / luminance, blue / luminance); + } + + private void CopyTruth(int to, int from) + { + SceneEv[to] = SceneEv[from]; + FlickerEv[to] = FlickerEv[from]; + SkyFlickerEv[to] = SkyFlickerEv[from]; + LandFlickerEv[to] = LandFlickerEv[from]; + ExposureOffsetEv[to] = ExposureOffsetEv[from]; + Kelvin[to] = Kelvin[from]; + RedJitter[to] = RedJitter[from]; + BlueJitter[to] = BlueJitter[from]; + } + + private static double Ev(double exposureTime, double fNumber, int iso) => Math.Log2(fNumber * fNumber / exposureTime) - Math.Log2(iso / 100.0); + + /// Uniform [0, 1) from a SplitMix64 hash of the inputs (stable across processes, unlike HashCode). + private static double Hash(int x, int y, int seed) + { + var z = unchecked((ulong)(uint)x * 0x9E3779B97F4A7C15UL ^ (ulong)(uint)y * 0xC2B2AE3D27D4EB4FUL ^ (ulong)(uint)seed * 0x165667B19E3779F9UL); + z = unchecked((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL); + z = unchecked((z ^ (z >> 27)) * 0x94D049BB133111EBUL); + z ^= z >> 31; + return (z >> 11) * (1.0 / (1UL << 53)); + } + + private static Guid DeterministicGuid(int seed, int index) + { + Span bytes = stackalloc byte[16]; + BitConverter.TryWriteBytes(bytes, (long)seed); + BitConverter.TryWriteBytes(bytes[8..], (long)index); + bytes[7] = (byte)((bytes[7] & 0x0F) | 0x40); + bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80); + return new Guid(bytes); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs b/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs new file mode 100644 index 00000000..35d6bf2f --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs @@ -0,0 +1,59 @@ +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; + +namespace Titano.Core.Tests.Analysis; + +/// Shared measurement helpers for the analysis tests. +internal static class AnalysisFixtures +{ + /// Trimmed-mean log2 luminance of every frame, optionally after applying a per-frame correction. + public static double[] MeasureSeries(SyntheticSequence sequence, Func? transform = null, float[]? mask = null) + { + var result = new double[sequence.Count]; + Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i => + { + using var image = sequence.Render(i); + var measured = transform is null ? image : transform(i, image); + result[i] = FrameStatistics.MeasureLogLuminance(measured, mask); + }); + return result; + } + + /// RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve, free of + /// any constant offset. + public static double FrameToFrameResidualRms(IReadOnlyList series, IReadOnlyList truth) + { + double sum = 0; + for (var i = 1; i < series.Count; i++) + { + var d = series[i] - series[i - 1] - (truth[i] - truth[i - 1]); + sum += d * d; + } + return Math.Sqrt(sum / (series.Count - 1)); + } + + /// Largest |series − truth − c| where c is the mean offset (the measurement constant). + public static double MaxDeviation(IReadOnlyList series, IReadOnlyList truth) + { + var offset = 0.0; + for (var i = 0; i < series.Count; i++) offset += series[i] - truth[i]; + offset /= series.Count; + var max = 0.0; + for (var i = 0; i < series.Count; i++) max = Math.Max(max, Math.Abs(series[i] - truth[i] - offset)); + return max; + } + + /// Land pixels at least rows below the true horizon (weight 1), else 0. + public static float[] TrueLandMask(SyntheticSequence sequence, double margin = 2) + { + var o = sequence.Options; + var mask = new float[o.Width * o.Height]; + for (var y = 0; y < o.Height; y++) + { + for (var x = 0; x < o.Width; x++) + mask[y * o.Width + x] = y + 0.5 > sequence.HorizonRow(x + 0.5) + margin ? 1 : 0; + } + return mask; + } +} diff --git a/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs b/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs new file mode 100644 index 00000000..c01652c3 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs @@ -0,0 +1,197 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class FrameStatisticsTests(TestContext context) +{ + /// + /// Gate: CCT within 100 K for Planckian colours from 2500 K to 10000 K, measured from images. The chromaticities + /// are exact blackbody values (Planck's law integrated against the CIE 1931 2° observer at 1 nm), independent of + /// the Krystek locus used by the estimator. + /// + [Theory] + [Case(2500, 0.476998, 0.413676)] + [Case(3000, 0.436934, 0.404075)] + [Case(3500, 0.405307, 0.390717)] + [Case(4000, 0.380442, 0.376749)] + [Case(5000, 0.345103, 0.351610)] + [Case(6000, 0.322085, 0.331755)] + [Case(6500, 0.313528, 0.323630)] + [Case(7500, 0.300336, 0.310268)] + [Case(8500, 0.290762, 0.299903)] + [Case(10000, 0.280634, 0.288289)] + public void ColourTemperatureOfPlanckianLightIsWithinOneHundredKelvin(int kelvin, double x, double y) + { + var rgb = Matrix3.XyzToRec709 * new Chromaticity(x, y).ToXyz(0.2); + using var image = new ImageBuffer(16, 16, 3); + image.Plane(0).Fill((float)rgb.X); + image.Plane(1).Fill((float)rgb.Y); + image.Plane(2).Fill((float)rgb.Z); + var estimate = Assert.NotNull(FrameStatistics.Measure(image).ColorTemperature); + context.Log(string.Create(CultureInfo.InvariantCulture, + $"{kelvin} K: estimate {estimate.Kelvin:F1} K (error {estimate.Kelvin - kelvin:F1}), raw McCamy {estimate.McCamyKelvin:F1} K, Duv {estimate.Duv:E2}")); + Assert.Approximately(kelvin, estimate.Kelvin, 100); + Assert.Less(Math.Abs(estimate.Duv), 2e-4); + } + + [Test] + public void OffLocusColoursHaveNoTemperature() + { + Assert.Null(ColorTemperature.Estimate(0.1, 0.5, 0.1)); + Assert.Null(ColorTemperature.Estimate(0.5, 0.1, 0.5)); + Assert.Null(ColorTemperature.Estimate(0, 0, 0)); + // 0.01 along the locus normal (towards green) keeps the CCT and stays within the ±0.02 validity band; + // 0.03 falls outside it. + var (u, v) = ColorTemperature.PlanckianUv(5000); + var (u1, v1) = ColorTemperature.PlanckianUv(4990); + var (u2, v2) = ColorTemperature.PlanckianUv(5010); + double nu = v1 - v2, nv = u2 - u1; + if (nv < 0) (nu, nv) = (-nu, -nv); + var length = Math.Sqrt(nu * nu + nv * nv); + Vector3D Tinted(double duv) => Matrix3.XyzToRec709 * Chromaticity.FromUv1960(u + duv * nu / length, v + duv * nv / length).ToXyz(); + var green = Tinted(0.01); + var estimate = Assert.NotNull(ColorTemperature.Estimate(green.X, green.Y, green.Z)); + Assert.Approximately(0.01, estimate.Duv, 1e-5); + Assert.Approximately(5000, estimate.Kelvin, 1); + var magenta = Tinted(-0.015); + Assert.Approximately(-0.015, Assert.NotNull(ColorTemperature.Estimate(magenta.X, magenta.Y, magenta.Z)).Duv, 1e-5); + var far = Tinted(0.03); + Assert.Null(ColorTemperature.Estimate(far.X, far.Y, far.Z)); + } + + [Test] + public void TrimmedLogMeanHistogramAndClipping() + { + // 1000 pixels: 900 at 2^-3, 50 crushed at zero, 50 clipped at 1. + using var image = new ImageBuffer(100, 10, 3); + for (var i = 0; i < 1000; i++) + { + var v = i < 50 ? 0f : i < 100 ? 1f : 0.125f; + for (var c = 0; c < 3; c++) image.Plane(c)[i] = v; + } + var stats = FrameStatistics.Measure(image); + Assert.Approximately(0.05, stats.ClipLowFraction, 1e-12); + Assert.Approximately(0.05, stats.ClipHighFraction, 1e-12); + Assert.Approximately(1, stats.Histogram.Sum(), 1e-12); + Assert.Approximately(0.9, stats.Histogram[(int)((-3 - FrameStatistics.HistogramMinEv) * 16)], 1e-12); + // Trimming 2 % per tail removes 20 of the 50 crushed and 20 of the 50 clipped pixels: (30·−14 + 900·−3 + 30·0) / 960. + Assert.Approximately((30 * -14.0 + 900 * -3.0) / 960, stats.MeanLogLuminance, 1e-9); + Assert.Approximately(0.05 + 0.9 * 0.125, stats.MeanGreen, 1e-6); + } + + [Test] + public void LogMeanFollowsExposureExactly() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1 }); + using var a = sequence.Render(0); + using var b = a.Clone(); + ExposureProcessor.Apply(b, -1.37); + Assert.Approximately(-1.37, FrameStatistics.MeasureLogLuminance(b) - FrameStatistics.MeasureLogLuminance(a), 2e-3); + } + + [Test] + public void MaskSelectsTheRegion() + { + using var image = new ImageBuffer(20, 20, 3); + var mask = new float[400]; + for (var y = 0; y < 20; y++) + { + for (var x = 0; x < 20; x++) + { + var top = y < 10; + for (var c = 0; c < 3; c++) image[c, x, y] = top ? 0.5f : 0.0625f; + mask[y * 20 + x] = top ? 0 : 1; + } + } + var stats = FrameStatistics.Measure(image, mask); + Assert.Approximately(-4, stats.MeanLogLuminance, 1e-6); + Assert.Approximately(200, stats.Weight, 1e-9); + Assert.Approximately(-1, FrameStatistics.MeasureLogLuminance(image, mask.Select(m => 1 - m).ToArray()), 1e-6); + Assert.Throws(() => FrameStatistics.Measure(image, new float[3])); + } + + [Test] + public void SharpnessDropsWhenBlurred() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, Width = 64, Height = 48 }); + using var sharp = sequence.Render(0); + using var blurred = sharp.Clone(); + for (var c = 0; c < 3; c++) + { + var plane = blurred.Plane(c); + var source = plane.ToArray(); + for (var y = 1; y < 47; y++) + { + for (var x = 1; x < 63; x++) + { + var sum = 0f; + for (var dy = -1; dy <= 1; dy++) + { + for (var dx = -1; dx <= 1; dx++) sum += source[(y + dy) * 64 + x + dx]; + } + plane[y * 64 + x] = sum / 9; + } + } + } + Assert.Greater(FrameStatistics.Measure(sharp).Sharpness, 3 * FrameStatistics.Measure(blurred).Sharpness); + } + + [Test] + public void ImmerkaerNoiseMatchesTheTrueSigma() + { + // Encoded-domain flat field 0.5 plus Gaussian noise of σ = 0.02 (the estimator works on sRGB-encoded luminance). + var random = new Random(17); + using var image = new ImageBuffer(128, 128, 1); + var plane = image.Plane(0); + for (var i = 0; i < plane.Length; i++) + { + var gaussian = Math.Sqrt(-2 * Math.Log(1 - random.NextDouble())) * Math.Cos(2 * Math.PI * random.NextDouble()); + plane[i] = (float)ColorSpace.SrgbToLinear(0.5 + 0.02 * gaussian); + } + var stats = FrameStatistics.Measure(image); + Assert.Approximately(0.02, stats.Noise, 0.001); + Assert.Null(stats.ColorTemperature); + } + + [Test] + public void DetectsBlackWhiteAndDuplicateFrames() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + FrameCount = 8, + FlickerEv = 0.1, + BlackFrames = [2], + WhiteFrames = [4], + DuplicateFrames = [6], + }); + var stats = Enumerable.Range(0, 8).Select(i => + { + using var image = sequence.Render(i); + return FrameStatistics.Measure(image); + }).ToArray(); + Assert.SequenceEqual([2], Enumerable.Range(0, 8).Where(i => stats[i].IsBlack())); + Assert.SequenceEqual([4], Enumerable.Range(0, 8).Where(i => stats[i].IsWhite())); + Assert.SequenceEqual([6], Enumerable.Range(1, 7).Where(i => FrameStatistics.AreLikelyDuplicates(stats[i - 1], stats[i]))); + } + + [Test] + public void DownscaleAveragesBlocks() + { + using var image = new ImageBuffer(101, 60, 3); + for (var c = 0; c < 3; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = (i % 101) % 2 == 0 ? 0.2f : 0.4f; + } + using var small = AnalysisImage.Downscale(image, 32); + Assert.Equal((25, 15), (small.Width, small.Height)); + Assert.True(small.Data.ToArray().All(v => Math.Abs(v - 0.3f) < 1e-6f)); + using var same = AnalysisImage.Downscale(image, 200); + Assert.Equal(101, same.Width); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs new file mode 100644 index 00000000..5873ce17 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs @@ -0,0 +1,196 @@ +using System.Diagnostics; +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class LightAnalyzerTests(TestContext context) +{ + private static SyntheticSequence Timeline() => SyntheticSequence.Create(new SyntheticSequenceOptions + { + FrameCount = 200, + IntervalSeconds = 10, + TimeShifts = + [ + new(40, 60), // 70 s interval: gap + new(100, 5400), // 90 min: session break + new(150, -3600), // daylight saving ends: clock jump + new(195, 7200), // 2 h break leaving a 5-frame tail session + ], + DuplicateFrames = [60], + ExposureSteps = + [ + new(50, 1.0 / 3, ExposureChange.Shutter), + new(120, -1, ExposureChange.Iso), + new(170, 0.5, ExposureChange.Aperture), + ], + }); + + [Test] + public void FindsSessionsGapsClockJumpsAndDuplicatesExactly() + { + var report = LightAnalyzer.Analyze(Timeline().LightFrames()); + + Assert.Equal(200, report.TimedFrameCount); + Assert.Equal(10.0, report.MedianIntervalSeconds); + Assert.Equal(0.0, report.JitterSeconds); + Assert.SequenceEqual([40, 100, 195], report.Gaps.Select(g => g.Index)); + Assert.SequenceEqual([IntervalKind.Gap, IntervalKind.SessionBreak, IntervalKind.SessionBreak], report.Gaps.Select(g => g.Kind)); + Assert.Approximately(70, report.Gaps[0].Seconds, 1e-9); + + // The 5-frame tail merges into the previous session. + Assert.Equal(2, report.Sessions.Count); + Assert.Equal((0, 99), (report.Sessions[0].StartIndex, report.Sessions[0].EndIndex)); + Assert.Equal((100, 199), (report.Sessions[1].StartIndex, report.Sessions[1].EndIndex)); + + Assert.SequenceEqual([(60, IntervalKind.Duplicate), (150, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind))); + Assert.Approximately(11050 + 3600, report.CaptureSpan.TotalSeconds, 1e-6); + Assert.Equal(report.AdjustedTimes[149]!.Value.AddSeconds(10), report.AdjustedTimes[150]!.Value); + + var keys = report.Findings.Select(f => f.Key).ToList(); + foreach (var key in new[] { FindingKeys.Gaps, FindingKeys.Sessions, FindingKeys.DuplicateTimestamps, FindingKeys.ClockJumps, FindingKeys.ExposureSteps }) + Assert.Contains(key, keys); + foreach (var key in new[] { FindingKeys.NonMonotonicTimestamps, FindingKeys.CameraChanged, FindingKeys.MixedResolution, FindingKeys.IrregularInterval, FindingKeys.NoTimestamps }) + Assert.DoesNotContain(key, keys); + var gaps = report.Findings.Single(f => f.Key == FindingKeys.Gaps); + Assert.Equal(FindingSeverity.Warning, gaps.Severity); + Assert.Equal(3, (int)gaps.Arguments[0]); + Assert.Approximately(7210, (double)gaps.Arguments[1], 1e-9); + } + + [Test] + public void FindsExposureStepsWithTheirAmplitude() + { + var report = LightAnalyzer.Analyze(Timeline().LightFrames()); + Assert.SequenceEqual([50, 120, 170], report.ExposureSteps.Select(s => s.Index)); + Assert.SequenceEqual([ExposureChange.Shutter, ExposureChange.Iso, ExposureChange.Aperture], report.ExposureSteps.Select(s => s.Changes)); + Assert.Approximately(1.0 / 3, report.ExposureSteps[0].DeltaEv, 1e-9); + Assert.Approximately(-1, report.ExposureSteps[1].DeltaEv, 1e-9); + Assert.Approximately(0.5, report.ExposureSteps[2].DeltaEv, 1e-9); + Assert.Equal(60.0, report.TypicalStepDistance); + Assert.Approximately(Math.Log2(64 / 0.01), report.ExposureValues[0]!.Value, 1e-9); + } + + [Test] + public void SmallBackwardStepIsNonMonotonic() + { + var frames = Timeline().LightFrames().Take(30).ToList(); + frames[10] = frames[10] with { CapturedAt = frames[10].CapturedAt!.Value.AddSeconds(-15) }; + var report = LightAnalyzer.Analyze(frames); + Assert.SequenceEqual([(10, IntervalKind.NonMonotonic)], report.TimestampIssues.Select(t => (t.Index, t.Kind))); + Assert.Contains(FindingKeys.NonMonotonicTimestamps, report.Findings.Select(f => f.Key)); + } + + [Test] + public void ForwardHourJumpOnCadenceIsAClockChange() + { + var frames = Timeline().LightFrames().Take(40).Select((f, i) => i >= 20 ? f with { CapturedAt = f.CapturedAt!.Value.AddHours(1) } : f).ToList(); + var report = LightAnalyzer.Analyze(frames); + Assert.SequenceEqual([(20, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind))); + Assert.Count(1, report.Sessions); + Assert.Approximately(390, report.CaptureSpan.TotalSeconds, 1e-6); + } + + [Test] + public void ReportsIdentityResolutionAndOrientationChanges() + { + var frames = Timeline().LightFrames().Take(100).ToList(); + frames[30] = frames[30] with { CameraModel = "Other" }; + for (var i = 80; i < 100; i++) frames[i] = frames[i] with { Lens = "Zoom 70-200" }; + frames[10] = frames[10] with { Width = 50 }; + frames[11] = frames[11] with { Orientation = 6 }; + frames[12] = frames[12] with { Lens = null, CameraMake = null, CameraModel = null }; + + var report = LightAnalyzer.Analyze(frames); + Assert.SequenceEqual([(30, IdentityKind.Camera), (31, IdentityKind.Camera), (80, IdentityKind.Lens)], report.IdentityChanges.Select(c => (c.Index, c.Kind))); + Assert.Equal("Titano Synthetic", report.IdentityChanges[1].After); + Assert.Equal((96, 64), report.DominantSize); + Assert.SequenceEqual([10, 11], report.ResolutionOutliers); + Assert.SequenceEqual([11], report.OrientationOutliers); + var keys = report.Findings.Select(f => f.Key).ToList(); + foreach (var key in new[] { FindingKeys.CameraChanged, FindingKeys.LensChanged, FindingKeys.MixedResolution, FindingKeys.MixedOrientation }) + Assert.Contains(key, keys); + } + + [Test] + public void LabelsDayPhasesFromGps() + { + const double lat = 45.07, lon = 7.69; + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + FrameCount = 240, + IntervalSeconds = 60, + Start = new DateTime(2024, 6, 21, 19, 0, 0), + UtcOffsetMinutes = 120, + Latitude = lat, + Longitude = lon, + }); + var report = LightAnalyzer.Analyze(sequence.LightFrames()); + var phases = report.DayPhases.Select(p => (int)Assert.NotNull(p)).ToList(); + Assert.Monotonic(phases.Select(p => (double)p), decreasing: true); + Assert.Equal((int)DayPhase.Day, phases[0]); + Assert.LessOrEqual(phases[^1], (int)DayPhase.NauticalTwilight); + + var sunset = SolarPosition.Events(new DateOnly(2024, 6, 21), lat, lon).Sunset!.Value.AddHours(2); + var firstTwilight = phases.FindIndex(p => p == (int)DayPhase.CivilTwilight); + var frameTime = new DateTime(2024, 6, 21, 19, 0, 0).AddMinutes(firstTwilight); + Assert.InRange((frameTime - sunset).TotalSeconds, 0, 60); + Assert.Contains(FindingKeys.DayNightTransition, report.Findings.Select(f => f.Key)); + Assert.DoesNotContain(FindingKeys.TimeZoneEstimated, report.Findings.Select(f => f.Key)); + + // A GPS time stamp gives the same offset; without either the zone is estimated from the longitude. + var viaGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null, GpsUtc = f.CapturedAt!.Value.AddHours(-2) }).ToList()); + Assert.SequenceEqual(report.DayPhases, viaGps.DayPhases); + var estimated = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null }).ToList()); + var finding = estimated.Findings.Single(f => f.Key == FindingKeys.TimeZoneEstimated); + Assert.Equal(60, (int)finding.Arguments[0]); + + var noGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { Latitude = null, Longitude = null }).ToList()); + Assert.True(noGps.DayPhases.All(p => p is null)); + } + + [Test] + public void TenThousandFramesTakeWellUnderASecond() + { + var start = new DateTime(2024, 3, 1, 5, 0, 0); + var frames = Enumerable.Range(0, 10_000).Select(i => new LightFrame + { + Index = i, + CapturedAt = start.AddSeconds(i * 5 + (i >= 5000 ? 3600 : 0)), + UtcOffsetMinutes = 60, + ExposureTime = i < 4000 ? 1.0 / 500 : 1.0 / 250, + FNumber = 5.6, + Iso = 100, + Width = 6000, + Height = 4000, + CameraMake = "Maker", + CameraModel = "Body", + Lens = "Lens", + Latitude = 46.5, + Longitude = 11.3, + }).ToList(); + LightAnalyzer.Analyze(frames.Take(100).ToList()); + var watch = Stopwatch.StartNew(); + var report = LightAnalyzer.Analyze(frames); + watch.Stop(); + context.Log(string.Create(CultureInfo.InvariantCulture, $"10,000 frames analysed in {watch.Elapsed.TotalMilliseconds:F1} ms")); + Assert.Equal(10_000, report.DayPhases.Length); + Assert.Count(1, report.ExposureSteps); + Assert.Less(watch.Elapsed.TotalSeconds, 2); + } + + [Test] + public void HandlesEmptyAndUntimedInput() + { + var empty = LightAnalyzer.Analyze(Array.Empty()); + Assert.Equal(0, empty.FrameCount); + Assert.Empty(empty.Sessions); + var untimed = LightAnalyzer.Analyze(new[] { new LightFrame(), new LightFrame { Index = 1 } }); + Assert.Contains(FindingKeys.NoTimestamps, untimed.Findings.Select(f => f.Key)); + Assert.Null(untimed.MedianIntervalSeconds); + Assert.Count(1, untimed.Sessions); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs b/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs new file mode 100644 index 00000000..8ed0539f --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs @@ -0,0 +1,80 @@ +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class SyntheticSequenceTests +{ + private static readonly SyntheticSequenceOptions Recipe = new() + { + FrameCount = 30, + Seed = 42, + StartEv = -1, + EndEv = 1, + FlickerEv = 0.1, + SkyFlickerEv = 0.05, + ExposureSteps = [new(10, -1), new(20, 0.5, ExposureChange.Aperture, Received: false)], + StartKelvin = 3000, + EndKelvin = 7000, + NoiseSigma = 0.001, + DuplicateFrames = [15], + Latitude = 45, + Longitude = 9, + }; + + [Test] + public void IsDeterministic() + { + var a = SyntheticSequence.Create(Recipe); + var b = SyntheticSequence.Create(Recipe); + Assert.SequenceEqual(a.FlickerEv, b.FlickerEv); + Assert.SequenceEqual(a.Frames.Select(f => f.Id), b.Frames.Select(f => f.Id)); + foreach (var i in new[] { 0, 7, 29 }) + { + using var x = a.Render(i); + using var y = b.Render(i); + using var again = a.Render(i); + Assert.True(x.Data.SequenceEqual(y.Data) && x.Data.SequenceEqual(again.Data), $"frame {i}"); + } + var other = SyntheticSequence.Create(Recipe with { Seed = 43 }); + Assert.False(other.FlickerEv.SequenceEqual(a.FlickerEv)); + } + + [Test] + public void MetadataMatchesTheRecipe() + { + var sequence = SyntheticSequence.Create(Recipe); + var ev = sequence.Frames.Select(f => f.ExposureValue!.Value).ToArray(); + Assert.Approximately(-1, ev[10] - ev[9], 1e-9); + Assert.Approximately(0.5, ev[20] - ev[19], 1e-9); + Assert.Approximately(1, sequence.ExposureOffsetEv[10], 1e-9); + Assert.Approximately(1, sequence.ExposureOffsetEv[29], 1e-9); + Assert.Equal(sequence.Frames[14].CapturedAt, sequence.Frames[15].CapturedAt); + Assert.Equal(TimeSpan.FromSeconds(10), sequence.Frames[2].CapturedAt!.Value - sequence.Frames[1].CapturedAt!.Value); + Assert.Equal(45.0, sequence.Metadata[0].Gps!.Latitude); + Assert.Equal("Synthetic", sequence.LightFrames()[3].CameraModel); + } + + [Test] + public void PixelsCarryTheTruthSeries() + { + var sequence = SyntheticSequence.Create(Recipe with { SkyFlickerEv = 0, NoiseSigma = 0, StartKelvin = 5000, EndKelvin = 5000 }); + var measured = AnalysisFixtures.MeasureSeries(sequence); + var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i] + sequence.FlickerEv[i]).ToArray(); + Assert.Less(AnalysisFixtures.MaxDeviation(measured, truth), 2e-3); + Assert.Equal(measured[14], measured[15]); + } + + [Test] + public void StarFieldIsDarkWithPointSources() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, StarField = true, StarCount = 60, Width = 128, Height = 96 }); + using var image = sequence.Render(0); + var stats = FrameStatistics.Measure(image); + Assert.Less(stats.MeanLogLuminance, -8); + var bright = image.Plane(1).ToArray().Count(v => v > 0.2f); + Assert.InRange(bright, 30, 100); + Assert.Throws(() => sequence.Render(1)); + } +} From d6772d2602354c1b0f9a9deb918f395b0bc5b5e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 045/188] feat(analysis): add deflicker engine and flicker spectrum Robust LOWESS target curve with intentional exposure offsets removed, blended by Tukey weight and surviving-window fraction; flicker spectrum from the autocorrelation of detrended luminance recommends a window of four periods. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/DeflickerEngine.cs | 130 ++++++++++++++++++ src/Titano.Core/Analysis/FlickerSpectrum.cs | 87 ++++++++++++ .../Analysis/DeflickerEngineTests.cs | 96 +++++++++++++ .../Analysis/FlickerSpectrumTests.cs | 66 +++++++++ 4 files changed, 379 insertions(+) create mode 100644 src/Titano.Core/Analysis/DeflickerEngine.cs create mode 100644 src/Titano.Core/Analysis/FlickerSpectrum.cs create mode 100644 tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs create mode 100644 tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs diff --git a/src/Titano.Core/Analysis/DeflickerEngine.cs b/src/Titano.Core/Analysis/DeflickerEngine.cs new file mode 100644 index 00000000..634dff88 --- /dev/null +++ b/src/Titano.Core/Analysis/DeflickerEngine.cs @@ -0,0 +1,130 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record DeflickerOptions +{ + public static DeflickerOptions Default { get; } = new(); + + /// Frames in each local fit (see for a recommendation). + public int Window { get; init; } = 21; + + /// Local polynomial degree, 1 or 2. + public int Degree { get; init; } = 1; + + /// Tukey reweighting passes. + public int RobustIterations { get; init; } = 3; + + /// 1 lands every frame on the fitted curve; lower values let trusted frames keep part of their own deviation. + public double Strength { get; init; } = 1; +} + +/// Flicker before and after correction, in EV. +/// RMS frame-to-frame step of the input relative to the fitted curve. +/// The same measure on the target curve. +/// RMS of input minus fitted curve over valid frames. +/// Frames whose robust weight fell below ½. +public sealed record DeflickerDiagnostics(double FlickerBefore, double FlickerAfter, double ResidualRms, int OutlierCount); + +/// Per-frame deflicker result; arrays have one entry per frame. +public sealed record DeflickerResult( + double[] Target, + double[] CorrectionEv, + double[] Fitted, + double[] RobustWeights, + double[] SurvivingFraction, + DeflickerDiagnostics Diagnostics); + +/// +/// Deflicker target curve (BRIEF §11.2): robust LOWESS () of per-frame log2 luminance +/// after removing intentional exposure offsets, then blended per frame. A frame keeps +/// (1 − Strength)·ρ·S of its deviation from the fit, where ρ is its own Tukey weight and S the surviving fraction of +/// its window, so outliers and frames in contaminated windows are pulled fully onto the fit. Corrections are +/// target − measured, in EV. +/// +public static class DeflickerEngine +{ + /// Measured log2 luminance per frame (NaN = unusable frame, corrected by 0). + /// Optional luminance change in EV caused on purpose (e.g. exposure steps); + /// it is removed before fitting and restored in the target so it is never treated as flicker. + public static DeflickerResult Compute(ReadOnlySpan logLuminance, DeflickerOptions? options = null, ReadOnlySpan intentionalOffsets = default) + { + options ??= DeflickerOptions.Default; + if (!(options.Strength >= 0 && options.Strength <= 1)) throw new ArgumentOutOfRangeException(nameof(options), "Strength must lie in [0, 1]."); + var n = logLuminance.Length; + if (!intentionalOffsets.IsEmpty && intentionalOffsets.Length != n) throw new ArgumentException("Offsets must have one value per frame.", nameof(intentionalOffsets)); + + var flat = new double[n]; + for (var i = 0; i < n; i++) flat[i] = logLuminance[i] - Offset(intentionalOffsets, i); + var fit = LocalRegression.Smooth(flat, options.Window, options.Degree, options.RobustIterations); + + var target = new double[n]; + var correction = new double[n]; + var keepScale = 1 - options.Strength; + for (var i = 0; i < n; i++) + { + var offset = Offset(intentionalOffsets, i); + var curve = fit.Fitted[i]; + if (!double.IsFinite(flat[i])) + { + target[i] = curve + offset; + continue; + } + var keep = keepScale * fit.RobustWeights[i] * fit.SurvivingFraction[i]; + target[i] = curve + keep * (flat[i] - curve) + offset; + correction[i] = target[i] - logLuminance[i]; + } + + return new DeflickerResult(target, correction, fit.Fitted, fit.RobustWeights, fit.SurvivingFraction, + Diagnose(flat, fit.Fitted, target, intentionalOffsets, fit.RobustWeights)); + } + + /// + /// Luminance offsets implied by metadata exposure: −(EV − EV of the first known frame). Frames without EV + /// inherit the previous known value. + /// + public static double[] OffsetsFromExposure(ReadOnlySpan exposureValues) + { + var offsets = new double[exposureValues.Length]; + double? reference = null; + double current = 0; + for (var i = 0; i < exposureValues.Length; i++) + { + if (exposureValues[i] is { } ev && double.IsFinite(ev)) + { + reference ??= ev; + current = reference.Value - ev; + } + offsets[i] = current; + } + return offsets; + } + + private static double Offset(ReadOnlySpan offsets, int i) => offsets.IsEmpty || !double.IsFinite(offsets[i]) ? 0 : offsets[i]; + + private static DeflickerDiagnostics Diagnose(double[] flat, double[] fitted, double[] target, ReadOnlySpan offsets, double[] robust) + { + double before = 0, after = 0, residual = 0; + int steps = 0, valid = 0, outliers = 0; + for (var i = 0; i < flat.Length; i++) + { + if (!double.IsFinite(flat[i])) continue; + valid++; + residual += (flat[i] - fitted[i]) * (flat[i] - fitted[i]); + if (robust[i] < 0.5) outliers++; + if (i == 0 || !double.IsFinite(flat[i - 1])) continue; + var curveStep = fitted[i] - fitted[i - 1]; + var inputStep = flat[i] - flat[i - 1] - curveStep; + var outputStep = target[i] - Offset(offsets, i) - (target[i - 1] - Offset(offsets, i - 1)) - curveStep; + before += inputStep * inputStep; + after += outputStep * outputStep; + steps++; + } + return new DeflickerDiagnostics( + steps > 0 ? Math.Sqrt(before / steps) : 0, + steps > 0 ? Math.Sqrt(after / steps) : 0, + valid > 0 ? Math.Sqrt(residual / valid) : 0, + outliers); + } +} diff --git a/src/Titano.Core/Analysis/FlickerSpectrum.cs b/src/Titano.Core/Analysis/FlickerSpectrum.cs new file mode 100644 index 00000000..47484cff --- /dev/null +++ b/src/Titano.Core/Analysis/FlickerSpectrum.cs @@ -0,0 +1,87 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record FlickerSpectrumOptions +{ + public static FlickerSpectrumOptions Default { get; } = new(); + + /// Smallest recommended deflicker window (frames, odd). + public int MinimumWindow { get; init; } = 15; + + /// Largest recommended deflicker window (frames, odd). + public int MaximumWindow { get; init; } = 151; + + /// A periodic peak must reach this autocorrelation (and 3/√n) to count. + public double PeakThreshold { get; init; } = 0.25; +} + +/// r(k) of the detrended luminance for k = 0 … max lag. +/// Period of a periodic flicker component in frames (sub-frame), or null. +/// Frames until r drops below 1/e: the time scale of aperiodic flicker. +/// 4 × (period or correlation length), odd, clamped to the options' bounds. +public sealed record FlickerSpectrumResult(double[] Autocorrelation, double? DominantPeriod, double PeakCorrelation, double CorrelationLength, int RecommendedWindow); + +/// +/// Flicker time scale from the autocorrelation of luminance residuals (BRIEF §10.2): the series is detrended with a +/// wide robust LOWESS, its autocorrelation searched for the strongest peak that follows a negative lobe (a true +/// oscillation), and the deflicker window set to four periods so each local fit averages several cycles. +/// +public static class FlickerSpectrum +{ + public static FlickerSpectrumResult Analyze(ReadOnlySpan logLuminance, FlickerSpectrumOptions? options = null) + { + options ??= FlickerSpectrumOptions.Default; + if (options.MinimumWindow < 3 || options.MaximumWindow < options.MinimumWindow) + throw new ArgumentOutOfRangeException(nameof(options), "Window bounds are invalid."); + var n = logLuminance.Length; + var maxLag = Math.Max(1, n / 4); + var detrendWindow = Math.Clamp(n / 3, 15, 501); + var trend = LocalRegression.Smooth(logLuminance, detrendWindow, degree: 2, robustIterations: 2).Fitted; + var residual = new double[n]; + for (var i = 0; i < n; i++) residual[i] = logLuminance[i] - trend[i]; + var r = new double[maxLag + 1]; + Statistics.Autocorrelation(residual, r); + + var threshold = Math.Max(options.PeakThreshold, 3 / Math.Sqrt(Math.Max(1, n))); + var seenNegative = false; + var peaks = new List(); + for (var k = 1; k < maxLag; k++) + { + if (r[k] < 0) seenNegative = true; + if (k >= 2 && seenNegative && r[k] >= threshold && r[k] >= r[k - 1] && r[k] > r[k + 1]) peaks.Add(k); + } + // The fundamental is the first peak close to the strongest: when the period falls between lags, a multiple + // of it can land on a lag and outscore it. + var best = -1; + if (peaks.Count > 0) + { + var strongest = peaks.Max(k => r[k]); + best = peaks.First(k => r[k] >= 0.8 * strongest); + } + + double? period = null; + if (best > 0) + { + var denominator = r[best - 1] - 2 * r[best] + r[best + 1]; + var shift = denominator < 0 ? 0.5 * (r[best - 1] - r[best + 1]) / denominator : 0; + period = best + Math.Clamp(shift, -0.5, 0.5); + } + + var correlationLength = (double)maxLag; + for (var k = 1; k <= maxLag; k++) + { + if (r[k] >= 1 / Math.E) continue; + // Linear interpolation of the 1/e crossing between k − 1 and k. + correlationLength = k - 1 + (r[k - 1] - 1 / Math.E) / (r[k - 1] - r[k]); + break; + } + + var scale = period ?? correlationLength; + var window = (int)Math.Round(4 * scale); + window = Math.Clamp(window, options.MinimumWindow, options.MaximumWindow); + if (window % 2 == 0) window = window + 1 <= options.MaximumWindow ? window + 1 : window - 1; + return new FlickerSpectrumResult(r, period, best > 0 ? r[best] : 0, correlationLength, window); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs b/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs new file mode 100644 index 00000000..874bc701 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs @@ -0,0 +1,96 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class DeflickerEngineTests(TestContext context) +{ + /// BRIEF §20.4: flicker reduction ≥ 60 % on the synthetic ramp with the ramp preserved within 0.05 EV, + /// measured end to end (measure → target curve → apply gains → re-measure). + [Test] + public void RampSequenceMeetsTheRegressionGate() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + FrameCount = 200, + Seed = 3, + StartEv = -2, + EndEv = 1, + FlickerEv = 0.1, + }); + var measured = AnalysisFixtures.MeasureSeries(sequence); + var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 21 }); + var corrected = AnalysisFixtures.MeasureSeries(sequence, (i, image) => + { + ExposureProcessor.Apply(image, result.CorrectionEv[i]); + return image; + }); + + var before = AnalysisFixtures.FrameToFrameResidualRms(measured, sequence.SceneEv); + var after = AnalysisFixtures.FrameToFrameResidualRms(corrected, sequence.SceneEv); + var reduction = 1 - after / before; + var rampError = AnalysisFixtures.MaxDeviation(corrected, sequence.SceneEv); + context.Log(string.Create(CultureInfo.InvariantCulture, + $"flicker before {before:F4} EV, after {after:F4} EV, reduction {reduction:P1}, max ramp deviation {rampError:F4} EV, diagnostics {result.Diagnostics}")); + Assert.GreaterOrEqual(reduction, 0.60); + Assert.LessOrEqual(rampError, 0.05); + Assert.Approximately(after, result.Diagnostics.FlickerAfter, 0.01); + Assert.Approximately(before, result.Diagnostics.FlickerBefore, 0.02); + } + + [Test] + public void IntentionalOffsetsAreNotTreatedAsFlicker() + { + var n = 120; + var ramp = Enumerable.Range(0, n).Select(i => -0.01 * i).ToArray(); + var offsets = Enumerable.Range(0, n).Select(i => i >= 60 ? 1.0 : 0.0).ToArray(); + var measured = ramp.Select((v, i) => v + offsets[i]).ToArray(); + var withOffsets = DeflickerEngine.Compute(measured, intentionalOffsets: offsets); + for (var i = 0; i < n; i++) Assert.Approximately(measured[i], withOffsets.Target[i], 1e-9); + + // Without them the step is smeared into a ramp over the window. + var naive = DeflickerEngine.Compute(measured); + Assert.Greater(Math.Abs(naive.CorrectionEv[59]), 0.2); + } + + [Test] + public void OutliersArePulledOntoTheFitAndStrengthBlendsTheRest() + { + var random = new Random(8); + var n = 150; + var truth = Enumerable.Range(0, n).Select(i => 0.02 * i).ToArray(); + var measured = truth.Select(v => v + 0.05 * (2 * random.NextDouble() - 1)).ToArray(); + measured[70] += 2.5; + var half = DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 0.5 }); + Assert.Less(half.RobustWeights[70], 0.01); + Assert.Approximately(truth[70], half.Target[70], 0.05); + Assert.Equal(1, half.Diagnostics.OutlierCount); + + // An inlier keeps about half of its own deviation from the fit. + var inlier = Enumerable.Range(0, n).First(i => i is > 10 and < 140 && Math.Abs(measured[i] - half.Fitted[i]) > 0.02 && half.RobustWeights[i] > 0.8); + var kept = (half.Target[inlier] - half.Fitted[inlier]) / (measured[inlier] - half.Fitted[inlier]); + Assert.InRange(kept, 0.5 * half.RobustWeights[inlier] * half.SurvivingFraction[inlier] - 1e-9, 0.5 + 1e-9); + Assert.Greater(kept, 0.35); + } + + [Test] + public void UnusableFramesGetTargetsButNoCorrection() + { + var measured = Enumerable.Range(0, 40).Select(i => 0.1 * i).ToArray(); + measured[12] = double.NaN; + var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 9 }); + Assert.Approximately(1.2, result.Target[12], 1e-9); + Assert.Equal(0.0, result.CorrectionEv[12]); + Assert.Throws(() => DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 2 })); + } + + [Test] + public void OffsetsFromExposureFollowMetadata() + { + double?[] ev = [null, 12, 12, 11.5, null, 13]; + var offsets = DeflickerEngine.OffsetsFromExposure(ev); + Assert.SequenceEqual([0.0, 0, 0, 0.5, 0.5, -1], offsets); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs b/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs new file mode 100644 index 00000000..33fa43f0 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs @@ -0,0 +1,66 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class FlickerSpectrumTests(TestContext context) +{ + [Theory] + [Case(12.0)] + [Case(7.5)] + [Case(20.0)] + public void RecoversAKnownPeriodFromRenderedFrames(double period) + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 48, + Height = 32, + FrameCount = 240, + Seed = 12, + StartEv = 0, + EndEv = -2, + FlickerEv = 0.1, + FlickerPeriodFrames = period, + LandFlickerEv = 0.02, + }); + var measured = AnalysisFixtures.MeasureSeries(sequence); + var result = FlickerSpectrum.Analyze(measured); + context.Log(string.Create(CultureInfo.InvariantCulture, + $"true period {period}, found {result.DominantPeriod:F3} (r = {result.PeakCorrelation:F3}), window {result.RecommendedWindow}")); + var found = Assert.NotNull(result.DominantPeriod); + Assert.Approximately(period, found, 0.5); + Assert.Equal(1, result.RecommendedWindow % 2); + Assert.InRange(result.RecommendedWindow, 4 * period - 1, 4 * period + 2); + } + + [Test] + public void WhiteFlickerHasNoPeriodAndGetsTheMinimumWindow() + { + var random = new Random(2); + var series = Enumerable.Range(0, 300).Select(i => -0.01 * i + 0.1 * (2 * random.NextDouble() - 1)).ToArray(); + var result = FlickerSpectrum.Analyze(series); + Assert.Null(result.DominantPeriod); + Assert.Less(result.CorrelationLength, 1.5); + Assert.Equal(FlickerSpectrumOptions.Default.MinimumWindow, result.RecommendedWindow); + } + + [Test] + public void SlowCorrelatedFlickerWidensTheWindow() + { + // AR(1) flicker with correlation 0.9 per frame: e-folding length about 9.5 frames. + var random = new Random(4); + var series = new double[400]; + var state = 0.0; + for (var i = 0; i < series.Length; i++) + { + state = 0.9 * state + 0.05 * (2 * random.NextDouble() - 1); + series[i] = state; + } + var result = FlickerSpectrum.Analyze(series); + Assert.InRange(result.CorrelationLength, 4, 15); + Assert.Greater(result.RecommendedWindow, 15); + Assert.Equal(1, result.RecommendedWindow % 2); + } +} From 731ab2c48bb6b0d07f1cfa8119ac2c958a644b09 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 046/188] feat(analysis): add sky/land segmentation and region deflicker Horizon from the strongest column-averaged row step (median over frames), refined per column by a dynamic-programming path and feathered; Otsu luminance fallback with morphology; confidences for both. Region deflicker fits sky and land separately and blends through the mask. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/RegionDeflicker.cs | 43 ++ src/Titano.Core/Analysis/RegionMask.cs | 98 +++++ src/Titano.Core/Analysis/RegionSegmenter.cs | 370 ++++++++++++++++++ .../Titano.Core.Tests/Analysis/RegionTests.cs | 201 ++++++++++ 4 files changed, 712 insertions(+) create mode 100644 src/Titano.Core/Analysis/RegionDeflicker.cs create mode 100644 src/Titano.Core/Analysis/RegionMask.cs create mode 100644 src/Titano.Core/Analysis/RegionSegmenter.cs create mode 100644 tests/Titano.Core.Tests/Analysis/RegionTests.cs diff --git a/src/Titano.Core/Analysis/RegionDeflicker.cs b/src/Titano.Core/Analysis/RegionDeflicker.cs new file mode 100644 index 00000000..4f8e0aa7 --- /dev/null +++ b/src/Titano.Core/Analysis/RegionDeflicker.cs @@ -0,0 +1,43 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Independent deflicker curves for the sky and land regions. +public sealed record RegionDeflickerResult(DeflickerResult Sky, DeflickerResult Land); + +/// +/// Region deflicker (BRIEF §11.2): sky and land are measured through the soft , each gets its +/// own target curve, and the two corrections are blended per pixel through the mask. +/// Use it when the regions flicker independently (moving clouds, city lights) and the mask confidence is high. +/// +public static class RegionDeflicker +{ + /// Trimmed-mean log2 luminance of the sky and land regions of one analysis image. + public static (double Sky, double Land) Measure(ImageBuffer analysisImage, RegionMask mask, double trimLow = 0.02, double trimHigh = 0.02) + { + ArgumentNullException.ThrowIfNull(analysisImage); + ArgumentNullException.ThrowIfNull(mask); + if (mask.Width != analysisImage.Width || mask.Height != analysisImage.Height) + throw new ArgumentException("Mask and image sizes differ.", nameof(mask)); + return (FrameStatistics.MeasureLogLuminance(analysisImage, mask.Sky, trimLow, trimHigh), + FrameStatistics.MeasureLogLuminance(analysisImage, mask.Land, trimLow, trimHigh)); + } + + public static RegionDeflickerResult Compute(ReadOnlySpan skyLogLuminance, ReadOnlySpan landLogLuminance, DeflickerOptions? options = null, ReadOnlySpan intentionalOffsets = default) + { + if (skyLogLuminance.Length != landLogLuminance.Length) throw new ArgumentException("Series lengths differ.", nameof(landLogLuminance)); + return new RegionDeflickerResult( + DeflickerEngine.Compute(skyLogLuminance, options, intentionalOffsets), + DeflickerEngine.Compute(landLogLuminance, options, intentionalOffsets)); + } + + /// Applies one frame's sky and land corrections (EV) in place; the mask is resampled to the image size + /// when needed (resample once up front when rendering many frames). + public static void Apply(ImageBuffer image, RegionMask mask, double skyEv, double landEv, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentNullException.ThrowIfNull(mask); + var fitted = mask.Resample(image.Width, image.Height); + ExposureProcessor.ApplyRegion(image, fitted.Sky, skyEv, landEv, gains, softClipKnee); + } +} diff --git a/src/Titano.Core/Analysis/RegionMask.cs b/src/Titano.Core/Analysis/RegionMask.cs new file mode 100644 index 00000000..c7c1a22c --- /dev/null +++ b/src/Titano.Core/Analysis/RegionMask.cs @@ -0,0 +1,98 @@ +namespace Titano.Core.Analysis; + +public enum RegionMethod +{ + /// Sky above a per-column horizon line. + Horizon, + + /// Sky = the brighter class of a luminance threshold. + Luminance, +} + +/// Soft sky/land segmentation: per-pixel sky weight in [0, 1] with a feathered transition. +public sealed class RegionMask +{ + private float[]? _land; + + public RegionMask(int width, int height, float[] sky, double[]? horizon, RegionMethod method, double confidence) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentNullException.ThrowIfNull(sky); + if (sky.Length != width * height) throw new ArgumentException("One weight per pixel required.", nameof(sky)); + if (horizon is not null && horizon.Length != width) throw new ArgumentException("One horizon row per column required.", nameof(horizon)); + Width = width; + Height = height; + Sky = sky; + Horizon = horizon; + Method = method; + Confidence = confidence; + } + + public int Width { get; } + public int Height { get; } + + /// Sky weight per pixel, row-major (1 = sky, 0 = land). + public float[] Sky { get; } + + /// Land weight per pixel (1 − sky). + public float[] Land + { + get + { + if (_land is not null) return _land; + var land = new float[Sky.Length]; + for (var i = 0; i < land.Length; i++) land[i] = 1 - Sky[i]; + return _land = land; + } + } + + /// Horizon position per column in rows from the top edge (horizon method only). + public double[]? Horizon { get; } + + public RegionMethod Method { get; } + + /// 0 … 1; region deflicker is advisable only when this is high. + public double Confidence { get; } + + /// Bilinear resampling to another resolution (e.g. analysis size → render size), pixel-centre aligned. + public RegionMask Resample(int width, int height) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (width == Width && height == Height) return this; + var sky = new float[width * height]; + var sx = (double)Width / width; + var sy = (double)Height / height; + Parallel.For(0, height, y => + { + var fy = Math.Clamp((y + 0.5) * sy - 0.5, 0, Height - 1); + var y0 = (int)fy; + var y1 = Math.Min(y0 + 1, Height - 1); + var ty = (float)(fy - y0); + for (var x = 0; x < width; x++) + { + var fx = Math.Clamp((x + 0.5) * sx - 0.5, 0, Width - 1); + var x0 = (int)fx; + var x1 = Math.Min(x0 + 1, Width - 1); + var tx = (float)(fx - x0); + var top = Sky[y0 * Width + x0] + (Sky[y0 * Width + x1] - Sky[y0 * Width + x0]) * tx; + var bottom = Sky[y1 * Width + x0] + (Sky[y1 * Width + x1] - Sky[y1 * Width + x0]) * tx; + sky[y * width + x] = top + (bottom - top) * ty; + } + }); + double[]? horizon = null; + if (Horizon is not null) + { + horizon = new double[width]; + for (var x = 0; x < width; x++) + { + var fx = Math.Clamp((x + 0.5) * sx - 0.5, 0, Width - 1); + var x0 = (int)fx; + var x1 = Math.Min(x0 + 1, Width - 1); + horizon[x] = (Horizon[x0] + (Horizon[x1] - Horizon[x0]) * (fx - x0)) / sy; + } + } + return new RegionMask(width, height, sky, horizon, Method, Confidence); + } +} diff --git a/src/Titano.Core/Analysis/RegionSegmenter.cs b/src/Titano.Core/Analysis/RegionSegmenter.cs new file mode 100644 index 00000000..043174e1 --- /dev/null +++ b/src/Titano.Core/Analysis/RegionSegmenter.cs @@ -0,0 +1,370 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record RegionSegmenterOptions +{ + public static RegionSegmenterOptions Default { get; } = new(); + + /// Frames sampled evenly from the sequence. + public int MaxFrames { get; init; } = 15; + + /// Below this the luminance fallback is tried and the more confident mask wins. + public double MinimumHorizonConfidence { get; init; } = 0.4; + + /// Row-step amplitude in EV that counts as a fully convincing horizon. + public double StrongStepEv { get; init; } = 0.5; + + /// Width of the feathered transition as a fraction of the image height. + public double FeatherFraction { get; init; } = 0.03; + + /// Path penalty per row of vertical movement between adjacent columns, relative to the horizon step. + public double SmoothnessPenalty { get; init; } = 0.05; +} + +/// +/// Sky/land segmentation for region deflicker (BRIEF §10.2, §11.2). Horizon: the strongest step of the +/// column-averaged log-luminance profile (median over frames, so robust to day/night polarity changes), refined per +/// column by a dynamic-programming path that maximises the local step with a smoothness penalty, then feathered. +/// Fallback: Otsu threshold of the temporal-median log luminance (brighter class = sky) cleaned by morphological +/// opening and closing. Each method reports a confidence in [0, 1]. +/// +public static class RegionSegmenter +{ + private const float LogFloor = -14; + + public static RegionMask Segment(IReadOnlyList frames, RegionSegmenterOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + options ??= RegionSegmenterOptions.Default; + if (frames.Count == 0) throw new ArgumentException("At least one frame is required.", nameof(frames)); + var width = frames[0].Width; + var height = frames[0].Height; + foreach (var f in frames) + { + if (f.Width != width || f.Height != height) throw new ArgumentException("Frames must share one size.", nameof(frames)); + } + if (height < 8) throw new ArgumentException("Frames must be at least 8 rows tall.", nameof(frames)); + + var count = Math.Min(Math.Max(1, options.MaxFrames), frames.Count); + var logs = new float[count][]; + Parallel.For(0, count, i => logs[i] = LogLuminance(frames[(int)((long)i * (frames.Count - 1) / Math.Max(1, count - 1))])); + var feather = Math.Max(1.5, options.FeatherFraction * height); + + var (horizon, horizonConfidence) = DetectHorizon(logs, width, height, options); + if (horizon is not null && horizonConfidence >= options.MinimumHorizonConfidence) + return new RegionMask(width, height, HorizonWeights(horizon, width, height, feather), horizon, RegionMethod.Horizon, horizonConfidence); + + var (sky, luminanceConfidence) = LuminanceWeights(logs, width, height, feather); + if (horizon is not null && horizonConfidence >= luminanceConfidence) + return new RegionMask(width, height, HorizonWeights(horizon, width, height, feather), horizon, RegionMethod.Horizon, horizonConfidence); + return new RegionMask(width, height, sky, null, RegionMethod.Luminance, luminanceConfidence); + } + + private static float[] LogLuminance(ImageBuffer image) + { + var y = new float[image.PlaneLength]; + ColorSpace.Luminance(image, y); + for (var i = 0; i < y.Length; i++) y[i] = y[i] > 6.1035156e-05f ? MathF.Log2(y[i]) : LogFloor; + return y; + } + + private static (double[]? Horizon, double Confidence) DetectHorizon(float[][] logs, int width, int height, RegionSegmenterOptions options) + { + var frames = logs.Length; + var k = Math.Max(2, height / 24); + var steps = new float[frames][]; + var profiles = new double[frames][]; + Parallel.For(0, frames, f => (steps[f], profiles[f]) = ColumnSteps(logs[f], width, height, k)); + + var score = new double[height]; + var column = new double[frames]; + for (var y = k; y <= height - k; y++) + { + for (var f = 0; f < frames; f++) column[f] = Math.Abs(profiles[f][y]); + score[y] = Statistics.MedianInPlace(column); + } + var y0 = k; + for (var y = k; y <= height - k; y++) + { + if (score[y] > score[y0]) y0 = y; + } + var peak = score[y0]; + if (!(peak > 1e-6)) return (null, 0); + + double second = 0; + for (var y = k; y <= height - k; y++) + { + if (Math.Abs(y - y0) > 2 * k) second = Math.Max(second, score[y]); + } + var consistent = 0; + var signs = new int[frames]; + for (var f = 0; f < frames; f++) + { + var best = k; + for (var y = k; y <= height - k; y++) + { + if (Math.Abs(profiles[f][y]) > Math.Abs(profiles[f][best])) best = y; + } + if (Math.Abs(best - y0) <= k) consistent++; + signs[f] = profiles[f][y0] < 0 ? -1 : 1; + } + var confidence = Math.Min(1, peak / options.StrongStepEv) * (1 - second / peak) * consistent / frames; + + // Per-column refinement: minimum-cost path through −(signed local step), median over frames. + var band = Math.Max(2 * k, height / 4); + var yLo = Math.Max(k, y0 - band); + var yHi = Math.Min(height - k, y0 + band); + var rows = yHi - yLo + 1; + var cost = new double[width * rows]; + Parallel.For(0, width, x => + { + var values = new double[frames]; + for (var j = 0; j < rows; j++) + { + var i = (yLo + j) * width + x; + for (var f = 0; f < frames; f++) values[f] = signs[f] * steps[f][i]; + cost[x * rows + j] = -Statistics.MedianInPlace(values); + } + }); + var path = MinimumPath(cost, width, rows, Math.Max(2, height / 48), options.SmoothnessPenalty * peak); + + var horizon = new double[width]; + for (var x = 0; x < width; x++) + { + var j = path[x]; + var offset = 0.0; + if (j > 0 && j < rows - 1) + { + double a = cost[x * rows + j - 1], c = cost[x * rows + j], b = cost[x * rows + j + 1]; + var curvature = a - 2 * c + b; + if (curvature > 0) offset = Math.Clamp(0.5 * (a - b) / curvature, -0.5, 0.5); + } + horizon[x] = yLo + j + offset; + } + return (horizon, Math.Clamp(confidence, 0, 1)); + } + + /// + /// Vertical box-difference step (mean of k rows above minus k rows below each row boundary) on a horizontally + /// box-smoothed log image, plus its column average. + /// + private static (float[] Steps, double[] Profile) ColumnSteps(float[] log, int width, int height, int k) + { + var radius = Math.Max(1, width / 64); + var smooth = new float[log.Length]; + var prefix = new double[width + 1]; + for (var y = 0; y < height; y++) + { + var row = y * width; + for (var x = 0; x < width; x++) prefix[x + 1] = prefix[x] + log[row + x]; + for (var x = 0; x < width; x++) + { + var a = Math.Max(0, x - radius); + var b = Math.Min(width, x + radius + 1); + smooth[row + x] = (float)((prefix[b] - prefix[a]) / (b - a)); + } + } + + var steps = new float[log.Length]; + var profile = new double[height]; + var columnPrefix = new double[height + 1]; + for (var x = 0; x < width; x++) + { + for (var y = 0; y < height; y++) columnPrefix[y + 1] = columnPrefix[y] + smooth[y * width + x]; + for (var y = k; y <= height - k; y++) + { + var above = columnPrefix[y] - columnPrefix[y - k]; + var below = columnPrefix[y + k] - columnPrefix[y]; + var step = (above - below) / k; + steps[y * width + x] = (float)step; + profile[y] += step; + } + } + for (var y = 0; y < height; y++) profile[y] /= width; + return (steps, profile); + } + + /// Dynamic programming over columns: each step may move at most rows at a + /// cost of per row. Returns the row index (within the band) per column. + private static int[] MinimumPath(double[] cost, int width, int rows, int slope, double penalty) + { + var energy = new double[width * rows]; + var from = new int[width * rows]; + Array.Copy(cost, energy, rows); + for (var x = 1; x < width; x++) + { + for (var j = 0; j < rows; j++) + { + var best = double.PositiveInfinity; + var arg = j; + for (var d = -slope; d <= slope; d++) + { + var p = j + d; + if (p < 0 || p >= rows) continue; + var e = energy[(x - 1) * rows + p] + penalty * Math.Abs(d); + if (e < best) + { + best = e; + arg = p; + } + } + energy[x * rows + j] = cost[x * rows + j] + best; + from[x * rows + j] = arg; + } + } + var path = new int[width]; + var end = 0; + for (var j = 1; j < rows; j++) + { + if (energy[(width - 1) * rows + j] < energy[(width - 1) * rows + end]) end = j; + } + path[width - 1] = end; + for (var x = width - 1; x > 0; x--) path[x - 1] = from[x * rows + path[x]]; + return path; + } + + private static float[] HorizonWeights(double[] horizon, int width, int height, double feather) + { + var sky = new float[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var t = Math.Clamp(0.5 + (horizon[x] - (y + 0.5)) / feather, 0, 1); + sky[y * width + x] = (float)(t * t * (3 - 2 * t)); + } + } + return sky; + } + + private static (float[] Sky, double Confidence) LuminanceWeights(float[][] logs, int width, int height, double feather) + { + var n = width * height; + var median = new double[n]; + var values = new double[logs.Length]; + for (var i = 0; i < n; i++) + { + for (var f = 0; f < logs.Length; f++) values[f] = logs[f][i]; + median[i] = Statistics.MedianInPlace(values); + } + + double min = double.PositiveInfinity, max = double.NegativeInfinity; + foreach (var v in median) + { + min = Math.Min(min, v); + max = Math.Max(max, v); + } + if (!(max - min > 1e-6)) return (new float[n], 0); + + var (threshold, separability) = Otsu(median, min, max); + var binary = new byte[n]; + for (var i = 0; i < n; i++) binary[i] = median[i] > threshold ? (byte)1 : (byte)0; + var radius = Math.Max(1, Math.Min(width, height) / 64); + binary = MinMax(MinMax(binary, width, height, radius, dilate: false), width, height, radius, dilate: true); + binary = MinMax(MinMax(binary, width, height, radius, dilate: true), width, height, radius, dilate: false); + + var sky = new float[n]; + for (var i = 0; i < n; i++) sky[i] = binary[i]; + BoxBlur(sky, width, height, Math.Max(1, (int)Math.Round(feather / 2))); + // Otsu's η is 2/π for a single Gaussian mode: rescale so a unimodal image scores 0 and two spikes score 1. + var confidence = Math.Clamp((separability - 2 / Math.PI) / (1 - 2 / Math.PI), 0, 1); + return (sky, confidence); + } + + /// Otsu (1979) threshold over a 256-bin histogram and its separability η = σ²between / σ²total. + private static (double Threshold, double Separability) Otsu(double[] values, double min, double max) + { + const int bins = 256; + var histogram = new double[bins]; + Statistics.AccumulateHistogram(values, min, max + (max - min) * 1e-9, histogram); + var width = (max - min) / bins; + double total = values.Length, sumAll = 0, sumSquares = 0; + for (var i = 0; i < bins; i++) + { + var centre = min + (i + 0.5) * width; + sumAll += histogram[i] * centre; + sumSquares += histogram[i] * centre * centre; + } + var mean = sumAll / total; + var variance = sumSquares / total - mean * mean; + double w0 = 0, sum0 = 0, bestBetween = -1; + var bestBin = 0; + for (var i = 0; i < bins - 1; i++) + { + w0 += histogram[i]; + sum0 += histogram[i] * (min + (i + 0.5) * width); + var w1 = total - w0; + if (w0 <= 0 || w1 <= 0) continue; + var m0 = sum0 / w0; + var m1 = (sumAll - sum0) / w1; + var between = w0 * w1 * (m0 - m1) * (m0 - m1) / (total * total); + if (between > bestBetween) + { + bestBetween = between; + bestBin = i; + } + } + return (min + (bestBin + 1) * width, variance > 0 ? Math.Max(0, bestBetween) / variance : 0); + } + + /// Binary erosion (min) or dilation (max) with a (2r+1)² square, as two separable passes. + private static byte[] MinMax(byte[] source, int width, int height, int radius, bool dilate) + { + var horizontal = new byte[source.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var v = dilate ? (byte)0 : (byte)1; + for (var d = -radius; d <= radius; d++) + { + var s = source[y * width + Math.Clamp(x + d, 0, width - 1)]; + v = dilate ? Math.Max(v, s) : Math.Min(v, s); + } + horizontal[y * width + x] = v; + } + } + var result = new byte[source.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var v = dilate ? (byte)0 : (byte)1; + for (var d = -radius; d <= radius; d++) + { + var s = horizontal[Math.Clamp(y + d, 0, height - 1) * width + x]; + v = dilate ? Math.Max(v, s) : Math.Min(v, s); + } + result[y * width + x] = v; + } + } + return result; + } + + /// Separable box blur with edge-shrunk windows, in place. + private static void BoxBlur(float[] data, int width, int height, int radius) + { + var line = new double[Math.Max(width, height) + 1]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) line[x + 1] = line[x] + data[y * width + x]; + for (var x = 0; x < width; x++) + { + int a = Math.Max(0, x - radius), b = Math.Min(width, x + radius + 1); + data[y * width + x] = (float)((line[b] - line[a]) / (b - a)); + } + } + for (var x = 0; x < width; x++) + { + for (var y = 0; y < height; y++) line[y + 1] = line[y] + data[y * width + x]; + for (var y = 0; y < height; y++) + { + int a = Math.Max(0, y - radius), b = Math.Min(height, y + radius + 1); + data[y * width + x] = (float)((line[b] - line[a]) / (b - a)); + } + } + } +} diff --git a/tests/Titano.Core.Tests/Analysis/RegionTests.cs b/tests/Titano.Core.Tests/Analysis/RegionTests.cs new file mode 100644 index 00000000..ad06ce20 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/RegionTests.cs @@ -0,0 +1,201 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class RegionTests(TestContext context) +{ + private static SyntheticSequence Landscape(int frames, double tilt, double wave, int seed = 5) => SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 128, + Height = 80, + FrameCount = frames, + Seed = seed, + StartEv = -1, + EndEv = 0, + HorizonFraction = 0.45, + HorizonTilt = tilt, + HorizonWave = wave, + SkyFlickerEv = 0.15, + LandFlickerEv = 0.15, + }); + + private static List RenderAll(SyntheticSequence sequence) => Enumerable.Range(0, sequence.Count).Select(sequence.Render).ToList(); + + [Test] + public void HorizonIsFoundPerColumnWithHighConfidence() + { + var sequence = Landscape(30, tilt: 0.08, wave: 3); + var frames = RenderAll(sequence); + try + { + var mask = RegionSegmenter.Segment(frames); + Assert.Equal(RegionMethod.Horizon, mask.Method); + Assert.Greater(mask.Confidence, 0.6); + var horizon = Assert.NotNull(mask.Horizon); + var worst = Enumerable.Range(0, mask.Width).Max(x => Math.Abs(horizon[x] - sequence.HorizonRow(x + 0.5))); + var agreement = Agreement(mask, sequence); + context.Log(string.Create(CultureInfo.InvariantCulture, $"confidence {mask.Confidence:F3}, worst column error {worst:F3} px, pixel agreement {agreement:P2}")); + Assert.LessOrEqual(worst, 1.0); + Assert.GreaterOrEqual(agreement, 0.98); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [Test] + public void HorizonSurvivesPolarityChangesAcrossFrames() + { + var day = Landscape(10, tilt: 0, wave: 0); + var night = SyntheticSequence.Create(day.Options with { SkyLevel = 0.01, LandLevel = 0.2, Seed = 6 }); + var frames = RenderAll(day).Concat(RenderAll(night)).ToList(); + try + { + var mask = RegionSegmenter.Segment(frames); + Assert.Equal(RegionMethod.Horizon, mask.Method); + var horizon = Assert.NotNull(mask.Horizon); + Assert.True(horizon.All(h => Math.Abs(h - 0.45 * 80) <= 1), "horizon row"); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [Test] + public void CliffFallsBackToLuminance() + { + // Sky above row 20 on the left half and above row 60 on the right: no single row step explains it. + var frames = new List(); + for (var f = 0; f < 6; f++) + { + var image = new ImageBuffer(96, 80, 3); + for (var y = 0; y < 80; y++) + { + for (var x = 0; x < 96; x++) + { + var sky = y < (x < 48 ? 20 : 60); + var v = sky ? 0.4f * (1 + 0.02f * f) : 0.03f * (1 + ((x * 7 + y * 13) % 5) * 0.1f); + for (var c = 0; c < 3; c++) image[c, x, y] = v; + } + } + frames.Add(image); + } + try + { + var mask = RegionSegmenter.Segment(frames); + Assert.Equal(RegionMethod.Luminance, mask.Method); + Assert.Greater(mask.Confidence, 0.5); + var correct = 0; + for (var y = 0; y < 80; y++) + { + for (var x = 0; x < 96; x++) + { + var sky = y < (x < 48 ? 20 : 60); + if (mask.Sky[y * 96 + x] >= 0.5f == sky) correct++; + } + } + Assert.GreaterOrEqual(correct / (96.0 * 80), 0.97); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [Test] + public void FeaturelessFramesHaveNoConfidence() + { + using var flat = new ImageBuffer(64, 48, 3); + flat.Data.Fill(0.2f); + var mask = RegionSegmenter.Segment([flat]); + Assert.Less(mask.Confidence, 0.05); + } + + /// BRIEF §20.4: with independent sky and land flicker, the land residual after region deflicker is at + /// most 25 % of the residual left by one global curve. + [Test] + public void RegionDeflickerMeetsTheRegressionGate() + { + var sequence = Landscape(150, tilt: 0.05, wave: 2); + var frames = RenderAll(sequence); + RegionMask mask; + double[] sky, land, global; + try + { + mask = RegionSegmenter.Segment(frames); + sky = new double[frames.Count]; + land = new double[frames.Count]; + global = new double[frames.Count]; + for (var i = 0; i < frames.Count; i++) + { + (sky[i], land[i]) = RegionDeflicker.Measure(frames[i], mask); + global[i] = FrameStatistics.MeasureLogLuminance(frames[i]); + } + } + finally + { + frames.ForEach(f => f.Dispose()); + } + + var options = new DeflickerOptions { Window = 31 }; + var globalResult = DeflickerEngine.Compute(global, options); + var regionResult = RegionDeflicker.Compute(sky, land, options); + var trueLand = AnalysisFixtures.TrueLandMask(sequence); + var landAfterGlobal = AnalysisFixtures.MeasureSeries(sequence, (i, image) => + { + ExposureProcessor.Apply(image, globalResult.CorrectionEv[i]); + return image; + }, trueLand); + var landAfterRegion = AnalysisFixtures.MeasureSeries(sequence, (i, image) => + { + RegionDeflicker.Apply(image, mask, regionResult.Sky.CorrectionEv[i], regionResult.Land.CorrectionEv[i]); + return image; + }, trueLand); + + var globalResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterGlobal, sequence.SceneEv); + var regionResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterRegion, sequence.SceneEv); + var ratio = regionResidual / globalResidual; + context.Log(string.Create(CultureInfo.InvariantCulture, + $"mask {mask.Method} confidence {mask.Confidence:F3}; land residual global {globalResidual:F4} EV, region {regionResidual:F4} EV, ratio {ratio:P1}")); + Assert.LessOrEqual(ratio, 0.25); + } + + [Test] + public void ResampledMaskKeepsTheHorizon() + { + var sequence = Landscape(6, tilt: 0, wave: 0); + var frames = RenderAll(sequence); + try + { + var mask = RegionSegmenter.Segment(frames); + var big = mask.Resample(256, 160); + Assert.Equal(256 * 160, big.Sky.Length); + Assert.Approximately(2 * mask.Horizon![10], big.Horizon![20], 0.6); + Assert.True(big.Sky[5 * 256 + 100] > 0.99f && big.Sky[150 * 256 + 100] < 0.01f); + Assert.Same(mask, mask.Resample(mask.Width, mask.Height)); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + private static double Agreement(RegionMask mask, SyntheticSequence sequence) + { + var correct = 0; + for (var y = 0; y < mask.Height; y++) + { + for (var x = 0; x < mask.Width; x++) + { + if (mask.Sky[y * mask.Width + x] >= 0.5f == sequence.IsSky(x, y)) correct++; + } + } + return correct / (double)(mask.Width * mask.Height); + } +} From f6adbf7a31409f03c40f4f41a6ee4cb7d4aeef7b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 047/188] feat(analysis): add holy-grail exposure step redistribution Metadata steps are verified against the detrended measured jump; only received steps are removed, the step-free series deflickered and the steps restored as smoothstep transitions that lengthen until no frame step exceeds 0.3 EV. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/HolyGrailEngine.cs | 221 ++++++++++++++++++ .../Analysis/HolyGrailEngineTests.cs | 88 +++++++ 2 files changed, 309 insertions(+) create mode 100644 src/Titano.Core/Analysis/HolyGrailEngine.cs create mode 100644 tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs diff --git a/src/Titano.Core/Analysis/HolyGrailEngine.cs b/src/Titano.Core/Analysis/HolyGrailEngine.cs new file mode 100644 index 00000000..38c4e5ca --- /dev/null +++ b/src/Titano.Core/Analysis/HolyGrailEngine.cs @@ -0,0 +1,221 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record HolyGrailOptions +{ + public static HolyGrailOptions Default { get; } = new(); + + /// Transition length in frames; null = half the typical distance between received steps. + public int? TransitionFrames { get; init; } + + /// Transition length when fewer than two steps were received and none is configured. + public int SingleStepTransitionFrames { get; init; } = 12; + + /// Largest allowed frame-to-frame change of the target curve, in EV. + public double MaxStepEv { get; init; } = 0.3; + + /// Metadata EV changes smaller than this are not steps. + public double MinimumStepEv { get; init; } = 0.05; + + /// A step is received when the measured jump has the expected sign and at least this fraction of its size. + public double MinimumReceivedFraction { get; init; } = 0.5; + + /// Frames measured on each side of a step. + public int MeasureFrames { get; init; } = 6; + + public DeflickerOptions Deflicker { get; init; } = DeflickerOptions.Default; +} + +/// One metadata exposure step and how it was redistributed. +/// First frame shot with the new settings. +/// Luminance change implied by the metadata (−ΔEV). +/// Detrended luminance jump measured across the step (NaN when not measurable). +/// Whether the pixels actually changed; ignored steps get no transition. +/// Frame position where the smooth transition starts (fractional). +/// Transition length in frames (0 when not received). +public sealed record ExposureTransition(int Index, double ExpectedEv, double MeasuredEv, bool Received, double Start, double Length); + +/// Target log2 luminance per frame. +/// Target − measured. +/// Cumulative received steps (the abrupt exposure offsets in the pixels). +/// The same steps spread over their transitions. +/// Largest |Target[i] − Target[i−1]|. +public sealed record HolyGrailResult( + double[] Target, + double[] CorrectionEv, + double[] StepOffsets, + double[] SmoothedOffsets, + IReadOnlyList Transitions, + DeflickerResult Deflicker, + double MaxFrameStepEv); + +/// +/// Holy-grail exposure-step redistribution (BRIEF §10.3, §11.2). Metadata EV steps are checked against the measured +/// luminance (detrended medians on both sides), steps the pixels did not receive are ignored, and each received step +/// is removed from the series, the step-free series deflickered, and the step added back as a smoothstep transition +/// centred on it. Transitions lengthen until no frame-to-frame change of the target exceeds +/// ; ramps are kept inside the sequence so the total change is preserved. +/// +public static class HolyGrailEngine +{ + /// Measured log2 luminance per frame (NaN = unusable). + /// Metadata EV (ISO 100) per frame; null when unknown. + public static HolyGrailResult Compute(ReadOnlySpan logLuminance, ReadOnlySpan exposureEv, HolyGrailOptions? options = null) + { + options ??= HolyGrailOptions.Default; + var n = logLuminance.Length; + if (exposureEv.Length != n) throw new ArgumentException("One exposure value per frame is required.", nameof(exposureEv)); + if (!(options.MaxStepEv > 0)) throw new ArgumentOutOfRangeException(nameof(options), "MaxStepEv must be positive."); + var luminance = logLuminance.ToArray(); + + var transitions = DetectSteps(luminance, exposureEv, options); + var offsets = new double[n]; + foreach (var t in transitions) + { + if (!t.Received) continue; + for (var i = t.Index; i < n; i++) offsets[i] += t.ExpectedEv; + } + var flat = new double[n]; + for (var i = 0; i < n; i++) flat[i] = luminance[i] - offsets[i]; + var deflicker = DeflickerEngine.Compute(flat, options.Deflicker); + + var received = transitions.Where(t => t.Received).ToList(); + var lengths = InitialLengths(received, deflicker.Target, n, options); + var smoothed = new double[n]; + var target = new double[n]; + var maxStep = 0.0; + for (var attempt = 0; attempt < 40; attempt++) + { + Ramps(received, lengths, n, smoothed); + for (var i = 0; i < n; i++) target[i] = deflicker.Target[i] + smoothed[i]; + maxStep = MaxStep(target); + if (maxStep <= options.MaxStepEv || lengths.All(l => l >= n - 1)) break; + for (var k = 0; k < lengths.Length; k++) lengths[k] = Math.Min(n - 1, Math.Max(lengths[k] + 1, lengths[k] * 1.25)); + } + + var correction = new double[n]; + for (var i = 0; i < n; i++) correction[i] = double.IsFinite(luminance[i]) ? target[i] - luminance[i] : 0; + var report = new List(transitions.Count); + var r = 0; + foreach (var t in transitions) + { + if (!t.Received) + { + report.Add(t); + continue; + } + report.Add(t with { Start = RampStart(t.Index, lengths[r], n), Length = lengths[r] }); + r++; + } + return new HolyGrailResult(target, correction, offsets, smoothed, report, deflicker, maxStep); + } + + private static List DetectSteps(double[] luminance, ReadOnlySpan exposureEv, HolyGrailOptions options) + { + var candidates = new List<(int Index, double Expected)>(); + double? last = null; + for (var i = 0; i < exposureEv.Length; i++) + { + if (exposureEv[i] is not { } ev || !double.IsFinite(ev)) continue; + if (last is { } p && Math.Abs(ev - p) >= options.MinimumStepEv) candidates.Add((i, -(ev - p))); + last = ev; + } + + var result = new List(candidates.Count); + for (var c = 0; c < candidates.Count; c++) + { + var (index, expected) = candidates[c]; + var from = Math.Max(c > 0 ? candidates[c - 1].Index : 0, index - options.MeasureFrames); + var to = Math.Min(c + 1 < candidates.Count ? candidates[c + 1].Index : luminance.Length, index + options.MeasureFrames); + var measured = MeasureJump(luminance, from, index, to); + var received = double.IsNaN(measured) + || (Math.Sign(measured) == Math.Sign(expected) && Math.Abs(measured) >= options.MinimumReceivedFraction * Math.Abs(expected)); + result.Add(new ExposureTransition(index, expected, measured, received, 0, 0)); + } + return result; + } + + /// + /// Jump between frames [from, index) and [index, to): the scene trend (median first difference on both sides, + /// excluding the step itself) is removed, then the medians of the two sides are compared. NaN when a side has no + /// valid frame. + /// + private static double MeasureJump(double[] luminance, int from, int index, int to) + { + var differences = new List(); + for (var j = from + 1; j < to; j++) + { + if (j == index) continue; + var d = luminance[j] - luminance[j - 1]; + if (double.IsFinite(d)) differences.Add(d); + } + var slope = differences.Count > 0 ? Statistics.Median(differences.ToArray()) : 0; + var left = new List(); + var right = new List(); + for (var j = from; j < to; j++) + { + if (!double.IsFinite(luminance[j])) continue; + var detrended = luminance[j] - slope * (j - (index - 0.5)); + (j < index ? left : right).Add(detrended); + } + if (left.Count == 0 || right.Count == 0) return double.NaN; + return Statistics.Median(right.ToArray()) - Statistics.Median(left.ToArray()); + } + + /// Half the typical spacing of received steps (or the configured length), lengthened per step so a lone + /// smoothstep (peak slope 1.5·|s|/L) fits in the budget left by the scene's own frame-to-frame change. + private static double[] InitialLengths(List received, double[] sceneTarget, int n, HolyGrailOptions options) + { + double baseLength; + if (options.TransitionFrames is { } configured) baseLength = configured; + else if (received.Count >= 2) + { + var spacing = new double[received.Count - 1]; + for (var i = 1; i < received.Count; i++) spacing[i - 1] = received[i].Index - received[i - 1].Index; + baseLength = Math.Round(Statistics.Median(spacing) / 2); + } + else baseLength = options.SingleStepTransitionFrames; + baseLength = Math.Max(2, baseLength); + + var budget = options.MaxStepEv - MaxStep(sceneTarget); + var lengths = new double[received.Count]; + for (var k = 0; k < lengths.Length; k++) + { + var needed = budget > 0 ? Math.Ceiling(1.5 * Math.Abs(received[k].ExpectedEv) / budget) : n - 1; + lengths[k] = Math.Min(Math.Max(1, n - 1), Math.Max(baseLength, needed)); + } + return lengths; + } + + private static void Ramps(List received, double[] lengths, int n, double[] smoothed) + { + Array.Clear(smoothed); + for (var k = 0; k < received.Count; k++) + { + var length = lengths[k]; + var start = RampStart(received[k].Index, length, n); + var amount = received[k].ExpectedEv; + for (var i = 0; i < n; i++) + { + var t = Math.Clamp((i - start) / length, 0, 1); + smoothed[i] += amount * t * t * (3 - 2 * t); + } + } + } + + /// Ramp centred on the boundary between frames index − 1 and index, shifted to lie inside [0, n − 1]. + private static double RampStart(int index, double length, int n) => Math.Clamp(index - 0.5 - length / 2, 0, Math.Max(0, n - 1 - length)); + + private static double MaxStep(double[] series) + { + var max = 0.0; + for (var i = 1; i < series.Length; i++) + { + var d = Math.Abs(series[i] - series[i - 1]); + if (double.IsFinite(d)) max = Math.Max(max, d); + } + return max; + } +} diff --git a/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs b/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs new file mode 100644 index 00000000..3becabf6 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs @@ -0,0 +1,88 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class HolyGrailEngineTests(TestContext context) +{ + /// + /// Sunset: the scene darkens 8 EV while the camera opens up 2/3 EV every 20 frames, plus one metadata change + /// the pixels never received. BRIEF §20.4: no target step above 0.3 EV; the total change is preserved. + /// + [Test] + public void SunsetStepsAreRedistributedWithinTheGate() + { + var steps = Enumerable.Range(1, 11).Select(k => new SyntheticExposureStep(k * 20, -2.0 / 3, k % 3 == 0 ? ExposureChange.Iso : ExposureChange.Shutter)).ToList(); + steps.Add(new SyntheticExposureStep(130, -1.0 / 3, ExposureChange.Aperture, Received: false)); + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + FrameCount = 240, + Seed = 9, + StartEv = 2, + EndEv = -6, + FlickerEv = 0.03, + ExposureSteps = steps, + }); + var measured = AnalysisFixtures.MeasureSeries(sequence); + var ev = sequence.Frames.Select(f => f.ExposureValue).ToArray(); + var result = HolyGrailEngine.Compute(measured, ev); + + var rawMaxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(measured[i] - measured[i - 1])); + var maxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(result.Target[i] - result.Target[i - 1])); + var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i]).ToArray(); + var totalTruth = truth[^1] - truth[0]; + var totalTarget = result.Target[^1] - result.Target[0]; + context.Log(string.Create(CultureInfo.InvariantCulture, + $"raw max step {rawMaxStep:F3} EV, target max step {maxStep:F3} EV, total change target {totalTarget:F3} vs truth {totalTruth:F3} EV, transition {result.Transitions[0].Length} frames")); + + Assert.Equal(12, result.Transitions.Count); + var ignored = Assert.NotNull(result.Transitions.SingleOrDefault(t => !t.Received)); + Assert.Equal(130, ignored.Index); + Assert.True(result.Transitions.Where(t => t.Index != 130).All(t => t.Received)); + Assert.Greater(rawMaxStep, 0.5); + Assert.LessOrEqual(maxStep, 0.3); + Assert.Approximately(maxStep, result.MaxFrameStepEv, 1e-12); + Assert.Approximately(totalTruth, totalTarget, 0.05); + // Default transition: half the 20-frame step spacing. + Assert.Equal(10.0, result.Transitions[0].Length); + } + + [Test] + public void LargeStepGetsALongerTransition() + { + var n = 100; + var measured = Enumerable.Range(0, n).Select(i => i >= 50 ? 1.5 : 0.0).ToArray(); + var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 50 ? 10.5 : 12.0)).ToArray(); + var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 4 }); + Assert.LessOrEqual(result.MaxFrameStepEv, 0.3); + Assert.GreaterOrEqual(result.Transitions[0].Length, 7.5); + Assert.Approximately(1.5, result.Target[^1] - result.Target[0], 1e-9); + Assert.Approximately(1.5, result.Transitions[0].MeasuredEv, 1e-9); + } + + [Test] + public void StepsNearTheEndsStayInsideTheSequence() + { + var n = 30; + var measured = Enumerable.Range(0, n).Select(i => i >= 2 ? 1.0 : 0.0).ToArray(); + var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 2 ? 11.0 : 12.0)).ToArray(); + var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 8 }); + Assert.Equal(0.0, result.Transitions[0].Start); + Assert.Approximately(0, result.SmoothedOffsets[0], 1e-12); + Assert.Approximately(1, result.SmoothedOffsets[^1], 1e-12); + Assert.LessOrEqual(result.MaxFrameStepEv, 0.3); + } + + [Test] + public void NoMetadataStepsMeansPlainDeflicker() + { + var measured = Enumerable.Range(0, 60).Select(i => 0.01 * i + (i % 2 == 0 ? 0.05 : -0.05)).ToArray(); + var ev = new double?[60]; + var result = HolyGrailEngine.Compute(measured, ev); + var plain = DeflickerEngine.Compute(measured); + Assert.Empty(result.Transitions); + Assert.SequenceEqual(plain.Target, result.Target); + } +} From a50ad7deb0229504430aa1b06166b335d43b40eb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 048/188] feat(analysis): add white-balance smoother Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/WhiteBalanceSmoother.cs | 55 ++++++++++++++ .../Analysis/WhiteBalanceSmootherTests.cs | 71 +++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 src/Titano.Core/Analysis/WhiteBalanceSmoother.cs create mode 100644 tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs diff --git a/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs b/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs new file mode 100644 index 00000000..293503e1 --- /dev/null +++ b/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs @@ -0,0 +1,55 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Per-frame white-balance smoothing result; ratios are log2(R/G) and log2(B/G). +public sealed record WhiteBalanceResult( + ChannelGains[] Gains, + double[] RedRatio, + double[] BlueRatio, + double[] SmoothedRedRatio, + double[] SmoothedBlueRatio); + +/// +/// White-balance smoothing (BRIEF §11.2): the channel ratios log2(R/G) and log2(B/G) of each frame's mean colour are +/// smoothed with robust LOWESS, and each frame gets the channel gains that move its ratios onto the smoothed ones. +/// Gains are normalised so the Rec.709 luminance of the frame's mean colour is unchanged (WB never alters exposure). +/// Frames with a non-positive channel mean get identity gains. +/// +public static class WhiteBalanceSmoother +{ + public static WhiteBalanceResult Smooth(ReadOnlySpan meanRed, ReadOnlySpan meanGreen, ReadOnlySpan meanBlue, int window = 31, int robustIterations = 2) + { + var n = meanRed.Length; + if (meanGreen.Length != n || meanBlue.Length != n) throw new ArgumentException("Channel series lengths differ.", nameof(meanGreen)); + var red = new double[n]; + var blue = new double[n]; + for (var i = 0; i < n; i++) + { + var valid = meanRed[i] > 0 && meanGreen[i] > 0 && meanBlue[i] > 0 && double.IsFinite(meanRed[i] + meanGreen[i] + meanBlue[i]); + red[i] = valid ? Math.Log2(meanRed[i] / meanGreen[i]) : double.NaN; + blue[i] = valid ? Math.Log2(meanBlue[i] / meanGreen[i]) : double.NaN; + } + var smoothRed = LocalRegression.Smooth(red, window, 1, robustIterations).Fitted; + var smoothBlue = LocalRegression.Smooth(blue, window, 1, robustIterations).Fitted; + + var gains = new ChannelGains[n]; + for (var i = 0; i < n; i++) + { + if (double.IsNaN(red[i])) + { + gains[i] = ChannelGains.Identity; + continue; + } + var gr = Math.Pow(2, smoothRed[i] - red[i]); + var gb = Math.Pow(2, smoothBlue[i] - blue[i]); + double r = meanRed[i], g = meanGreen[i], b = meanBlue[i]; + var k = Luma(r, g, b) / Luma(gr * r, g, gb * b); + gains[i] = new ChannelGains(k * gr, k, k * gb); + } + return new WhiteBalanceResult(gains, red, blue, smoothRed, smoothBlue); + } + + private static double Luma(double r, double g, double b) => ColorSpace.LumaR * r + ColorSpace.LumaG * g + ColorSpace.LumaB * b; +} diff --git a/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs b/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs new file mode 100644 index 00000000..dad739b9 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs @@ -0,0 +1,71 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +public sealed class WhiteBalanceSmootherTests(TestContext context) +{ + [Test] + public void RemovesJitterAndKeepsTheDrift() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 48, + Height = 32, + FrameCount = 150, + Seed = 21, + StartKelvin = 3500, + EndKelvin = 6500, + WhiteBalanceJitter = 0.08, + FlickerEv = 0.05, + }); + var stats = Measure(sequence, null); + var result = WhiteBalanceSmoother.Smooth(stats.Select(s => s.MeanRed).ToArray(), stats.Select(s => s.MeanGreen).ToArray(), stats.Select(s => s.MeanBlue).ToArray()); + var corrected = Measure(sequence, result.Gains); + + // Truth: the ratio of the drifting light without jitter. + var truthRed = new double[sequence.Count]; + var truthBlue = new double[sequence.Count]; + for (var i = 0; i < sequence.Count; i++) + { + var rgb = ColorTemperature.PlanckianRgb(sequence.Kelvin[i]); + truthRed[i] = Math.Log2(rgb.X / rgb.Y); + truthBlue[i] = Math.Log2(rgb.Z / rgb.Y); + } + var before = AnalysisFixtures.FrameToFrameResidualRms(result.RedRatio, truthRed); + var after = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanRed / s.MeanGreen)).ToArray(), truthRed); + var afterBlue = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanBlue / s.MeanGreen)).ToArray(), truthBlue); + var drift = AnalysisFixtures.MaxDeviation(result.SmoothedBlueRatio, truthBlue); + context.Log(string.Create(CultureInfo.InvariantCulture, $"R/G jitter before {before:F4}, after {after:F4}; B/G after {afterBlue:F4}; drift deviation {drift:F4}")); + Assert.Less(after, 0.2 * before); + Assert.Less(afterBlue, 0.2 * before); + Assert.Less(drift, 0.03); + + // Gains never change exposure. + for (var i = 0; i < sequence.Count; i++) + Assert.Approximately(stats[i].MeanLogLuminance, corrected[i].MeanLogLuminance, 0.01); + } + + [Test] + public void InvalidFramesGetIdentityGains() + { + var result = WhiteBalanceSmoother.Smooth([0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], window: 3); + Assert.Equal(ChannelGains.Identity, result.Gains[1]); + Assert.Approximately(1, result.Gains[0].Red, 1e-12); + Assert.Throws(() => WhiteBalanceSmoother.Smooth([1.0], [1.0, 2.0], [1.0])); + } + + private static FrameStatistics[] Measure(SyntheticSequence sequence, ChannelGains[]? gains) + { + var stats = new FrameStatistics[sequence.Count]; + Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i => + { + using var image = sequence.Render(i); + if (gains is not null) ExposureProcessor.Apply(image, 0, gains[i]); + stats[i] = FrameStatistics.Measure(image); + }); + return stats; + } +} From 6c4f1b7b224fb20c9a3d0d9832e3f63a5402c26b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:51:43 +0000 Subject: [PATCH 049/188] test(analysis): add seeded property tests for the analysis modules Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/AnalysisPropertyTests.cs | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs diff --git a/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs b/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs new file mode 100644 index 00000000..008f0fae --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs @@ -0,0 +1,93 @@ +using Titano.Core.Analysis; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +/// Seeded random inputs: outputs stay finite where defined and repeat exactly. +public sealed class AnalysisPropertyTests +{ + private static double[] RandomSeries(Random random, int n, double missing) + { + var level = 0.0; + var series = new double[n]; + for (var i = 0; i < n; i++) + { + level += 0.05 * (random.NextDouble() - 0.5); + series[i] = random.NextDouble() < missing ? double.NaN : level + 0.3 * (random.NextDouble() - 0.5) + (random.NextDouble() < 0.03 ? 4 : 0); + } + return series; + } + + [Test] + public void DeflickerHolyGrailAndSpectrumAreFiniteAndDeterministic() + { + var random = new Random(1234); + for (var trial = 0; trial < 25; trial++) + { + var n = 2 + random.Next(300); + var series = RandomSeries(random, n, missing: 0.1); + if (series.All(double.IsNaN)) series[0] = 0; + var ev = new double?[n]; + double camera = 12; + for (var i = 0; i < n; i++) + { + if (random.NextDouble() < 0.05) camera -= Math.Round(random.NextDouble() * 6 - 3) / 3; + ev[i] = random.NextDouble() < 0.05 ? null : camera; + } + var options = new DeflickerOptions { Window = 3 + random.Next(40), Degree = 1 + random.Next(2), Strength = random.NextDouble() }; + + var a = DeflickerEngine.Compute(series, options); + var b = DeflickerEngine.Compute(series, options); + Assert.True(a.Target.All(double.IsFinite) && a.CorrectionEv.All(double.IsFinite), $"deflicker trial {trial}"); + Assert.SequenceEqual(a.Target, b.Target); + + var grail = HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options }); + Assert.True(grail.Target.All(double.IsFinite) && grail.CorrectionEv.All(double.IsFinite), $"holy grail trial {trial}"); + Assert.SequenceEqual(grail.Target, HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options }).Target); + + var spectrum = FlickerSpectrum.Analyze(series); + Assert.True(spectrum.Autocorrelation.All(double.IsFinite)); + Assert.Equal(1, spectrum.RecommendedWindow % 2); + + var region = RegionDeflicker.Compute(series, RandomSeries(random, n, 0.2), options); + Assert.True(region.Land.CorrectionEv.All(double.IsFinite)); + } + } + + [Test] + public void WhiteBalanceAndLightAnalysisSurviveRandomMetadata() + { + var random = new Random(77); + for (var trial = 0; trial < 20; trial++) + { + var n = 1 + random.Next(200); + double Channel() => random.NextDouble() < 0.05 ? 0 : 0.01 + random.NextDouble(); + var red = Enumerable.Range(0, n).Select(_ => Channel()).ToArray(); + var green = Enumerable.Range(0, n).Select(_ => Channel()).ToArray(); + var blue = Enumerable.Range(0, n).Select(_ => Channel()).ToArray(); + var wb = WhiteBalanceSmoother.Smooth(red, green, blue, window: 1 + random.Next(40)); + Assert.True(wb.Gains.All(g => double.IsFinite(g.Red) && g.Red > 0 && double.IsFinite(g.Blue) && g.Blue > 0), $"wb trial {trial}"); + + var start = new DateTime(2024, 1, 1); + var frames = Enumerable.Range(0, n).Select(i => new LightFrame + { + Index = i, + CapturedAt = random.NextDouble() < 0.05 ? null : start.AddSeconds(i * 7 + random.Next(-20, 20) + (random.NextDouble() < 0.02 ? 9000 : 0)), + ExposureTime = random.NextDouble() < 0.05 ? null : 1.0 / (1 + random.Next(3)), + FNumber = 2.8, + Iso = random.NextDouble() < 0.5 ? 100 : null, + Width = 100 + random.Next(2), + Height = 80, + Orientation = random.NextDouble() < 0.05 ? 6 : 1, + Latitude = random.NextDouble() < 0.5 ? -60 + 120 * random.NextDouble() : null, + Longitude = 170 * (random.NextDouble() - 0.5), + }).ToList(); + var first = LightAnalyzer.Analyze(frames); + var second = LightAnalyzer.Analyze(frames); + Assert.SequenceEqual(first.Intervals, second.Intervals); + Assert.SequenceEqual(first.Findings.Select(f => f.Key), second.Findings.Select(f => f.Key)); + Assert.Equal(n, first.Sessions.Sum(s => s.FrameCount)); + Assert.True(first.CaptureSpan >= TimeSpan.Zero); + } + } +} From 5738fc16948a59e3808cafc13f94af8c89a97fc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:53:03 +0000 Subject: [PATCH 050/188] perf(motion): vectorise the flow median filter and parallelise stabiliser patches The flow median filter runs the odd-even transposition network on Vector blocks in the interior (shared with the temporal median), which removes the dominant cost of Best-quality flow. The stabiliser analyses its nine patches in parallel with one correlator each and gathers results in patch order, so output stays deterministic. Adds brute-force reference tests for the median, box and binomial kernels. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/PlaneOps.cs | 51 ++++++++-- src/Titano.Core/Motion/Stabilizer.cs | 61 ++++++------ src/Titano.Core/Motion/TemporalStacker.cs | 13 +-- .../Titano.Core.Tests/Motion/PlaneOpsTests.cs | 97 +++++++++++++++++++ 4 files changed, 178 insertions(+), 44 deletions(-) create mode 100644 tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs diff --git a/src/Titano.Core/Motion/PlaneOps.cs b/src/Titano.Core/Motion/PlaneOps.cs index b93b65ef..c4c95d52 100644 --- a/src/Titano.Core/Motion/PlaneOps.cs +++ b/src/Titano.Core/Motion/PlaneOps.cs @@ -137,26 +137,65 @@ internal static class PlaneOps }); } - /// Median over a (2r+1)² window with replicated edges. + /// + /// Median over a (2r+1)² window with replicated edges. Interior pixels run the vectorised sorting network + /// on Vector<float> blocks of neighbouring pixels; borders use scalar selection. + /// public static void MedianFilter(float[] source, float[] destination, int width, int height, int radius) { ForRows(height, width, y => { var size = 2 * radius + 1; - Span window = stackalloc float[size * size]; - for (var x = 0; x < width; x++) + var count = size * size; + Span window = stackalloc float[count]; + var vc = Vector.Count; + var interior = Vector.IsHardwareAccelerated && y >= radius && y < height - radius; + Span> lanes = interior ? stackalloc Vector[count] : default; + for (var x = 0; x < width;) { - var n = 0; + if (interior && x >= radius && x + vc + radius <= width) + { + var n = 0; + for (var dy = -radius; dy <= radius; dy++) + { + var row = (y + dy) * width + x; + for (var dx = -radius; dx <= radius; dx++) lanes[n++] = new Vector(source, row + dx); + } + MedianOfLanes(lanes).CopyTo(destination, y * width + x); + x += vc; + continue; + } + var k = 0; for (var dy = -radius; dy <= radius; dy++) { var row = int.Clamp(y + dy, 0, height - 1) * width; - for (var dx = -radius; dx <= radius; dx++) window[n++] = source[row + int.Clamp(x + dx, 0, width - 1)]; + for (var dx = -radius; dx <= radius; dx++) window[k++] = source[row + int.Clamp(x + dx, 0, width - 1)]; } - destination[y * width + x] = Select(window, n / 2); + destination[y * width + x] = Select(window, count / 2); + x++; } }); } + /// + /// Lane-wise exact median of the vectors (mean of the middle pair for even counts) by odd–even + /// transposition sort (Habermann 1972): n passes of branch-free min/max; reorders . + /// + public static Vector MedianOfLanes(Span> lanes) + { + var n = lanes.Length; + for (var pass = 0; pass < n; pass++) + { + for (var k = pass & 1; k + 1 < n; k += 2) + { + var lo = Vector.Min(lanes[k], lanes[k + 1]); + lanes[k + 1] = Vector.Max(lanes[k], lanes[k + 1]); + lanes[k] = lo; + } + } + return (n & 1) != 0 ? lanes[n / 2] : (lanes[n / 2 - 1] + lanes[n / 2]) * 0.5f; + } + /// Exact median (mean of the two middle values for even counts); reorders . public static float Median(Span values) { diff --git a/src/Titano.Core/Motion/Stabilizer.cs b/src/Titano.Core/Motion/Stabilizer.cs index 7bb44d60..2cc05e26 100644 --- a/src/Titano.Core/Motion/Stabilizer.cs +++ b/src/Titano.Core/Motion/Stabilizer.cs @@ -58,7 +58,7 @@ public sealed record StabilizationResult( /// /// Video stabilisation. Per frame: Kuglin–Hines phase correlation of nine patches on a 3×3 grid against the -/// previous frame, texture gating (noise-compensated gradient energy, Immerkær 1996 noise estimate; a +/// previous frame (patches analysed in parallel), texture gating (noise-compensated gradient energy, Immerkær 1996 noise estimate; a /// textureless frame yields no vectors and therefore no motion), then a robust similarity fit (exhaustive /// two-point hypotheses as deterministic RANSAC, plausibility limits, weighted least squares on the /// inliers). accumulates the camera path, smooths its translation, rotation and log-scale @@ -71,11 +71,12 @@ public sealed class Stabilizer : IDisposable // Expected smoothed-gradient energy of unit-variance white noise: 2 · Σ([−1 −2 0 2 1]/8)² · Σ([1 2 1]/4)². private const double NoiseGradientGain = 2 * (10.0 / 64) * (6.0 / 16); - private readonly PhaseCorrelator _correlator; + private readonly PhaseCorrelator[] _correlators; + private readonly PhaseCorrelation?[] _results = new PhaseCorrelation?[9]; private readonly (int X, int Y)[] _patches; private readonly double[] _previousEnergy; private readonly double[] _currentEnergy; - private readonly float[] _smooth; + private readonly float[][] _smooth; private readonly Match[] _matches = new Match[9]; private readonly List _motions = []; private float[]? _previous; @@ -91,7 +92,14 @@ public sealed class Stabilizer : IDisposable PatchSize = Options.PatchSize > 0 ? int.Min(Options.PatchSize, int.Min(width, height)) : int.Clamp(1 << BitOperations.Log2((uint)(int.Min(width, height) / 3)), 8, 256); - _correlator = new PhaseCorrelator(PatchSize, PatchSize); + // One correlator and blur buffer per patch so the nine patches are analysed in parallel. + _correlators = new PhaseCorrelator[9]; + _smooth = new float[9][]; + for (var i = 0; i < 9; i++) + { + _correlators[i] = new PhaseCorrelator(PatchSize, PatchSize); + _smooth[i] = new float[PatchSize * PatchSize]; + } _patches = new (int, int)[9]; for (var j = 0; j < 3; j++) { @@ -104,7 +112,6 @@ public sealed class Stabilizer : IDisposable } _previousEnergy = new double[9]; _currentEnergy = new double[9]; - _smooth = new float[PatchSize * PatchSize]; _previous = ArrayPool.Shared.Rent(width * height); _current = ArrayPool.Shared.Rent(width * height); } @@ -191,27 +198,27 @@ public sealed class Stabilizer : IDisposable private FrameMotion Analyse() { var current = CurrentPlane; - for (var i = 0; i < 9; i++) _currentEnergy[i] = TextureEnergy(current, _patches[i].X, _patches[i].Y); + var first = _motions.Count == 0; + var previous = _previous!; + Parallel.For(0, 9, i => + { + var (x0, y0) = _patches[i]; + _currentEnergy[i] = TextureEnergy(current, x0, y0, _smooth[i]); + _results[i] = first || double.Min(_previousEnergy[i], _currentEnergy[i]) < Options.TextureThreshold + ? null + : _correlators[i].Correlate(previous, current, Width, x0, y0); + }); - FrameMotion motion; - if (_motions.Count == 0) + // Gathered in patch order, so the fit does not depend on thread scheduling. + var count = 0; + var half = (PatchSize - 1) / 2.0; + for (var i = 0; i < 9; i++) { - motion = new FrameMotion(Affine2D.Identity, 0, 0); - } - else - { - var count = 0; - var half = (PatchSize - 1) / 2.0; - for (var i = 0; i < 9; i++) - { - if (double.Min(_previousEnergy[i], _currentEnergy[i]) < Options.TextureThreshold) continue; - var (x0, y0) = _patches[i]; - var r = _correlator.Correlate(_previous, current, Width, x0, y0); - if (r.Confidence < Options.MinimumConfidence) continue; - _matches[count++] = new Match(x0 + half, y0 + half, x0 + half + r.Dx, y0 + half + r.Dy, r.Confidence); - } - motion = FitSimilarity(_matches.AsSpan(0, count)); + if (_results[i] is not { } r || r.Confidence < Options.MinimumConfidence) continue; + var (x0, y0) = _patches[i]; + _matches[count++] = new Match(x0 + half, y0 + half, x0 + half + r.Dx, y0 + half + r.Dy, r.Confidence); } + var motion = first ? new FrameMotion(Affine2D.Identity, 0, 0) : FitSimilarity(_matches.AsSpan(0, count)); _motions.Add(motion); (_previous, _current) = (_current, _previous); @@ -220,7 +227,7 @@ public sealed class Stabilizer : IDisposable } /// Noise-compensated mean squared gradient of the blurred patch. - private double TextureEnergy(float[] plane, int x0, int y0) + private double TextureEnergy(float[] plane, int x0, int y0, float[] smooth) { var p = PatchSize; var w = Width; @@ -234,7 +241,7 @@ public sealed class Stabilizer : IDisposable float a = plane[c - w - 1], b = plane[c - w], d = plane[c - w + 1]; float e = plane[c - 1], f = plane[c], g = plane[c + 1]; float h = plane[c + w - 1], i = plane[c + w], j = plane[c + w + 1]; - _smooth[y * p + x] = (a + d + h + j + 2 * (b + e + g + i) + 4 * f) * (1f / 16); + smooth[y * p + x] = (a + d + h + j + 2 * (b + e + g + i) + 4 * f) * (1f / 16); laplacian += float.Abs(a + d + h + j - 2 * (b + e + g + i) + 4 * f); } } @@ -247,8 +254,8 @@ public sealed class Stabilizer : IDisposable for (var x = 2; x < p - 2; x++) { var k = y * p + x; - var gx = 0.5 * (_smooth[k + 1] - _smooth[k - 1]); - var gy = 0.5 * (_smooth[k + p] - _smooth[k - p]); + var gx = 0.5 * (smooth[k + 1] - smooth[k - 1]); + var gy = 0.5 * (smooth[k + p] - smooth[k - p]); energy += gx * gx + gy * gy; samples++; } diff --git a/src/Titano.Core/Motion/TemporalStacker.cs b/src/Titano.Core/Motion/TemporalStacker.cs index 27a965a7..aec5f762 100644 --- a/src/Titano.Core/Motion/TemporalStacker.cs +++ b/src/Titano.Core/Motion/TemporalStacker.cs @@ -18,6 +18,7 @@ public enum StackMode /// combines the frames currently in the window. Medians are exact: for up to /// frames an odd–even transposition sorting network runs on Vector<float> /// lanes (many pixels per instruction, no branches), beyond that Hoare's selection runs per pixel. +/// Rows of every channel run in parallel. /// public sealed class TemporalStacker : IDisposable { @@ -100,17 +101,7 @@ public sealed class TemporalStacker : IDisposable { var at = offset + i; for (var k = 0; k < n; k++) lanes[k] = new Vector(planes[k], at); - // n passes of odd–even transposition sort every lane. - for (var pass = 0; pass < n; pass++) - { - for (var k = pass & 1; k + 1 < n; k += 2) - { - var lo = Vector.Min(lanes[k], lanes[k + 1]); - lanes[k + 1] = Vector.Max(lanes[k], lanes[k + 1]); - lanes[k] = lo; - } - } - var median = (n & 1) != 0 ? lanes[n / 2] : (lanes[n / 2 - 1] + lanes[n / 2]) * 0.5f; + var median = PlaneOps.MedianOfLanes(lanes); median.CopyTo(dst, at); } } diff --git a/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs b/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs new file mode 100644 index 00000000..959fab08 --- /dev/null +++ b/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs @@ -0,0 +1,97 @@ +using Titano.Core.Motion; +using Titano.Testing; + +namespace Titano.Core.Tests.Motion; + +public sealed class PlaneOpsTests +{ + private const int Width = 37; + private const int Height = 23; + + [Theory] + [Case(1)] + [Case(2)] + public void MedianFilterMatchesBruteForce(int radius) + { + var source = RandomPlane(seed: radius); + var output = new float[source.Length]; + PlaneOps.MedianFilter(source, output, Width, Height, radius); + for (var y = 0; y < Height; y++) + { + for (var x = 0; x < Width; x++) + { + var window = new List(); + for (var dy = -radius; dy <= radius; dy++) + for (var dx = -radius; dx <= radius; dx++) + window.Add(source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]); + window.Sort(); + Assert.Equal(window[window.Count / 2], output[y * Width + x]); + } + } + } + + [Theory] + [Case(1)] + [Case(3)] + public void BoxFilterMatchesBruteForce(int radius) + { + var source = RandomPlane(seed: 10 + radius); + var output = new float[source.Length]; + PlaneOps.BoxFilter(source, output, new float[source.Length], Width, Height, radius); + for (var y = 0; y < Height; y++) + { + for (var x = 0; x < Width; x++) + { + double sum = 0; + for (var dy = -radius; dy <= radius; dy++) + for (var dx = -radius; dx <= radius; dx++) + sum += source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]; + Assert.Approximately(sum / ((2 * radius + 1) * (2 * radius + 1)), output[y * Width + x], 1e-5); + } + } + } + + [Test] + public void BinomialBlurKeepsConstantsAndMean() + { + var flat = new float[Width * Height]; + flat.AsSpan().Fill(0.7f); + PlaneOps.Binomial5(flat, flat, new float[flat.Length], Width, Height); + Assert.True(flat.All(v => double.Abs(v - 0.7) < 1e-6)); + + var impulse = new float[Width * Height]; + impulse[11 * Width + 17] = 1; + var blurred = new float[impulse.Length]; + PlaneOps.Binomial5(impulse, blurred, new float[impulse.Length], Width, Height); + Assert.Approximately(1, blurred.Sum(v => (double)v), 1e-6); + Assert.Approximately(36.0 / 256, blurred[11 * Width + 17], 1e-7); + } + + [Test] + public void SelectionAndMedian() + { + var values = new float[] { 5, 1, 4, 2, 3 }; + Assert.Equal(3f, PlaneOps.Median(values)); + Assert.Equal(2.5f, PlaneOps.Median(new float[] { 4, 1, 3, 2 })); + Assert.Equal(1f, PlaneOps.Select(new float[] { 3, 1, 2 }, 0)); + Assert.Equal(7f, PlaneOps.Median(new float[] { 7 })); + } + + [Test] + public void BilinearIsExactAtPixelCentresAndClamps() + { + var plane = RandomPlane(seed: 3); + Assert.Equal(plane[5 * Width + 9], PlaneOps.Bilinear(plane, Width, Height, 9, 5)); + Assert.Equal(plane[0], PlaneOps.Bilinear(plane, Width, Height, -3, -8)); + var mid = 0.5f * (plane[5 * Width + 9] + plane[5 * Width + 10]); + Assert.Approximately(mid, PlaneOps.Bilinear(plane, Width, Height, 9.5f, 5), 1e-6); + } + + private static float[] RandomPlane(int seed) + { + var random = new Random(seed); + var plane = new float[Width * Height]; + for (var i = 0; i < plane.Length; i++) plane[i] = (float)random.NextDouble(); + return plane; + } +} From 310379d2da2eeae2d0bbd253fbafe37c1d1bd3d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:54:01 +0000 Subject: [PATCH 051/188] test(motion): log measured FFT and motion-blur energy figures Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Core.Tests/Motion/FourierTests.cs | 13 ++++++++++--- tests/Titano.Core.Tests/Motion/MotionBlurTests.cs | 6 ++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/Titano.Core.Tests/Motion/FourierTests.cs b/tests/Titano.Core.Tests/Motion/FourierTests.cs index 621d1fd6..f123eaca 100644 --- a/tests/Titano.Core.Tests/Motion/FourierTests.cs +++ b/tests/Titano.Core.Tests/Motion/FourierTests.cs @@ -5,6 +5,10 @@ namespace Titano.Core.Tests.Motion; public sealed class FourierTests { + private readonly TestContext _context; + + public FourierTests(TestContext context) => _context = context; + [Theory] [Case(1)] [Case(2)] @@ -17,7 +21,9 @@ public sealed class FourierTests var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone()); Fourier.Forward(re, im); Fourier.Inverse(re, im); - Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5); + var error = MaxError(r0, i0, re, im); + _context.Log($"n = {n}: round-trip max error {error:E2}"); + Assert.LessOrEqual(error, 1e-5); } [Theory] @@ -32,8 +38,9 @@ public sealed class FourierTests var (re, im) = RandomSignal(n, seed: n); var (er, ei) = Dft(re, im); Fourier.Forward(re, im); - var scale = double.Sqrt(n); - Assert.LessOrEqual(MaxError(er, ei, re, im) / scale, 1e-9); + var error = MaxError(er, ei, re, im) / double.Sqrt(n); + _context.Log($"n = {n}: Bluestein vs direct DFT, max error / √n {error:E2}"); + Assert.LessOrEqual(error, 1e-9); } [Theory] diff --git a/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs index 96c94d7e..731d49dd 100644 --- a/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs +++ b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs @@ -8,6 +8,10 @@ public sealed class MotionBlurTests { private const int Size = 128; + private readonly TestContext _context; + + public MotionBlurTests(TestContext context) => _context = context; + [Theory] [Case(180.0, 90.0, 0.4330127018922193)] [Case(180.0, 0.0, 0.5)] @@ -58,6 +62,7 @@ public sealed class MotionBlurTests columns.Add(x); } } + _context.Log($"point energy after blur {total:F6}, segment columns {columns.Min()}..{columns.Max()}"); Assert.Approximately(1, total, 1e-4); Assert.InRange(columns.Min(), 58, 60); Assert.InRange(columns.Max(), 68, 70); @@ -82,6 +87,7 @@ public sealed class MotionBlurTests { var before = Mean(source.Plane(c), 16); var after = Mean(output.Plane(c), 16); + _context.Log($"channel {c}: mean {before:F6} → {after:F6} ({(after - before) / before:P3})"); Assert.Approximately(before, after, 2e-3 * before); } Assert.False(source.Data.SequenceEqual(output.Data)); From 3bc55449ae24b8a1dc653a4f3c87a09e4606525b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:27 +0000 Subject: [PATCH 052/188] refactor(math): drop unused vector helpers and test moments Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/Matrix3.cs | 14 +------------- src/Titano.Core/Math/Point2.cs | 2 -- tests/Titano.Core.Tests/Math/StatisticsTests.cs | 11 ++++++++++- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/Titano.Core/Math/Matrix3.cs b/src/Titano.Core/Math/Matrix3.cs index 73b877cb..3e1bfc91 100644 --- a/src/Titano.Core/Math/Matrix3.cs +++ b/src/Titano.Core/Math/Matrix3.cs @@ -1,16 +1,7 @@ namespace Titano.Core.Mathematics; /// A 3-vector in double precision (colour triplets, homogeneous 2-D points). -public readonly record struct Vector3D(double X, double Y, double Z) -{ - public static Vector3D operator +(Vector3D a, Vector3D b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z); - - public static Vector3D operator -(Vector3D a, Vector3D b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z); - - public static Vector3D operator *(Vector3D a, double s) => new(a.X * s, a.Y * s, a.Z * s); - - public static double Dot(Vector3D a, Vector3D b) => a.X * b.X + a.Y * b.Y + a.Z * b.Z; -} +public readonly record struct Vector3D(double X, double Y, double Z); /// Row-major 3×3 matrix in double precision for colour-space and planar projective work. public readonly record struct Matrix3( @@ -47,9 +38,6 @@ public readonly record struct Matrix3( m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z, m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z); - public static Matrix3 operator *(Matrix3 m, double s) => new( - m.M11 * s, m.M12 * s, m.M13 * s, m.M21 * s, m.M22 * s, m.M23 * s, m.M31 * s, m.M32 * s, m.M33 * s); - public double Determinant => M11 * (M22 * M33 - M23 * M32) - M12 * (M21 * M33 - M23 * M31) + M13 * (M21 * M32 - M22 * M31); diff --git a/src/Titano.Core/Math/Point2.cs b/src/Titano.Core/Math/Point2.cs index 848095ae..d1c1522c 100644 --- a/src/Titano.Core/Math/Point2.cs +++ b/src/Titano.Core/Math/Point2.cs @@ -14,6 +14,4 @@ public readonly record struct Point2(double X, double Y) public double Length => Math.Sqrt(X * X + Y * Y); public static double Distance(Point2 a, Point2 b) => (a - b).Length; - - public static Point2 Lerp(Point2 a, Point2 b, double t) => new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); } diff --git a/tests/Titano.Core.Tests/Math/StatisticsTests.cs b/tests/Titano.Core.Tests/Math/StatisticsTests.cs index 0161826b..b845d789 100644 --- a/tests/Titano.Core.Tests/Math/StatisticsTests.cs +++ b/tests/Titano.Core.Tests/Math/StatisticsTests.cs @@ -119,9 +119,18 @@ public sealed class StatisticsTests var random = new Random(11); var values = Enumerable.Range(0, 501).Select(_ => random.NextDouble() < 0.1 ? double.NaN : random.NextDouble() * 10 - 5).ToArray(); double Run() => Statistics.Median(values) + Statistics.MedianAbsoluteDeviation(values) + Statistics.TrimmedMean(values, 0.02, 0.02) - + Statistics.Percentile(values, 0.9) + Statistics.Mean(values) + Statistics.StandardDeviation(values); + + Statistics.Percentile(values, 0.9) + Statistics.Mean(values) + Statistics.StandardDeviation(values) + Statistics.Rms(values); var first = Run(); Assert.True(double.IsFinite(first)); Assert.Equal(first, Run()); } + + [Test] + public void MomentsOfAKnownSet() + { + double[] values = [2, 4, double.NaN, 4, 4, 5, 5, 7, 9]; + Assert.Approximately(5, Statistics.Mean(values), 1e-12); + Assert.Approximately(Math.Sqrt(32.0 / 7), Statistics.StandardDeviation(values), 1e-12); + Assert.Approximately(Math.Sqrt(232.0 / 8), Statistics.Rms(values), 1e-12); + } } From 1b0c979308743cc0973623156d2c5135814d5d74 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:27 +0000 Subject: [PATCH 053/188] test: log solar and LOWESS deviations, cover domain-frame analysis Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/LightAnalyzerTests.cs | 5 +++ .../Math/LocalRegressionTests.cs | 5 ++- .../Math/SolarPositionTests.cs | 33 +++++++++++-------- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs index 5873ce17..75cdb54b 100644 --- a/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs +++ b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs @@ -59,6 +59,11 @@ public sealed class LightAnalyzerTests(TestContext context) Assert.Equal(FindingSeverity.Warning, gaps.Severity); Assert.Equal(3, (int)gaps.Arguments[0]); Assert.Approximately(7210, (double)gaps.Arguments[1], 1e-9); + + // Domain frames (no camera or GPS fields) give the same timing and exposure analysis. + var fromFrames = LightAnalyzer.Analyze(Timeline().Frames); + Assert.SequenceEqual(report.Intervals, fromFrames.Intervals); + Assert.SequenceEqual(report.ExposureSteps.Select(s => s.Index), fromFrames.ExposureSteps.Select(s => s.Index)); } [Test] diff --git a/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs index 66b7d158..194b6724 100644 --- a/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs +++ b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs @@ -1,9 +1,10 @@ +using System.Globalization; using Titano.Core.Mathematics; using Titano.Testing; namespace Titano.Core.Tests.Mathematics; -public sealed class LocalRegressionTests +public sealed class LocalRegressionTests(TestContext context) { [Theory] [Case(1)] @@ -46,6 +47,8 @@ public sealed class LocalRegressionTests var robustShift = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - reference.Fitted[i])); var plainShift = Enumerable.Range(0, n).Max(i => Math.Abs(plain.Fitted[i] - reference.Fitted[i])); var robustError = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - truth[i])); + context.Log(string.Create(CultureInfo.InvariantCulture, + $"20 % outliers: robust fit moved {robustShift:F4} (error vs truth {robustError:F4}), non-robust fit moved {plainShift:F4}")); Assert.Less(robustShift, 0.03, "robust fit moved by the outliers"); Assert.Less(robustError, 0.04); Assert.Greater(plainShift, 10 * robustShift); diff --git a/tests/Titano.Core.Tests/Math/SolarPositionTests.cs b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs index a81f514b..306b14ca 100644 --- a/tests/Titano.Core.Tests/Math/SolarPositionTests.cs +++ b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs @@ -8,7 +8,7 @@ namespace Titano.Core.Tests.Mathematics; /// Reference values are NOAA Solar Calculator results (spreadsheet equations as implemented by the /// astral package, cross-checked against PyEphem/VSOP87 to within 35 s), UTC, for the local solar day. /// -public sealed class SolarPositionTests +public sealed class SolarPositionTests(TestContext context) { private const double OneMinute = 60; @@ -29,14 +29,18 @@ public sealed class SolarPositionTests { var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture); var events = SolarPosition.Events(day, latitude, longitude); - Check(place + " sunrise", day, sunrise, events.Sunrise); - Check(place + " sunset", day, sunset, events.Sunset); - Check(place + " civil dawn", day, civilDawn, events.CivilDawn); - Check(place + " civil dusk", day, civilDusk, events.CivilDusk); - Check(place + " nautical dawn", day, nauticalDawn, events.NauticalDawn); - Check(place + " nautical dusk", day, nauticalDusk, events.NauticalDusk); - Check(place + " astronomical dawn", day, astroDawn, events.AstronomicalDawn); - Check(place + " astronomical dusk", day, astroDusk, events.AstronomicalDusk); + double[] deviations = + [ + Check(place + " sunrise", day, sunrise, events.Sunrise), + Check(place + " sunset", day, sunset, events.Sunset), + Check(place + " civil dawn", day, civilDawn, events.CivilDawn), + Check(place + " civil dusk", day, civilDusk, events.CivilDusk), + Check(place + " nautical dawn", day, nauticalDawn, events.NauticalDawn), + Check(place + " nautical dusk", day, nauticalDusk, events.NauticalDusk), + Check(place + " astronomical dawn", day, astroDawn, events.AstronomicalDawn), + Check(place + " astronomical dusk", day, astroDusk, events.AstronomicalDusk), + ]; + context.Log(string.Create(CultureInfo.InvariantCulture, $"{place}: worst deviation {deviations.Max():F1} s")); } [Theory] @@ -87,18 +91,21 @@ public sealed class SolarPositionTests Assert.Throws(() => SolarPosition.Compute(DateTime.UtcNow, 91, 0)); } - /// Expected "HH:mm:ss" on ; a leading '-' or '+' means the previous or next UTC day. - private static void Check(string label, DateOnly day, string? expected, DateTime? actual) + /// Expected "HH:mm:ss" on ; a leading '-' or '+' means the previous or next UTC day. + /// Returns the absolute deviation in seconds (0 when the event is correctly absent). + private static double Check(string label, DateOnly day, string? expected, DateTime? actual) { if (expected is null) { Assert.Null(actual); - return; + return 0; } var offsetDays = expected[0] switch { '-' => -1, '+' => 1, _ => 0 }; var clock = TimeOnly.ParseExact(expected.TrimStart('+', '-'), "HH:mm:ss", CultureInfo.InvariantCulture); var reference = day.AddDays(offsetDays).ToDateTime(clock, DateTimeKind.Utc); var value = Assert.NotNull(actual, label); - Assert.Approximately(0, (value - reference).TotalSeconds, OneMinute, label); + var deviation = (value - reference).TotalSeconds; + Assert.Approximately(0, deviation, OneMinute, label); + return Math.Abs(deviation); } } From 17bdaeebf6b2030ff3ba85200573e403bba3d2f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:35 +0000 Subject: [PATCH 054/188] docs(motion): clarify stabiliser option and memory summaries Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Motion/Stabilizer.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Titano.Core/Motion/Stabilizer.cs b/src/Titano.Core/Motion/Stabilizer.cs index 2cc05e26..ac8547c3 100644 --- a/src/Titano.Core/Motion/Stabilizer.cs +++ b/src/Titano.Core/Motion/Stabilizer.cs @@ -23,9 +23,10 @@ public sealed record StabilizerOptions /// Residual (px) under which a patch vector is an inlier of a similarity hypothesis. public double InlierThreshold { get; init; } = 1.0; - /// Largest plausible frame-to-frame rotation (radians) and |ln scale| of a hypothesis. + /// Largest plausible frame-to-frame rotation (radians) of a hypothesis. public double MaxRotation { get; init; } = 0.05; + /// Largest plausible frame-to-frame |ln scale| of a hypothesis. public double MaxScaleChange { get; init; } = 0.05; /// σ (frames) of the Gaussian-weighted local linear regression that smooths the camera path; 0 disables. @@ -58,13 +59,13 @@ public sealed record StabilizationResult( /// /// Video stabilisation. Per frame: Kuglin–Hines phase correlation of nine patches on a 3×3 grid against the -/// previous frame (patches analysed in parallel), texture gating (noise-compensated gradient energy, Immerkær 1996 noise estimate; a -/// textureless frame yields no vectors and therefore no motion), then a robust similarity fit (exhaustive -/// two-point hypotheses as deterministic RANSAC, plausibility limits, weighted least squares on the -/// inliers). accumulates the camera path, smooths its translation, rotation and log-scale -/// with Gaussian-weighted local linear regression (pans survive unchanged), and reports per-frame -/// corrections (smoothed ∘ raw⁻¹), shake RMS and the crop needed to hide borders. Memory holds two -/// luminance planes regardless of sequence length. +/// previous frame (patches analysed in parallel), texture gating (noise-compensated gradient energy, +/// Immerkær 1996 noise estimate; a textureless frame yields no vectors and therefore no motion), then a +/// robust similarity fit (exhaustive two-point hypotheses as deterministic RANSAC, plausibility limits, +/// weighted least squares on the inliers). accumulates the camera path, smooths its +/// translation, rotation and log-scale with Gaussian-weighted local linear regression (pans survive +/// unchanged), and reports per-frame corrections (smoothed ∘ raw⁻¹), shake RMS and the crop needed to hide +/// borders. Memory is two luminance planes plus one small record per frame. /// public sealed class Stabilizer : IDisposable { From d79ab1e41bffa65f5d7a59040a6ebf7407c4f5ee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:37 +0000 Subject: [PATCH 055/188] feat(packaging): add TPK1 self-extracting payload format Installer payload appended to the setup program: JSON manifest (components, files with size/SHA-256/offsets/mtime, shortcuts, file types) plus deflate or stored entries and a 64-byte footer with the manifest hash. The reader finds the footer before an Authenticode table, validates every offset, rejects unsafe paths and bounds inflation by the declared size; the writer is deterministic, deduplicates identical content and strips a signed stub. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Packaging/PayloadException.cs | 21 ++ src/Titano.Core/Packaging/PayloadFormat.cs | 52 ++++ src/Titano.Core/Packaging/PayloadManifest.cs | 214 ++++++++++++++++ src/Titano.Core/Packaging/PayloadPath.cs | 68 +++++ src/Titano.Core/Packaging/PayloadReader.cs | 235 ++++++++++++++++++ src/Titano.Core/Packaging/PayloadWriter.cs | 225 +++++++++++++++++ src/Titano.Core/Packaging/PeImage.cs | 56 +++++ src/Titano.Core/Packaging/WindowStream.cs | 42 ++++ .../Packaging/PackagingFixture.cs | 130 ++++++++++ .../Packaging/PayloadIntegrityTests.cs | 213 ++++++++++++++++ .../Packaging/PayloadPathTests.cs | 60 +++++ .../Packaging/PayloadRoundTripTests.cs | 172 +++++++++++++ 12 files changed, 1488 insertions(+) create mode 100644 src/Titano.Core/Packaging/PayloadException.cs create mode 100644 src/Titano.Core/Packaging/PayloadFormat.cs create mode 100644 src/Titano.Core/Packaging/PayloadManifest.cs create mode 100644 src/Titano.Core/Packaging/PayloadPath.cs create mode 100644 src/Titano.Core/Packaging/PayloadReader.cs create mode 100644 src/Titano.Core/Packaging/PayloadWriter.cs create mode 100644 src/Titano.Core/Packaging/PeImage.cs create mode 100644 src/Titano.Core/Packaging/WindowStream.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PackagingFixture.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs diff --git a/src/Titano.Core/Packaging/PayloadException.cs b/src/Titano.Core/Packaging/PayloadException.cs new file mode 100644 index 00000000..ebe08039 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadException.cs @@ -0,0 +1,21 @@ +namespace Titano.Core.Packaging; + +/// Why a TPK1 payload could not be read, written or extracted. +public enum PayloadError +{ + /// The file carries no payload footer: not a packed installer, or its end was cut off. + NotFound, + + /// Footer, manifest or entry data are inconsistent, truncated or fail their SHA-256. + Corrupt, + + /// A path is absolute, escapes the target folder or uses a name Windows cannot store. + UnsafePath, +} + +/// A payload problem with a machine-readable for exit codes and UI messages. +public sealed class PayloadException(PayloadError error, string message, Exception? innerException = null) + : Exception(message, innerException) +{ + public PayloadError Error { get; } = error; +} diff --git a/src/Titano.Core/Packaging/PayloadFormat.cs b/src/Titano.Core/Packaging/PayloadFormat.cs new file mode 100644 index 00000000..a9d8d4f7 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadFormat.cs @@ -0,0 +1,52 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Packaging; + +/// +/// The TPK1 self-extracting layout: [setup stub][manifest JSON][entry data][zero padding][footer], optionally +/// followed by an Authenticode certificate table that signtool appends when the installer is signed. +/// The footer is 64 bytes, little-endian: magic "TPK1END\0" · payload offset (int64, absolute offset of the +/// manifest) · manifest length (int64) · data length (int64) · SHA-256 of the manifest bytes (32 bytes). +/// Entry offsets in the manifest are relative to the first byte after the manifest. Padding aligns the end of the +/// footer to 8 bytes so a signature can be appended without signtool inserting bytes of its own. +/// +public static class PayloadFormat +{ + public const int FooterLength = 64; + public const int Alignment = 8; + public const int ManifestFormatVersion = 1; + + /// Upper bound for the manifest; a larger value in a footer means corruption. + public const int MaxManifestLength = 64 << 20; + + /// Deflate cannot expand data by more than about 1032:1; larger declared sizes are rejected up front. + public const int MaxDeflateRatio = 1032; + + public static ReadOnlySpan Magic => "TPK1END\0"u8; +} + +/// Decoded TPK1 footer. +internal readonly record struct PayloadFooter(long PayloadOffset, long ManifestLength, long DataLength, byte[] ManifestHash) +{ + public void WriteTo(Span destination) + { + PayloadFormat.Magic.CopyTo(destination); + BinaryPrimitives.WriteInt64LittleEndian(destination[8..], PayloadOffset); + BinaryPrimitives.WriteInt64LittleEndian(destination[16..], ManifestLength); + BinaryPrimitives.WriteInt64LittleEndian(destination[24..], DataLength); + ManifestHash.CopyTo(destination[32..]); + } + + /// Parses a footer; false when the magic does not match. + public static bool TryParse(ReadOnlySpan source, out PayloadFooter footer) + { + footer = default; + if (source.Length < PayloadFormat.FooterLength || !source[..8].SequenceEqual(PayloadFormat.Magic)) return false; + footer = new PayloadFooter( + BinaryPrimitives.ReadInt64LittleEndian(source[8..]), + BinaryPrimitives.ReadInt64LittleEndian(source[16..]), + BinaryPrimitives.ReadInt64LittleEndian(source[24..]), + source.Slice(32, 32).ToArray()); + return true; + } +} diff --git a/src/Titano.Core/Packaging/PayloadManifest.cs b/src/Titano.Core/Packaging/PayloadManifest.cs new file mode 100644 index 00000000..e4b304cc --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadManifest.cs @@ -0,0 +1,214 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; + +namespace Titano.Core.Packaging; + +/// How an entry's bytes are stored in the data region. +public enum PayloadCompression +{ + Stored, + Deflate, +} + +/// Describes everything a TPK1 installer carries: product, components, files, shortcuts and file types. +public sealed partial class PayloadManifest +{ + public int FormatVersion { get; init; } = PayloadFormat.ManifestFormatVersion; + public required string Product { get; init; } + public required string Version { get; init; } + public List Components { get; init; } = []; + public List Files { get; init; } = []; + public List Shortcuts { get; init; } = []; + public List Associations { get; init; } = []; + + /// The component with (ordinal, case-insensitive), or null. + public PayloadComponent? FindComponent(string id) => + Components.FirstOrDefault(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + /// + /// Files installed by the given components, one entry per path in manifest order. A path shared by several + /// components (identical content, enforced by ) is listed once. + /// + public IReadOnlyList FilesFor(IEnumerable componentIds) + { + var selected = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var id in componentIds) + { + var component = FindComponent(id) ?? throw new ArgumentException($"Unknown component '{id}'.", nameof(componentIds)); + selected.Add(component.Id); + } + var seen = new HashSet(PayloadPath.Comparer); + var result = new List(); + foreach (var file in Files) + { + if (selected.Contains(file.Component) && seen.Add(file.Path)) result.Add(file); + } + return result; + } + + /// Rejects manifests that are inconsistent with themselves or with a data region of bytes. + public void Validate(long dataLength) + { + if (FormatVersion != PayloadFormat.ManifestFormatVersion) Fail($"unsupported manifest format {FormatVersion}"); + if (!PayloadPath.IsValidSegment(Product) || Product.Length > 100) Fail("invalid product name"); + if (string.IsNullOrWhiteSpace(Version) || Version.Length > 64) Fail("invalid version"); + if (Components.Count == 0) Fail("no components"); + + var componentIds = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var c in Components) + { + if (c is null || !IdentifierRegex().IsMatch(c.Id)) Fail("invalid component id"); + if (!componentIds.Add(c.Id)) Fail($"duplicate component {c.Id}"); + if (string.IsNullOrWhiteSpace(c.DisplayName) || c.DisplayName.Length > 100) Fail($"invalid display name for {c.Id}"); + if (c.EstimatedSize < 0) Fail($"negative size for {c.Id}"); + } + + var perComponent = new HashSet<(string, string)>(); + var byPath = new Dictionary(PayloadPath.Comparer); + foreach (var f in Files) + { + if (f is null) Fail("empty file entry"); + if (!PayloadPath.IsValid(f.Path)) throw new PayloadException(PayloadError.UnsafePath, $"Unsafe payload path '{f.Path}'."); + if (!componentIds.Contains(f.Component)) Fail($"{f.Path} belongs to an unknown component"); + if (!perComponent.Add((f.Component.ToUpperInvariant(), f.Path.ToUpperInvariant()))) Fail($"duplicate file {f.Path}"); + if (f.Size < 0 || f.Offset < 0 || f.Length < 0 || f.Offset > dataLength || f.Length > dataLength - f.Offset) + Fail($"{f.Path} lies outside the data region"); + if (!Sha256Regex().IsMatch(f.Sha256)) Fail($"{f.Path} has no valid SHA-256"); + switch (f.Compression) + { + case PayloadCompression.Stored when f.Length != f.Size: + Fail($"{f.Path}: stored length differs from size"); + break; + case PayloadCompression.Deflate when f.Size / PayloadFormat.MaxDeflateRatio > f.Length: + Fail($"{f.Path}: declared size exceeds the deflate limit"); + break; + case PayloadCompression.Stored or PayloadCompression.Deflate: + break; + default: + Fail($"{f.Path}: unknown compression"); + break; + } + if (byPath.TryGetValue(f.Path, out var other) && (other.Size != f.Size || !other.Sha256.Equals(f.Sha256, StringComparison.Ordinal))) + Fail($"{f.Path} differs between components {other.Component} and {f.Component}"); + byPath.TryAdd(f.Path, f); + } + + foreach (var s in Shortcuts) + { + if (s is null || !PayloadPath.IsValidSegment(s.Name)) Fail("invalid shortcut name"); + if (!OwnsFile(s.Component, s.Target)) Fail($"shortcut {s.Name} targets a file outside its component"); + } + + foreach (var a in Associations) + { + if (a is null || !ExtensionRegex().IsMatch(a.Extension)) Fail("invalid file extension"); + if (!ProgIdRegex().IsMatch(a.ProgId) || a.ProgId.Length > 39) Fail($"invalid ProgID for {a.Extension}"); + if (string.IsNullOrWhiteSpace(a.Description) || a.Description.Length > 100) Fail($"invalid description for {a.Extension}"); + if (!OwnsFile(a.Component, a.Target)) Fail($"{a.Extension} opens a file outside its component"); + } + + bool OwnsFile(string? component, string? path) => + component is not null && path is not null && perComponent.Contains((component.ToUpperInvariant(), path.ToUpperInvariant())); + } + + /// Serializes with a fixed property order and no whitespace, so identical inputs give identical bytes. + public byte[] ToJsonBytes() => JsonSerializer.SerializeToUtf8Bytes(this, PayloadJson.Default.PayloadManifest); + + /// Parses manifest bytes; malformed JSON is reported as . + public static PayloadManifest Parse(ReadOnlySpan json) + { + try + { + return JsonSerializer.Deserialize(json, PayloadJson.Default.PayloadManifest) + ?? throw new PayloadException(PayloadError.Corrupt, "The installer manifest is empty."); + } + catch (JsonException ex) + { + throw new PayloadException(PayloadError.Corrupt, "The installer manifest is not valid JSON.", ex); + } + } + + [DoesNotReturn] + private static void Fail(string reason) => throw new PayloadException(PayloadError.Corrupt, "Invalid installer manifest: " + reason + "."); + + [GeneratedRegex("^[A-Za-z][A-Za-z0-9]{0,63}$")] + internal static partial Regex IdentifierRegex(); + + [GeneratedRegex("^[0-9a-f]{64}$")] + private static partial Regex Sha256Regex(); + + [GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")] + private static partial Regex ExtensionRegex(); + + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")] + private static partial Regex ProgIdRegex(); +} + +/// A selectable part of the product (Titano, Uploader, Server). +public sealed class PayloadComponent +{ + public required string Id { get; init; } + public required string DisplayName { get; init; } + public bool DefaultSelected { get; init; } + + /// Installed size in bytes (sum of the component's files). + public long EstimatedSize { get; init; } +} + +/// One installed file and where its bytes live in the data region. +public sealed class PayloadFile +{ + /// Canonical relative path (). + public required string Path { get; init; } + public required string Component { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 of the uncompressed content. + public required string Sha256 { get; init; } + public PayloadCompression Compression { get; init; } + + /// Offset of the stored bytes, relative to the start of the data region. + public long Offset { get; init; } + + /// Number of stored (possibly compressed) bytes. + public long Length { get; init; } + + /// Last write time, Unix epoch seconds (UTC). + public long ModifiedUnixSeconds { get; init; } +} + +/// A shortcut to one of a component's files, created in the Start menu and/or on the desktop. +public sealed class PayloadShortcut +{ + public required string Component { get; init; } + + /// File name of the shortcut without .lnk. + public required string Name { get; init; } + + /// Payload path of the program the shortcut opens. + public required string Target { get; init; } + public bool StartMenu { get; init; } + public bool Desktop { get; init; } +} + +/// A file type registered to open with one of a component's programs ("target" "%1"). +public sealed class PayloadAssociation +{ + public required string Component { get; init; } + + /// Extension including the dot, e.g. .titano. + public required string Extension { get; init; } + public required string ProgId { get; init; } + + /// File type name shown by Explorer. + public required string Description { get; init; } + + /// Payload path of the program that opens the file. + public required string Target { get; init; } +} + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)] +[JsonSerializable(typeof(PayloadManifest))] +internal sealed partial class PayloadJson : JsonSerializerContext; diff --git a/src/Titano.Core/Packaging/PayloadPath.cs b/src/Titano.Core/Packaging/PayloadPath.cs new file mode 100644 index 00000000..45904c7f --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadPath.cs @@ -0,0 +1,68 @@ +namespace Titano.Core.Packaging; + +/// +/// Canonical payload paths: relative, forward slashes, every segment a name Windows can store. Anything rooted, +/// drive-qualified, stream-qualified (a:b), containing ./.. or empty segments is rejected, so an +/// archive can never write outside the folder it is extracted into. +/// +public static class PayloadPath +{ + public const int MaxLength = 1024; + public const int MaxSegmentLength = 255; + + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + /// Path comparison used for payload paths: Windows file systems are case-insensitive. + public static StringComparer Comparer => StringComparer.OrdinalIgnoreCase; + + /// True when is a canonical, safe relative payload path. + public static bool IsValid(string? path) + { + if (string.IsNullOrEmpty(path) || path.Length > MaxLength) return false; + foreach (var segment in path.Split('/')) + { + if (!IsValidSegment(segment)) return false; + } + return true; + } + + /// True when is a single file or folder name Windows accepts verbatim. + public static bool IsValidSegment(string? name) + { + if (string.IsNullOrEmpty(name) || name.Length > MaxSegmentLength || name is "." or "..") return false; + foreach (var c in name) + { + if (c < 0x20 || c is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*') return false; + } + // Windows silently strips trailing dots and spaces, which would alias two different names. + if (name[^1] is '.' or ' ') return false; + var dot = name.IndexOf('.', StringComparison.Ordinal); + var stem = (dot < 0 ? name : name[..dot]).TrimEnd(' '); + return !ReservedNames.Contains(stem); + } + + /// Converts a path relative to a source folder (either separator) into its canonical payload form. + public static string FromRelative(string relative) + { + var canonical = relative.Replace('\\', '/'); + if (!IsValid(canonical)) throw new PayloadException(PayloadError.UnsafePath, $"'{relative}' cannot be stored in an installer."); + return canonical; + } + + /// Full path of under ; throws when unsafe or outside the root. + public static string Resolve(string root, string relative) + { + if (!IsValid(relative)) throw new PayloadException(PayloadError.UnsafePath, $"Unsafe payload path '{relative}'."); + var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var full = Path.GetFullPath(Path.Combine(fullRoot, relative.Replace('/', Path.DirectorySeparatorChar))); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (!full.StartsWith(fullRoot + Path.DirectorySeparatorChar, comparison)) + throw new PayloadException(PayloadError.UnsafePath, $"Payload path '{relative}' leaves the target folder."); + return full; + } +} diff --git a/src/Titano.Core/Packaging/PayloadReader.cs b/src/Titano.Core/Packaging/PayloadReader.cs new file mode 100644 index 00000000..05bb94f5 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadReader.cs @@ -0,0 +1,235 @@ +using System.Buffers; +using System.IO.Compression; +using System.Security.Cryptography; + +namespace Titano.Core.Packaging; + +/// Extraction progress: bytes written so far, total bytes, and the file being written. +public readonly record struct PayloadProgress(long Done, long Total, string CurrentPath); + +/// +/// Reads a TPK1 payload from the end of an installer. Opening validates the footer, the manifest SHA-256 and every +/// manifest offset; extraction verifies each file's SHA-256 and never writes more bytes than the manifest declares. +/// +public sealed class PayloadReader : IDisposable +{ + private const int BufferSize = 1 << 16; + private readonly FileStream _stream; + private readonly long _dataOffset; + + private PayloadReader(string path, FileStream stream) + { + ArchivePath = path; + _stream = stream; + var footerOffset = LocateFooter(stream, out var footer); + var (payloadOffset, manifestLength, dataLength) = (footer.PayloadOffset, footer.ManifestLength, footer.DataLength); + if (payloadOffset < 0 || manifestLength <= 0 || manifestLength > PayloadFormat.MaxManifestLength || dataLength < 0 + || payloadOffset > footerOffset || manifestLength > footerOffset - payloadOffset + || dataLength > footerOffset - payloadOffset - manifestLength) + throw Corrupt("The installer footer points outside the file."); + if (footerOffset - payloadOffset - manifestLength - dataLength >= PayloadFormat.Alignment) + throw Corrupt("The installer has unexpected bytes before its footer."); + + var manifestBytes = new byte[manifestLength]; + stream.Position = payloadOffset; + stream.ReadExactly(manifestBytes); + if (!SHA256.HashData(manifestBytes).AsSpan().SequenceEqual(footer.ManifestHash)) + throw Corrupt("The installer manifest does not match its SHA-256."); + + Manifest = PayloadManifest.Parse(manifestBytes); + Manifest.Validate(dataLength); + PayloadOffset = payloadOffset; + _dataOffset = payloadOffset + manifestLength; + } + + /// The installer file the payload was read from. + public string ArchivePath { get; } + + /// Absolute offset where the payload starts; the bytes before it are the setup program. + public long PayloadOffset { get; } + + public PayloadManifest Manifest { get; } + + /// Opens the payload appended to the running executable. + public static PayloadReader OpenCurrentProcess() => + Open(Environment.ProcessPath ?? throw new PayloadException(PayloadError.NotFound, "The setup program path is unknown.")); + + /// Opens and validates the payload of . + public static PayloadReader Open(string path) + { + FileStream stream; + try + { + stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.RandomAccess); + } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + throw new PayloadException(PayloadError.NotFound, $"'{path}' does not exist.", ex); + } + try + { + return new PayloadReader(path, stream); + } + catch (IOException ex) + { + stream.Dispose(); + throw Corrupt("The installer could not be read to the end.", ex); + } + catch + { + stream.Dispose(); + throw; + } + } + + /// + /// Writes every file of under , verifying sizes and hashes. + /// The directory should be a fresh staging folder: on failure it holds partial output the caller discards. + /// + public void Extract(IReadOnlyList files, string directory, IProgress? progress = null, CancellationToken cancellationToken = default) + { + long total = 0; + foreach (var f in files) total += f.Size; + long done = 0; + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + foreach (var file in files) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new PayloadProgress(done, total, file.Path)); + var target = PayloadPath.Resolve(directory, file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + ExtractOne(file, target, buffer, ref done, total, progress, cancellationToken); + } + progress?.Report(new PayloadProgress(done, total, string.Empty)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Writes the setup program alone: the bytes before the payload, with the signature directory cleared because + /// the installer's signature covered the payload as well. Used for the uninstaller copy. + /// + public void WriteStub(string destinationPath) + { + using var output = new FileStream(destinationPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize); + _stream.Position = 0; + CopyExactly(_stream, output, PayloadOffset); + PeImage.ClearCertificateDirectory(output); + output.Flush(flushToDisk: true); + } + + public void Dispose() => _stream.Dispose(); + + private void ExtractOne(PayloadFile file, string target, byte[] buffer, ref long done, long total, IProgress? progress, CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize)) + { + var window = new WindowStream(_stream, _dataOffset + file.Offset, file.Length); + using var input = file.Compression == PayloadCompression.Deflate ? new DeflateStream(window, CompressionMode.Decompress) : (Stream)window; + long written = 0; + var lastReport = 0L; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + int read; + try + { + read = input.Read(buffer, 0, buffer.Length); + } + catch (InvalidDataException ex) + { + throw Corrupt($"'{file.Path}' is damaged in the installer.", ex); + } + if (read == 0) break; + // Never write past the declared size: a crafted entry cannot inflate beyond what the manifest promised. + if (read > file.Size - written) throw Corrupt($"'{file.Path}' is larger than the installer declares."); + output.Write(buffer, 0, read); + hash.AppendData(buffer, 0, read); + written += read; + done += read; + if (progress is not null && written - lastReport >= 4 << 20) + { + lastReport = written; + progress.Report(new PayloadProgress(done, total, file.Path)); + } + } + if (written != file.Size) throw Corrupt($"'{file.Path}' is shorter than the installer declares."); + output.Flush(flushToDisk: true); + } + if (!Convert.ToHexStringLower(hash.GetHashAndReset()).Equals(file.Sha256, StringComparison.Ordinal)) + throw Corrupt($"'{file.Path}' does not match its SHA-256."); + File.SetLastWriteTimeUtc(target, FromUnixSeconds(file.ModifiedUnixSeconds)); + } + + /// True when ends with a TPK1 footer (an installer must not become another one's stub). + internal static bool HasFooter(FileStream stream) + { + try + { + LocateFooter(stream, out _); + return true; + } + catch (PayloadException) + { + return false; + } + finally + { + stream.Position = 0; + } + } + + /// Finds the footer just before the end of the content (the file end, or the start of a signature). + private static long LocateFooter(FileStream stream, out PayloadFooter footer) + { + var end = PeImage.ContentEnd(stream); + if (end < PayloadFormat.FooterLength) throw new PayloadException(PayloadError.NotFound, "The file is too small to hold an installer payload."); + // signtool may zero-pad up to 7 bytes before the certificate table; the packer aligns, but accept either. + var tailLength = (int)Math.Min(end, PayloadFormat.FooterLength + PayloadFormat.Alignment - 1); + var tail = new byte[tailLength]; + stream.Position = end - tailLength; + stream.ReadExactly(tail); + for (var pad = 0; pad < PayloadFormat.Alignment && pad + PayloadFormat.FooterLength <= tailLength; pad++) + { + var start = tailLength - pad - PayloadFormat.FooterLength; + if (tail.AsSpan(tailLength - pad).ContainsAnyExcept((byte)0)) break; + if (PayloadFooter.TryParse(tail.AsSpan(start, PayloadFormat.FooterLength), out footer)) return end - pad - PayloadFormat.FooterLength; + } + throw new PayloadException(PayloadError.NotFound, "The file carries no installer payload."); + } + + private static void CopyExactly(Stream source, Stream destination, long count) + { + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + while (count > 0) + { + var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, count)); + if (read == 0) throw Corrupt("The setup program is truncated."); + destination.Write(buffer, 0, read); + count -= read; + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private static DateTime FromUnixSeconds(long seconds) + { + // File times start in 1601; clamp to a range every file system accepts. + const long min = 315532800; // 1980-01-01 + const long max = 253402300799; // 9999-12-31 + return DateTime.UnixEpoch.AddSeconds(Math.Clamp(seconds, min, max)); + } + + private static PayloadException Corrupt(string message, Exception? inner = null) => new(PayloadError.Corrupt, message, inner); +} diff --git a/src/Titano.Core/Packaging/PayloadWriter.cs b/src/Titano.Core/Packaging/PayloadWriter.cs new file mode 100644 index 00000000..65d7db84 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadWriter.cs @@ -0,0 +1,225 @@ +using System.Buffers; +using System.IO.Compression; +using System.Security.Cryptography; +using Titano.Core.IO; + +namespace Titano.Core.Packaging; + +/// A component to pack: its manifest identity and the folder whose whole tree it installs. +public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder); + +/// Everything the packer needs besides the setup program. +public sealed class PayloadSource +{ + public required string Product { get; init; } + public required string Version { get; init; } + public IReadOnlyList Components { get; init; } = []; + public IReadOnlyList Shortcuts { get; init; } = []; + public IReadOnlyList Associations { get; init; } = []; +} + +/// Sizes of a written installer. +public sealed record PayloadWriteResult(long InstallerBytes, long PayloadBytes, long InstalledBytes, int FileCount); + +/// +/// Builds a self-extracting installer: the setup program followed by a TPK1 payload (). +/// Output is deterministic: files are ordered by component then ordinal path, the manifest has a fixed shape, +/// and identical content is stored once. +/// +public static class PayloadWriter +{ + private const int BufferSize = 1 << 16; + private static readonly string EmptySha256 = Convert.ToHexStringLower(SHA256.HashData([])); + + /// Packs after into (written atomically). + public static PayloadWriteResult Write(string stubPath, PayloadSource source, string outputPath, IProgress? progress = null, CancellationToken cancellationToken = default) + { + var output = Path.GetFullPath(outputPath); + var inputs = Enumerate(source, output); + long total = 0; + foreach (var input in inputs) total += new FileInfo(input.FullPath).Length; + + var spoolPath = output + "." + Guid.NewGuid().ToString("N")[..8] + ".spool"; + using var spool = new FileStream(spoolPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize, FileOptions.DeleteOnClose); + var files = Spool(inputs, spool, total, progress, cancellationToken); + + var components = source.Components.Select(c => new PayloadComponent + { + Id = c.Id, + DisplayName = c.DisplayName, + DefaultSelected = c.DefaultSelected, + EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size), + }).ToList(); + var manifest = new PayloadManifest + { + Product = source.Product, + Version = source.Version, + Components = components, + Files = files, + Shortcuts = [.. source.Shortcuts], + Associations = [.. source.Associations], + }; + manifest.Validate(spool.Length); + var manifestBytes = manifest.ToJsonBytes(); + + var temp = AtomicFile.TempPathFor(output); + long installerLength; + try + { + using (var installer = new FileStream(temp, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize)) + { + var payloadOffset = WriteStub(stubPath, installer); + installer.Write(manifestBytes); + spool.Position = 0; + spool.CopyTo(installer, BufferSize); + installer.Write(new byte[(PayloadFormat.Alignment - installer.Position % PayloadFormat.Alignment) % PayloadFormat.Alignment]); + Span footer = stackalloc byte[PayloadFormat.FooterLength]; + new PayloadFooter(payloadOffset, manifestBytes.Length, spool.Length, SHA256.HashData(manifestBytes)).WriteTo(footer); + installer.Write(footer); + installerLength = installer.Length; + } + AtomicFile.Commit(temp, output); + } + catch + { + if (File.Exists(temp)) File.Delete(temp); + throw; + } + + return new PayloadWriteResult(installerLength, manifestBytes.Length + spool.Length, components.Sum(c => c.EstimatedSize), files.Count); + } + + private sealed record Input(string Component, string Path, string FullPath); + + private static List Enumerate(PayloadSource source, string output) + { + var options = new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0, IgnoreInaccessible = false }; + var inputs = new List(); + foreach (var component in source.Components) + { + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(component.Folder)); + if (!Directory.Exists(root)) throw new DirectoryNotFoundException($"Component folder '{component.Folder}' does not exist."); + if (output.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'.", nameof(output)); + inputs.AddRange(Directory.EnumerateFiles(root, "*", options) + .Select(f => new Input(component.Id, PayloadPath.FromRelative(Path.GetRelativePath(root, f)), f)) + .OrderBy(i => i.Path, StringComparer.Ordinal)); + } + return inputs; + } + + /// Compresses every input into the spool, storing each distinct content once. + private static List Spool(List inputs, FileStream spool, long total, IProgress? progress, CancellationToken cancellationToken) + { + var blobs = new Dictionary(StringComparer.Ordinal); + var files = new List(inputs.Count); + var buffer = ArrayPool.Shared.Rent(BufferSize); + long done = 0; + try + { + foreach (var input in inputs) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new PayloadProgress(done, total, input.Path)); + var start = spool.Position; + long size = 0; + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using (var file = new FileStream(input.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan)) + using (var deflate = new DeflateStream(spool, CompressionLevel.Optimal, leaveOpen: true)) + { + int read; + while ((read = file.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + hash.AppendData(buffer, 0, read); + deflate.Write(buffer, 0, read); + size += read; + } + } + done += size; + var sha = size == 0 ? EmptySha256 : Convert.ToHexStringLower(hash.GetHashAndReset()); + + (long Offset, long Length, PayloadCompression Compression) blob; + if (size == 0) + { + Rewind(spool, start); + blob = (0, 0, PayloadCompression.Stored); + } + else if (blobs.TryGetValue(sha, out var existing)) + { + Rewind(spool, start); + blob = existing; + } + else if (spool.Position - start >= size) + { + // Incompressible content (already compressed media, signed binaries): store it verbatim. + Rewind(spool, start); + using (var file = new FileStream(input.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan)) + CopyExactly(file, spool, size, buffer); + blob = blobs[sha] = (start, size, PayloadCompression.Stored); + } + else + { + blob = blobs[sha] = (start, spool.Position - start, PayloadCompression.Deflate); + } + + files.Add(new PayloadFile + { + Path = input.Path, + Component = input.Component, + Size = size, + Sha256 = sha, + Compression = blob.Compression, + Offset = blob.Offset, + Length = blob.Length, + ModifiedUnixSeconds = new DateTimeOffset(File.GetLastWriteTimeUtc(input.FullPath)).ToUnixTimeSeconds(), + }); + } + progress?.Report(new PayloadProgress(done, Math.Max(total, done), string.Empty)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + return files; + } + + /// Copies the setup program, dropping an Authenticode table (the installer is signed as a whole later). + private static long WriteStub(string stubPath, FileStream installer) + { + using (var stub = new FileStream(stubPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize)) + { + if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program.", nameof(stubPath)); + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + CopyExactly(stub, installer, PeImage.ContentEnd(stub), buffer); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + PeImage.ClearCertificateDirectory(installer); + installer.Seek(0, SeekOrigin.End); + return installer.Position; + } + + private static void Rewind(FileStream spool, long position) + { + spool.SetLength(position); + spool.Position = position; + } + + private static void CopyExactly(Stream source, Stream destination, long count, byte[] buffer) + { + source.Position = 0; + while (count > 0) + { + var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, count)); + if (read == 0) throw new IOException("The file changed while it was being packed."); + destination.Write(buffer, 0, read); + count -= read; + } + } +} diff --git a/src/Titano.Core/Packaging/PeImage.cs b/src/Titano.Core/Packaging/PeImage.cs new file mode 100644 index 00000000..a42f41df --- /dev/null +++ b/src/Titano.Core/Packaging/PeImage.cs @@ -0,0 +1,56 @@ +using System.Reflection.PortableExecutable; + +namespace Titano.Core.Packaging; + +/// +/// The Authenticode certificate table of a PE file. signtool appends it at the end of the file and points the +/// security data directory at it (a file offset, not an RVA). The payload footer therefore ends where the table +/// starts, and a signed stub must lose its table before a payload is appended (the installer is signed as a whole). +/// +internal readonly record struct PeImage(long CertificateOffset, long CertificateSize, long DirectoryEntryOffset) +{ + private const int SecurityDirectoryIndex = 4; + + public bool IsSigned => CertificateSize > 0; + + /// Reads the PE headers at the start of ; null when it is not a PE file. + public static PeImage? TryRead(Stream stream) + { + stream.Position = 0; + try + { + var headers = new PEHeaders(stream, (int)Math.Min(stream.Length, int.MaxValue)); + if (headers.PEHeader is not { } pe || pe.NumberOfRvaAndSizes <= SecurityDirectoryIndex) return new PeImage(0, 0, -1); + // Data directories follow the fixed optional-header fields: 96 bytes in PE32, 112 in PE32+. + var directories = headers.PEHeaderStartOffset + (pe.Magic == PEMagic.PE32Plus ? 112 : 96); + var table = pe.CertificateTableDirectory; + return new PeImage(table.RelativeVirtualAddress, table.Size, directories + SecurityDirectoryIndex * 8); + } + catch (BadImageFormatException) + { + return null; + } + finally + { + stream.Position = 0; + } + } + + /// Where meaningful content ends: the certificate table when one sits inside the file, else the file end. + public static long ContentEnd(Stream stream) + { + var image = TryRead(stream); + return image is { IsSigned: true } pe && pe.CertificateOffset > 0 && pe.CertificateOffset + pe.CertificateSize <= stream.Length + ? pe.CertificateOffset + : stream.Length; + } + + /// Clears the security directory entry so the file no longer claims a signature. + public static void ClearCertificateDirectory(Stream stream) + { + if (TryRead(stream) is not { DirectoryEntryOffset: >= 0 } pe || !pe.IsSigned) return; + stream.Position = pe.DirectoryEntryOffset; + stream.Write(stackalloc byte[8]); + stream.Position = 0; + } +} diff --git a/src/Titano.Core/Packaging/WindowStream.cs b/src/Titano.Core/Packaging/WindowStream.cs new file mode 100644 index 00000000..42a3ff45 --- /dev/null +++ b/src/Titano.Core/Packaging/WindowStream.cs @@ -0,0 +1,42 @@ +namespace Titano.Core.Packaging; + +/// Read-only view of [offset, offset + length) of a seekable stream; reads never cross the window. +internal sealed class WindowStream(Stream inner, long offset, long length) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var remaining = length - _position; + if (remaining <= 0 || buffer.IsEmpty) return 0; + if (buffer.Length > remaining) buffer = buffer[..(int)remaining]; + inner.Position = offset + _position; + var read = inner.Read(buffer); + if (read == 0) throw new PayloadException(PayloadError.Corrupt, "The installer ends inside a file entry."); + _position += read; + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs b/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs new file mode 100644 index 00000000..94109aee --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs @@ -0,0 +1,130 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +/// Synthetic stubs, component trees and hand-made installers for the packaging tests. +internal sealed class PackagingFixture(TestContext context) +{ + public static readonly DateTime FixedTime = new(2026, 3, 14, 15, 9, 26, DateTimeKind.Utc); + + private static readonly byte[] CraftStub = [(byte)'M', (byte)'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + public string Root { get; } = context.CreateTempDirectory("packaging"); + + /// A setup "program": any bytes work, the format does not interpret the stub unless it is a PE. + public string Stub(int length = 4096) + { + var path = Path.Combine(Root, "Titano.Setup.exe"); + var bytes = new byte[length]; + new Random(7).NextBytes(bytes); + "MZ"u8.CopyTo(bytes); + File.WriteAllBytes(path, bytes); + return path; + } + + /// Creates (payload path → content) under a new folder with a fixed mtime. + public string Folder(string name, params (string Path, byte[] Content)[] files) + { + var dir = Path.Combine(Root, name); + Directory.CreateDirectory(dir); + foreach (var (relative, content) in files) + { + var path = Path.Combine(dir, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, content); + File.SetLastWriteTimeUtc(path, FixedTime); + } + return dir; + } + + public static byte[] Text(string s, int repeat = 1) => Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat(s, repeat))); + + public static byte[] Random(int length, int seed) + { + var bytes = new byte[length]; + new Random(seed).NextBytes(bytes); + return bytes; + } + + public static PayloadSource Source(params PayloadComponentSource[] components) => new() + { + Product = "Titano", + Version = "1.2.3", + Components = components, + }; + + public string Pack(string stub, PayloadSource source, string name = "Titano-Setup.exe") + { + var output = Path.Combine(Root, "out", name); + Directory.CreateDirectory(Path.GetDirectoryName(output)!); + PayloadWriter.Write(stub, source, output); + return output; + } + + /// + /// A minimal PE32+ header (no sections) followed by filler, with an optional certificate table at the end the + /// way signtool lays it out: 8-byte aligned, pointed at by the security data directory. + /// + public static byte[] PortableExecutable(int fillerLength, byte[]? certificate = null) + { + const int peOffset = 0x80; + const int optionalHeaderSize = 240; + var headerLength = peOffset + 4 + 20 + optionalHeaderSize; + var image = new byte[headerLength + fillerLength]; + "MZ"u8.CopyTo(image); + BinaryPrimitives.WriteInt32LittleEndian(image.AsSpan(0x3C), peOffset); + "PE\0\0"u8.CopyTo(image.AsSpan(peOffset)); + var coff = image.AsSpan(peOffset + 4); + BinaryPrimitives.WriteUInt16LittleEndian(coff, 0x8664); + BinaryPrimitives.WriteUInt16LittleEndian(coff[16..], optionalHeaderSize); + BinaryPrimitives.WriteUInt16LittleEndian(coff[18..], 0x0022); + var optional = image.AsSpan(peOffset + 24); + BinaryPrimitives.WriteUInt16LittleEndian(optional, 0x20B); + BinaryPrimitives.WriteUInt32LittleEndian(optional[32..], 0x1000); // SectionAlignment + BinaryPrimitives.WriteUInt32LittleEndian(optional[36..], 0x200); // FileAlignment + BinaryPrimitives.WriteUInt32LittleEndian(optional[108..], 16); // NumberOfRvaAndSizes + new Random(3).NextBytes(image.AsSpan(headerLength)); + return certificate is null ? image : Sign(image, certificate); + } + + /// Appends a certificate table and points the security directory at it, as signtool does. + public static byte[] Sign(byte[] file, byte[] certificate) + { + var aligned = (file.Length + 7) / 8 * 8; + var signed = new byte[aligned + certificate.Length]; + file.CopyTo(signed, 0); + certificate.CopyTo(signed, aligned); + var entry = SecurityDirectoryOffset(signed); + BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry), (uint)aligned); + BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry + 4), (uint)certificate.Length); + return signed; + } + + /// File offset of the security data directory entry of an image built by . + public static int SecurityDirectoryOffset(byte[] image) => + BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)) + 4 + 20 + 112 + 4 * 8; + + /// Assembles an installer by hand from a manifest and data region, bypassing the writer's checks. + public string Craft(PayloadManifest manifest, byte[] data, string name = "crafted.exe") + { + var stub = CraftStub; + var json = manifest.ToJsonBytes(); + using var ms = new MemoryStream(); + ms.Write(stub); + ms.Write(json); + ms.Write(data); + ms.Write(new byte[(8 - ms.Length % 8) % 8]); + var footer = new byte[PayloadFormat.FooterLength]; + new PayloadFooter(stub.Length, json.Length, data.Length, SHA256.HashData(json)).WriteTo(footer); + ms.Write(footer); + var path = Path.Combine(Root, name); + File.WriteAllBytes(path, ms.ToArray()); + return path; + } + + public static string Sha256(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content)); +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs new file mode 100644 index 00000000..a9ba9231 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs @@ -0,0 +1,213 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadIntegrityTests(TestContext context) +{ + private readonly PackagingFixture _fx = new(context); + + private (string Installer, long PayloadOffset, byte[] Bytes) PackSample() + { + var app = _fx.Folder("app", + ("Titano.exe", PackagingFixture.Text("program ", 3000)), + ("noise.bin", PackagingFixture.Random(40_000, 5)), + ("docs/readme.txt", PackagingFixture.Text("read me ", 200))); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + using var reader = PayloadReader.Open(installer); + return (installer, reader.PayloadOffset, File.ReadAllBytes(installer)); + } + + [Test] + public void TamperedManifestIsRejected() + { + var (installer, offset, bytes) = PackSample(); + // Flip the first letter of "Titano" in "product":"Titano". + var at = Array.IndexOf(bytes, (byte)'T', (int)offset); + bytes[at] = (byte)'X'; + File.WriteAllBytes(installer, bytes); + var ex = Assert.Throws(() => PayloadReader.Open(installer)); + Assert.Equal(PayloadError.Corrupt, ex.Error); + Assert.Contains("SHA-256", ex.Message); + } + + [Test] + public void TamperedFooterHashIsRejected() + { + var (installer, _, bytes) = PackSample(); + bytes[^1] ^= 0x5A; + File.WriteAllBytes(installer, bytes); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void FooterPointingOutsideTheFileIsRejected() + { + var (installer, _, bytes) = PackSample(); + BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - PayloadFormat.FooterLength + 16), long.MaxValue - 3); + File.WriteAllBytes(installer, bytes); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void CorruptStoredEntryFailsItsHash() + { + var (installer, _, bytes) = PackSample(); + PayloadFile noise; + long dataOffset; + using (var reader = PayloadReader.Open(installer)) + { + noise = reader.Manifest.Files.Single(f => f.Path == "noise.bin"); + dataOffset = DataOffset(bytes, reader.PayloadOffset); + } + Assert.Equal(PayloadCompression.Stored, noise.Compression); + bytes[dataOffset + noise.Offset + 1234] ^= 0xFF; + File.WriteAllBytes(installer, bytes); + + using var tampered = PayloadReader.Open(installer); + var ex = Assert.Throws(() => tampered.Extract([noise], context.CreateTempDirectory())); + Assert.Equal(PayloadError.Corrupt, ex.Error); + Assert.Contains("noise.bin", ex.Message); + } + + [Test] + public void EveryCorruptPayloadByteIsDetectedOrHarmless() + { + var (installer, offset, original) = PackSample(); + var expected = new Dictionary + { + ["Titano.exe"] = PackagingFixture.Text("program ", 3000), + ["noise.bin"] = PackagingFixture.Random(40_000, 5), + ["docs/readme.txt"] = PackagingFixture.Text("read me ", 200), + }; + var step = Math.Max(1, (int)((original.Length - offset) / 150)); + for (var at = offset; at < original.Length; at += step) + { + var bytes = (byte[])original.Clone(); + bytes[at] ^= 0xFF; + File.WriteAllBytes(installer, bytes); + var target = context.CreateTempDirectory("fuzz"); + try + { + using var reader = PayloadReader.Open(installer); + reader.Extract(reader.Manifest.Files, target); + foreach (var (path, content) in expected) + Assert.BytesEqual(content, File.ReadAllBytes(Path.Combine(target, path.Replace('/', Path.DirectorySeparatorChar))), $"flip at {at} produced wrong {path}"); + } + catch (PayloadException) + { + // Detected: the expected outcome for almost every byte. + } + } + } + + [Test] + public void TruncatedInstallersFailCleanly() + { + var (installer, _, original) = PackSample(); + var lengths = new List { 0, 1, 7, PayloadFormat.FooterLength - 1, PayloadFormat.FooterLength, original.Length - 1, original.Length - PayloadFormat.FooterLength }; + for (var n = 97; n < original.Length; n += original.Length / 60) lengths.Add(n); + foreach (var length in lengths) + { + File.WriteAllBytes(installer, original.AsSpan(0, length).ToArray()); + var ex = Assert.Throws(() => PayloadReader.Open(installer), $"truncated to {length}"); + Assert.True(ex.Error is PayloadError.NotFound or PayloadError.Corrupt, $"truncated to {length}: {ex.Error}"); + } + } + + [Test] + public void MissingFileIsReportedAsNotFound() => + Assert.Equal(PayloadError.NotFound, Assert.Throws(() => PayloadReader.Open(Path.Combine(_fx.Root, "nope.exe"))).Error); + + [Theory] + [Case("../evil.txt")] + [Case("a/../../evil.txt")] + [Case("/etc/passwd")] + [Case("C:/Windows/evil.dll")] + [Case("sub\\evil.txt")] + [Case("file.txt:stream")] + public void ManifestPathEscapingTheTargetIsRejected(string path) + { + var content = PackagingFixture.Text("x"); + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true, EstimatedSize = 1 }], + Files = [new PayloadFile { Path = path, Component = "Titano", Size = 1, Sha256 = PackagingFixture.Sha256(content), Compression = PayloadCompression.Stored, Offset = 0, Length = 1 }], + }; + var installer = _fx.Craft(manifest, content); + Assert.Equal(PayloadError.UnsafePath, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void DeclaredSizeBeyondTheDeflateLimitIsRejectedUpFront() + { + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }], + Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1L << 40, Sha256 = new string('0', 64), Compression = PayloadCompression.Deflate, Offset = 0, Length = 16 }], + }; + var installer = _fx.Craft(manifest, new byte[16]); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void EntryInflatingPastItsDeclaredSizeStopsAtTheLimit() + { + var zeros = new byte[4 << 20]; + using var compressed = new MemoryStream(); + using (var deflate = new DeflateStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) deflate.Write(zeros); + var data = compressed.ToArray(); + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }], + Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1000, Sha256 = PackagingFixture.Sha256(new byte[1000]), Compression = PayloadCompression.Deflate, Offset = 0, Length = data.Length }], + }; + using var reader = PayloadReader.Open(_fx.Craft(manifest, data)); + var target = context.CreateTempDirectory(); + var ex = Assert.Throws(() => reader.Extract(reader.Manifest.Files, target)); + Assert.Contains("larger", ex.Message); + Assert.True(new FileInfo(Path.Combine(target, "bomb.bin")).Length <= 1000); + } + + [Test] + public void SignedStubLosesItsSignatureAndSignedInstallerStillOpens() + { + var stubBytes = PackagingFixture.PortableExecutable(5000, certificate: PackagingFixture.Random(1500, 9)); + var stub = Path.Combine(_fx.Root, "signed-stub.exe"); + File.WriteAllBytes(stub, stubBytes); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 50))); + var installer = _fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + + var packed = File.ReadAllBytes(installer); + var entry = PackagingFixture.SecurityDirectoryOffset(packed); + Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(packed.AsSpan(entry)), "stub signature directory cleared"); + + // Sign the whole installer the way signtool does, then read it back. + File.WriteAllBytes(installer, PackagingFixture.Sign(packed, PackagingFixture.Random(2048, 4))); + using var reader = PayloadReader.Open(installer); + Assert.Equal((long)(stubBytes.Length - 1500), reader.PayloadOffset); + var target = context.CreateTempDirectory(); + reader.Extract(reader.Manifest.Files, target); + Assert.BytesEqual(PackagingFixture.Text("app", 50), File.ReadAllBytes(Path.Combine(target, "Titano.exe"))); + + var copy = Path.Combine(target, "Uninstall Titano.exe"); + reader.WriteStub(copy); + var copied = File.ReadAllBytes(copy); + Assert.Equal(reader.PayloadOffset, (long)copied.Length); + Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(copied.AsSpan(entry)), "uninstaller signature directory cleared"); + } + + private static long DataOffset(byte[] installer, long payloadOffset) + { + var footer = installer.AsSpan(installer.Length - PayloadFormat.FooterLength); + return payloadOffset + BinaryPrimitives.ReadInt64LittleEndian(footer[16..]); + } +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs new file mode 100644 index 00000000..f6c58fd0 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs @@ -0,0 +1,60 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadPathTests(TestContext context) +{ + [Theory] + [Case("Titano.exe")] + [Case("lib/deep/file.dll")] + [Case("città/日本語 ✓.txt")] + [Case(".hidden")] + [Case("CONFIG.SYS")] + [Case("console.log")] + public void AcceptsCanonicalRelativePaths(string path) => Assert.True(PayloadPath.IsValid(path), path); + + [Theory] + [Case("")] + [Case("..")] + [Case("../x")] + [Case("a/../b")] + [Case("a/./b")] + [Case("a//b")] + [Case("/rooted")] + [Case("trailing/")] + [Case("C:/x")] + [Case("a\\b")] + [Case("a:stream")] + [Case("con")] + [Case("aux.txt")] + [Case("COM1")] + [Case("lpt9.log")] + [Case("dot.")] + [Case("space ")] + [Case("tab\tname")] + [Case("star*")] + public void RejectsUnsafePaths(string path) => Assert.False(PayloadPath.IsValid(path), path); + + [Test] + public void RejectsOverlongPaths() + { + Assert.False(PayloadPath.IsValid(new string('a', 256))); + Assert.False(PayloadPath.IsValid(string.Join('/', Enumerable.Repeat("abcdefghij", 100)))); + } + + [Test] + public void ResolveStaysInsideTheRoot() + { + var root = context.CreateTempDirectory(); + Assert.Equal(Path.Combine(root, "a", "b.txt"), PayloadPath.Resolve(root, "a/b.txt")); + Assert.Equal(PayloadError.UnsafePath, Assert.Throws(() => PayloadPath.Resolve(root, "../b.txt")).Error); + } + + [Test] + public void ConvertsNativeSeparators() + { + Assert.Equal("a/b/c.txt", PayloadPath.FromRelative("a\\b\\c.txt")); + Assert.Throws(() => PayloadPath.FromRelative("..\\c.txt")); + } +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs new file mode 100644 index 00000000..55d2f575 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs @@ -0,0 +1,172 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadRoundTripTests(TestContext context) +{ + private readonly PackagingFixture _fx = new(context); + + [Test] + public void ExtractsNestedEmptyUnicodeAndIncompressibleFilesExactly() + { + var files = new (string Path, byte[] Content)[] + { + ("Titano.exe", PackagingFixture.Text("MZ program body ", 4000)), + ("lib/deep/er/still/config.json", PackagingFixture.Text("{\"a\":1}", 50)), + ("empty.txt", []), + ("città/日本語 ✓.txt", PackagingFixture.Text("ciao 世界 ", 300)), + ("media/noise.bin", PackagingFixture.Random(3 << 20, seed: 11)), + }; + var app = _fx.Folder("app", files); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + + using var reader = PayloadReader.Open(installer); + var manifest = reader.Manifest; + Assert.Equal("Titano", manifest.Product); + Assert.Equal("1.2.3", manifest.Version); + Assert.Count(files.Length, manifest.Files); + Assert.Equal(files.Sum(f => (long)f.Content.Length), manifest.Components[0].EstimatedSize); + Assert.Equal(PayloadCompression.Stored, manifest.Files.Single(f => f.Path == "media/noise.bin").Compression); + Assert.Equal(PayloadCompression.Deflate, manifest.Files.Single(f => f.Path == "Titano.exe").Compression); + var empty = manifest.Files.Single(f => f.Path == "empty.txt"); + Assert.Equal(0L, empty.Length); + + var target = context.CreateTempDirectory("extract"); + reader.Extract(manifest.FilesFor(["Titano"]), target); + foreach (var (relative, content) in files) + { + var path = Path.Combine(target, relative.Replace('/', Path.DirectorySeparatorChar)); + Assert.BytesEqual(content, File.ReadAllBytes(path), relative); + Assert.Equal(PackagingFixture.FixedTime, File.GetLastWriteTimeUtc(path), relative); + } + } + + [Test] + public void ReportsProgressUpToTheTotalSize() + { + var app = _fx.Folder("app", ("a.bin", PackagingFixture.Random(9 << 20, 1)), ("b.txt", PackagingFixture.Text("b", 10))); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + using var reader = PayloadReader.Open(installer); + var reports = new List(); + reader.Extract(reader.Manifest.Files, context.CreateTempDirectory(), new SyncProgress(reports.Add)); + Assert.True(reports.Count >= 3); + Assert.Monotonic(reports.Select(r => (double)r.Done)); + Assert.Equal(reports[^1].Total, reports[^1].Done); + Assert.Equal((9L << 20) + 10, reports[^1].Total); + } + + [Test] + public void IdenticalInputsProduceIdenticalInstallers() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 999)), ("sub/z.txt", PackagingFixture.Text("z")), ("sub/a.txt", PackagingFixture.Text("a"))); + var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("uploader", 500))); + var stub = _fx.Stub(); + var source = PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Titano Uploader", false, up)); + var first = _fx.Pack(stub, source, "first.exe"); + var second = _fx.Pack(stub, source, "second.exe"); + Assert.BytesEqual(File.ReadAllBytes(first), File.ReadAllBytes(second)); + Assert.Equal(0L, new FileInfo(first).Length % PayloadFormat.Alignment); + } + + [Test] + public void SharedFilesAreStoredOnceAndInstalledOnce() + { + var shared = PackagingFixture.Text("shared runtime ", 2000); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 100)), ("runtime.dll", shared)); + var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("up", 100)), ("runtime.dll", shared)); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Uploader", true, up))); + + using var reader = PayloadReader.Open(installer); + var copies = reader.Manifest.Files.Where(f => f.Path == "runtime.dll").ToList(); + Assert.Count(2, copies); + Assert.Equal(copies[0].Offset, copies[1].Offset); + var both = reader.Manifest.FilesFor(["Titano", "Uploader"]); + Assert.Count(3, both); + Assert.Count(2, reader.Manifest.FilesFor(["uploader"])); + Assert.Throws(() => reader.Manifest.FilesFor(["Server"])); + } + + [Test] + public void DifferentContentAtTheSamePathAcrossComponentsIsRejected() + { + var app = _fx.Folder("app", ("same.dll", PackagingFixture.Text("one"))); + var up = _fx.Folder("uploader", ("same.dll", PackagingFixture.Text("two"))); + var ex = Assert.Throws(() => _fx.Pack(_fx.Stub(), PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Uploader", true, up)))); + Assert.Equal(PayloadError.Corrupt, ex.Error); + } + + [Test] + public void ShortcutsAndAssociationsSurviveTheRoundTrip() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = new PayloadSource + { + Product = "Titano", + Version = "2.0.0-beta.1", + Components = [new PayloadComponentSource("Titano", "Titano", true, app)], + Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Titano", Target = "Titano.exe", StartMenu = true, Desktop = true }], + Associations = [new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }], + }; + using var reader = PayloadReader.Open(_fx.Pack(_fx.Stub(), source)); + var shortcut = reader.Manifest.Shortcuts.Single(); + Assert.True(shortcut.Desktop && shortcut.StartMenu); + Assert.Equal("Titano.exe", shortcut.Target); + Assert.Equal("Titano.Project", reader.Manifest.Associations.Single().ProgId); + } + + [Test] + public void ShortcutToAFileOutsideItsComponentIsRejected() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = new PayloadSource + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponentSource("Titano", "Titano", true, app)], + Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Missing", Target = "Missing.exe", StartMenu = true }], + }; + Assert.Throws(() => _fx.Pack(_fx.Stub(), source)); + } + + [Test] + public void StubCopyEndsAtThePayload() + { + var stub = _fx.Stub(10_000); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 10))); + using var reader = PayloadReader.Open(_fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)))); + Assert.Equal(10_000L, reader.PayloadOffset); + var copy = Path.Combine(context.CreateTempDirectory(), "Uninstall Titano.exe"); + reader.WriteStub(copy); + Assert.BytesEqual(File.ReadAllBytes(stub), File.ReadAllBytes(copy)); + Assert.Equal(PayloadError.NotFound, Assert.Throws(() => PayloadReader.Open(copy)).Error); + } + + [Test] + public void OutputInsideAComponentFolderIsRefused() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + Assert.Throws(() => PayloadWriter.Write(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)), Path.Combine(app, "setup.exe"))); + } + + [Test] + public void AnInstallerCannotBeUsedAsStub() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)); + var installer = _fx.Pack(_fx.Stub(), source); + Assert.Throws(() => _fx.Pack(installer, source, "nested.exe")); + } + + /// Synchronous (Progress<T> posts to the thread pool). + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(T value) => report(value); + } +} From fc8df1f411021e1b67ddb17c0d4b3588fa64dc91 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:37 +0000 Subject: [PATCH 056/188] feat(packaging): add staged install transaction and logged file removal Extracted files land in a staging folder inside the target and are moved into place with backups of replaced files; a failed move rolls everything back. Removal deletes only logged payload paths and prunes folders left empty. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Packaging/InstallTransaction.cs | 175 ++++++++++++++++++ .../Packaging/InstallTransactionTests.cs | 103 +++++++++++ 2 files changed, 278 insertions(+) create mode 100644 src/Titano.Core/Packaging/InstallTransaction.cs create mode 100644 tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs diff --git a/src/Titano.Core/Packaging/InstallTransaction.cs b/src/Titano.Core/Packaging/InstallTransaction.cs new file mode 100644 index 00000000..fc606eaf --- /dev/null +++ b/src/Titano.Core/Packaging/InstallTransaction.cs @@ -0,0 +1,175 @@ +using Titano.Core.Diagnostics; + +namespace Titano.Core.Packaging; + +/// +/// Installs a verified file set without leaving a half-updated folder. Files are first written into a staging +/// folder inside the target (same volume, so moves are renames); then moves them into place, +/// parking every replaced file in a backup folder. If any move fails, completed moves are undone in reverse order +/// and the previous install is restored. Staging and backup folders are removed on dispose. +/// +public sealed class InstallTransaction : IDisposable +{ + private const string StagingPrefix = ".setup-staging-"; + private const string BackupPrefix = ".setup-backup-"; + private readonly string _backup; + + public InstallTransaction(string targetDirectory) + { + TargetDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(targetDirectory)); + Directory.CreateDirectory(TargetDirectory); + RemoveStaleFolders(TargetDirectory); + var id = Guid.NewGuid().ToString("N")[..8]; + StagingDirectory = Path.Combine(TargetDirectory, StagingPrefix + id); + _backup = Path.Combine(TargetDirectory, BackupPrefix + id); + Directory.CreateDirectory(StagingDirectory); + } + + public string TargetDirectory { get; } + + /// Where the new files are written before . + public string StagingDirectory { get; } + + /// Moves the staged files (payload-relative paths) into the target, all or nothing. + public void Commit(IReadOnlyCollection relativePaths) + { + var completed = new List<(string Staged, string Target, string? Backup)>(relativePaths.Count); + try + { + foreach (var relative in relativePaths) + { + var staged = PayloadPath.Resolve(StagingDirectory, relative); + var target = PayloadPath.Resolve(TargetDirectory, relative); + if (!File.Exists(staged)) throw new FileNotFoundException($"Staged file '{relative}' is missing.", staged); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + string? backup = null; + if (File.Exists(target)) + { + backup = PayloadPath.Resolve(_backup, relative); + Directory.CreateDirectory(Path.GetDirectoryName(backup)!); + File.Move(target, backup); + } + try + { + File.Move(staged, target); + } + catch + { + if (backup is not null) File.Move(backup, target); + throw; + } + completed.Add((staged, target, backup)); + } + } + catch + { + Rollback(completed); + throw; + } + } + + public void Dispose() + { + TryDeleteTree(StagingDirectory); + TryDeleteTree(_backup); + } + + private static void Rollback(List<(string Staged, string Target, string? Backup)> completed) + { + for (var i = completed.Count - 1; i >= 0; i--) + { + var (staged, target, backup) = completed[i]; + try + { + File.Move(target, staged, overwrite: true); + if (backup is not null) File.Move(backup, target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Error("setup", $"Rollback could not restore '{target}'", ex); + } + } + } + + /// Removes staging/backup folders left by an interrupted earlier run (they are always ours by name). + private static void RemoveStaleFolders(string target) + { + foreach (var dir in Directory.EnumerateDirectories(target, ".setup-*")) + { + var name = Path.GetFileName(dir); + if (name.StartsWith(StagingPrefix, StringComparison.Ordinal) || name.StartsWith(BackupPrefix, StringComparison.Ordinal)) + TryDeleteTree(dir); + } + } + + private static void TryDeleteTree(string path) + { + try + { + if (Directory.Exists(path)) Directory.Delete(path, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + } + } +} + +/// Removes installed files by their logged payload paths, never anything else under the folder. +public static class InstalledFiles +{ + /// + /// Deletes each listed file under and prunes folders the deletion left empty (the root + /// itself only when ). Missing files count as removed; returns the paths that + /// could not be deleted, for example because a program still holds them open. + /// + public static IReadOnlyList Remove(string root, IEnumerable relativePaths, bool removeEmptyRoot = false) + { + var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var failed = new List(); + var folders = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var relative in relativePaths) + { + var path = PayloadPath.Resolve(fullRoot, relative); + try + { + if (File.Exists(path)) + { + File.SetAttributes(path, FileAttributes.Normal); + File.Delete(path); + } + folders.Add(Path.GetDirectoryName(path)!); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + failed.Add(relative); + } + } + + // Deepest folders first, so a parent is examined after its children were pruned. + foreach (var folder in folders.OrderByDescending(f => f.Length)) + { + for (var dir = folder; dir.Length > fullRoot.Length; dir = Path.GetDirectoryName(dir)!) + { + if (!TryRemoveEmpty(dir)) break; + } + } + if (removeEmptyRoot) TryRemoveEmpty(fullRoot); + return failed; + } + + private static bool TryRemoveEmpty(string dir) + { + try + { + if (!Directory.Exists(dir) || Directory.EnumerateFileSystemEntries(dir).Any()) return false; + Directory.Delete(dir); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } +} diff --git a/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs new file mode 100644 index 00000000..c79e980b --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs @@ -0,0 +1,103 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class InstallTransactionTests(TestContext context) +{ + [Test] + public void CommitReplacesFilesAndCleansUp() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + File.WriteAllText(Path.Combine(target, "user-notes.txt"), "keep"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "lib/new.dll", "dll"); + tx.Commit(["Titano.exe", "lib/new.dll"]); + } + + Assert.Equal("new", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.Equal("dll", File.ReadAllText(Path.Combine(target, "lib", "new.dll"))); + Assert.Equal("keep", File.ReadAllText(Path.Combine(target, "user-notes.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void FailedCommitRestoresThePreviousInstall() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + // A folder where the new version has a file makes the second move fail. + Directory.CreateDirectory(Path.Combine(target, "blocked")); + File.WriteAllText(Path.Combine(target, "blocked", "inside.txt"), "x"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "added.dll", "added"); + Write(tx.StagingDirectory, "blocked", "file"); + // Linux reports IOException, Windows UnauthorizedAccessException for a file moved onto a folder. + var ex = Assert.Throws(() => tx.Commit(["Titano.exe", "added.dll", "blocked"])); + Assert.True(ex is IOException or UnauthorizedAccessException, ex.GetType().Name); + } + + Assert.Equal("old", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.FileMissing(Path.Combine(target, "added.dll")); + Assert.Equal("x", File.ReadAllText(Path.Combine(target, "blocked", "inside.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void StaleStagingFoldersFromAnInterruptedRunAreRemoved() + { + var target = context.CreateTempDirectory(); + Directory.CreateDirectory(Path.Combine(target, ".setup-staging-deadbeef", "sub")); + Directory.CreateDirectory(Path.Combine(target, ".setup-other")); + using (new InstallTransaction(target)) + { + } + Assert.False(Directory.Exists(Path.Combine(target, ".setup-staging-deadbeef"))); + Assert.True(Directory.Exists(Path.Combine(target, ".setup-other"))); + } + + [Test] + public void RemoveDeletesOnlyLoggedFilesAndPrunesEmptyFolders() + { + var root = context.CreateTempDirectory(); + Write(root, "Titano.exe", "a"); + Write(root, "lib/x/y.dll", "b"); + Write(root, "lib/keep.txt", "user"); + + var failed = InstalledFiles.Remove(root, ["Titano.exe", "lib/x/y.dll", "already-gone.dll"], removeEmptyRoot: true); + + Assert.Empty(failed); + Assert.FileMissing(Path.Combine(root, "Titano.exe")); + Assert.False(Directory.Exists(Path.Combine(root, "lib", "x"))); + Assert.Equal("user", File.ReadAllText(Path.Combine(root, "lib", "keep.txt"))); + Assert.True(Directory.Exists(root), "root keeps unlisted files"); + + InstalledFiles.Remove(root, ["lib/keep.txt"], removeEmptyRoot: true); + Assert.False(Directory.Exists(root)); + } + + [Test] + public void RemoveRefusesPathsOutsideTheRoot() + { + var parent = context.CreateTempDirectory(); + var root = Path.Combine(parent, "install"); + Directory.CreateDirectory(root); + Write(parent, "outside.txt", "precious"); + Assert.Throws(() => InstalledFiles.Remove(root, ["../outside.txt"])); + Assert.FileExists(Path.Combine(parent, "outside.txt")); + } + + private static void Write(string root, string relative, string content) + { + var path = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } +} From c591aced94dbdfc1eaebbb5bab1f80e2fb555ade Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:58:29 +0000 Subject: [PATCH 057/188] feat(tools): add pack-installer command Appends a TPK1 payload to Titano.Setup.exe from repeatable --component Id=folder options, as release.yml invokes it. Known components (Titano, Uploader, Server) get display names, default selection, Start menu/desktop shortcuts and the .titano file type; prints file count and sizes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Packaging/PayloadWriter.cs | 4 +- .../Commands/PackInstallerCommand.cs | 109 ++++++++++++++++++ src/Titano.Tools/Program.cs | 1 + 3 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 src/Titano.Tools/Commands/PackInstallerCommand.cs diff --git a/src/Titano.Core/Packaging/PayloadWriter.cs b/src/Titano.Core/Packaging/PayloadWriter.cs index 65d7db84..09b3d5ac 100644 --- a/src/Titano.Core/Packaging/PayloadWriter.cs +++ b/src/Titano.Core/Packaging/PayloadWriter.cs @@ -100,7 +100,7 @@ public static class PayloadWriter var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(component.Folder)); if (!Directory.Exists(root)) throw new DirectoryNotFoundException($"Component folder '{component.Folder}' does not exist."); if (output.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'.", nameof(output)); + throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'."); inputs.AddRange(Directory.EnumerateFiles(root, "*", options) .Select(f => new Input(component.Id, PayloadPath.FromRelative(Path.GetRelativePath(root, f)), f)) .OrderBy(i => i.Path, StringComparer.Ordinal)); @@ -189,7 +189,7 @@ public static class PayloadWriter { using (var stub = new FileStream(stubPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize)) { - if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program.", nameof(stubPath)); + if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program."); var buffer = ArrayPool.Shared.Rent(BufferSize); try { diff --git a/src/Titano.Tools/Commands/PackInstallerCommand.cs b/src/Titano.Tools/Commands/PackInstallerCommand.cs new file mode 100644 index 00000000..24720315 --- /dev/null +++ b/src/Titano.Tools/Commands/PackInstallerCommand.cs @@ -0,0 +1,109 @@ +using System.Globalization; +using Titano.Core.Packaging; + +namespace Titano.Tools.Commands; + +/// +/// pack-installer --setup Titano.Setup.exe --product Titano --version 1.2.3 --component Id=folder … --out file: +/// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default +/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. +/// +internal sealed class PackInstallerCommand : ICommand +{ + private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association); + + private static readonly Dictionary Known = new(StringComparer.OrdinalIgnoreCase) + { + ["Titano"] = new("Titano", true, "Titano.exe", Desktop: true, + new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }), + ["Uploader"] = new("Titano Uploader", true, "Titano.Uploader.exe", Desktop: true, null), + ["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null), + }; + + public string Name => "pack-installer"; + public string Summary => "--setup --product --version --component Id=dir … --out "; + + public Task RunAsync(string[] args) + { + var options = Parse(args); + var setup = Required(options, "setup"); + var output = Required(options, "out"); + if (!File.Exists(setup)) throw new ToolException($"Setup program '{setup}' not found."); + if (!options.TryGetValue("component", out var specs)) throw new ToolException("At least one --component Id=folder is required."); + + var components = new List(); + var shortcuts = new List(); + var associations = new List(); + foreach (var spec in specs) + { + var eq = spec.IndexOf('=', StringComparison.Ordinal); + if (eq <= 0 || eq == spec.Length - 1) throw new ToolException($"--component expects Id=folder, got '{spec}'."); + var id = spec[..eq]; + var folder = spec[(eq + 1)..]; + if (!PayloadManifest.IdentifierRegex().IsMatch(id)) throw new ToolException($"Component id '{id}' must be letters and digits."); + if (components.Any(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase))) throw new ToolException($"Component '{id}' given twice."); + if (!Directory.Exists(folder)) throw new ToolException($"Component folder '{folder}' not found."); + + if (!Known.TryGetValue(id, out var known)) + { + components.Add(new PayloadComponentSource(id, id, true, folder)); + continue; + } + components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder)); + if (!File.Exists(Path.Combine(folder, known.Program))) + { + Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered."); + continue; + } + shortcuts.Add(new PayloadShortcut { Component = id, Name = known.DisplayName, Target = known.Program, StartMenu = true, Desktop = known.Desktop }); + if (known.Association is { } association) associations.Add(association); + } + + var source = new PayloadSource + { + Product = Required(options, "product"), + Version = Required(options, "version"), + Components = components, + Shortcuts = shortcuts, + Associations = associations, + }; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); + var result = PayloadWriter.Write(setup, source, output); + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{output}: {result.FileCount} files in {components.Count} component(s), {Megabytes(result.InstallerBytes)} ({result.InstallerBytes:N0} bytes), installs {Megabytes(result.InstalledBytes)}")); + return Task.FromResult(0); + } + catch (Exception ex) when (ex is PayloadException or ArgumentException or IOException) + { + throw new ToolException("pack-installer: " + ex.Message); + } + } + + /// --key value pairs; every key may repeat (only --component is meant to). + private static Dictionary> Parse(string[] args) + { + var allowed = new HashSet(StringComparer.OrdinalIgnoreCase) { "setup", "product", "version", "component", "out" }; + var options = new Dictionary>(StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < args.Length; i++) + { + if (!args[i].StartsWith("--", StringComparison.Ordinal) || !allowed.Contains(args[i][2..])) + throw new ToolException($"Unexpected argument '{args[i]}'."); + if (i + 1 >= args.Length) throw new ToolException($"{args[i]} needs a value."); + var key = args[i][2..]; + if (!options.TryGetValue(key, out var values)) options[key] = values = []; + values.Add(args[++i]); + } + return options; + } + + private static string Required(Dictionary> options, string key) + { + if (!options.TryGetValue(key, out var values) || string.IsNullOrWhiteSpace(values[^1])) throw new ToolException($"--{key} is required."); + if (values.Count > 1) throw new ToolException($"--{key} given more than once."); + return values[0]; + } + + private static string Megabytes(long bytes) => (bytes / 1_000_000d).ToString("0.0", CultureInfo.InvariantCulture) + " MB"; +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index d5575d16..78f6e44d 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -8,6 +8,7 @@ var commands = new ICommand[] new XamlLintCommand(), new PackageGuardCommand(), new ChangelogCommand(), + new PackInstallerCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") From db672af3cafbc3044c5dd3cee72b9e67d824df4b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:59:21 +0000 Subject: [PATCH 058/188] docs: record analysis and motion decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/ARCHITECTURE.md | 2 +- docs/DECISIONS.md | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 351f5587..8a51336d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -30,7 +30,7 @@ Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). | `Video` | `Mp4Muxer`, box writer, Annex-B/OBU parsing, MP4 inspector, AVI-MJPEG writer, managed encoder provider, encoder contracts | | `Analysis` | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light/deep analysis | | `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabilisation, virtual camera, interpolation, stacking | -| `Math` | Splines (Fritsch–Carlson, Catmull-Rom, Bézier), robust local regression, statistics, solar position | +| `Math` (namespace `Titano.Core.Mathematics`, so it never shadows `System.Math`) | Splines (Fritsch–Carlson, Catmull-Rom, Bézier), robust local regression, statistics, solar position, 3×3 colour matrices | | `Render` | Render plan, pipeline, export presets | | `Advisor` | Recommendation rules with localisable reasons, sequence presets | | `Archive` | Archive layout, sidecars (`sequence.json`, `project.json`), scanner, rebuild, verify, duplicates, orphans, adopt | diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 236d3f8e..c43c94b9 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -30,3 +30,17 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Volume watcher uses a hidden top-level tool window plus 3 s polling. | Message-only window | Message-only windows do not receive broadcast WM_DEVICECHANGE. | | 2026-10-02 | Camera RAW is "native" via WIC only when the Raw Image Extension package is installed. | Decoder CLSID alone | The in-box RAW codec shares the CLSID but only reads embedded previews. | | 2026-10-02 | HEVC/AV1 decoder presence is detected with `MFTEnumEx`. | Store package names | Also covers OEM and hardware decoders. | +| 2026-10-02 | Math code lives in `src/Titano.Core/Math` with namespace `Titano.Core.Mathematics`. | `Titano.Core.Math` | That namespace would shadow `System.Math` in every `Titano.Core.*` file. | +| 2026-10-02 | CCT = McCamy refined to the nearest Planckian point (Krystek, CIE 1960 uv), valid for \|Duv\| ≤ 0.02. | Plain McCamy | McCamy alone misses the 100 K gate above ~9000 K. | +| 2026-10-02 | Deflicker keeps (1 − strength)·ρ·S of a frame's deviation (ρ own Tukey weight, S window surviving fraction). | Blend by S only | S alone barely isolates outliers. | +| 2026-10-02 | LOWESS uses the k nearest valid samples with bandwidth = farthest distance + one spacing. | Fixed half-width | Constant sample count at sequence edges. | +| 2026-10-02 | Clock jump = backward step > 3× median interval or a ±1 h offset from cadence (DST); counts as one interval. | Any whole-hour step | Scheduled multi-hour pauses look the same. | +| 2026-10-02 | Time zone for solar labels: recorded offset → camera−GPS clock (15 min) → longitude/15 with a "time zone estimated" finding. | No day phases | Usable labels, honestly flagged. | +| 2026-10-02 | Holy-grail step is "received" when the detrended median jump ≥ 50 % of the metadata step (same sign); metadata amplitude is redistributed with smoothstep ramps lengthened until ≤ 0.3 EV/frame. | Measured amplitude | Flicker makes the measured jump noisy. | +| 2026-10-02 | Flicker fundamental = first autocorrelation peak within 80 % of the strongest; window ∈ [15, 151], odd. | Strongest peak | Avoids harmonics at fractional periods. | +| 2026-10-02 | Optical flow: dense pyramidal Lucas–Kanade with box filters, neighbour-flow correction, σ = 1 px pre-blur; grid step 4/2/1 px for Draft/Balanced/Best. | Farnebäck | Separable, SIMD-friendly, stable and as accurate on smooth motion. | +| 2026-10-02 | Phase correlation: Gaussian-shaped peak + log-parabola sub-pixel fit, both patches in one complex FFT. | Foroosh sinc fit | Exact for Gaussian peaks, half the FFT work. | +| 2026-10-02 | Stabiliser: noise-corrected texture gate, exhaustive pairwise similarity hypotheses (≤ 36) + weighted LS, path smoothed by Gaussian-weighted local linear regression (σ = 12). | RANSAC / plain Gaussian | Deterministic with nine patches; keeps intentional pans. | +| 2026-10-02 | Interpolation chooses velocities by forward–backward consistency with per-sample flow-agreement weights (τ = 3 px). | Super SloMo combination | Better at motion boundaries (36.8 vs 33 dB). | +| 2026-10-02 | Virtual-camera zoom is interpolated geometrically; trail length L ↦ decay 0.01^(1/L). | Linear zoom / half-life | Even perceived speed; the trail is gone at its stated length. | +| 2026-10-02 | Motion estimation, sharpness and noise use sRGB-encoded luminance. | Linear light | Shadows keep texture weight; less exposure dependence. | From 654c45a2744d29666c386ef0b49a893944287038 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:00 +0000 Subject: [PATCH 059/188] feat(metadata): add parser infrastructure and XMP reader Bounds-checked positional stream reads, an in-memory span reader, Exif/XMP date parsing, and the MetadataBuilder accumulator that applies every fallback chain (timestamps, ISO, serial/lens, orientation, preview kinds) in one place. XMP is read with XmlReader (no DTDs, no resolver, 4 MB cap) in both attribute and element forms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Metadata/MakerNotes/MakerNoteValues.cs | 12 + src/Titano.Core/Metadata/MetadataBuilder.cs | 250 ++++++++++++++++++ src/Titano.Core/Metadata/MetadataDates.cs | 112 ++++++++ src/Titano.Core/Metadata/SpanReader.cs | 88 ++++++ src/Titano.Core/Metadata/StreamExtensions.cs | 30 +++ src/Titano.Core/Metadata/Xmp/XmpParser.cs | 171 ++++++++++++ src/Titano.Core/Metadata/Xmp/XmpValues.cs | 41 +++ 7 files changed, 704 insertions(+) create mode 100644 src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs create mode 100644 src/Titano.Core/Metadata/MetadataBuilder.cs create mode 100644 src/Titano.Core/Metadata/MetadataDates.cs create mode 100644 src/Titano.Core/Metadata/SpanReader.cs create mode 100644 src/Titano.Core/Metadata/StreamExtensions.cs create mode 100644 src/Titano.Core/Metadata/Xmp/XmpParser.cs create mode 100644 src/Titano.Core/Metadata/Xmp/XmpValues.cs diff --git a/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs b/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs new file mode 100644 index 00000000..9d2625b9 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/MakerNoteValues.cs @@ -0,0 +1,12 @@ +namespace Titano.Core.Metadata.MakerNotes; + +/// Values recovered from a vendor MakerNote. They fill a field only when the standard tags left it empty. +internal sealed class MakerNoteValues +{ + public string? BodySerial { get; set; } + public string? LensModel { get; set; } + public long? ShutterCount { get; set; } + public bool? ImageStabilization { get; set; } + public int? Iso { get; set; } + public int? ColorTemperature { get; set; } +} diff --git a/src/Titano.Core/Metadata/MetadataBuilder.cs b/src/Titano.Core/Metadata/MetadataBuilder.cs new file mode 100644 index 00000000..f55fe60e --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataBuilder.cs @@ -0,0 +1,250 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Xmp; +using Titano.Core.Model; + +namespace Titano.Core.Metadata; + +/// +/// Mutable accumulator shared by the container parsers. Parsers assign standard values with ??= in the order +/// of authority (so the first source wins); MakerNote and XMP values are kept apart and applies +/// every fallback chain in one place. +/// +internal sealed class MetadataBuilder +{ + private const int MaxWarnings = 64; + private const int MaxPreviews = 32; + private const int MaxRasters = 64; + private const int ThumbnailLongEdge = 640; + private const double FullSizeRatio = 0.9; + private const int SaturatedIso = 65535; + + private readonly List _warnings = []; + private readonly List _previews = []; + private readonly List _rasters = []; + private Raster? _container; + + public MetadataBuilder(Stream stream, CancellationToken cancellation) + { + Stream = stream; + Length = stream.Length; + Cancellation = cancellation; + } + + public Stream Stream { get; } + public long Length { get; } + public CancellationToken Cancellation { get; } + public ImageFileFormat Format { get; set; } + + public string? Make { get; set; } + public string? Model { get; set; } + public string? BodySerial { get; set; } + public string? LensModel { get; set; } + public string? Software { get; set; } + public string? Artist { get; set; } + public string? Copyright { get; set; } + public CaptureStamp? DateTimeOriginal { get; set; } + public CaptureStamp? DateTimeDigitized { get; set; } + public double? ExposureTime { get; set; } + public double? FNumber { get; set; } + + /// Exif ISOSpeedRatings (first value); 65535 means "at least 65535". + public int? IsoSpeedRatings { get; set; } + + /// RecommendedExposureIndex, StandardOutputSensitivity, ISOSpeed or a RAW-header ISO. + public int? IsoFallback { get; set; } + + public double? FocalLength { get; set; } + public double? FocalLength35 { get; set; } + public double? ExposureBias { get; set; } + public int? ExposureProgram { get; set; } + public int? MeteringMode { get; set; } + public int? WhiteBalanceMode { get; set; } + public int? Flash { get; set; } + + /// Raw Exif/TIFF orientation value (validated in ). + public int? ExifOrientation { get; set; } + + /// Orientation implied by container transforms (HEIF irot/imir); overrides Exif. + public int? ContainerOrientation { get; set; } + + public int? PixelXDimension { get; set; } + public int? PixelYDimension { get; set; } + + /// Bit depth of the coded main image when the container states it apart from the raster size (CR2 lossless-JPEG + /// SOF3, RAF FujiIFD, HEIF pixi); preferred over IFD BitsPerSample. + public int? CodedBitsPerSample { get; set; } + + /// GPS position without its timestamp (merged in ). + public GpsPosition? Gps { get; set; } + + public DateTime? GpsUtc { get; set; } + public int? ExifRating { get; set; } + public MakerNoteValues MakerNote { get; } = new(); + public XmpValues Xmp { get; } = new(); + public IReadOnlyList Warnings => _warnings; + + public void Warn(string message) + { + if (_warnings.Count < MaxWarnings && !_warnings.Contains(message)) _warnings.Add(message); + } + + public void AddWarnings(IEnumerable messages) + { + foreach (var message in messages) Warn(message); + } + + public void ThrowIfCancelled() => Cancellation.ThrowIfCancellationRequested(); + + /// Main-image size defined by the container itself (JPEG SOF, PNG IHDR, HEIF ispe, RAF header…); first call wins + /// and it overrides TIFF raster IFDs. + public void SetContainerSize(int width, int height, int? bitsPerSample = null) + { + if (_container is null && width > 0 && height > 0) _container = new Raster(width, height, bitsPerSample, true); + } + + /// A raster IFD; is false for reduced-resolution images (NewSubfileType bit 0). + public void AddRaster(int width, int height, int? bitsPerSample, bool primary) + { + if (width > 0 && height > 0 && _rasters.Count < MaxRasters) _rasters.Add(new Raster(width, height, bitsPerSample, primary)); + } + + /// Records a validated embedded JPEG; duplicates (same offset) keep the first. + public void AddPreview(long offset, long length, int width, int height, PreviewKind? kind = null) + { + if (width <= 0 || height <= 0 || length <= 0 || _previews.Count >= MaxPreviews) return; + foreach (var p in _previews) + { + if (p.Offset == offset) return; + } + _previews.Add(new PreviewCandidate(offset, length, width, height, kind)); + } + + public void AddXmp(byte[]? packet) + { + if (packet is not null && XmpParser.Parse(packet, Xmp) is { } problem) Warn(problem); + } + + /// Applies the fallback rules and produces the immutable result. + /// File modification time; used when no capture time is recorded. + public FrameMetadata Build(DateTime? fileModified) + { + var main = _container ?? BestRaster() ?? (PixelXDimension is > 0 && PixelYDimension is > 0 + ? new Raster(PixelXDimension.Value, PixelYDimension.Value, null, true) + : default(Raster?)); + var (captured, offset, source) = ResolveCaptureTime(fileModified); + var orientation = ResolveOrientation(); + return new FrameMetadata + { + Format = Format, + Make = Make, + Model = Model, + BodySerial = BodySerial ?? MakerNote.BodySerial ?? Xmp.BodySerial, + LensModel = LensModel ?? MakerNote.LensModel ?? Xmp.Lens, + Software = Software, + Artist = Artist, + Copyright = Copyright, + CapturedAt = captured, + UtcOffsetMinutes = offset, + TimestampSource = source, + ExposureTime = ExposureTime, + FNumber = FNumber, + Iso = ResolveIso(), + FocalLength = FocalLength, + FocalLength35 = FocalLength35, + ExposureBias = ExposureBias, + ExposureProgram = ExposureProgram, + MeteringMode = MeteringMode, + WhiteBalanceMode = WhiteBalanceMode, + ColorTemperature = MakerNote.ColorTemperature, + Flash = Flash, + Orientation = orientation, + Width = main?.Width ?? 0, + Height = main?.Height ?? 0, + BitsPerSample = CodedBitsPerSample ?? main?.Bits, + Gps = Gps is { } g ? g with { UtcTimestamp = GpsUtc } : null, + Rating = Xmp.Rating ?? (ExifRating is >= -1 and <= 5 ? ExifRating : null), + Label = Xmp.Label, + ShutterCount = MakerNote.ShutterCount, + ImageStabilization = MakerNote.ImageStabilization, + Previews = ResolvePreviews(main is { } m ? Math.Max(m.Width, m.Height) : 0), + Warnings = _warnings.ToArray(), + }; + } + + /// Largest full-resolution raster (NewSubfileType bit 0 clear); any raster when none is full-resolution. + private Raster? BestRaster() + { + Raster? best = null; + foreach (var r in _rasters) + { + if (best is not { } b || (r.Primary && !b.Primary) || (r.Primary == b.Primary && r.Area > b.Area)) best = r; + } + return best; + } + + /// Exif original → Exif digitized → XMP → GPS (UTC) → file time. + private (DateTime? Value, int? Offset, TimestampSource Source) ResolveCaptureTime(DateTime? fileModified) + { + if (DateTimeOriginal is { } original) return (original.Value, original.OffsetMinutes, TimestampSource.ExifOriginal); + if (DateTimeDigitized is { } digitized) return (digitized.Value, digitized.OffsetMinutes, TimestampSource.ExifCreate); + if (Xmp.CaptureTime is { } xmp) return (xmp.Value, xmp.OffsetMinutes, TimestampSource.Xmp); + if (GpsUtc is { } utc) return (DateTime.SpecifyKind(utc, DateTimeKind.Unspecified), 0, TimestampSource.Gps); + if (fileModified is { } file) + { + int? fileOffset = file.Kind switch + { + DateTimeKind.Local => (int)TimeZoneInfo.Local.GetUtcOffset(file).TotalMinutes, + DateTimeKind.Utc => 0, + _ => null, + }; + return (DateTime.SpecifyKind(file, DateTimeKind.Unspecified), fileOffset, TimestampSource.FileSystem); + } + return (null, null, TimestampSource.Unknown); + } + + /// ISOSpeedRatings unless absent or saturated (65535), then REI/SOS/ISOSpeed, then the MakerNote. + private int? ResolveIso() + { + if (IsoSpeedRatings is > 0 and < SaturatedIso) return IsoSpeedRatings; + return (IsoFallback is > 0 ? IsoFallback : null) + ?? (MakerNote.Iso is > 0 ? MakerNote.Iso : null) + ?? (IsoSpeedRatings is > 0 ? IsoSpeedRatings : null); + } + + private int ResolveOrientation() + { + if (ContainerOrientation is >= 1 and <= 8) return ContainerOrientation.Value; + if (ExifOrientation is >= 1 and <= 8) return ExifOrientation.Value; + if (ExifOrientation is { } invalid) Warn($"Invalid orientation {invalid} ignored"); + return Xmp.Orientation ?? 1; + } + + /// Largest first; kinds by long edge: < 640 px thumbnail, ≥ 90 % of the main image full size. + private EmbeddedPreview[] ResolvePreviews(int mainLongEdge) + { + var result = new EmbeddedPreview[_previews.Count]; + for (var i = 0; i < result.Length; i++) + { + var p = _previews[i]; + var longEdge = Math.Max(p.Width, p.Height); + var kind = p.Kind ?? (longEdge < ThumbnailLongEdge ? PreviewKind.Thumbnail + : mainLongEdge > 0 && longEdge >= FullSizeRatio * mainLongEdge ? PreviewKind.FullSize + : PreviewKind.Preview); + result[i] = new EmbeddedPreview(p.Offset, p.Length, p.Width, p.Height, kind); + } + Array.Sort(result, static (a, b) => + { + var byArea = ((long)b.Width * b.Height).CompareTo((long)a.Width * a.Height); + return byArea != 0 ? byArea : b.Length.CompareTo(a.Length); + }); + return result; + } + + private readonly record struct Raster(int Width, int Height, int? Bits, bool Primary) + { + public long Area => (long)Width * Height; + } + + private readonly record struct PreviewCandidate(long Offset, long Length, int Width, int Height, PreviewKind? Kind); +} diff --git a/src/Titano.Core/Metadata/MetadataDates.cs b/src/Titano.Core/Metadata/MetadataDates.cs new file mode 100644 index 00000000..77d38baf --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataDates.cs @@ -0,0 +1,112 @@ +namespace Titano.Core.Metadata; + +/// Camera wall-clock time (DateTimeKind.Unspecified) plus the UTC offset when the file records one. +internal readonly record struct CaptureStamp(DateTime Value, int? OffsetMinutes); + +/// Parsers for Exif ("YYYY:MM:DD HH:MM:SS"), sub-second, UTC-offset, GPS-date and XMP (ISO 8601) strings. +/// Blank, zeroed or out-of-range values yield null rather than a guess. +internal static class MetadataDates +{ + private const int MaxOffsetMinutes = 14 * 60; + + /// Exif date-time; separators are not checked so "YYYY-MM-DD HH:MM:SS" also parses. + public static DateTime? ParseExif(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 19) return null; + return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d + && Number(s, 11, 2) is { } h && Number(s, 14, 2) is { } mi && Number(s, 17, 2) is { } sec + ? Create(y, mo, d, h, mi, sec, 0) + : null; + } + + /// Exif date ("YYYY:MM:DD", e.g. GPSDateStamp) at midnight. + public static DateTime? ParseDate(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 10) return null; + return Number(s, 0, 4) is { } y && Number(s, 5, 2) is { } mo && Number(s, 8, 2) is { } d ? Create(y, mo, d, 0, 0, 0, 0) : null; + } + + /// SubSecTime digits as a fraction of a second in ticks ("5" → 0.5 s, "123" → 0.123 s). + public static long SubSecondTicks(string? text) + { + if (text is null) return 0; + long ticks = 0; + var digits = 0; + foreach (var c in text.AsSpan().Trim()) + { + if (c is < '0' or > '9' || digits == 7) break; + ticks = ticks * 10 + (c - '0'); + digits++; + } + if (digits == 0) return 0; + for (; digits < 7; digits++) ticks *= 10; + return ticks; + } + + /// "+HH:MM", "-HH:MM", "+HHMM" or "Z" as minutes east of UTC. + public static int? ParseOffset(ReadOnlySpan text) + { + var s = text.Trim(); + if (s is "Z") return 0; + if (s.Length < 5 || s[0] is not ('+' or '-')) return null; + var minuteStart = s[3] == ':' ? 4 : 3; + if (Number(s, 1, 2) is not { } h || Number(s, minuteStart, 2) is not { } m || m > 59) return null; + var total = h * 60 + m; + if (total > MaxOffsetMinutes) return null; + return s[0] == '-' ? -total : total; + } + + public static int? ParseOffset(string? text) => text is null ? null : ParseOffset(text.AsSpan()); + + /// XMP date "YYYY-MM-DDThh:mm[:ss[.f…]][Z|±hh:mm]"; Exif-style ':' date separators are tolerated. + /// Date-only values return null because midnight would be a fabricated capture time. + public static CaptureStamp? ParseIso8601(string? text) + { + if (text is null) return null; + var s = text.AsSpan().Trim(); + if (s.Length < 16 || s[10] is not ('T' or ' ')) return null; + if (Number(s, 0, 4) is not { } y || Number(s, 5, 2) is not { } mo || Number(s, 8, 2) is not { } d + || Number(s, 11, 2) is not { } h || Number(s, 14, 2) is not { } mi) + return null; + var pos = 16; + var sec = 0; + long ticks = 0; + if (pos < s.Length && s[pos] == ':') + { + if (Number(s, 17, 2) is not { } parsed) return null; + sec = parsed; + pos = 19; + if (pos < s.Length && s[pos] is '.' or ',') + { + var end = pos + 1; + while (end < s.Length && char.IsAsciiDigit(s[end])) end++; + ticks = SubSecondTicks(s[(pos + 1)..end].ToString()); + pos = end; + } + } + var offset = pos < s.Length ? ParseOffset(s[pos..]) : null; + return Create(y, mo, d, h, mi, sec, ticks) is { } value ? new CaptureStamp(value, offset) : null; + } + + private static int? Number(ReadOnlySpan s, int start, int length) + { + if (start + length > s.Length) return null; + var value = 0; + foreach (var c in s.Slice(start, length)) + { + if (!char.IsAsciiDigit(c)) return null; + value = value * 10 + (c - '0'); + } + return value; + } + + private static DateTime? Create(int y, int mo, int d, int h, int mi, int s, long ticks) + { + if (y < 1 || mo is < 1 or > 12 || d < 1 || d > DateTime.DaysInMonth(y, mo) || h > 23 || mi > 59 || s > 59) return null; + return new DateTime(y, mo, d, h, mi, s, DateTimeKind.Unspecified).AddTicks(ticks); + } +} diff --git a/src/Titano.Core/Metadata/SpanReader.cs b/src/Titano.Core/Metadata/SpanReader.cs new file mode 100644 index 00000000..9f2c5cf8 --- /dev/null +++ b/src/Titano.Core/Metadata/SpanReader.cs @@ -0,0 +1,88 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Metadata; + +/// +/// Forward-only reader over bytes already in memory. Reading past the end returns zeros and clears , +/// so a parser can read a whole structure and validate once. +/// +internal ref struct SpanReader +{ + private readonly ReadOnlySpan _data; + private readonly bool _bigEndian; + private int _position; + + public SpanReader(ReadOnlySpan data, bool bigEndian = true) + { + _data = data; + _bigEndian = bigEndian; + Ok = true; + } + + public bool Ok { get; private set; } + + public readonly int Position => _position; + + public readonly int Remaining => _data.Length - _position; + + public byte U8() => Take(1) is [var b] ? b : (byte)0; + + public ushort U16() + { + var s = Take(2); + return s.Length < 2 ? (ushort)0 : _bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s); + } + + public uint U32() + { + var s = Take(4); + return s.Length < 4 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(s) : BinaryPrimitives.ReadUInt32LittleEndian(s); + } + + public ulong U64() + { + var s = Take(8); + return s.Length < 8 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt64BigEndian(s) : BinaryPrimitives.ReadUInt64LittleEndian(s); + } + + /// Unsigned integer stored in 0, 4 or 8 bytes (ISO-BMFF iloc field sizes); other sizes fail. + public ulong Sized(int bytes) + { + switch (bytes) + { + case 0: return 0; + case 4: return U32(); + case 8: return U64(); + default: + Ok = false; + return 0; + } + } + + public void Skip(int count) => Take(count); + + /// The next bytes; empty (and cleared) when fewer remain. + public ReadOnlySpan Take(int count) + { + if (count < 0 || count > Remaining) + { + Ok = false; + _position = _data.Length; + return default; + } + var s = _data.Slice(_position, count); + _position += count; + return s; + } + + /// NUL-terminated UTF-8 string (the terminator is consumed); the rest of the data when unterminated. + public string CString() + { + var rest = _data[_position..]; + var end = rest.IndexOf((byte)0); + var length = end < 0 ? rest.Length : end; + _position += end < 0 ? length : length + 1; + return Encoding.UTF8.GetString(rest[..length]); + } +} diff --git a/src/Titano.Core/Metadata/StreamExtensions.cs b/src/Titano.Core/Metadata/StreamExtensions.cs new file mode 100644 index 00000000..6a9c476e --- /dev/null +++ b/src/Titano.Core/Metadata/StreamExtensions.cs @@ -0,0 +1,30 @@ +namespace Titano.Core.Metadata; + +/// Bounds-checked positional reads shared by the container parsers (windowed access, never whole files). +internal static class StreamExtensions +{ + /// Fills from ; false when the range leaves the stream. + public static bool TryReadAt(this Stream stream, long position, Span buffer) + { + if (position < 0 || position > stream.Length - buffer.Length) return false; + stream.Position = position; + return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length; + } + + /// Reads bytes at ; null when out of range or above . + public static byte[]? ReadAt(this Stream stream, long position, long length, long maxLength) + { + if (length < 0 || length > maxLength || position < 0 || position > stream.Length - length) return null; + var buffer = new byte[length]; + return stream.TryReadAt(position, buffer) ? buffer : null; + } + + /// Reads up to .Length bytes at ; returns the count read. + public static int ReadUpTo(this Stream stream, long position, Span buffer) + { + if (position < 0 || position >= stream.Length) return 0; + var n = (int)Math.Min(buffer.Length, stream.Length - position); + stream.Position = position; + return stream.ReadAtLeast(buffer[..n], n, throwOnEndOfStream: false); + } +} diff --git a/src/Titano.Core/Metadata/Xmp/XmpParser.cs b/src/Titano.Core/Metadata/Xmp/XmpParser.cs new file mode 100644 index 00000000..7d62054a --- /dev/null +++ b/src/Titano.Core/Metadata/Xmp/XmpParser.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using System.Xml; + +namespace Titano.Core.Metadata.Xmp; + +/// +/// Streaming XMP reader (no DTDs, no external resolution, 4 MB cap). Reads both the attribute form +/// (<rdf:Description xmp:Rating="5"/>) and the element form (<xmp:Rating>5</xmp:Rating>, +/// including values nested in rdf:Alt/rdf:Seq) of the properties in . +/// +internal static class XmpParser +{ + public const int MaxPacketBytes = 4 * 1024 * 1024; + + private const string NsXmp = "http://ns.adobe.com/xap/1.0/"; + private const string NsExif = "http://ns.adobe.com/exif/1.0/"; + private const string NsAux = "http://ns.adobe.com/exif/1.0/aux/"; + private const string NsExifEx = "http://cipa.jp/exif/1.0/"; + private const string NsPhotoshop = "http://ns.adobe.com/photoshop/1.0/"; + private const string NsTiff = "http://ns.adobe.com/tiff/1.0/"; + private const string NsXmpNote = "http://ns.adobe.com/xmp/note/"; + + private static readonly XmlReaderSettings Settings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + IgnoreWhitespace = true, + MaxCharactersInDocument = MaxPacketBytes, + CloseInput = true, + }; + + private enum Property + { + None, + Rating, + Label, + DateTimeOriginal, + DateCreated, + CreateDate, + Orientation, + AuxSerialNumber, + BodySerialNumber, + AuxLens, + LensModel, + HasExtendedXmp, + } + + /// Parses one packet into , keeping values that are already set. + /// Null on success; otherwise why parsing stopped (values read before the problem are kept). + public static string? Parse(byte[] packet, XmpValues values) + { + var length = packet.Length; + while (length > 0 && packet[length - 1] == 0) length--; + if (length == 0) return "Empty XMP packet"; + if (length > MaxPacketBytes) return "XMP packet larger than 4 MB ignored"; + try + { + using var reader = XmlReader.Create(new MemoryStream(packet, 0, length, writable: false), Settings); + var pending = Property.None; + var pendingDepth = 0; + while (reader.Read()) + { + switch (reader.NodeType) + { + case XmlNodeType.Element: + if (reader.MoveToFirstAttribute()) + { + do Assign(values, Lookup(reader.NamespaceURI, reader.LocalName), reader.Value); + while (reader.MoveToNextAttribute()); + reader.MoveToElement(); + } + if (pending == Property.None && !reader.IsEmptyElement) + { + pending = Lookup(reader.NamespaceURI, reader.LocalName); + pendingDepth = reader.Depth; + } + break; + case XmlNodeType.Text or XmlNodeType.CDATA: + if (pending != Property.None) + { + Assign(values, pending, reader.Value); + pending = Property.None; + } + break; + case XmlNodeType.EndElement: + if (reader.Depth <= pendingDepth) pending = Property.None; + break; + } + } + return null; + } + catch (XmlException ex) + { + return "Malformed XMP: " + ex.Message; + } + } + + private static Property Lookup(string ns, string name) => ns switch + { + NsXmp => name switch + { + "Rating" => Property.Rating, + "Label" => Property.Label, + "CreateDate" => Property.CreateDate, + _ => Property.None, + }, + NsExif when name == "DateTimeOriginal" => Property.DateTimeOriginal, + NsPhotoshop when name == "DateCreated" => Property.DateCreated, + NsTiff when name == "Orientation" => Property.Orientation, + NsAux => name switch + { + "SerialNumber" => Property.AuxSerialNumber, + "Lens" => Property.AuxLens, + _ => Property.None, + }, + NsExifEx => name switch + { + "BodySerialNumber" => Property.BodySerialNumber, + "LensModel" => Property.LensModel, + _ => Property.None, + }, + NsXmpNote when name == "HasExtendedXMP" => Property.HasExtendedXmp, + _ => Property.None, + }; + + private static void Assign(XmpValues v, Property property, string raw) + { + var text = raw.Trim(); + if (property == Property.None || text.Length == 0) return; + switch (property) + { + case Property.Rating: + if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var rating) && rating is >= -1 and <= 5) + v.Rating ??= (int)Math.Round(rating); + break; + case Property.Label: + v.Label ??= text; + break; + case Property.DateTimeOriginal: + v.DateTimeOriginal ??= MetadataDates.ParseIso8601(text); + break; + case Property.DateCreated: + v.DateCreated ??= MetadataDates.ParseIso8601(text); + break; + case Property.CreateDate: + v.CreateDate ??= MetadataDates.ParseIso8601(text); + break; + case Property.Orientation: + if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var o) && o is >= 1 and <= 8) + v.Orientation ??= o; + break; + case Property.AuxSerialNumber: + v.AuxSerialNumber ??= text; + break; + case Property.BodySerialNumber: + v.BodySerialNumber ??= text; + break; + case Property.AuxLens: + v.AuxLens ??= text; + break; + case Property.LensModel: + v.LensModel ??= text; + break; + case Property.HasExtendedXmp: + v.ExtendedXmpGuid ??= text; + break; + } + } +} diff --git a/src/Titano.Core/Metadata/Xmp/XmpValues.cs b/src/Titano.Core/Metadata/Xmp/XmpValues.cs new file mode 100644 index 00000000..2a258592 --- /dev/null +++ b/src/Titano.Core/Metadata/Xmp/XmpValues.cs @@ -0,0 +1,41 @@ +namespace Titano.Core.Metadata.Xmp; + +/// The XMP properties Titano reads. Each is set by the first packet that carries it. +internal sealed class XmpValues +{ + public int? Rating { get; set; } + public string? Label { get; set; } + + /// exif:DateTimeOriginal. + public CaptureStamp? DateTimeOriginal { get; set; } + + /// photoshop:DateCreated. + public CaptureStamp? DateCreated { get; set; } + + /// xmp:CreateDate. + public CaptureStamp? CreateDate { get; set; } + + public int? Orientation { get; set; } + + /// aux:SerialNumber. + public string? AuxSerialNumber { get; set; } + + /// exifEX:BodySerialNumber. + public string? BodySerialNumber { get; set; } + + /// aux:Lens. + public string? AuxLens { get; set; } + + /// exifEX:LensModel. + public string? LensModel { get; set; } + + /// xmpNote:HasExtendedXMP: GUID of the extended packet split across JPEG APP1 segments. + public string? ExtendedXmpGuid { get; set; } + + /// Capture time in MWG order: DateTimeOriginal, DateCreated, CreateDate. + public CaptureStamp? CaptureTime => DateTimeOriginal ?? DateCreated ?? CreateDate; + + public string? BodySerial => BodySerialNumber ?? AuxSerialNumber; + + public string? Lens => LensModel ?? AuxLens; +} From d12c0b41c5eb6bea886bb7a30dc365537d22f7bf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:12 +0000 Subject: [PATCH 060/188] feat(metadata): parse TIFF/Exif, JPEG segments and MakerNotes ExifParser walks IFD0, Exif, GPS and SubIFDs, selects the main raster (largest full-resolution IFD), and enumerates embedded JPEG previews (JPEGInterchangeFormat, single-strip/tile Compression 6/7, lossless raw strips excluded). JpegParser scans APP1 Exif/XMP/extended XMP, APP2 MPF large thumbnails and SOFn up to SOS, tolerating fill bytes and garbage. Vendor MakerNotes (Canon, Nikon, Sony, Fujifilm, Olympus/OM, Panasonic) fill serial, lens, shutter count, stabiliser, ISO and colour temperature only when standard tags did not. TiffTags gains GPSVersionID, GPSStatus, YCbCrPositioning, StandardOutputSensitivity and ISOSpeed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Metadata/Jpeg/JpegParser.cs | 277 ++++++++++++++++++ .../Metadata/MakerNotes/CanonMakerNote.cs | 39 +++ .../Metadata/MakerNotes/FujifilmMakerNote.cs | 31 ++ .../Metadata/MakerNotes/MakerNoteParser.cs | 81 +++++ .../Metadata/MakerNotes/NikonMakerNote.cs | 54 ++++ .../Metadata/MakerNotes/OlympusMakerNote.cs | 66 +++++ .../Metadata/MakerNotes/PanasonicMakerNote.cs | 27 ++ .../Metadata/MakerNotes/SonyMakerNote.cs | 46 +++ src/Titano.Core/Metadata/Tiff/ExifParser.cs | 247 ++++++++++++++++ src/Titano.Core/Metadata/Tiff/IfdValue.cs | 45 +++ src/Titano.Core/Metadata/Tiff/TiffTags.cs | 5 + 11 files changed, 918 insertions(+) create mode 100644 src/Titano.Core/Metadata/Jpeg/JpegParser.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs create mode 100644 src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs create mode 100644 src/Titano.Core/Metadata/Tiff/ExifParser.cs create mode 100644 src/Titano.Core/Metadata/Tiff/IfdValue.cs diff --git a/src/Titano.Core/Metadata/Jpeg/JpegParser.cs b/src/Titano.Core/Metadata/Jpeg/JpegParser.cs new file mode 100644 index 00000000..a5db9a65 --- /dev/null +++ b/src/Titano.Core/Metadata/Jpeg/JpegParser.cs @@ -0,0 +1,277 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Jpeg; + +/// Frame header (SOFn) of a JPEG. +internal readonly record struct JpegFrame(int Width, int Height, int Precision, bool Lossless); + +/// +/// JPEG marker scan: APP1 Exif, APP1 XMP and extended XMP (reassembled by GUID/offset), APP2 MPF large-thumbnail +/// entries, SOFn. Reads only segment headers and the payloads it parses, stops at SOS, and tolerates fill bytes and +/// garbage between segments. +/// +internal static class JpegParser +{ + /// Most bytes read while looking for an embedded JPEG's frame header. + public const int MaxFrameScanBytes = 64 * 1024; + + private const int MaxSegments = 1024; + private const int MaxGarbageBytes = 64 * 1024; + private const int MaxMpEntries = 64; + private const ushort MpEntryTag = 0xB002; + private const uint MpLargeThumbnailVga = 0x010001; + private const uint MpLargeThumbnailFullHd = 0x010002; + private const int ExtendedHeaderLength = 75; + + private static ReadOnlySpan ExifSignature => "Exif\0"u8; + private static ReadOnlySpan XmpSignature => "http://ns.adobe.com/xap/1.0/\0"u8; + private static ReadOnlySpan ExtendedXmpSignature => "http://ns.adobe.com/xmp/extension/\0"u8; + private static ReadOnlySpan MpfSignature => "MPF\0"u8; + + /// Scans the JPEG at [, ). A primary JPEG defines the main image + /// size; an embedded one (RAF, RW2 JpgFromRaw) contributes its Exif/XMP and is recorded as a preview. + public static void Parse(MetadataBuilder m, long start, long end, bool primary) + { + var scanner = new SegmentScanner(m.Stream, start, Math.Min(end, m.Length), long.MaxValue); + if (!scanner.StartsWithSoi()) + { + m.Warn("JPEG start-of-image marker not found"); + return; + } + JpegFrame? frame = null; + var exifSeen = false; + List? extended = null; + while (scanner.Next(out var segment)) + { + m.ThrowIfCancelled(); + if (segment.Marker is 0xDA or 0xD9) break; + if (segment.Marker == 0xE1) ReadApp1(m, segment, ref exifSeen, ref extended); + else if (segment.Marker == 0xE2) ReadMpf(m, segment); + else if (frame is null && IsFrameMarker(segment.Marker)) frame = ReadFrameHeader(m.Stream, segment); + } + if (scanner.Garbage) m.Warn("JPEG: garbage between segments skipped"); + if (scanner.Truncated) m.Warn("JPEG: truncated segment"); + if (frame is { } f) + { + if (primary) m.SetContainerSize(f.Width, f.Height, f.Precision); + else if (!f.Lossless && end <= m.Length) m.AddPreview(start, end - start, f.Width, f.Height); + } + else if (primary) + { + m.Warn("JPEG frame header not found"); + } + if (extended is not null) AssembleExtendedXmp(m, extended); + } + + /// Frame header of an embedded JPEG reading at most ; null when the bytes are + /// not a JPEG or no SOFn precedes the scan data. + public static JpegFrame? ReadFrame(Stream stream, long offset, long length) + { + if (offset < 0 || length < 4 || offset > stream.Length - length) return null; + var scanner = new SegmentScanner(stream, offset, offset + length, MaxFrameScanBytes); + if (!scanner.StartsWithSoi()) return null; + while (scanner.Next(out var segment)) + { + if (segment.Marker is 0xDA or 0xD9) return null; + if (IsFrameMarker(segment.Marker)) return ReadFrameHeader(stream, segment); + } + return null; + } + + /// Validates an embedded JPEG and records it as a preview unless it is lossless (raw data). + /// The frame header, or null when the range holds no readable JPEG. + public static JpegFrame? AddPreview(MetadataBuilder m, long offset, long length, PreviewKind? kind = null) + { + if (offset < 0 || length <= 0 || offset > m.Length - length) + { + m.Warn("Embedded JPEG outside the file"); + return null; + } + var frame = ReadFrame(m.Stream, offset, length); + if (frame is { Lossless: false } f) m.AddPreview(offset, length, f.Width, f.Height, kind); + return frame; + } + + private static bool IsFrameMarker(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC); + + private static JpegFrame? ReadFrameHeader(Stream stream, Segment segment) + { + Span sof = stackalloc byte[6]; + if (segment.Length < 6 || !stream.TryReadAt(segment.Payload, sof)) return null; + var lossless = segment.Marker is 0xC3 or 0xC7 or 0xCB or 0xCF; + return new JpegFrame(BinaryPrimitives.ReadUInt16BigEndian(sof[3..]), BinaryPrimitives.ReadUInt16BigEndian(sof[1..]), sof[0], lossless); + } + + private static void ReadApp1(MetadataBuilder m, Segment segment, ref bool exifSeen, ref List? extended) + { + Span head = stackalloc byte[ExtendedHeaderLength]; + var n = m.Stream.ReadUpTo(segment.Payload, head[..Math.Min(head.Length, segment.Length)]); + var h = head[..n]; + if (h.StartsWith(ExifSignature) && segment.Length > 6) + { + if (!exifSeen) ExifParser.ParseEmbedded(m, segment.Payload + 6); + exifSeen = true; + } + else if (h.StartsWith(XmpSignature)) + { + m.AddXmp(m.Stream.ReadAt(segment.Payload + XmpSignature.Length, segment.Length - XmpSignature.Length, XmpParser.MaxPacketBytes)); + } + else if (h.StartsWith(ExtendedXmpSignature) && n == ExtendedHeaderLength) + { + var guid = Encoding.ASCII.GetString(h.Slice(ExtendedXmpSignature.Length, 32)); + var full = BinaryPrimitives.ReadUInt32BigEndian(h[67..]); + var offset = BinaryPrimitives.ReadUInt32BigEndian(h[71..]); + (extended ??= []).Add(new ExtendedXmpChunk(guid, full, offset, segment.Payload + ExtendedHeaderLength, segment.Length - ExtendedHeaderLength)); + } + } + + /// APP2 Multi-Picture Format: secondary large thumbnails (type 0x010001/0x010002) become previews. Offsets are + /// relative to the MP header; other secondary types (disparity, gain maps…) are not previews. + private static void ReadMpf(MetadataBuilder m, Segment segment) + { + Span head = stackalloc byte[4]; + if (segment.Length < 16 || !m.Stream.TryReadAt(segment.Payload, head) || !head.SequenceEqual(MpfSignature)) return; + var mpBase = segment.Payload + 4; + var r = TiffReader.Open(m.Stream, mpBase); + if (r?.ReadIfd(r.FirstIfdOffset) is not { } index || !index.Entries.TryGetValue(MpEntryTag, out var entry)) return; + if (entry.Count % 16 != 0 || entry.Count > 16 * MaxMpEntries || r.ReadBytes(entry) is not { } entries) + { + m.Warn("MPF entry table malformed"); + return; + } + for (var i = 16; i + 16 <= entries.Length; i += 16) + { + var e = entries.AsSpan(i, 16); + var type = r.U32(e) & 0xFFFFFF; + var size = r.U32(e[4..]); + var offset = r.U32(e[8..]); + if (type is MpLargeThumbnailVga or MpLargeThumbnailFullHd && offset > 0 && size > 0) AddPreview(m, mpBase + offset, size); + } + m.AddWarnings(r.Warnings); + } + + private static void AssembleExtendedXmp(MetadataBuilder m, List chunks) + { + var guid = m.Xmp.ExtendedXmpGuid; + if (guid is null) + { + m.Warn("Extended XMP present but not referenced by the main packet"); + return; + } + uint full = 0; + long covered = 0; + foreach (var c in chunks) + { + if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase)) continue; + if (full == 0) full = c.FullLength; + if (c.FullLength == full) covered += c.Length; + } + if (full == 0 || full > XmpParser.MaxPacketBytes || covered < full) + { + m.Warn("Extended XMP incomplete"); + return; + } + var buffer = new byte[full]; + foreach (var c in chunks) + { + if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase) || c.FullLength != full || (long)c.Offset + c.Length > full) continue; + if (!m.Stream.TryReadAt(c.Position, buffer.AsSpan((int)c.Offset, c.Length))) + { + m.Warn("Extended XMP chunk unreadable"); + return; + } + } + m.AddXmp(buffer); + } + + private readonly record struct Segment(byte Marker, long Payload, int Length); + + private readonly record struct ExtendedXmpChunk(string Guid, uint FullLength, uint Offset, long Position, int Length); + + /// Walks marker segments of one JPEG, reading only marker and length bytes within a read budget. + private sealed class SegmentScanner(Stream stream, long start, long end, long readBudget) + { + private readonly byte[] _buffer = new byte[16]; + private long _position = start + 2; + private long _budget = readBudget; + private int _count; + + public bool Garbage { get; private set; } + + public bool Truncated { get; private set; } + + public bool StartsWithSoi() => Read(start, 2) == 2 && _buffer[0] == 0xFF && _buffer[1] == 0xD8; + + public bool Next(out Segment segment) + { + segment = default; + if (++_count > MaxSegments) return false; + long skipped = 0; + while (true) + { + var n = Read(_position, _buffer.Length); + if (n < 2) + { + if (_position < end) Truncated = true; + return false; + } + var i = 0; + while (i < n - 1 && !(_buffer[i] == 0xFF && _buffer[i + 1] is not (0xFF or 0x00))) i++; + if (i == n - 1) + { + Garbage |= _buffer.AsSpan(0, n - 1).ContainsAnyExcept((byte)0xFF); + _position += n - 1; + skipped += n - 1; + if (skipped > MaxGarbageBytes) return false; + continue; + } + Garbage |= _buffer.AsSpan(0, i).ContainsAnyExcept((byte)0xFF); + var marker = _buffer[i + 1]; + var markerPosition = _position + i + 1; + if (marker is 0xD8 or 0xD9 or 0x01 or (>= 0xD0 and <= 0xD7)) + { + _position = markerPosition + 1; + segment = new Segment(marker, _position, 0); + return true; + } + int length; + if (i + 3 < n) + { + length = _buffer[i + 2] << 8 | _buffer[i + 3]; + } + else if (Read(markerPosition + 1, 2) == 2) + { + length = _buffer[0] << 8 | _buffer[1]; + } + else + { + Truncated = true; + return false; + } + if (length < 2) + { + Garbage = true; + return false; + } + var payload = markerPosition + 3; + var available = (int)Math.Clamp(end - payload, 0, length - 2); + Truncated |= available < length - 2; + segment = new Segment(marker, payload, available); + _position = payload + length - 2; + return true; + } + } + + private int Read(long position, int count) + { + if (position >= end || _budget <= 0) return 0; + var n = (int)Math.Min(Math.Min(count, end - position), _budget); + n = stream.ReadUpTo(position, _buffer.AsSpan(0, n)); + _budget -= n; + return n; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs new file mode 100644 index 00000000..6c60030e --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/CanonMakerNote.cs @@ -0,0 +1,39 @@ +using System.Globalization; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Canon MakerNote: a bare IFD whose offsets are relative to the enclosing TIFF header (also CR3 CMT3). +internal static class CanonMakerNote +{ + private const ushort CameraSettings = 0x0001; + private const ushort SerialNumber = 0x000C; + private const ushort LensModel = 0x0095; + private const ushort InternalSerialNumber = 0x0096; + private const ushort ColorTemperature = 0x00AE; + private const int ImageStabilizationIndex = 34; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (IfdValue.UInt(r, ifd, SerialNumber) is { } serial and > 0) + { + // Canon prints 6 digits on EOS-1D bodies and 10 elsewhere. + var digits = m.Model?.Contains("EOS-1D", StringComparison.OrdinalIgnoreCase) == true ? "D6" : "D10"; + v.BodySerial ??= serial.ToString(digits, CultureInfo.InvariantCulture); + } + v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber); + v.LensModel ??= IfdValue.String(r, ifd, LensModel); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null; + if (IfdValue.UInts(r, ifd, CameraSettings) is { Length: > ImageStabilizationIndex } settings) + { + // 0 Off, 1 On, 2 Shoot only, 3 Panning, 4 Dynamic; +256 for the "(2)" variants. + v.ImageStabilization ??= (settings[ImageStabilizationIndex] & 0xFF) switch + { + 0 => false, + >= 1 and <= 4 => true, + _ => null, + }; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs new file mode 100644 index 00000000..1b5f93e6 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/FujifilmMakerNote.cs @@ -0,0 +1,31 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Fujifilm MakerNote: "FUJIFILM" + little-endian IFD offset, offsets relative to the MakerNote start, +/// always little-endian. +internal static class FujifilmMakerNote +{ + private const ushort SerialNumber = 0x0010; + private const ushort ColorTemperature = 0x1005; + private const ushort ImageStabilization = 0x1422; + + public static void Parse(MetadataBuilder m, long start, ReadOnlySpan header) + { + if (header.Length < 12) return; + var reader = TiffReader.ForEmbedded(m.Stream, start, littleEndian: true); + MakerNoteParser.Vendor(reader, BinaryPrimitives.ReadUInt32LittleEndian(header[8..]), m, ParseIfd); + m.AddWarnings(reader.Warnings); + } + + private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null; + // [0] type (0 none, 1 optical, 2 sensor-shift, …), [1] mode (0 off, 1/2 on). + if (IfdValue.UInts(r, ifd, ImageStabilization) is [var type, var mode, ..]) + v.ImageStabilization ??= type != 0 && mode != 0; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs b/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs new file mode 100644 index 00000000..578d1b6b --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/MakerNoteParser.cs @@ -0,0 +1,81 @@ +using System.Globalization; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// +/// Locates the vendor IFD inside an Exif MakerNote (by header signature, then by camera make) and hands it to the +/// vendor parser. Best effort: unknown layouts are skipped, and every read goes through the bounds-checked +/// . +/// +internal static class MakerNoteParser +{ + private const int HeaderBytes = 16; + + /// Reader of the TIFF block holding the Exif IFD (base and byte order of relative offsets). + /// The Exif 0x927C entry. + public static void Parse(TiffReader exif, IfdEntry makerNote, MetadataBuilder m) + { + if (makerNote.IsInline || makerNote.ByteLength < 14) return; + var start = makerNote.ValuePosition(exif.Base); + if (start < exif.Base || start > m.Length - makerNote.ByteLength) + { + m.Warn("MakerNote outside the file"); + return; + } + Span head = stackalloc byte[HeaderBytes]; + var h = head[..m.Stream.ReadUpTo(start, head[..(int)Math.Min(HeaderBytes, makerNote.ByteLength)])]; + var make = m.Make ?? string.Empty; + var relative = (uint)(start - exif.Base); + + if (h.StartsWith("Nikon\0"u8)) + { + NikonMakerNote.Parse(exif, start, h, m); + } + else if (h.StartsWith("OLYMPUS\0"u8) || h.StartsWith("OM SYSTEM\0"u8) || h.StartsWith("OLYMP\0"u8)) + { + OlympusMakerNote.Parse(exif, start, h, m); + } + else if (h.StartsWith("FUJIFILM"u8)) + { + FujifilmMakerNote.Parse(m, start, h); + } + else if (h.StartsWith("Panasonic\0"u8)) + { + Vendor(exif, relative + 12, m, PanasonicMakerNote.Parse); + } + else if (h.StartsWith("SONY"u8)) + { + Vendor(exif, relative + 12, m, SonyMakerNote.Parse); + } + else if (make.StartsWith("Canon", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, CanonMakerNote.Parse); + } + else if (make.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, NikonMakerNote.ParseIfd); + } + else if (make.StartsWith("SONY", StringComparison.OrdinalIgnoreCase)) + { + Vendor(exif, relative, m, SonyMakerNote.Parse); + } + } + + /// Reads the IFD at a base-relative offset with and runs on it. + internal static void Vendor(TiffReader reader, uint offset, MetadataBuilder m, Action parse) + { + if (reader.ReadIfd(offset) is { } ifd) parse(reader, ifd, m); + else m.Warn("MakerNote IFD unreadable"); + } + + /// "24-70mm f/2.8", "50mm f/1.8" or "18-55mm F3.5-5.6" from focal-length and aperture ranges. + internal static string FormatLens(double minFocal, double maxFocal, double minAperture, double maxAperture, string aperturePrefix) + { + static string N(double v) => Math.Round(v, 1).ToString("0.#", CultureInfo.InvariantCulture); + var focal = maxFocal > minFocal ? $"{N(minFocal)}-{N(maxFocal)}mm" : $"{N(minFocal)}mm"; + if (minAperture <= 0) return focal; + var aperture = maxAperture > minAperture ? $"{N(minAperture)}-{N(maxAperture)}" : N(minAperture); + return $"{focal} {aperturePrefix}{aperture}"; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs new file mode 100644 index 00000000..a7e50bb7 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/NikonMakerNote.cs @@ -0,0 +1,54 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Nikon MakerNote. Type 3 ("Nikon\0" + version 2.x) embeds its own TIFF header 10 bytes in; type 1 +/// ("Nikon\0" + version 1) has an IFD at +8 and headerless type 2 an IFD at +0, both relative to the Exif TIFF. +internal static class NikonMakerNote +{ + private const ushort Iso = 0x0002; + private const ushort SerialNumber = 0x001D; + private const ushort VrInfo = 0x001F; + private const ushort Lens = 0x0084; + private const ushort ShutterCount = 0x00A7; + + public static void Parse(TiffReader exif, long start, ReadOnlySpan header, MetadataBuilder m) + { + if (header.Length > 6 && header[6] == 2) + { + if (TiffReader.Open(m.Stream, start + 10) is { } inner) + { + MakerNoteParser.Vendor(inner, inner.FirstIfdOffset, m, ParseIfd); + m.AddWarnings(inner.Warnings); + } + else + { + m.Warn("Nikon MakerNote TIFF header missing"); + } + } + else + { + MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd); + } + } + + public static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, SerialNumber); + v.ShutterCount ??= IfdValue.UInt(r, ifd, ShutterCount); + v.Iso ??= IfdValue.UInts(r, ifd, Iso) is [_, var iso, ..] && iso is > 0 and <= int.MaxValue ? (int)iso : null; + if (IfdValue.Doubles(r, ifd, Lens, 4) is [var minFocal, var maxFocal, var minAperture, var maxAperture, ..] && minFocal > 0) + v.LensModel ??= MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture, maxAperture, "f/"); + if (ifd.Entries.TryGetValue(VrInfo, out var vr) && vr.Count is >= 5 and <= 64 && r.ReadBytes(vr) is { } bytes) + { + // Byte 4: 1 = on, 2 = off. + v.ImageStabilization ??= bytes[4] switch + { + 1 => true, + 2 => false, + _ => null, + }; + } + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs new file mode 100644 index 00000000..e00e90b5 --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/OlympusMakerNote.cs @@ -0,0 +1,66 @@ +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// +/// Olympus / OM System MakerNote. "OLYMPUS\0II\3\0" (IFD at +12) and "OM SYSTEM\0\0\0II\4\0" (IFD at +16) use offsets +/// relative to the MakerNote start and their own byte order; legacy "OLYMP\0" has its IFD at +8 relative to the +/// Exif TIFF. Equipment (0x2010) gives serial and lens; CameraSettings (0x2020) gives the ORF preview and stabiliser. +/// +internal static class OlympusMakerNote +{ + private const ushort Equipment = 0x2010; + private const ushort CameraSettings = 0x2020; + private const ushort EquipmentSerialNumber = 0x0101; + private const ushort EquipmentLensModel = 0x0203; + private const ushort PreviewImageValid = 0x0100; + private const ushort PreviewImageStart = 0x0101; + private const ushort PreviewImageLength = 0x0102; + private const ushort ImageStabilization = 0x0604; + + public static void Parse(TiffReader exif, long start, ReadOnlySpan header, MetadataBuilder m) + { + if (header.StartsWith("OLYMP\0"u8)) + { + MakerNoteParser.Vendor(exif, (uint)(start - exif.Base + 8), m, ParseIfd); + return; + } + var orderAt = header.StartsWith("OM SYSTEM\0"u8) ? 12 : 8; + if (header.Length < orderAt + 4 || header[orderAt] != header[orderAt + 1] || header[orderAt] is not ((byte)'I' or (byte)'M')) + { + m.Warn("Olympus MakerNote header malformed"); + return; + } + var reader = TiffReader.ForEmbedded(m.Stream, start, header[orderAt] == 'I'); + MakerNoteParser.Vendor(reader, (uint)(orderAt + 4), m, ParseIfd); + m.AddWarnings(reader.Warnings); + } + + private static void ParseIfd(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (SubIfd(r, ifd, Equipment) is { } equipment) + { + v.BodySerial ??= IfdValue.String(r, equipment, EquipmentSerialNumber); + v.LensModel ??= IfdValue.String(r, equipment, EquipmentLensModel); + } + if (SubIfd(r, ifd, CameraSettings) is not { } settings) return; + v.ImageStabilization ??= IfdValue.UInt(r, settings, ImageStabilization) switch + { + 0 => false, + >= 1 and <= 4 => true, + _ => null, + }; + if (IfdValue.UInt(r, settings, PreviewImageValid) != 0 + && IfdValue.UInt(r, settings, PreviewImageStart) is { } offset and > 0 + && IfdValue.UInt(r, settings, PreviewImageLength) is { } length and > 0) + { + JpegParser.AddPreview(m, r.Base + offset, length); + } + } + + /// Sub-IFD stored either as an IFD/LONG pointer or as an UNDEFINED block; both resolve to the value offset. + private static Ifd? SubIfd(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && !(e.IsInline && e.Type == TiffType.Undefined) ? r.ReadIfd(e.ValueOffset) : null; +} diff --git a/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs new file mode 100644 index 00000000..9709903c --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/PanasonicMakerNote.cs @@ -0,0 +1,27 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Panasonic MakerNote: "Panasonic\0\0\0" then an IFD whose offsets are relative to the Exif TIFF. +internal static class PanasonicMakerNote +{ + private const ushort ImageStabilization = 0x001A; + private const ushort InternalSerialNumber = 0x0025; + private const ushort ColorTempKelvin = 0x0044; + private const ushort LensType = 0x0051; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber); + v.LensModel ??= IfdValue.String(r, ifd, LensType); + v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTempKelvin) is { } kelvin and > 0 and < 65535 ? kelvin : null; + // 3 = off; 2, 4–7, 9–12 = optical/body/dual IS modes. + v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch + { + 3 => false, + 2 or (>= 4 and <= 7) or (>= 9 and <= 12) => true, + _ => null, + }; + } +} diff --git a/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs b/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs new file mode 100644 index 00000000..692a129b --- /dev/null +++ b/src/Titano.Core/Metadata/MakerNotes/SonyMakerNote.cs @@ -0,0 +1,46 @@ +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.MakerNotes; + +/// Sony MakerNote ("SONY DSC/CAM" 12-byte header or headerless; offsets relative to the Exif TIFF). +/// Lens: the unencrypted LensSpec (BCD focal/aperture range); numeric LensType tables are not shipped. +internal static class SonyMakerNote +{ + private const ushort ColorTemperature = 0xB021; + private const ushort ImageStabilization = 0xB026; + private const ushort LensSpec = 0xB02A; + + public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m) + { + var v = m.MakerNote; + if (ifd.Entries.TryGetValue(LensSpec, out var spec) && spec.Count == 8 && r.ReadBytes(spec) is { } bytes) + v.LensModel ??= DecodeLensSpec(bytes); + v.ColorTemperature ??= IfdValue.UInt(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? (int)kelvin : null; + v.ImageStabilization ??= IfdValue.UInt(r, ifd, ImageStabilization) switch + { + 0 => false, + 1 => true, + _ => null, + }; + } + + /// Bytes 1–2 short focal, 3–4 long focal (BCD mm), 5–6 apertures (BCD ×10); flags 0 and 7 are not decoded. + private static string? DecodeLensSpec(ReadOnlySpan s) + { + if (!TryBcd(s.Slice(1, 2), out var minFocal) || !TryBcd(s.Slice(3, 2), out var maxFocal) + || !TryBcd(s.Slice(5, 1), out var minAperture) || !TryBcd(s.Slice(6, 1), out var maxAperture) || minFocal == 0) + return null; + return MakerNoteParser.FormatLens(minFocal, maxFocal, minAperture / 10.0, maxAperture / 10.0, "F"); + } + + private static bool TryBcd(ReadOnlySpan bytes, out int value) + { + value = 0; + foreach (var b in bytes) + { + if (b >> 4 > 9 || (b & 0xF) > 9) return false; + value = value * 100 + (b >> 4) * 10 + (b & 0xF); + } + return true; + } +} diff --git a/src/Titano.Core/Metadata/Tiff/ExifParser.cs b/src/Titano.Core/Metadata/Tiff/ExifParser.cs new file mode 100644 index 00000000..a0ba6fa8 --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/ExifParser.cs @@ -0,0 +1,247 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Tiff; + +/// +/// Maps TIFF/Exif structures onto a : IFD0, Exif IFD, GPS IFD, MakerNote, the 0x02BC XMP +/// packet, raster IFDs (main-image selection across the IFD chain and SubIFDs) and embedded JPEG previews. +/// +internal static class ExifParser +{ + private const int MaxImageIfds = 64; + private const int MaxSubIfdDepth = 4; + private const uint MaxSubIfdsPerIfd = 16; + private const uint PhotometricCfa = 32803; + private const uint PhotometricLinearRaw = 34892; + + // Panasonic RW2/RWL IFD0 (PanasonicRaw) tags. + private const ushort PanasonicSensorWidth = 0x0002; + private const ushort PanasonicSensorHeight = 0x0003; + private const ushort PanasonicSensorTop = 0x0004; + private const ushort PanasonicSensorLeft = 0x0005; + private const ushort PanasonicSensorBottom = 0x0006; + private const ushort PanasonicSensorRight = 0x0007; + private const ushort PanasonicBitsPerSample = 0x000A; + private const ushort PanasonicIso = 0x0017; + private const ushort PanasonicJpgFromRaw = 0x002E; + + /// Parses a TIFF-based file (TIFF, DNG, TIFF-like RAWs) whose header is at offset 0. + public static void ParseFile(MetadataBuilder m) => Walk(m, 0, isFile: true); + + /// Parses an Exif TIFF block embedded in another container (JPEG APP1, PNG eXIf, WebP EXIF, HEIF item…). + /// Its IFD1 thumbnail is reported as a preview; raster IFDs do not compete for the main image size. + public static void ParseEmbedded(MetadataBuilder m, long tiffBase) => Walk(m, tiffBase, isFile: false); + + /// Exif data prefixed by a 4-byte big-endian TIFF-header offset (HEIF Exif item, JPEG XL Exif box). + /// Falls back to searching the first bytes for a TIFF header when the offset is wrong. + public static void ParseOffsetPrefixed(MetadataBuilder m, long start, long length) + { + Span head = stackalloc byte[40]; + var n = m.Stream.ReadUpTo(start, head[..(int)Math.Min(head.Length, Math.Max(0, length))]); + if (n < 12) + { + m.Warn("Exif item too short"); + return; + } + var declared = BinaryPrimitives.ReadUInt32BigEndian(head); + if (declared < length - 12 && TiffReader.Open(m.Stream, start + 4 + declared) is not null) + { + ParseEmbedded(m, start + 4 + declared); + return; + } + for (var i = 4; i + 4 <= n; i++) + { + if (head[i..].StartsWith("II*\0"u8) || head[i..].StartsWith("MM\0*"u8)) + { + ParseEmbedded(m, start + i); + return; + } + } + m.Warn("Exif item has no TIFF header"); + } + + /// IFD0 fields plus the Exif and GPS sub-IFDs it points to. + public static void ReadTree(TiffReader r, Ifd ifd0, MetadataBuilder m, HashSet visited) + { + ReadIfd0(r, ifd0, m); + if (Pointer(r, ifd0, TiffTags.ExifIfd, visited) is { } exif) ReadExif(r, exif, m); + if (Pointer(r, ifd0, TiffTags.GpsIfd, visited) is { } gps) ReadGps(r, gps, m); + } + + /// Camera identity, authorship, orientation, rating and XMP from IFD0. + public static void ReadIfd0(TiffReader r, Ifd ifd, MetadataBuilder m) + { + m.Make ??= IfdValue.String(r, ifd, TiffTags.Make); + m.Model ??= IfdValue.String(r, ifd, TiffTags.Model); + m.Software ??= IfdValue.String(r, ifd, TiffTags.Software); + m.Artist ??= IfdValue.String(r, ifd, TiffTags.Artist); + m.Copyright ??= IfdValue.String(r, ifd, TiffTags.Copyright); + m.ExifOrientation ??= IfdValue.Int(r, ifd, TiffTags.Orientation); + m.ExifRating ??= IfdValue.Int(r, ifd, TiffTags.Rating); + if (ifd.Entries.TryGetValue(TiffTags.Xmp, out var xmp)) m.AddXmp(r.ReadBytes(xmp, XmpParser.MaxPacketBytes)); + } + + /// Exposure, capture time, lens/body identity and the MakerNote from an Exif IFD. + public static void ReadExif(TiffReader r, Ifd ifd, MetadataBuilder m) + { + m.ExposureTime ??= Positive(IfdValue.Double(r, ifd, TiffTags.ExposureTime)) + ?? (IfdValue.Double(r, ifd, TiffTags.ShutterSpeedValue) is { } tv and > -32 and < 32 ? Math.Pow(2, -tv) : (double?)null); + m.FNumber ??= Positive(IfdValue.Double(r, ifd, TiffTags.FNumber)) + ?? (IfdValue.Double(r, ifd, TiffTags.ApertureValue) is { } av and >= 0 and < 64 ? Math.Pow(2, av / 2) : (double?)null); + m.IsoSpeedRatings ??= IfdValue.Int(r, ifd, TiffTags.IsoSpeedRatings); + m.IsoFallback ??= IfdValue.Int(r, ifd, TiffTags.RecommendedExposureIndex) + ?? IfdValue.Int(r, ifd, TiffTags.StandardOutputSensitivity) + ?? IfdValue.Int(r, ifd, TiffTags.IsoSpeed); + var commonOffset = IfdValue.String(r, ifd, TiffTags.OffsetTime); + m.DateTimeOriginal ??= Stamp(r, ifd, TiffTags.DateTimeOriginal, TiffTags.SubSecTimeOriginal, TiffTags.OffsetTimeOriginal, commonOffset); + m.DateTimeDigitized ??= Stamp(r, ifd, TiffTags.DateTimeDigitized, TiffTags.SubSecTimeDigitized, TiffTags.OffsetTimeDigitized, commonOffset); + m.FocalLength ??= Positive(IfdValue.Double(r, ifd, TiffTags.FocalLength)); + m.FocalLength35 ??= Positive(IfdValue.Double(r, ifd, TiffTags.FocalLengthIn35mmFilm)); + m.ExposureBias ??= IfdValue.Double(r, ifd, TiffTags.ExposureBiasValue) is { } bias and > -64 and < 64 ? bias : (double?)null; + m.ExposureProgram ??= IfdValue.Int(r, ifd, TiffTags.ExposureProgram); + m.MeteringMode ??= IfdValue.Int(r, ifd, TiffTags.MeteringMode); + m.WhiteBalanceMode ??= IfdValue.Int(r, ifd, TiffTags.WhiteBalance); + m.Flash ??= IfdValue.Int(r, ifd, TiffTags.Flash); + m.PixelXDimension ??= IfdValue.Int(r, ifd, TiffTags.PixelXDimension); + m.PixelYDimension ??= IfdValue.Int(r, ifd, TiffTags.PixelYDimension); + m.BodySerial ??= IfdValue.String(r, ifd, TiffTags.BodySerialNumber); + m.LensModel ??= IfdValue.String(r, ifd, TiffTags.LensModel); + if (ifd.Entries.TryGetValue(TiffTags.MakerNote, out var makerNote)) MakerNoteParser.Parse(r, makerNote, m); + } + + /// Position (status "V" = void is ignored), altitude and the UTC date/time stamp from a GPS IFD. + public static void ReadGps(TiffReader r, Ifd ifd, MetadataBuilder m) + { + if (m.Gps is null && IfdValue.String(r, ifd, TiffTags.GpsStatus) != "V" + && Degrees(r, ifd, TiffTags.GpsLatitude, TiffTags.GpsLatitudeRef, 'S', 90) is { } lat + && Degrees(r, ifd, TiffTags.GpsLongitude, TiffTags.GpsLongitudeRef, 'W', 180) is { } lon) + { + var altitude = IfdValue.Double(r, ifd, TiffTags.GpsAltitude) is { } alt and >= 0 and < 1e6 + ? IfdValue.Int(r, ifd, TiffTags.GpsAltitudeRef) == 1 ? -alt : alt + : (double?)null; + m.Gps = new GpsPosition(lat, lon, altitude, null); + } + if (m.GpsUtc is null + && MetadataDates.ParseDate(IfdValue.String(r, ifd, TiffTags.GpsDateStamp)) is { } date + && IfdValue.Doubles(r, ifd, TiffTags.GpsTimeStamp, 3) is [var h, var min, var sec, ..] + && h is >= 0 and < 24 && min is >= 0 and < 60 && sec is >= 0 and < 61) + { + m.GpsUtc = DateTime.SpecifyKind(date.AddSeconds(h * 3600 + min * 60 + sec), DateTimeKind.Utc); + } + } + + private static void Walk(MetadataBuilder m, long tiffBase, bool isFile) + { + var r = TiffReader.Open(m.Stream, tiffBase); + if (r is null) + { + m.Warn(isFile ? "TIFF header not found" : "Exif TIFF header not found"); + return; + } + var chain = r.ReadChain(); + if (chain.Count == 0) + { + m.Warn("No readable IFD"); + } + else + { + var visited = new HashSet(); + foreach (var ifd in chain) visited.Add(ifd.Position); + ReadTree(r, chain[0], m, visited); + if (isFile && m.Format is ImageFileFormat.Rw2 or ImageFileFormat.Rwl or ImageFileFormat.Raw) ReadPanasonicRaw(r, chain[0], m); + var budget = MaxImageIfds; + foreach (var ifd in chain) VisitImage(r, ifd, m, visited, 0, isFile, ref budget); + // DNG CameraSerialNumber ranks after Exif BodySerialNumber and before the MakerNote. + if (isFile) m.BodySerial ??= IfdValue.String(r, chain[0], TiffTags.CameraSerialNumber); + } + m.AddWarnings(r.Warnings); + } + + /// Raster candidate, embedded previews and SubIFDs (depth- and count-capped) of one image IFD. + private static void VisitImage(TiffReader r, Ifd ifd, MetadataBuilder m, HashSet visited, int depth, bool isFile, ref int budget) + { + if (--budget < 0) return; + m.ThrowIfCancelled(); + if (isFile) + { + var width = IfdValue.Int(r, ifd, TiffTags.ImageWidth) ?? 0; + var height = IfdValue.Int(r, ifd, TiffTags.ImageLength) ?? 0; + var primary = ((IfdValue.UInt(r, ifd, TiffTags.NewSubfileType) ?? 0) & 1) == 0; + m.AddRaster(width, height, IfdValue.Int(r, ifd, TiffTags.BitsPerSample), primary); + } + AddPreviews(r, ifd, m, isFile); + if (depth >= MaxSubIfdDepth || !ifd.Entries.TryGetValue(TiffTags.SubIfds, out var sub) || sub.Count > MaxSubIfdsPerIfd) return; + foreach (var offset in r.GetUInts(sub) ?? []) + { + if (r.ReadIfd(offset, visited) is { } child) VisitImage(r, child, m, visited, depth + 1, isFile, ref budget); + } + } + + /// JPEGInterchangeFormat thumbnails/previews and single-strip/tile JPEG images (Compression 6/7, not CFA). + private static void AddPreviews(TiffReader r, Ifd ifd, MetadataBuilder m, bool isFile) + { + if (IfdValue.UInt(r, ifd, TiffTags.JpegInterchangeFormat) is { } offset and > 0 + && IfdValue.UInt(r, ifd, TiffTags.JpegInterchangeFormatLength) is { } length and > 0) + { + JpegParser.AddPreview(m, r.Base + offset, length); + } + if (IfdValue.UInt(r, ifd, TiffTags.Compression) is not (6 or 7) + || IfdValue.UInt(r, ifd, TiffTags.PhotometricInterpretation) is PhotometricCfa or PhotometricLinearRaw) + return; + var (offsetTag, countTag) = ifd.Has(TiffTags.StripOffsets) + ? (TiffTags.StripOffsets, TiffTags.StripByteCounts) + : (TiffTags.TileOffsets, TiffTags.TileByteCounts); + if (ifd.Entries.TryGetValue(offsetTag, out var e) && e.Count == 1 + && IfdValue.UInt(r, ifd, offsetTag) is { } dataOffset + && IfdValue.UInt(r, ifd, countTag) is { } dataLength and > 0 + && JpegParser.AddPreview(m, r.Base + dataOffset, dataLength) is { Lossless: true } raw + && isFile) + { + m.CodedBitsPerSample ??= raw.Precision; + } + } + + /// Panasonic RW2 header: sensor crop size, bit depth, ISO and the JpgFromRaw that carries the Exif block. + private static void ReadPanasonicRaw(TiffReader r, Ifd ifd0, MetadataBuilder m) + { + var top = IfdValue.Int(r, ifd0, PanasonicSensorTop) ?? 0; + var left = IfdValue.Int(r, ifd0, PanasonicSensorLeft) ?? 0; + var bottom = IfdValue.Int(r, ifd0, PanasonicSensorBottom) ?? 0; + var right = IfdValue.Int(r, ifd0, PanasonicSensorRight) ?? 0; + var (width, height) = right > left && bottom > top + ? (right - left, bottom - top) + : (IfdValue.Int(r, ifd0, PanasonicSensorWidth) ?? 0, IfdValue.Int(r, ifd0, PanasonicSensorHeight) ?? 0); + m.SetContainerSize(width, height, IfdValue.Int(r, ifd0, PanasonicBitsPerSample)); + m.IsoFallback ??= IfdValue.Int(r, ifd0, PanasonicIso); + if (ifd0.Entries.TryGetValue(PanasonicJpgFromRaw, out var jpeg) && !jpeg.IsInline) + { + var start = jpeg.ValuePosition(r.Base); + JpegParser.Parse(m, start, start + jpeg.ByteLength, primary: false); + } + } + + private static Ifd? Pointer(TiffReader r, Ifd ifd, ushort tag, HashSet visited) => + IfdValue.UInt(r, ifd, tag) is { } offset and > 0 ? r.ReadIfd(offset, visited) : null; + + private static CaptureStamp? Stamp(TiffReader r, Ifd ifd, ushort dateTag, ushort subSecTag, ushort offsetTag, string? fallbackOffset) + { + if (MetadataDates.ParseExif(IfdValue.String(r, ifd, dateTag)) is not { } value) return null; + var ticks = MetadataDates.SubSecondTicks(IfdValue.String(r, ifd, subSecTag)); + var offset = MetadataDates.ParseOffset(IfdValue.String(r, ifd, offsetTag)) ?? MetadataDates.ParseOffset(fallbackOffset); + return new CaptureStamp(value.AddTicks(ticks), offset); + } + + private static double? Degrees(TiffReader r, Ifd ifd, ushort tag, ushort refTag, char negative, double limit) + { + if (IfdValue.Doubles(r, ifd, tag, 3) is not [var d, var min, var sec, ..]) return null; + var value = d + min / 60 + sec / 3600; + if (!(value >= 0 && value <= limit)) return null; + return IfdValue.String(r, ifd, refTag) is { Length: > 0 } reference && char.ToUpperInvariant(reference[0]) == negative ? -value : value; + } + + private static double? Positive(double? value) => value is > 0 ? value : null; +} diff --git a/src/Titano.Core/Metadata/Tiff/IfdValue.cs b/src/Titano.Core/Metadata/Tiff/IfdValue.cs new file mode 100644 index 00000000..53c7f14c --- /dev/null +++ b/src/Titano.Core/Metadata/Tiff/IfdValue.cs @@ -0,0 +1,45 @@ +namespace Titano.Core.Metadata.Tiff; + +/// Single-value accessors over that refuse oversized counts, so a corrupt +/// count can never trigger a large read when only the first value is needed. +internal static class IfdValue +{ + /// Largest value count read for scalar/array tags (GPS triples, lens info, Canon camera settings…). + public const uint MaxCount = 256; + + public static uint? UInt(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && e.Count is > 0 and <= MaxCount && r.GetUInts(e) is [var v, ..] ? v : null; + + public static int? Int(TiffReader r, Ifd ifd, ushort tag) => UInt(r, ifd, tag) is { } v && v <= int.MaxValue ? (int)v : null; + + public static uint[]? UInts(TiffReader r, Ifd ifd, ushort tag) => + ifd.Entries.TryGetValue(tag, out var e) && e.Count is > 0 and <= MaxCount ? r.GetUInts(e) : null; + + /// First value as a finite double (rationals divided). + public static double? Double(TiffReader r, Ifd ifd, ushort tag) => Doubles(r, ifd, tag, 1) is [var v, ..] ? v : null; + + /// All values when at least are present and every one is finite. + public static double[]? Doubles(TiffReader r, Ifd ifd, ushort tag, int minCount) + { + if (!ifd.Entries.TryGetValue(tag, out var e) || e.Count < minCount || e.Count > MaxCount) return null; + var values = r.GetDoubles(e); + if (values is null) return null; + foreach (var v in values) + { + if (!double.IsFinite(v)) return null; + } + return values; + } + + /// Text value with control characters removed; null when empty. + public static string? String(TiffReader r, Ifd ifd, ushort tag) + { + var s = r.GetString(ifd, tag); + if (s is null) return null; + if (s.AsSpan().IndexOfAnyInRange('\0', '\u001F') >= 0) + { + s = string.Concat(s.Where(c => !char.IsControl(c))).Trim(); + } + return s.Length == 0 ? null : s; + } +} diff --git a/src/Titano.Core/Metadata/Tiff/TiffTags.cs b/src/Titano.Core/Metadata/Tiff/TiffTags.cs index e279e5a1..a1ca5a26 100644 --- a/src/Titano.Core/Metadata/Tiff/TiffTags.cs +++ b/src/Titano.Core/Metadata/Tiff/TiffTags.cs @@ -37,6 +37,7 @@ public static class TiffTags public const ushort JpegInterchangeFormat = 0x0201; public const ushort JpegInterchangeFormatLength = 0x0202; public const ushort YCbCrSubSampling = 0x0212; + public const ushort YCbCrPositioning = 0x0213; public const ushort Rating = 0x4746; public const ushort Xmp = 0x02BC; public const ushort Copyright = 0x8298; @@ -50,7 +51,9 @@ public static class TiffTags public const ushort ExposureProgram = 0x8822; public const ushort IsoSpeedRatings = 0x8827; public const ushort SensitivityType = 0x8830; + public const ushort StandardOutputSensitivity = 0x8831; public const ushort RecommendedExposureIndex = 0x8832; + public const ushort IsoSpeed = 0x8833; public const ushort ExifVersion = 0x9000; public const ushort DateTimeOriginal = 0x9003; public const ushort DateTimeDigitized = 0x9004; @@ -78,6 +81,7 @@ public static class TiffTags public const ushort LensModel = 0xA434; // GPS + public const ushort GpsVersionId = 0x0000; public const ushort GpsLatitudeRef = 0x0001; public const ushort GpsLatitude = 0x0002; public const ushort GpsLongitudeRef = 0x0003; @@ -85,6 +89,7 @@ public static class TiffTags public const ushort GpsAltitudeRef = 0x0005; public const ushort GpsAltitude = 0x0006; public const ushort GpsTimeStamp = 0x0007; + public const ushort GpsStatus = 0x0009; public const ushort GpsDateStamp = 0x001D; // DNG From 28c4d5ca7fa0ce26b6e1e46446294e2079023616 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:21 +0000 Subject: [PATCH 061/188] feat(metadata): add ISO-BMFF walker with HEIF and CR3 parsers BmffReader reads box headers only (32/64-bit and to-end sizes, uuid user types, per-container count and path depth caps). HeifParser handles hdlr/pitm/iinf (infe v2/v3)/iloc (v0-v2, multi-extent, idat)/ iprp: size from the primary item's ispe, bit depth from pixi, Exif and XMP items; irot/imir define the orientation and override Exif because HEIF decoders apply them. Cr3Parser reads CMT1-4 and THMB from the Canon uuid box, PRVW, the XMP uuid, track 1's full-size JPEG through the sample tables and the raw size from the CRAW/CMP1 header. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Metadata/Bmff/BmffReader.cs | 127 +++++++++ src/Titano.Core/Metadata/Bmff/Cr3Parser.cs | 158 +++++++++++ src/Titano.Core/Metadata/Bmff/HeifParser.cs | 282 ++++++++++++++++++++ 3 files changed, 567 insertions(+) create mode 100644 src/Titano.Core/Metadata/Bmff/BmffReader.cs create mode 100644 src/Titano.Core/Metadata/Bmff/Cr3Parser.cs create mode 100644 src/Titano.Core/Metadata/Bmff/HeifParser.cs diff --git a/src/Titano.Core/Metadata/Bmff/BmffReader.cs b/src/Titano.Core/Metadata/Bmff/BmffReader.cs new file mode 100644 index 00000000..8f57a992 --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/BmffReader.cs @@ -0,0 +1,127 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Metadata.Bmff; + +/// One ISO-BMFF box header: four-character type, absolute start, total size and header size +/// (8, 16 with a 64-bit size, plus 16 for a uuid user type). +public readonly record struct BmffBox(uint Type, long Start, long Size, int HeaderSize, Guid UserType) +{ + public long End => Start + Size; + public long PayloadStart => Start + HeaderSize; + public long PayloadLength => Size - HeaderSize; + + public bool Is(string fourCC) => Type == FourCC.From(fourCC); + + public override string ToString() => $"{FourCC.Format(Type)} @{Start} ({Size} bytes)"; +} + +/// Four-character codes as big-endian 32-bit integers. +public static class FourCC +{ + public static uint From(ReadOnlySpan code) + { + if (code.Length != 4) throw new ArgumentException("A four-character code has exactly four characters.", nameof(code)); + return (uint)(byte)code[0] << 24 | (uint)(byte)code[1] << 16 | (uint)(byte)code[2] << 8 | (byte)code[3]; + } + + public static string Format(uint code) => + string.Create(4, code, static (span, c) => + { + for (var i = 0; i < 4; i++) + { + var b = (char)((c >> (24 - 8 * i)) & 0xFF); + span[i] = b is >= ' ' and <= '~' ? b : '?'; + } + }); +} + +/// +/// Fuzz-safe ISO-BMFF box walker over a seekable stream: 32-bit, 64-bit (largesize) and to-end (size 0) boxes, +/// uuid user types, a cap on boxes per container and on descent depth. Only headers are read. +/// +public static class BmffReader +{ + public const int MaxBoxesPerContainer = 4096; + public const int MaxDepth = 16; + + private static readonly uint Uuid = FourCC.From("uuid"); + + /// Box headers inside [, ). Stops at the first malformed header; + /// a box running past is clamped so truncated files still expose their leading boxes. + public static IReadOnlyList ReadChildren(Stream stream, long start, long end, ICollection? warnings = null) + { + ArgumentNullException.ThrowIfNull(stream); + var boxes = new List(); + end = Math.Min(end, stream.Length); + Span h = stackalloc byte[32]; + var pos = Math.Max(0, start); + while (pos <= end - 8) + { + if (boxes.Count == MaxBoxesPerContainer) + { + warnings?.Add($"More than {MaxBoxesPerContainer} boxes at {start}; rest ignored"); + break; + } + var n = stream.ReadUpTo(pos, h[..(int)Math.Min(h.Length, end - pos)]); + if (n < 8) break; + long size = BinaryPrimitives.ReadUInt32BigEndian(h); + var type = BinaryPrimitives.ReadUInt32BigEndian(h[4..]); + var header = 8; + if (size == 1) + { + if (n < 16) break; + size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(h[8..]), long.MaxValue); + header = 16; + } + else if (size == 0) + { + size = end - pos; + } + var userType = Guid.Empty; + if (type == Uuid) + { + if (n < header + 16) break; + userType = new Guid(h.Slice(header, 16), bigEndian: true); + header += 16; + } + if (size < header) + { + warnings?.Add($"Malformed box header at {pos}"); + break; + } + if (size > end - pos) + { + warnings?.Add($"Box '{FourCC.Format(type)}' at {pos} runs past its container"); + size = end - pos; + } + boxes.Add(new BmffBox(type, pos, size, header, userType)); + pos += size; + } + return boxes; + } + + /// First box of in , or null. + public static BmffBox? Find(IReadOnlyList boxes, string type) + { + var code = FourCC.From(type); + foreach (var b in boxes) + { + if (b.Type == code) return b; + } + return null; + } + + /// Follows a path of plain (non-full) container boxes from 's payload, + /// taking the first match at each level. + public static BmffBox? FindPath(Stream stream, BmffBox parent, params ReadOnlySpan path) + { + if (path.Length > MaxDepth) throw new ArgumentException($"Paths are limited to {MaxDepth} levels.", nameof(path)); + BmffBox? current = parent; + foreach (var type in path) + { + if (current is not { } box) return null; + current = Find(ReadChildren(stream, box.PayloadStart, box.End), type); + } + return current; + } +} diff --git a/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs b/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs new file mode 100644 index 00000000..a02d63ce --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/Cr3Parser.cs @@ -0,0 +1,158 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.MakerNotes; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Bmff; + +/// +/// Canon CR3 (ISO-BMFF, brand crx ): the Canon uuid box in moov holds CMT1 (IFD0), CMT2 (Exif IFD), +/// CMT3 (Canon MakerNote), CMT4 (GPS IFD) as little TIFF files plus the THMB thumbnail; a top-level uuid holds the +/// PRVW preview and another the XMP packet. Track 1's first sample is the full-size JPEG; the main size and bit depth come +/// from the largest raw track (CRAW sample entry with a CMP1 header), else from CMT1. +/// +internal static class Cr3Parser +{ + private static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48"); + private static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16"); + private static readonly Guid XmpUuid = new("be7acfcb-97a9-42e8-9c71-999491e3afac"); + + /// Offset of the child boxes inside a CRAW visual sample entry (8-byte header + 78 bytes of fields). + private const int CrawChildrenOffset = 86; + + /// The JPEG of THMB and PRVW starts within this many bytes of the box payload. + private const int JpegSearchBytes = 32; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + var warnings = new List(); + var top = BmffReader.ReadChildren(s, 0, m.Length, warnings); + var trackIndex = 0; + (int Width, int Height, int Bits) raw = default; + foreach (var box in top) + { + m.ThrowIfCancelled(); + if (box.Is("moov")) + { + foreach (var child in BmffReader.ReadChildren(s, box.PayloadStart, box.End, warnings)) + { + m.ThrowIfCancelled(); + if (child.Is("uuid") && child.UserType == CanonUuid) ReadCanonBox(m, child, warnings); + else if (child.Is("trak")) ReadTrack(m, child, trackIndex++ == 0, ref raw); + } + } + else if (box.Is("uuid") && box.UserType == PreviewUuid) + { + ReadPreviewBox(m, box); + } + else if (box.Is("uuid") && box.UserType == XmpUuid) + { + m.AddXmp(s.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes)); + } + } + m.AddWarnings(warnings); + if (raw.Width > 0) m.SetContainerSize(raw.Width, raw.Height, raw.Bits > 0 ? raw.Bits : null); + } + + private static void ReadCanonBox(MetadataBuilder m, BmffBox canon, List warnings) + { + foreach (var box in BmffReader.ReadChildren(m.Stream, canon.PayloadStart, canon.End, warnings)) + { + if (box.Is("THMB")) + { + AddJpeg(m, box); + continue; + } + if (!(box.Is("CMT1") || box.Is("CMT2") || box.Is("CMT3") || box.Is("CMT4"))) continue; + var r = TiffReader.Open(m.Stream, box.PayloadStart); + if (r?.ReadIfd(r.FirstIfdOffset) is not { } ifd) + { + m.Warn($"CR3 {FourCC.Format(box.Type)} is not a TIFF block"); + continue; + } + if (box.Is("CMT1")) + { + ExifParser.ReadIfd0(r, ifd, m); + m.AddRaster(IfdValue.Int(r, ifd, TiffTags.ImageWidth) ?? 0, IfdValue.Int(r, ifd, TiffTags.ImageLength) ?? 0, null, true); + } + else if (box.Is("CMT2")) + { + ExifParser.ReadExif(r, ifd, m); + } + else if (box.Is("CMT3")) + { + CanonMakerNote.Parse(r, ifd, m); + } + else + { + ExifParser.ReadGps(r, ifd, m); + } + m.AddWarnings(r.Warnings); + } + } + + /// Track 1's first sample is the full-size JPEG; any track whose CRAW entry has a CMP1 header is raw data. + private static void ReadTrack(MetadataBuilder m, BmffBox trak, bool first, ref (int Width, int Height, int Bits) raw) + { + var s = m.Stream; + if (BmffReader.FindPath(s, trak, "mdia", "minf", "stbl") is not { } stbl) return; + var tables = BmffReader.ReadChildren(s, stbl.PayloadStart, stbl.End); + if (BmffReader.Find(tables, "stsd") is { } stsd && FirstSampleEntry(s, stsd) is { } entry && entry.Is("CRAW") + && BmffReader.Find(BmffReader.ReadChildren(s, entry.Start + CrawChildrenOffset, entry.End), "CMP1") is { } cmp1) + { + // CMP1 (big-endian): +8 width, +12 height, +24 bits per sample. + Span h = stackalloc byte[25]; + if (s.TryReadAt(cmp1.PayloadStart, h)) + { + var width = BinaryPrimitives.ReadInt32BigEndian(h[8..]); + var height = BinaryPrimitives.ReadInt32BigEndian(h[12..]); + if (width > 0 && height > 0 && (long)width * height > (long)raw.Width * raw.Height) raw = (width, height, h[24]); + } + } + if (first && FirstSample(s, tables) is { } sample) JpegParser.AddPreview(m, sample.Offset, sample.Length, PreviewKind.FullSize); + } + + private static BmffBox? FirstSampleEntry(Stream s, BmffBox stsd) => + BmffReader.ReadChildren(s, stsd.PayloadStart + 8, stsd.End) is [var entry, ..] ? entry : null; + + /// Offset (stco/co64) and size (stsz) of a track's first sample. + private static (long Offset, long Length)? FirstSample(Stream s, IReadOnlyList tables) + { + Span b = stackalloc byte[16]; + if (BmffReader.Find(tables, "stsz") is not { } stsz || !s.TryReadAt(stsz.PayloadStart, b)) return null; + long size = BinaryPrimitives.ReadUInt32BigEndian(b[4..]); + if (size == 0) size = BinaryPrimitives.ReadUInt32BigEndian(b[8..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[12..]) : 0; + long offset; + if (BmffReader.Find(tables, "co64") is { } co64 && s.TryReadAt(co64.PayloadStart, b)) + offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(b[8..]), long.MaxValue) : 0; + else if (BmffReader.Find(tables, "stco") is { } stco && s.TryReadAt(stco.PayloadStart, b[..12])) + offset = BinaryPrimitives.ReadUInt32BigEndian(b[4..]) > 0 ? BinaryPrimitives.ReadUInt32BigEndian(b[8..]) : 0; + else + return null; + return offset > 0 && size > 0 ? (offset, size) : null; + } + + /// The preview uuid holds 8 bytes of header fields, then a PRVW box. + private static void ReadPreviewBox(MetadataBuilder m, BmffBox uuid) + { + if (BmffReader.Find(BmffReader.ReadChildren(m.Stream, uuid.PayloadStart + 8, uuid.End), "PRVW") is { } prvw) AddJpeg(m, prvw); + else m.Warn("CR3 PRVW box not found"); + } + + /// THMB/PRVW: a few header fields (version, size, dimensions) followed by the JPEG to the end of the box. + private static void AddJpeg(MetadataBuilder m, BmffBox box) + { + Span head = stackalloc byte[JpegSearchBytes]; + var n = m.Stream.ReadUpTo(box.PayloadStart, head[..(int)Math.Min(head.Length, box.PayloadLength)]); + var at = head[..n].IndexOf([(byte)0xFF, (byte)0xD8, (byte)0xFF]); + if (at < 0) + { + m.Warn($"CR3 {FourCC.Format(box.Type)} holds no JPEG"); + return; + } + var start = box.PayloadStart + at; + JpegParser.AddPreview(m, start, box.End - start); + } +} diff --git a/src/Titano.Core/Metadata/Bmff/HeifParser.cs b/src/Titano.Core/Metadata/Bmff/HeifParser.cs new file mode 100644 index 00000000..b29c5c70 --- /dev/null +++ b/src/Titano.Core/Metadata/Bmff/HeifParser.cs @@ -0,0 +1,282 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Bmff; + +/// +/// HEIF / HEIC / AVIF: meta → hdlr, pitm, iinf/infe (v2/v3), iloc (v0–v2), +/// iprp/ipco/ipma. Main size from the primary item's ispe, bit depth from pixi, +/// Exif from the Exif item and XMP from the application/rdf+xml mime item. +/// +/// +/// Orientation rule: when the primary item carries irot and/or imir, their composition (in association +/// order) defines and the Exif orientation is ignored — HEIF decoders apply those +/// transforms themselves (ISO/IEC 23008-12), so honouring Exif as well would rotate twice. Without them, Exif applies. +/// imir axis 0 mirrors top↔bottom and axis 1 left↔right (23008-12 2nd edition, as libheif). +/// +internal static class HeifParser +{ + private const int MaxPropertyBytes = 64; + private const int MaxTableBytes = 1024 * 1024; + private const int MaxInfeBytes = 4096; + private const int MaxExtentsPerItem = 1024; + private static readonly uint Exif = FourCC.From("Exif"); + private static readonly uint Mime = FourCC.From("mime"); + + // Exif orientations 1–8 as integer matrices (a, b, c, d) mapping stored (x, y) to displayed (ax + by, cx + dy), y down. + private static readonly (int A, int B, int C, int D)[] Orientations = + [ + (1, 0, 0, 1), (-1, 0, 0, 1), (-1, 0, 0, -1), (1, 0, 0, -1), + (0, 1, 1, 0), (0, -1, 1, 0), (0, -1, -1, 0), (0, 1, -1, 0), + ]; + + public static void Parse(MetadataBuilder m) + { + var warnings = new List(); + var meta = BmffReader.Find(BmffReader.ReadChildren(m.Stream, 0, m.Length, warnings), "meta"); + m.AddWarnings(warnings); + if (meta is { } box) ParseMeta(m, box); + else m.Warn("HEIF meta box not found"); + } + + private static void ParseMeta(MetadataBuilder m, BmffBox meta) + { + var s = m.Stream; + var warnings = new List(); + var children = BmffReader.ReadChildren(s, meta.PayloadStart + 4, meta.End, warnings); + var items = new Dictionary(); + uint? primary = null; + BmffBox? iprp = null; + long idat = -1; + foreach (var child in children) + { + m.ThrowIfCancelled(); + if (child.Is("hdlr")) CheckHandler(m, child); + else if (child.Is("pitm")) primary = ReadPrimary(s, child); + else if (child.Is("iinf")) ReadItemInfo(m, child, items, warnings); + else if (child.Is("iloc")) ReadLocations(m, child, items); + else if (child.Is("iprp")) iprp = child; + else if (child.Is("idat")) idat = child.PayloadStart; + } + m.AddWarnings(warnings); + if (primary is { } id && iprp is { } properties) ReadPrimaryProperties(m, properties, id); + else m.Warn("HEIF primary item or properties missing"); + + foreach (var item in items.Values) + { + if (item.ConstructionMethod == 1 && idat < 0) continue; + var origin = item.ConstructionMethod == 1 ? idat : 0; + if (item.Type == Exif) ReadExifItem(m, item, origin); + else if (item.Type == Mime && item.ContentType == "application/rdf+xml") ReadXmpItem(m, item, origin); + } + } + + private static void CheckHandler(MetadataBuilder m, BmffBox hdlr) + { + Span b = stackalloc byte[12]; + if (!m.Stream.TryReadAt(hdlr.PayloadStart, b) || !b[8..].SequenceEqual("pict"u8)) m.Warn("HEIF handler is not 'pict'"); + } + + private static uint? ReadPrimary(Stream s, BmffBox pitm) + { + Span b = stackalloc byte[8]; + var n = s.ReadUpTo(pitm.PayloadStart, b[..(int)Math.Min(b.Length, pitm.PayloadLength)]); + if (n < 6) return null; + return b[0] == 0 ? BinaryPrimitives.ReadUInt16BigEndian(b[4..]) : n >= 8 ? BinaryPrimitives.ReadUInt32BigEndian(b[4..]) : null; + } + + /// iinf → infe v2/v3: item id, type and (for mime items) content type. Earlier infe versions carry no type. + private static void ReadItemInfo(MetadataBuilder m, BmffBox iinf, Dictionary items, List warnings) + { + Span head = stackalloc byte[1]; + if (!m.Stream.TryReadAt(iinf.PayloadStart, head)) return; + var first = iinf.PayloadStart + (head[0] == 0 ? 6 : 8); + foreach (var infe in BmffReader.ReadChildren(m.Stream, first, iinf.End, warnings)) + { + m.ThrowIfCancelled(); + if (!infe.Is("infe") || m.Stream.ReadAt(infe.PayloadStart, Math.Min(infe.PayloadLength, MaxInfeBytes), MaxInfeBytes) is not { } data) continue; + var r = new SpanReader(data); + var version = r.U8(); + r.Skip(3); + if (version < 2) continue; + var id = version == 2 ? r.U16() : r.U32(); + r.Skip(2); + var type = r.U32(); + if (!r.Ok) continue; + r.CString(); + var item = Get(items, id); + item.Type = type; + if (type == Mime && r.Remaining > 0) item.ContentType = r.CString(); + } + } + + /// iloc v0–v2: offset/length/base-offset/index field sizes, construction methods 0 (file) and 1 (idat), + /// any number of extents. + private static void ReadLocations(MetadataBuilder m, BmffBox iloc, Dictionary items) + { + if (m.Stream.ReadAt(iloc.PayloadStart, iloc.PayloadLength, MaxTableBytes) is not { } data) + { + m.Warn("HEIF iloc unreadable"); + return; + } + var r = new SpanReader(data); + var version = r.U8(); + r.Skip(3); + var sizes = r.U8(); + var sizes2 = r.U8(); + int offsetSize = sizes >> 4, lengthSize = sizes & 0xF, baseOffsetSize = sizes2 >> 4; + var indexSize = version is 1 or 2 ? sizes2 & 0xF : 0; + if (version > 2) + { + m.Warn($"HEIF iloc version {version} unsupported"); + return; + } + var count = version < 2 ? r.U16() : r.U32(); + for (uint i = 0; i < count && r.Ok; i++) + { + var id = version < 2 ? r.U16() : r.U32(); + var method = version is 1 or 2 ? r.U16() & 0xF : 0; + r.Skip(2); + var baseOffset = r.Sized(baseOffsetSize); + var extents = r.U16(); + var item = Get(items, id); + item.ConstructionMethod = method; + for (var e = 0; e < extents && r.Ok; e++) + { + r.Sized(indexSize); + var offset = baseOffset + r.Sized(offsetSize); + var length = r.Sized(lengthSize); + if (r.Ok && e < MaxExtentsPerItem && offset <= long.MaxValue && length <= long.MaxValue) + item.Extents.Add(((long)offset, (long)length)); + } + } + if (!r.Ok) m.Warn("HEIF iloc truncated or malformed"); + } + + /// ispe, pixi, irot and imir associated with the primary item through ipma (1-based ipco indices). + private static void ReadPrimaryProperties(MetadataBuilder m, BmffBox iprp, uint primary) + { + var s = m.Stream; + var children = BmffReader.ReadChildren(s, iprp.PayloadStart, iprp.End); + if (BmffReader.Find(children, "ipco") is not { } ipco || BmffReader.Find(children, "ipma") is not { } ipma) return; + var properties = BmffReader.ReadChildren(s, ipco.PayloadStart, ipco.End); + var transform = Orientations[0]; + var transformed = false; + foreach (var index in Associations(m, ipma, primary)) + { + if (index < 1 || index > properties.Count) continue; + var p = properties[index - 1]; + var data = s.ReadAt(p.PayloadStart, Math.Min(p.PayloadLength, MaxPropertyBytes), MaxPropertyBytes); + if (data is null) continue; + if (p.Is("ispe") && data.Length >= 12) + { + var width = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4)); + var height = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(8)); + if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height); + } + else if (p.Is("pixi") && data.Length >= 6 && data[4] > 0) + { + m.CodedBitsPerSample ??= data[5]; + } + else if (p.Is("irot") && data.Length >= 1) + { + // Anticlockwise quarter turns: 1 → orientation 8, 2 → 3, 3 → 6. + transform = Multiply(Orientations[(data[0] & 3) switch { 1 => 7, 2 => 2, 3 => 5, _ => 0 }], transform); + transformed = true; + } + else if (p.Is("imir") && data.Length >= 1) + { + transform = Multiply(Orientations[(data[0] & 1) == 0 ? 3 : 1], transform); + transformed = true; + } + } + if (transformed) m.ContainerOrientation = Array.IndexOf(Orientations, transform) + 1; + } + + private static List Associations(MetadataBuilder m, BmffBox ipma, uint primary) + { + var result = new List(); + if (m.Stream.ReadAt(ipma.PayloadStart, ipma.PayloadLength, MaxTableBytes) is not { } data) return result; + var r = new SpanReader(data); + var version = r.U8(); + r.Skip(2); + var wideIndex = (r.U8() & 1) != 0; + var count = r.U32(); + for (uint i = 0; i < count && r.Ok; i++) + { + var id = version < 1 ? r.U16() : r.U32(); + var associations = r.U8(); + for (var a = 0; a < associations && r.Ok; a++) + { + var index = wideIndex ? r.U16() & 0x7FFF : r.U8() & 0x7F; + if (id == primary && r.Ok) result.Add(index); + } + } + if (!r.Ok) m.Warn("HEIF ipma truncated"); + return result; + } + + private static void ReadExifItem(MetadataBuilder m, Item item, long origin) + { + if (item.Extents.Count == 0) return; + var (start, length) = item.Extents[0]; + for (var i = 1; i < item.Extents.Count; i++) + { + if (item.Extents[i].Offset != start + length) + { + m.Warn("Fragmented HEIF Exif item not supported"); + return; + } + length += item.Extents[i].Length; + } + start += origin; + if (length == 0) length = m.Length - start; + if (start < 0 || length <= 0 || start > m.Length - length) + { + m.Warn("HEIF Exif item outside the file"); + return; + } + ExifParser.ParseOffsetPrefixed(m, start, length); + } + + private static void ReadXmpItem(MetadataBuilder m, Item item, long origin) + { + long total = 0; + foreach (var (_, length) in item.Extents) total += length; + if (total <= 0 || total > XmpParser.MaxPacketBytes) + { + m.Warn("HEIF XMP item empty or too large"); + return; + } + var packet = new byte[total]; + var at = 0; + foreach (var (offset, length) in item.Extents) + { + if (!m.Stream.TryReadAt(origin + offset, packet.AsSpan(at, (int)length))) + { + m.Warn("HEIF XMP item outside the file"); + return; + } + at += (int)length; + } + m.AddXmp(packet); + } + + private static (int, int, int, int) Multiply((int A, int B, int C, int D) x, (int A, int B, int C, int D) y) => + (x.A * y.A + x.B * y.C, x.A * y.B + x.B * y.D, x.C * y.A + x.D * y.C, x.C * y.B + x.D * y.D); + + private static Item Get(Dictionary items, uint id) + { + if (!items.TryGetValue(id, out var item)) items[id] = item = new Item(); + return item; + } + + private sealed class Item + { + public uint Type { get; set; } + public string? ContentType { get; set; } + public int ConstructionMethod { get; set; } + public List<(long Offset, long Length)> Extents { get; } = []; + } +} From 63d1855f82b972666758b4674936aa37b1f3c3ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:27 +0000 Subject: [PATCH 062/188] feat(core): project settings with Auto/manual values and export presets Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 1 + src/Titano.Core/Export/ExportPreset.cs | 131 ++++++++++++ src/Titano.Core/Project/Auto.cs | 31 +++ src/Titano.Core/Project/ProjectSettings.cs | 200 ++++++++++++++++++ .../Project/ProjectSettingsTests.cs | 60 ++++++ 5 files changed, 423 insertions(+) create mode 100644 src/Titano.Core/Export/ExportPreset.cs create mode 100644 src/Titano.Core/Project/Auto.cs create mode 100644 src/Titano.Core/Project/ProjectSettings.cs create mode 100644 tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index c43c94b9..b98dc3e8 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -44,3 +44,4 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Interpolation chooses velocities by forward–backward consistency with per-sample flow-agreement weights (τ = 3 px). | Super SloMo combination | Better at motion boundaries (36.8 vs 33 dB). | | 2026-10-02 | Virtual-camera zoom is interpolated geometrically; trail length L ↦ decay 0.01^(1/L). | Linear zoom / half-life | Even perceived speed; the trail is gone at its stated length. | | 2026-10-02 | Motion estimation, sharpness and noise use sRGB-encoded luminance. | Linear light | Shadows keep texture weight; less exposure dependence. | +| 2026-10-02 | Archive presets use 0.30 bpp (≈60 Mb/s at 4K24 HEVC 10-bit); share presets use the brief's per-codec defaults (0.10/0.07/0.05). | 0.07 bpp everywhere | An archive must survive later re-encoding; star fields are the hardest content. | diff --git a/src/Titano.Core/Export/ExportPreset.cs b/src/Titano.Core/Export/ExportPreset.cs new file mode 100644 index 00000000..8931e91a --- /dev/null +++ b/src/Titano.Core/Export/ExportPreset.cs @@ -0,0 +1,131 @@ +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// +/// A bundle of export values (BRIEF §11.4). Bit rate follows bits-per-pixel-per-frame +/// (≈ 0.10 H.264, 0.07 HEVC, 0.05 AV1) unless fixed. is the localized display name. +/// +public sealed record ExportPreset +{ + public required string Id { get; init; } + public required string NameKey { get; init; } + public required VideoCodec Codec { get; init; } + public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec); + public CodecProfile Profile { get; init; } = CodecProfile.Auto; + public int BitDepth { get; init; } = 8; + + /// Output size; 0×0 = source size (image sequences). + public int Width { get; init; } + + public int Height { get; init; } + public Rational FrameRate { get; init; } = new(30, 1); + + /// Fixed bit rate in bit/s; 0 = derived from . + public long BitRate { get; init; } + + public double BitsPerPixel { get; init; } + + /// Key-frame distance in seconds. + public double GopSeconds { get; init; } = 1; + + public int BFrames { get; init; } = 2; + + /// JPEG/MJPEG/GIF quality 1–100. + public int Quality { get; init; } = 92; + + public bool IsBuiltIn { get; init; } = true; + + /// Category for grouping in the Export tab. + public string Group { get; init; } = "video"; + + /// Average bit rate in bit/s for the preset's size and frame rate. + public long EffectiveBitRate(int width, int height, Rational fps) + { + if (BitRate > 0) return BitRate; + var bpp = BitsPerPixel > 0 ? BitsPerPixel : DefaultBitsPerPixel(Codec); + return (long)Math.Round(bpp * width * height * fps.Value); + } + + public static double DefaultBitsPerPixel(VideoCodec codec) => codec switch + { + VideoCodec.H264 => 0.10, + VideoCodec.Hevc => 0.07, + VideoCodec.Av1 => 0.05, + _ => 0, + }; + + /// Encode settings for this preset at a given output size. + public EncodeSettings ToEncodeSettings(string outputPath, int width, int height, Rational? fps = null) + { + var rate = fps ?? FrameRate; + return new EncodeSettings + { + OutputPath = outputPath, + Codec = Codec, + Width = width, + Height = height, + FrameRate = rate, + Profile = Profile, + BitDepth = BitDepth, + RateControl = RateControl.Vbr, + BitRate = EffectiveBitRate(width, height, rate), + Quality = Quality, + GopLength = Math.Max(1, (int)Math.Round(GopSeconds * rate.Value)), + BFrames = BFrames, + }; + } +} + +/// The built-in presets of BRIEF §11.4. +public static class ExportPresets +{ + private static readonly Rational Fps24 = new(24, 1); + private static readonly Rational Fps25 = new(25, 1); + private static readonly Rational Fps30 = new(30, 1); + private static readonly Rational Fps60 = new(60, 1); + + /// Archive presets keep ~4× the share budget so star fields and gradients survive re-encoding. + public const double ArchiveBitsPerPixel = 0.30; + + public static IReadOnlyList BuiltIn { get; } = + [ + new() { Id = "8k-hevc10-archive", NameKey = "Export.Preset.8kArchive", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain10, BitDepth = 10, Width = 7680, Height = 4320, FrameRate = Fps24, BitsPerPixel = ArchiveBitsPerPixel }, + new() { Id = "4k-hevc10-archive", NameKey = "Export.Preset.4kArchive", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain10, BitDepth = 10, Width = 3840, Height = 2160, FrameRate = Fps24, BitsPerPixel = ArchiveBitsPerPixel }, + new() { Id = "4k-hevc", NameKey = "Export.Preset.4kHevc", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain, Width = 3840, Height = 2160, FrameRate = Fps30 }, + new() { Id = "4k-h264", NameKey = "Export.Preset.4kH264", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 3840, Height = 2160, FrameRate = Fps24 }, + new() { Id = "dci4k-hevc", NameKey = "Export.Preset.Dci4k", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain10, BitDepth = 10, Width = 4096, Height = 2160, FrameRate = Fps24 }, + new() { Id = "cinema-21x9", NameKey = "Export.Preset.Cinema", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain10, BitDepth = 10, Width = 4096, Height = 1716, FrameRate = Fps24 }, + new() { Id = "4k60", NameKey = "Export.Preset.4k60", Codec = VideoCodec.Hevc, Profile = CodecProfile.HevcMain, Width = 3840, Height = 2160, FrameRate = Fps60 }, + new() { Id = "1440p-h264", NameKey = "Export.Preset.1440p", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 2560, Height = 1440, FrameRate = Fps30 }, + new() { Id = "1080p-h264", NameKey = "Export.Preset.1080pShare", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 1920, Height = 1080, FrameRate = Fps30 }, + new() { Id = "1080p60", NameKey = "Export.Preset.1080p60", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 1920, Height = 1080, FrameRate = Fps60 }, + new() { Id = "vertical-1080x1920", NameKey = "Export.Preset.Vertical", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 1080, Height = 1920, FrameRate = Fps30, Group = "social" }, + new() { Id = "portrait-1080x1350", NameKey = "Export.Preset.Portrait", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 1080, Height = 1350, FrameRate = Fps30, Group = "social" }, + new() { Id = "square-1440", NameKey = "Export.Preset.Square", Codec = VideoCodec.H264, Profile = CodecProfile.H264High, Width = 1440, Height = 1440, FrameRate = Fps30, Group = "social" }, + new() { Id = "720p-preview", NameKey = "Export.Preset.Preview", Codec = VideoCodec.H264, Profile = CodecProfile.H264Main, Width = 1280, Height = 720, FrameRate = Fps30, GopSeconds = 1, BFrames = 0 }, + new() { Id = "4k-av1", NameKey = "Export.Preset.4kAv1", Codec = VideoCodec.Av1, Profile = CodecProfile.Av1Main, BitDepth = 10, Width = 3840, Height = 2160, FrameRate = Fps30 }, + new() { Id = "mjpeg-avi", NameKey = "Export.Preset.Mjpeg", Codec = VideoCodec.Mjpeg, Width = 3840, Height = 2160, FrameRate = Fps25, Quality = 95, Group = "intermediate" }, + new() { Id = "png-sequence", NameKey = "Export.Preset.Png", Codec = VideoCodec.PngSequence, FrameRate = Fps30, Group = "sequence" }, + new() { Id = "jpeg-sequence", NameKey = "Export.Preset.Jpeg", Codec = VideoCodec.JpegSequence, FrameRate = Fps30, Quality = 95, Group = "sequence" }, + new() { Id = "tiff16-sequence", NameKey = "Export.Preset.Tiff16", Codec = VideoCodec.Tiff16Sequence, BitDepth = 16, FrameRate = Fps30, Group = "sequence" }, + new() { Id = "dng-sequence", NameKey = "Export.Preset.LinearDng", Codec = VideoCodec.LinearDngSequence, BitDepth = 16, FrameRate = Fps30, Group = "sequence" }, + new() { Id = "gif-preview", NameKey = "Export.Preset.Gif", Codec = VideoCodec.Gif, Width = 480, Height = 270, FrameRate = new Rational(15, 1), Quality = 80, Group = "web" }, + new() { Id = "apng", NameKey = "Export.Preset.Apng", Codec = VideoCodec.Apng, Width = 960, Height = 540, FrameRate = new Rational(15, 1), Group = "web" }, + ]; + + public static ExportPreset? Find(string id) => BuiltIn.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + /// Standard resolutions offered in the Custom editor (BRIEF §11.4). + public static IReadOnlyList<(string Key, int Width, int Height)> Resolutions { get; } = + [ + ("720p", 1280, 720), ("1080p", 1920, 1080), ("1440p", 2560, 1440), ("4k", 3840, 2160), ("dci4k", 4096, 2160), + ("5k", 5120, 2880), ("6k", 6144, 3456), ("8k", 7680, 4320), + ]; + + /// Frame rates offered (BRIEF §11.4). + public static IReadOnlyList FrameRates { get; } = + [ + Rational.Fps23976, new(24, 1), new(25, 1), Rational.Fps2997, new(30, 1), new(48, 1), new(50, 1), Rational.Fps5994, new(60, 1), new(120, 1), + ]; +} diff --git a/src/Titano.Core/Project/Auto.cs b/src/Titano.Core/Project/Auto.cs new file mode 100644 index 00000000..469ce46c --- /dev/null +++ b/src/Titano.Core/Project/Auto.cs @@ -0,0 +1,31 @@ +namespace Titano.Core.Project; + +/// +/// A parameter the advisor can decide (BRIEF §10.4). In Auto the advisor's applies and +/// / explain it; touching the control stores a manual +/// value; reset returns to Auto. +/// +public sealed record Auto +{ + public bool IsAuto { get; init; } = true; + + /// The advisor's value (null until analysis provides one). + public T? AutoValue { get; init; } + + /// The user's value when is false. + public T? Manual { get; init; } + + /// Localization key of the reason shown in the Auto pill tooltip. + public string? ReasonKey { get; init; } + + public IReadOnlyList? ReasonArgs { get; init; } + + /// The value in force: manual when set by the user, otherwise the advisor's, otherwise . + public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : AutoValue ?? fallback; + + public Auto WithManual(T value) => this with { IsAuto = false, Manual = value }; + + public Auto Reset() => this with { IsAuto = true, Manual = default }; + + public Auto WithAdvice(T value, string? reasonKey, params string[] args) => this with { AutoValue = value, ReasonKey = reasonKey, ReasonArgs = args }; +} diff --git a/src/Titano.Core/Project/ProjectSettings.cs b/src/Titano.Core/Project/ProjectSettings.cs new file mode 100644 index 00000000..82bffb78 --- /dev/null +++ b/src/Titano.Core/Project/ProjectSettings.cs @@ -0,0 +1,200 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Titano.Core.Project; + +public enum TimingMode +{ + /// Every source frame lasts one output frame. + Constant, + + /// Output time follows capture time (deliberate intervalometer pauses are kept short, gaps preserved). + Adaptive, + + /// Missing frames in sparse gaps are synthesised from motion. + Interpolated, + + /// A monotone curve maps output time to source position (speed ramps). + Remapped, +} + +public enum RegionMode +{ + Off, + Auto, + Horizon, + Luminance, +} + +public enum FlowQualitySetting +{ + Draft, + Balanced, + Best, +} + +public enum StackSetting +{ + None, + Median, + Mean, + StarTrails, +} + +/// A control point of the time-remap curve: output fraction → source fraction (both 0..1). +public sealed record CurvePoint(double X, double Y); + +/// Virtual-camera keyframe in normalised coordinates. +public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut"); + +public sealed record TimingSettings +{ + public Auto Mode { get; init; } = new(); + + /// Output frame rate as "num/den" or an integer (e.g. "24000/1001", "30"). + public Auto FrameRate { get; init; } = new(); + + /// When set, the plan is scaled so the video lasts this many seconds. + public double? FitToSeconds { get; init; } + + public IReadOnlyList RemapCurve { get; init; } = [new(0, 0), new(1, 1)]; +} + +public sealed record ExposureSettings +{ + public Auto Deflicker { get; init; } = new(); + + /// Local-regression window in frames (odd). + public Auto DeflickerWindow { get; init; } = new(); + + /// 0..1: share of the flicker removed. + public Auto DeflickerStrength { get; init; } = new(); + + public Auto Regions { get; init; } = new(); + + public Auto HolyGrail { get; init; } = new(); + + /// Transition length in frames for redistributed exposure steps. + public Auto TransitionLength { get; init; } = new(); + + public Auto WhiteBalanceSmoothing { get; init; } = new(); + + /// Global exposure offset in EV applied after correction. + public double ExposureOffsetEv { get; init; } + + /// Soft highlight knee (linear), null = hard clip at the encoder. + public double? HighlightKnee { get; init; } = 0.9; +} + +public sealed record MotionSettings +{ + public Auto MotionBlur { get; init; } = new(); + + /// Target shutter angle in degrees (180 = film look). + public Auto TargetShutterAngle { get; init; } = new(); + + public Auto FlowQuality { get; init; } = new(); + + public Auto Stabilize { get; init; } = new(); + + /// Path smoothing in frames (Gaussian sigma). + public Auto StabilizeSmoothing { get; init; } = new(); +} + +public sealed record CameraSettings +{ + /// Normalised crop (0..1) or null for the full frame. + public double[]? Crop { get; init; } + + /// "source", "16:9", "21:9", "4:3", "3:2", "1:1", "9:16", "4:5" or "w:h". + public Auto Aspect { get; init; } = new(); + + public double OffsetX { get; init; } + public double OffsetY { get; init; } + public IReadOnlyList Keyframes { get; init; } = []; +} + +public sealed record StackSettings +{ + public StackSetting Mode { get; init; } = StackSetting.None; + + /// Window (median/mean) or trail length (star trails) in frames. + public int Length { get; init; } = 9; +} + +/// Values of an export; null fields take the preset's value (BRIEF §11.4: editing any value makes it "Custom"). +public sealed record ExportOverrides +{ + public string? Codec { get; init; } + public string? Container { get; init; } + public string? Profile { get; init; } + public int? BitDepth { get; init; } + public int? Width { get; init; } + public int? Height { get; init; } + public string? FrameRate { get; init; } + public long? BitRate { get; init; } + public int? GopFrames { get; init; } + public int? BFrames { get; init; } + public int? Quality { get; init; } + public string? RateControl { get; init; } + public string? Encoder { get; init; } +} + +public sealed record ExportSettings +{ + /// Id of the selected preset (built-in or user); "custom" when values differ from every preset. + public Auto Preset { get; init; } = new(); + + public ExportOverrides Overrides { get; init; } = new(); + + /// Output file name template (tokens: date, title, preset, width, height, fps, codec). + public string NameTemplate { get; init; } = "{date} {title} - {preset}"; + + /// Output folder; null = the sequence's exports folder. + public string? Folder { get; init; } + + /// Presets queued together by "Render another preset" / batch. + public IReadOnlyList Batch { get; init; } = []; +} + +/// +/// The "project" of a sequence (.titano/project.json, BRIEF §7): every render decision. Originals are +/// never modified; all edits live here. +/// +public sealed record ProjectSettings +{ + public const int CurrentVersion = 1; + + public int Version { get; init; } = CurrentVersion; + public TimingSettings Timing { get; init; } = new(); + public ExposureSettings Exposure { get; init; } = new(); + public MotionSettings Motion { get; init; } = new(); + public CameraSettings Camera { get; init; } = new(); + public StackSettings Stack { get; init; } = new(); + public ExportSettings Export { get; init; } = new(); + + /// Frame indices excluded from renders. + public IReadOnlyList ExcludedFrames { get; init; } = []; + + /// Index of the hero frame (sequence thumbnail). + public int? HeroFrame { get; init; } + + public string ToJson() => JsonSerializer.Serialize(this, ProjectJson.Default.ProjectSettings); + + public static ProjectSettings FromJson(string json) + { + var settings = JsonSerializer.Deserialize(json, ProjectJson.Default.ProjectSettings) ?? new ProjectSettings(); + if (settings.Version > CurrentVersion) + throw new InvalidDataException($"project.json version {settings.Version} is newer than this Titano ({CurrentVersion})."); + return settings; + } +} + +[JsonSourceGenerationOptions( + WriteIndented = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + UseStringEnumConverter = true, + PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(ProjectSettings))] +internal sealed partial class ProjectJson : JsonSerializerContext; diff --git a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs new file mode 100644 index 00000000..99712dd2 --- /dev/null +++ b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs @@ -0,0 +1,60 @@ +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Project; + +public sealed class ProjectSettingsTests +{ + [Test] + public void JsonRoundTripKeepsAutoAndManualValues() + { + var settings = new ProjectSettings + { + Exposure = new ExposureSettings + { + DeflickerWindow = new Auto().WithAdvice(41, "Advisor.Reason.FlickerPeriod", "10.2"), + DeflickerStrength = new Auto().WithManual(0.8), + }, + Timing = new TimingSettings { FrameRate = new Auto().WithAdvice("24", null) }, + ExcludedFrames = [3, 7], + }; + var back = ProjectSettings.FromJson(settings.ToJson()); + Assert.Equal(41, back.Exposure.DeflickerWindow.Resolve(0)); + Assert.True(back.Exposure.DeflickerWindow.IsAuto); + Assert.Equal("Advisor.Reason.FlickerPeriod", back.Exposure.DeflickerWindow.ReasonKey); + Assert.Equal(0.8, back.Exposure.DeflickerStrength.Resolve(1.0)); + Assert.False(back.Exposure.DeflickerStrength.IsAuto); + Assert.SequenceEqual(new[] { 3, 7 }, back.ExcludedFrames); + Assert.Contains("\"deflickerWindow\"", settings.ToJson()); + } + + [Test] + public void ResetReturnsToAdvice() + { + var a = new Auto().WithAdvice(41, null).WithManual(15); + Assert.Equal(15, a.Resolve(0)); + Assert.Equal(41, a.Reset().Resolve(0)); + } + + [Test] + public void NewerVersionIsRefused() => + Assert.Throws(() => ProjectSettings.FromJson("{\"version\": 99}")); + + [Test] + public void BuiltInPresetIdsAreUnique() => + Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count()); + + [Test] + public void BitRateFollowsBitsPerPixel() + { + var p = Assert.NotNull(ExportPresets.Find("4k-hevc10-archive")); + // 0.30 × 3840 × 2160 × 24 ≈ 59.7 Mb/s (archive budget); share presets use the codec default. + Assert.Equal(59_719_680L, p.EffectiveBitRate(3840, 2160, new Rational(24, 1))); + Assert.Equal(19_906_560L, ExportPresets.Find("4k-h264")!.EffectiveBitRate(3840, 2160, new Rational(24, 1))); + var s = p.ToEncodeSettings("out.mp4", 3840, 2160); + Assert.Equal(24, s.GopLength); + Assert.Equal(10, s.BitDepth); + } +} From 1df3f152405f90a3b9ac472ebe79903b367dcbd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:30 +0000 Subject: [PATCH 063/188] feat(metadata): parse RAF, PNG, WebP and minimal formats RAF: embedded JPEG Exif and preview, size from the RAF directory (0x0111 cropped, else 0x0100), bit depth from the FujiIFD. PNG: IHDR, eXIf and iTXt/tEXt XMP (zlib supported), seeking over image data. WebP: VP8X canvas or VP8/VP8L headers, EXIF and XMP chunks. GIF and BMP sizes, the JPEG XR IFD and the JPEG XL size header plus container Exif/XML boxes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Metadata/MinimalFormatParser.cs | 119 ++++++++++++++++++ src/Titano.Core/Metadata/Png/PngParser.cs | 111 ++++++++++++++++ src/Titano.Core/Metadata/Raf/RafParser.cs | 81 ++++++++++++ src/Titano.Core/Metadata/Riff/WebPParser.cs | 63 ++++++++++ 4 files changed, 374 insertions(+) create mode 100644 src/Titano.Core/Metadata/MinimalFormatParser.cs create mode 100644 src/Titano.Core/Metadata/Png/PngParser.cs create mode 100644 src/Titano.Core/Metadata/Raf/RafParser.cs create mode 100644 src/Titano.Core/Metadata/Riff/WebPParser.cs diff --git a/src/Titano.Core/Metadata/MinimalFormatParser.cs b/src/Titano.Core/Metadata/MinimalFormatParser.cs new file mode 100644 index 00000000..7b561690 --- /dev/null +++ b/src/Titano.Core/Metadata/MinimalFormatParser.cs @@ -0,0 +1,119 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata; + +/// Formats with "minimal" metadata (BRIEF §8.1): GIF and BMP sizes; JPEG XR IFD (size, Exif, GPS, XMP); +/// JPEG XL size header plus the container's Exif and XML boxes. +internal static class MinimalFormatParser +{ + private const ushort JxrImageWidth = 0xBC80; + private const ushort JxrImageHeight = 0xBC81; + + public static void ParseGif(MetadataBuilder m) + { + Span h = stackalloc byte[10]; + if (m.Stream.TryReadAt(0, h)) m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[6..]), BinaryPrimitives.ReadUInt16LittleEndian(h[8..])); + else m.Warn("GIF header truncated"); + } + + /// BITMAPCOREHEADER (16-bit sizes) or BITMAPINFOHEADER and later (signed 32-bit; negative height = top-down). + public static void ParseBmp(MetadataBuilder m) + { + Span h = stackalloc byte[26]; + if (!m.Stream.TryReadAt(0, h)) + { + m.Warn("BMP header truncated"); + return; + } + if (BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12) + { + m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(h[18..]), BinaryPrimitives.ReadUInt16LittleEndian(h[20..])); + return; + } + var width = BinaryPrimitives.ReadInt32LittleEndian(h[18..]); + var height = BinaryPrimitives.ReadInt32LittleEndian(h[22..]); + if (height != int.MinValue) m.SetContainerSize(width, Math.Abs(height)); + } + + /// JPEG XR: a little-endian TIFF-like IFD (magic 0x01BC) with standard Make/Exif/GPS/XMP tags. + public static void ParseJpegXr(MetadataBuilder m) + { + Span h = stackalloc byte[8]; + if (!m.Stream.TryReadAt(0, h)) + { + m.Warn("JPEG XR header truncated"); + return; + } + var r = TiffReader.ForEmbedded(m.Stream, 0, littleEndian: true); + if (r.ReadIfd(BinaryPrimitives.ReadUInt32LittleEndian(h[4..])) is { } ifd) + { + ExifParser.ReadTree(r, ifd, m, [ifd.Position]); + m.SetContainerSize(IfdValue.Int(r, ifd, JxrImageWidth) ?? 0, IfdValue.Int(r, ifd, JxrImageHeight) ?? 0); + } + m.AddWarnings(r.Warnings); + } + + /// JPEG XL: bare codestream (FF 0A) or ISO-BMFF container with jxlc/jxlp, Exif and "xml " boxes. + public static void ParseJpegXl(MetadataBuilder m) + { + Span h = stackalloc byte[2]; + if (m.Stream.TryReadAt(0, h) && h[0] == 0xFF && h[1] == 0x0A) + { + ReadSizeHeader(m, 0); + return; + } + var codestream = false; + foreach (var box in BmffReader.ReadChildren(m.Stream, 0, m.Length)) + { + m.ThrowIfCancelled(); + if (box.Is("Exif")) ExifParser.ParseOffsetPrefixed(m, box.PayloadStart, box.PayloadLength); + else if (box.Is("xml ")) m.AddXmp(m.Stream.ReadAt(box.PayloadStart, box.PayloadLength, XmpParser.MaxPacketBytes)); + else if (!codestream && box.Is("jxlc")) codestream = ReadSizeHeader(m, box.PayloadStart); + else if (!codestream && box.Is("jxlp")) codestream = ReadSizeHeader(m, box.PayloadStart + 4); + } + } + + /// Codestream SizeHeader (ISO/IEC 18181-1 §D.2): small sizes in multiples of 8, else U32 distributions; + /// width either explicit or derived from a fixed aspect ratio. + private static bool ReadSizeHeader(MetadataBuilder m, long position) + { + Span b = stackalloc byte[18]; + var n = m.Stream.ReadUpTo(position, b); + if (n < 3 || b[0] != 0xFF || b[1] != 0x0A) + { + m.Warn("JPEG XL codestream signature missing"); + return false; + } + b[n..].Clear(); + var bits = new BitReader(BinaryPrimitives.ReadUInt128LittleEndian(b[2..])); + var small = bits.Read(1) == 1; + var height = small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1; + var ratio = (int)bits.Read(3); + var width = ratio != 0 + ? height * (ulong)RatioNumerator[ratio] / (ulong)RatioDenominator[ratio] + : small ? (bits.Read(5) + 1) * 8 : Distribution(ref bits) + 1; + if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height); + return true; + } + + private static ReadOnlySpan RatioNumerator => [0, 1, 12, 4, 3, 16, 5, 2]; + private static ReadOnlySpan RatioDenominator => [1, 1, 10, 3, 2, 9, 4, 1]; + + private static ulong Distribution(ref BitReader bits) => bits.Read(bits.Read(2) switch { 0 => 9, 1 => 13, 2 => 18, _ => 30 }); + + /// LSB-first bit reader over the 128 bits following the signature (a SizeHeader uses at most 68). + private struct BitReader(UInt128 value) + { + private UInt128 _value = value; + + public ulong Read(int count) + { + var v = (ulong)(_value & ((UInt128.One << count) - 1)); + _value >>= count; + return v; + } + } +} diff --git a/src/Titano.Core/Metadata/Png/PngParser.cs b/src/Titano.Core/Metadata/Png/PngParser.cs new file mode 100644 index 00000000..af7ff78e --- /dev/null +++ b/src/Titano.Core/Metadata/Png/PngParser.cs @@ -0,0 +1,111 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Png; + +/// PNG chunks: IHDR (size, bit depth), eXIf (TIFF), iTXt/tEXt "XML:com.adobe.xmp" (XMP, zlib-compressed iTXt +/// supported). Image data chunks are skipped by seeking; CRCs are not verified. +internal static class PngParser +{ + private const int MaxChunks = 4096; + private const int KeywordProbeBytes = 80; + private static ReadOnlySpan XmpKeyword => "XML:com.adobe.xmp\0"u8; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + Span head = stackalloc byte[8 + 13]; + long pos = 8; + for (var i = 0; i < MaxChunks; i++) + { + m.ThrowIfCancelled(); + var n = s.ReadUpTo(pos, head); + if (n < 8) + { + m.Warn("PNG truncated before IEND"); + return; + } + var length = BinaryPrimitives.ReadUInt32BigEndian(head); + var type = head.Slice(4, 4); + var data = pos + 8; + if (length > int.MaxValue || data > m.Length - length) + { + m.Warn("PNG chunk runs past the end of the file"); + return; + } + if (type.SequenceEqual("IHDR"u8) && length >= 13 && n == head.Length) + { + var width = BinaryPrimitives.ReadUInt32BigEndian(head[8..]); + var height = BinaryPrimitives.ReadUInt32BigEndian(head[12..]); + if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height, head[16]); + } + else if (type.SequenceEqual("eXIf"u8) && length >= 8) + { + var exif = n >= 14 && head[8..].StartsWith("Exif\0\0"u8) ? data + 6 : data; + ExifParser.ParseEmbedded(m, exif); + } + else if (type.SequenceEqual("iTXt"u8) || type.SequenceEqual("tEXt"u8)) + { + ReadText(m, data, (int)length, international: type[0] == 'i'); + } + else if (type.SequenceEqual("IEND"u8)) + { + return; + } + pos = data + length + 4; + } + m.Warn("PNG has too many chunks; rest ignored"); + } + + /// XMP text chunk: keyword "XML:com.adobe.xmp"; iTXt adds compression flag/method, language and translated keyword. + private static void ReadText(MetadataBuilder m, long data, int length, bool international) + { + Span probe = stackalloc byte[XmpKeyword.Length]; + if (length < probe.Length || !m.Stream.TryReadAt(data, probe) || !probe.SequenceEqual(XmpKeyword)) return; + if (m.Stream.ReadAt(data, length, XmpParser.MaxPacketBytes + KeywordProbeBytes) is not { } chunk) + { + m.Warn("PNG XMP chunk too large"); + return; + } + var r = new SpanReader(chunk); + r.Skip(XmpKeyword.Length); + var compressed = false; + if (international) + { + compressed = r.U8() == 1; + r.Skip(1); + r.CString(); + r.CString(); + } + if (!r.Ok) return; + var text = chunk.AsMemory(r.Position); + if (!compressed) + { + m.AddXmp(text.ToArray()); + return; + } + try + { + using var z = new ZLibStream(new MemoryStream(chunk, r.Position, text.Length, writable: false), CompressionMode.Decompress); + using var packet = new MemoryStream(); + var buffer = new byte[16 * 1024]; + int read; + while ((read = z.Read(buffer)) > 0) + { + if (packet.Length + read > XmpParser.MaxPacketBytes) + { + m.Warn("PNG XMP larger than 4 MB ignored"); + return; + } + packet.Write(buffer, 0, read); + } + m.AddXmp(packet.ToArray()); + } + catch (InvalidDataException) + { + m.Warn("PNG compressed XMP is corrupt"); + } + } +} diff --git a/src/Titano.Core/Metadata/Raf/RafParser.cs b/src/Titano.Core/Metadata/Raf/RafParser.cs new file mode 100644 index 00000000..ac4631e6 --- /dev/null +++ b/src/Titano.Core/Metadata/Raf/RafParser.cs @@ -0,0 +1,81 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata.Raf; + +/// +/// Fujifilm RAF: "FUJIFILMCCD-RAW " header with a big-endian directory (0x54 JPEG offset/length, 0x5C RAF-directory +/// offset/length, 0x64 CFA offset/length). Camera fields come from the embedded JPEG's Exif, which is also the +/// preview; the main size from the RAF directory records (0x0111 cropped, else 0x0100 full), bit depth from the +/// FujiIFD at the CFA offset when that is a TIFF block. +/// +internal static class RafParser +{ + private const int HeaderLength = 0x6C; + private const int MaxDirectoryBytes = 64 * 1024; + private const int MaxRecords = 512; + private const ushort RawImageFullSize = 0x0100; + private const ushort RawImageCroppedSize = 0x0111; + private const ushort FujiIfd = 0xF000; + private const ushort FujiRawWidth = 0xF001; + private const ushort FujiRawHeight = 0xF002; + private const ushort FujiBitsPerSample = 0xF003; + + public static void Parse(MetadataBuilder m) + { + var header = m.Stream.ReadAt(0, HeaderLength, HeaderLength); + if (header is null) + { + m.Warn("RAF header truncated"); + return; + } + var h = header.AsSpan(); + var jpegOffset = BinaryPrimitives.ReadUInt32BigEndian(h[0x54..]); + var jpegLength = BinaryPrimitives.ReadUInt32BigEndian(h[0x58..]); + if (jpegOffset >= HeaderLength && jpegLength > 0 && jpegOffset <= m.Length - jpegLength) + JpegParser.Parse(m, jpegOffset, (long)jpegOffset + jpegLength, primary: false); + else + m.Warn("RAF embedded JPEG missing"); + ReadDirectory(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x5C..]), BinaryPrimitives.ReadUInt32BigEndian(h[0x60..])); + ReadFujiIfd(m, BinaryPrimitives.ReadUInt32BigEndian(h[0x64..])); + m.Make ??= "FUJIFILM"; + m.Model ??= Ascii(h.Slice(0x1C, 32)); + } + + /// RAF directory: u32 count, then (u16 tag, u16 size, data) records; sizes are (height, width) pairs. + private static void ReadDirectory(MetadataBuilder m, uint offset, uint length) + { + if (offset == 0 || m.Stream.ReadAt(offset, Math.Min(length, MaxDirectoryBytes), MaxDirectoryBytes) is not { } data) return; + var r = new SpanReader(data); + var count = Math.Min(r.U32(), MaxRecords); + (int Width, int Height) full = default, cropped = default; + for (var i = 0; i < count && r.Ok; i++) + { + var tag = r.U16(); + var record = r.Take(r.U16()); + if (!r.Ok || record.Length < 4) continue; + var size = (BinaryPrimitives.ReadUInt16BigEndian(record[2..]), BinaryPrimitives.ReadUInt16BigEndian(record)); + if (tag == RawImageFullSize) full = size; + else if (tag == RawImageCroppedSize) cropped = size; + } + var best = cropped.Width > 0 && cropped.Height > 0 ? cropped : full; + m.SetContainerSize(best.Width, best.Height); + } + + private static void ReadFujiIfd(MetadataBuilder m, uint offset) + { + if (offset == 0 || TiffReader.Open(m.Stream, offset) is not { } r) return; + if (r.ReadIfd(r.FirstIfdOffset) is not { } ifd0 || IfdValue.UInt(r, ifd0, FujiIfd) is not { } sub || r.ReadIfd(sub) is not { } fuji) return; + m.CodedBitsPerSample ??= IfdValue.Int(r, fuji, FujiBitsPerSample); + m.AddRaster(IfdValue.Int(r, fuji, FujiRawWidth) ?? 0, IfdValue.Int(r, fuji, FujiRawHeight) ?? 0, null, true); + } + + private static string? Ascii(ReadOnlySpan field) + { + var end = field.IndexOf((byte)0); + var s = Encoding.ASCII.GetString(end < 0 ? field : field[..end]).Trim(); + return s.Length > 0 && !s.Any(char.IsControl) ? s : null; + } +} diff --git a/src/Titano.Core/Metadata/Riff/WebPParser.cs b/src/Titano.Core/Metadata/Riff/WebPParser.cs new file mode 100644 index 00000000..89932943 --- /dev/null +++ b/src/Titano.Core/Metadata/Riff/WebPParser.cs @@ -0,0 +1,63 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; + +namespace Titano.Core.Metadata.Riff; + +/// RIFF/WebP: canvas size from VP8X, else the VP8 key-frame or VP8L header; Exif from "EXIF" (with or without +/// an "Exif\0\0" prefix) and XMP from "XMP ". Image data is skipped by seeking. +internal static class WebPParser +{ + private const int MaxChunks = 1024; + + public static void Parse(MetadataBuilder m) + { + var s = m.Stream; + Span h = stackalloc byte[8 + 10]; + if (!s.TryReadAt(0, h[..12])) + { + m.Warn("WebP header truncated"); + return; + } + var end = Math.Min(m.Length, 8 + (long)BinaryPrimitives.ReadUInt32LittleEndian(h[4..])); + long pos = 12; + for (var i = 0; i < MaxChunks && pos <= end - 8; i++) + { + m.ThrowIfCancelled(); + var n = s.ReadUpTo(pos, h); + var size = BinaryPrimitives.ReadUInt32LittleEndian(h[4..]); + var data = pos + 8; + var payload = h[8..n]; + if (size > end - data) + { + m.Warn("WebP chunk runs past the end of the file"); + size = (uint)(end - data); + } + var fourCC = h[..4]; + if (fourCC.SequenceEqual("VP8X"u8) && payload.Length >= 10) + { + m.SetContainerSize(1 + UInt24(payload[4..]), 1 + UInt24(payload[7..]), 8); + } + else if (fourCC.SequenceEqual("VP8 "u8) && payload.Length >= 10 && payload[3..6].SequenceEqual((ReadOnlySpan)[0x9D, 0x01, 0x2A])) + { + m.SetContainerSize(BinaryPrimitives.ReadUInt16LittleEndian(payload[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(payload[8..]) & 0x3FFF, 8); + } + else if (fourCC.SequenceEqual("VP8L"u8) && payload.Length >= 5 && payload[0] == 0x2F) + { + var bits = BinaryPrimitives.ReadUInt32LittleEndian(payload[1..]); + m.SetContainerSize((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1, 8); + } + else if (fourCC.SequenceEqual("EXIF"u8) && size >= 8) + { + ExifParser.ParseEmbedded(m, payload.StartsWith("Exif\0\0"u8) ? data + 6 : data); + } + else if (fourCC.SequenceEqual("XMP "u8)) + { + m.AddXmp(s.ReadAt(data, size, XmpParser.MaxPacketBytes)); + } + pos = data + size + (size & 1); + } + } + + private static int UInt24(ReadOnlySpan b) => b[0] | b[1] << 8 | b[2] << 16; +} From c8ed872fb5f502b9c6498d798254bdd080e20258 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:38 +0000 Subject: [PATCH 064/188] feat(metadata): add signature detection and MetadataReader ImageSignature.Detect identifies every BRIEF 8.1 format by magic bytes, refining TIFF-based RAWs by the CR2 marker, DNGVersion and Make, and ISO-BMFF files by ftyp brands; the extension only breaks ties. MetadataReader.Read (path or seekable stream) dispatches to the container parsers, opens files shared for read/write/delete with a small buffer, honours cancellation and turns any parser defect into a warning so malformed input never throws. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Metadata/ImageSignature.cs | 149 +++++++++++++++++++++ src/Titano.Core/Metadata/MetadataReader.cs | 110 +++++++++++++++ 2 files changed, 259 insertions(+) create mode 100644 src/Titano.Core/Metadata/ImageSignature.cs create mode 100644 src/Titano.Core/Metadata/MetadataReader.cs diff --git a/src/Titano.Core/Metadata/ImageSignature.cs b/src/Titano.Core/Metadata/ImageSignature.cs new file mode 100644 index 00000000..1b5becc2 --- /dev/null +++ b/src/Titano.Core/Metadata/ImageSignature.cs @@ -0,0 +1,149 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Identifies a file's format from its leading bytes. TIFF-based files are refined by the CR2 marker, IFD0 +/// DNGVersion and Make; ISO-BMFF files by their ftyp brands. The file-name extension only breaks +/// ties between formats that share a container (NEF/NRW, ARW/SRF/SR2, 3FR/FFF, RW2/RWL/RAW, TIFF vs camera RAW). +/// +public static class ImageSignature +{ + private const int HeadBytes = 32; + private const int MaxFtypBytes = 256; + + private static ReadOnlySpan PngSignature => [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A]; + private static ReadOnlySpan JpegXrSignature => [(byte)'I', (byte)'I', 0xBC]; + private static ReadOnlySpan JpegXlBox => [0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A]; + + private static readonly HashSet TiffBasedRaws = + [ + ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Nrw, ImageFileFormat.Arw, + ImageFileFormat.Srf, ImageFileFormat.Sr2, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Raw, + ImageFileFormat.Rwl, ImageFileFormat.Pef, ImageFileFormat.Srw, ImageFileFormat.ThreeFr, ImageFileFormat.Fff, + ImageFileFormat.Iiq, ImageFileFormat.Gpr, + ]; + + /// Detects the format of the bytes in (read from offset 0; the position is restored). + /// Optional name or path whose extension breaks ties; never overrides the signature. + /// when no known signature matches. + public static ImageFileFormat Detect(Stream stream, string? fileName) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + var position = stream.Position; + try + { + var extension = string.IsNullOrEmpty(fileName) ? ImageFileFormat.Unknown : ImageFormatInfo.FromPath(fileName).Format; + return DetectCore(stream, extension); + } + catch (IOException) + { + return ImageFileFormat.Unknown; + } + finally + { + stream.Position = position; + } + } + + private static ImageFileFormat DetectCore(Stream stream, ImageFileFormat extension) + { + Span buffer = stackalloc byte[HeadBytes]; + var h = buffer[..stream.ReadUpTo(0, buffer)]; + if (h.StartsWith((ReadOnlySpan)[0xFF, 0xD8, 0xFF])) return ImageFileFormat.Jpeg; + if (h.StartsWith(PngSignature)) return ImageFileFormat.Png; + if (h.StartsWith("GIF87a"u8) || h.StartsWith("GIF89a"u8)) return ImageFileFormat.Gif; + if (h.StartsWith("FUJIFILMCCD-RAW "u8)) return ImageFileFormat.Raf; + if (h.Length >= 12 && h.StartsWith("RIFF"u8) && h[8..12].SequenceEqual("WEBP"u8)) return ImageFileFormat.WebP; + if (h.StartsWith((ReadOnlySpan)[0xFF, 0x0A]) || h.StartsWith(JpegXlBox)) return ImageFileFormat.JpegXl; + if (h.Length >= 12 && h[4..8].SequenceEqual("ftyp"u8)) return FromBrands(stream, BinaryPrimitives.ReadUInt32BigEndian(h)); + if (h.Length >= 4 && h.StartsWith(JpegXrSignature) && h[3] <= 1) return ImageFileFormat.JpegXr; + if (h.Length >= 14 && h[6..14].SequenceEqual("HEAPCCDR"u8)) return ImageFileFormat.Crw; + if (h.StartsWith("IIRO"u8) || h.StartsWith("IIRS"u8) || h.StartsWith("MMOR"u8)) return ImageFileFormat.Orf; + if (h.StartsWith("IIU\0"u8)) return Panasonic(stream, extension); + if (h.StartsWith("II*\0"u8) || h.StartsWith("MM\0*"u8)) return Tiff(stream, h, extension); + if (h.Length >= 18 && h.StartsWith("BM"u8) && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124) + return ImageFileFormat.Bmp; + return ImageFileFormat.Unknown; + } + + /// CR3 (crx), AVIF (avif/avis) or HEIF (heic, heix, hevc, hevx, heim, heis, mif1, msf1); major brand first. + private static ImageFileFormat FromBrands(Stream stream, uint ftypSize) + { + Span buffer = stackalloc byte[MaxFtypBytes]; + var n = stream.ReadUpTo(0, buffer[..(int)Math.Clamp(ftypSize, 16, MaxFtypBytes)]); + if (n < 12) return ImageFileFormat.Unknown; + var major = Brand(buffer[8..12]); + if (major == BrandKind.Cr3) return ImageFileFormat.Cr3; + if (major == BrandKind.Avif) return ImageFileFormat.Avif; + if (major == BrandKind.Heif) return ImageFileFormat.Heif; + var heif = major == BrandKind.Image; + for (var i = 16; i + 4 <= n; i += 4) + { + var brand = Brand(buffer.Slice(i, 4)); + if (brand == BrandKind.Avif) return ImageFileFormat.Avif; + heif |= brand is BrandKind.Heif or BrandKind.Image; + } + return heif ? ImageFileFormat.Heif : ImageFileFormat.Unknown; + } + + private enum BrandKind + { + Other, + Cr3, + Avif, + Heif, + Image, + } + + private static BrandKind Brand(ReadOnlySpan b) => + b.SequenceEqual("crx "u8) ? BrandKind.Cr3 + : b.SequenceEqual("avif"u8) || b.SequenceEqual("avis"u8) ? BrandKind.Avif + : b.SequenceEqual("heic"u8) || b.SequenceEqual("heix"u8) || b.SequenceEqual("hevc"u8) || b.SequenceEqual("hevx"u8) + || b.SequenceEqual("heim"u8) || b.SequenceEqual("heis"u8) ? BrandKind.Heif + : b.SequenceEqual("mif1"u8) || b.SequenceEqual("msf1"u8) ? BrandKind.Image + : BrandKind.Other; + + private static ImageFileFormat Panasonic(Stream stream, ImageFileFormat extension) + { + if (extension is ImageFileFormat.Rwl or ImageFileFormat.Raw) return extension; + return Make(stream)?.StartsWith("LEICA", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Rwl : ImageFileFormat.Rw2; + } + + private static ImageFileFormat Tiff(Stream stream, ReadOnlySpan h, ImageFileFormat extension) + { + if (h.Length >= 10 && h[8..10].SequenceEqual("CR"u8)) return ImageFileFormat.Cr2; + var reader = TiffReader.Open(stream); + var ifd0 = reader?.ReadIfd(reader.FirstIfdOffset); + var make = reader is not null && ifd0 is not null ? IfdValue.String(reader, ifd0, TiffTags.Make) : null; + if (ifd0?.Has(TiffTags.DngVersion) == true) + return extension == ImageFileFormat.Gpr || make?.StartsWith("GoPro", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Gpr : ImageFileFormat.Dng; + if (extension == ImageFileFormat.Tiff) return ImageFileFormat.Tiff; + var byMake = ByMake(make, extension); + if (byMake != ImageFileFormat.Unknown) return byMake; + return TiffBasedRaws.Contains(extension) ? extension : ImageFileFormat.Tiff; + } + + private static ImageFileFormat ByMake(string? make, ImageFileFormat extension) + { + if (make is null) return ImageFileFormat.Unknown; + bool Is(string prefix) => make.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); + if (Is("NIKON")) return extension == ImageFileFormat.Nrw ? ImageFileFormat.Nrw : ImageFileFormat.Nef; + if (Is("SONY")) return extension is ImageFileFormat.Srf or ImageFileFormat.Sr2 ? extension : ImageFileFormat.Arw; + if (Is("PENTAX") || Is("RICOH")) return ImageFileFormat.Pef; + if (Is("SAMSUNG")) return ImageFileFormat.Srw; + if (Is("Hasselblad")) return extension == ImageFileFormat.Fff ? ImageFileFormat.Fff : ImageFileFormat.ThreeFr; + if (Is("Imacon")) return ImageFileFormat.Fff; + if (Is("Phase One") || Is("Leaf")) return ImageFileFormat.Iiq; + return ImageFileFormat.Unknown; + } + + private static string? Make(Stream stream) + { + var reader = TiffReader.Open(stream); + return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? IfdValue.String(reader, ifd, TiffTags.Make) : null; + } +} diff --git a/src/Titano.Core/Metadata/MetadataReader.cs b/src/Titano.Core/Metadata/MetadataReader.cs new file mode 100644 index 00000000..74bca4df --- /dev/null +++ b/src/Titano.Core/Metadata/MetadataReader.cs @@ -0,0 +1,110 @@ +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Metadata.Jpeg; +using Titano.Core.Metadata.Png; +using Titano.Core.Metadata.Raf; +using Titano.Core.Metadata.Riff; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Metadata; + +/// +/// Reads from any supported photo (BRIEF §9). Detects the container by signature, then +/// reads only the structures it needs through bounded seeks (a RAW's image data is never read). Malformed input never +/// throws: the result carries whatever was readable plus . +/// +public static class MetadataReader +{ + private const string LogCategory = "Metadata"; + private const int FileBufferSize = 4096; + + /// Reads the file at ; its modification time is the last-resort capture time. + /// The file cannot be opened (missing or locked). + /// Access to the file is denied. + public static FrameMetadata Read(string path, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(path); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess); + return Read(stream, Path.GetFileName(path), File.GetLastWriteTime(path), cancellationToken); + } + + /// Reads metadata from a readable, seekable stream (the position is left undefined). + /// Name used only to break signature ties (see ). + /// File time used when no capture time is recorded (); + /// its UTC offset is taken from the local zone for values. + /// Cancelled through . + public static FrameMetadata Read(Stream stream, string? fileName, DateTime? fileModifiedLocal = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + cancellationToken.ThrowIfCancellationRequested(); + var m = new MetadataBuilder(stream, cancellationToken); + try + { + m.Format = ImageSignature.Detect(stream, fileName); + Parse(m); + } + catch (OperationCanceledException) + { + throw; + } + catch (IOException ex) + { + m.Warn("I/O error: " + ex.Message); + } + catch (Exception ex) + { + // Safety net: parsers are written not to throw, but a defect must cost one file's metadata, not the import. + m.Warn($"Parser fault: {ex.GetType().Name}: {ex.Message}"); + Log.Warning(LogCategory, $"Metadata parser fault in {fileName ?? "stream"}", ex); + } + return m.Build(fileModifiedLocal); + } + + private static void Parse(MetadataBuilder m) + { + switch (m.Format) + { + case ImageFileFormat.Jpeg: + JpegParser.Parse(m, 0, m.Length, primary: true); + break; + case ImageFileFormat.Png: + PngParser.Parse(m); + break; + case ImageFileFormat.WebP: + WebPParser.Parse(m); + break; + case ImageFileFormat.Heif or ImageFileFormat.Avif: + HeifParser.Parse(m); + break; + case ImageFileFormat.Cr3: + Cr3Parser.Parse(m); + break; + case ImageFileFormat.Raf: + RafParser.Parse(m); + break; + case ImageFileFormat.Gif: + MinimalFormatParser.ParseGif(m); + break; + case ImageFileFormat.Bmp: + MinimalFormatParser.ParseBmp(m); + break; + case ImageFileFormat.JpegXr: + MinimalFormatParser.ParseJpegXr(m); + break; + case ImageFileFormat.JpegXl: + MinimalFormatParser.ParseJpegXl(m); + break; + case ImageFileFormat.Crw: + m.Warn("CRW (CIFF) metadata is not supported"); + break; + case ImageFileFormat.Unknown: + m.Warn("Unrecognised file signature"); + break; + default: + ExifParser.ParseFile(m); + break; + } + } +} From ef9d28449672f80eb8715ed8f85e2b0fcc4ac8db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:45 +0000 Subject: [PATCH 065/188] feat(metadata): add ExifWriter for proxies and exports BuildTiff writes a little-endian TIFF with IFD0 (camera, orientation, software, date, authorship, resolution), the Exif IFD (capture time with sub-seconds and offset, exposure, ISO with RecommendedExposureIndex above 65535, focal lengths, bias, body serial, lens) and a GPS IFD when known. BuildJpegApp1 wraps it in a complete APP1 segment; strings are capped at 2000 UTF-8 bytes on character boundaries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Metadata/ExifWriter.cs | 254 +++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 src/Titano.Core/Metadata/ExifWriter.cs diff --git a/src/Titano.Core/Metadata/ExifWriter.cs b/src/Titano.Core/Metadata/ExifWriter.cs new file mode 100644 index 00000000..9fdd6416 --- /dev/null +++ b/src/Titano.Core/Metadata/ExifWriter.cs @@ -0,0 +1,254 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.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. +/// +public static class ExifWriter +{ + /// Longest string written, in UTF-8 bytes; keeps the APP1 segment far below its 64 KB limit. + public const int MaxStringBytes = 2000; + + private const int MaxShortIso = 65535; + private const uint GpsDegreeDenominator = 10_000_000; + + private static ReadOnlySpan ExifHeader => "Exif\0\0"u8; + + /// A complete TIFF structure ("II*\0" header, IFD0, Exif IFD, optional GPS IFD). + public static byte[] BuildTiff(FrameMetadata metadata) + { + ArgumentNullException.ThrowIfNull(metadata); + var m = metadata; + var date = m.CapturedAt?.ToString("yyyy':'MM':'dd HH':'mm':'ss", CultureInfo.InvariantCulture); + + var ifd0 = new IfdBuilder(); + ifd0.Ascii(TiffTags.Make, m.Make); + ifd0.Ascii(TiffTags.Model, m.Model); + ifd0.Short(TiffTags.Orientation, (ushort)(m.Orientation is >= 1 and <= 8 ? m.Orientation : 1)); + ifd0.Rational(TiffTags.XResolution, 72, 1); + ifd0.Rational(TiffTags.YResolution, 72, 1); + ifd0.Short(TiffTags.ResolutionUnit, 2); + ifd0.Ascii(TiffTags.Software, m.Software); + ifd0.Ascii(TiffTags.DateTime, date); + ifd0.Ascii(TiffTags.Artist, m.Artist); + ifd0.Short(TiffTags.YCbCrPositioning, 1); + ifd0.Ascii(TiffTags.Copyright, m.Copyright); + + var exif = new IfdBuilder(); + exif.Rational(TiffTags.ExposureTime, m.ExposureTime); + exif.Rational(TiffTags.FNumber, m.FNumber); + if (m.Iso is { } iso and > 0) + { + exif.Short(TiffTags.IsoSpeedRatings, (ushort)Math.Min(iso, MaxShortIso)); + if (iso >= MaxShortIso) + { + // ISOSpeedRatings saturates at 65535; SensitivityType 2 declares RecommendedExposureIndex as the value. + exif.Short(TiffTags.SensitivityType, 2); + exif.Long(TiffTags.RecommendedExposureIndex, (uint)iso); + } + } + exif.Undefined(TiffTags.ExifVersion, "0232"u8); + exif.Ascii(TiffTags.DateTimeOriginal, date); + if (m.CapturedAt is { } captured && captured.Ticks % TimeSpan.TicksPerSecond is > 0 and var fraction) + exif.Ascii(TiffTags.SubSecTimeOriginal, fraction.ToString("D7", CultureInfo.InvariantCulture).TrimEnd('0')); + 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.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); + exif.Ascii(TiffTags.LensModel, m.LensModel); + + var gps = m.Gps is { } position ? BuildGps(position) : null; + + // Pointers are fixed-size LONGs, so the IFD sizes are known before their offsets. + ifd0.Long(TiffTags.ExifIfd, 0); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, 0); + var exifOffset = 8 + ifd0.Size; + var gpsOffset = exifOffset + exif.Size; + ifd0.Long(TiffTags.ExifIfd, (uint)exifOffset); + if (gps is not null) ifd0.Long(TiffTags.GpsIfd, (uint)gpsOffset); + + var tiff = new byte[gpsOffset + (gps?.Size ?? 0)]; + "II*\0"u8.CopyTo(tiff); + BinaryPrimitives.WriteUInt32LittleEndian(tiff.AsSpan(4), 8); + ifd0.Write(tiff, 8); + exif.Write(tiff, exifOffset); + gps?.Write(tiff, gpsOffset); + return tiff; + } + + /// A complete JPEG APP1 segment: FF E1, big-endian length, "Exif\0\0", then . + public static byte[] BuildJpegApp1(FrameMetadata metadata) + { + var tiff = BuildTiff(metadata); + var segment = new byte[4 + ExifHeader.Length + tiff.Length]; + segment[0] = 0xFF; + segment[1] = 0xE1; + BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), checked((ushort)(segment.Length - 2))); + ExifHeader.CopyTo(segment.AsSpan(4)); + tiff.CopyTo(segment, 4 + ExifHeader.Length); + return segment; + } + + /// Coordinates as decimal degrees (1e-7° resolution) in the degrees rational, minutes and seconds zero. + private static IfdBuilder BuildGps(GpsPosition gps) + { + var ifd = new IfdBuilder(); + ifd.Bytes(TiffTags.GpsVersionId, TiffType.Byte, [2, 3, 0, 0]); + if (double.IsFinite(gps.Latitude) && double.IsFinite(gps.Longitude)) + { + ifd.Ascii(TiffTags.GpsLatitudeRef, gps.Latitude < 0 ? "S" : "N"); + ifd.Rationals(TiffTags.GpsLatitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Latitude), 90) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + ifd.Ascii(TiffTags.GpsLongitudeRef, gps.Longitude < 0 ? "W" : "E"); + ifd.Rationals(TiffTags.GpsLongitude, [((uint)Math.Round(Math.Min(Math.Abs(gps.Longitude), 180) * GpsDegreeDenominator), GpsDegreeDenominator), (0, 1), (0, 1)]); + } + if (gps.Altitude is { } altitude && double.IsFinite(altitude)) + { + ifd.Bytes(TiffTags.GpsAltitudeRef, TiffType.Byte, [altitude < 0 ? (byte)1 : (byte)0]); + ifd.Rationals(TiffTags.GpsAltitude, [ToRational(Math.Abs(altitude))]); + } + if (gps.UtcTimestamp is { } utc) + { + var t = utc.TimeOfDay; + ifd.Rationals(TiffTags.GpsTimeStamp, [((uint)t.Hours, 1), ((uint)t.Minutes, 1), ((uint)Math.Round((t.Seconds + t.Milliseconds / 1000.0) * 1000), 1000)]); + ifd.Ascii(TiffTags.GpsDateStamp, utc.ToString("yyyy':'MM':'dd", CultureInfo.InvariantCulture)); + } + return ifd; + } + + /// Exact 1/n for exposure-style fractions, else a fixed denominator reduced by the GCD. + private static (uint Numerator, uint Denominator) ToRational(double value) + { + if (!double.IsFinite(value) || value <= 0) return (0, 1); + if (value < 1) + { + var inverse = Math.Round(1 / value); + if (inverse <= uint.MaxValue && Math.Abs(1 / inverse - value) <= value * 1e-6) return (1, (uint)inverse); + } + var denominator = value < 400_000 ? 10_000u : 1u; + var numerator = Math.Round(value * denominator); + if (numerator > uint.MaxValue) return (uint.MaxValue, 1); + var n = (uint)numerator; + var gcd = Gcd(n, denominator); + return (n / gcd, denominator / gcd); + } + + private static uint Gcd(uint a, uint b) + { + while (b != 0) (a, b) = (b, a % b); + return a == 0 ? 1 : a; + } + + /// Collects entries of one IFD and serialises them sorted by tag, values over 4 bytes word-aligned after it. + private sealed class IfdBuilder + { + private readonly SortedDictionary _entries = new(); + + /// Bytes taken by the IFD including its out-of-line values. + public int Size + { + get + { + var size = 2 + 12 * _entries.Count + 4; + foreach (var e in _entries.Values) + { + if (e.Data.Length > 4) size += e.Data.Length + (e.Data.Length & 1); + } + return size; + } + } + + public void Bytes(ushort tag, TiffType type, byte[] data) => _entries[tag] = (type, (uint)(data.Length / TiffTypeInfo.Size(type)), data); + + public void Undefined(ushort tag, ReadOnlySpan data) => Bytes(tag, TiffType.Undefined, data.ToArray()); + + public void Ascii(ushort tag, string? value) + { + if (string.IsNullOrWhiteSpace(value)) return; + var text = value.Trim(); + var nul = text.IndexOf('\0'); + if (nul >= 0) text = text[..nul]; + var bytes = Encoding.UTF8.GetBytes(text); + var length = Math.Min(bytes.Length, MaxStringBytes); + while (length < bytes.Length && length > 0 && (bytes[length] & 0xC0) == 0x80) length--; + var data = new byte[length + 1]; + bytes.AsSpan(0, length).CopyTo(data); + Bytes(tag, TiffType.Ascii, data); + } + + public void Short(ushort tag, ushort value) + { + var data = new byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(data, value); + Bytes(tag, TiffType.Short, data); + } + + public void Long(ushort tag, uint value) + { + var data = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(data, value); + Bytes(tag, TiffType.Long, data); + } + + public void Rational(ushort tag, double? value) + { + if (value is { } v and > 0 && double.IsFinite(v)) Rationals(tag, [ToRational(v)]); + } + + public void Rational(ushort tag, uint numerator, uint denominator) => Rationals(tag, [(numerator, denominator)]); + + public void Rationals(ushort tag, ReadOnlySpan<(uint Numerator, uint Denominator)> values) + { + var data = new byte[8 * values.Length]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8 * i + 4), values[i].Denominator); + } + Bytes(tag, TiffType.Rational, data); + } + + public void SRational(ushort tag, double? value) + { + if (value is not { } v || !double.IsFinite(v) || Math.Abs(v) >= 200_000) return; + var (n, d) = ToRational(Math.Abs(v)); + var data = new byte[8]; + BinaryPrimitives.WriteInt32LittleEndian(data, v < 0 ? -(int)n : (int)n); + BinaryPrimitives.WriteInt32LittleEndian(data.AsSpan(4), (int)d); + Bytes(tag, TiffType.SRational, data); + } + + public void Write(byte[] tiff, int offset) + { + var span = tiff.AsSpan(); + BinaryPrimitives.WriteUInt16LittleEndian(span[offset..], (ushort)_entries.Count); + var entry = offset + 2; + var data = offset + 2 + 12 * _entries.Count + 4; + foreach (var (tag, (type, count, bytes)) in _entries) + { + BinaryPrimitives.WriteUInt16LittleEndian(span[entry..], tag); + BinaryPrimitives.WriteUInt16LittleEndian(span[(entry + 2)..], (ushort)type); + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 4)..], count); + if (bytes.Length <= 4) + { + bytes.CopyTo(span[(entry + 8)..]); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(span[(entry + 8)..], (uint)data); + bytes.CopyTo(span[data..]); + data += bytes.Length + (bytes.Length & 1); + } + entry += 12; + } + BinaryPrimitives.WriteUInt32LittleEndian(span[entry..], 0); + } + } +} From ef680420e9a78785727250b7ff6fd5308545aab6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:01:55 +0000 Subject: [PATCH 066/188] test(metadata): add synthetic file builders IfdSpec/TiffFile emit TIFF structures in either byte order with child IFDs, data blobs and position-dependent MakerNote IFDs; JpegBuilder emits SOI/APPn/MPF/SOF/SOS/EOI with extended XMP; Box helpers build ISO-BMFF, RIFF and PNG chunks. Fixtures cover JPEG, CR2, NEF, DNG, ARW, ORF, RW2, CR3, HEIC, AVIF, RAF, WebP and PNG around one canonical camera, plus sparse and counting streams for I/O-bound tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Metadata/Builders/Box.cs | 68 +++ .../Metadata/Builders/Fixtures.cs | 417 ++++++++++++++++++ .../Metadata/Builders/IfdSpec.cs | 276 ++++++++++++ .../Metadata/Builders/JpegBuilder.cs | 149 +++++++ .../Metadata/Builders/TestStreams.cs | 86 ++++ 5 files changed, 996 insertions(+) create mode 100644 tests/Titano.Core.Tests/Metadata/Builders/Box.cs create mode 100644 tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs create mode 100644 tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs create mode 100644 tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs create mode 100644 tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs diff --git a/tests/Titano.Core.Tests/Metadata/Builders/Box.cs b/tests/Titano.Core.Tests/Metadata/Builders/Box.cs new file mode 100644 index 00000000..d26ee4d1 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/Box.cs @@ -0,0 +1,68 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// ISO-BMFF / RIFF / PNG byte helpers for synthetic containers. +internal static class Box +{ + public static byte[] Make(string type, params byte[][] content) + { + var size = 8 + content.Sum(c => c.Length); + return [.. U32((uint)size), .. Encoding.Latin1.GetBytes(type), .. content.SelectMany(c => c)]; + } + + public static byte[] Full(string type, byte version, uint flags, params byte[][] content) => + Make(type, [[version, (byte)(flags >> 16), (byte)(flags >> 8), (byte)flags], .. content]); + + public static byte[] Uuid(Guid userType, params byte[][] content) => + Make("uuid", [userType.ToByteArray(bigEndian: true), .. content]); + + public static byte[] U8(byte v) => [v]; + + public static byte[] U16(ushort v) + { + var b = new byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(b, v); + return b; + } + + public static byte[] U32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(b, v); + return b; + } + + public static byte[] U64(ulong v) + { + var b = new byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(b, v); + return b; + } + + public static byte[] Ascii(string s) => Encoding.Latin1.GetBytes(s); + + public static byte[] Zeros(int n) => new byte[n]; + + /// RIFF chunk: FourCC, little-endian size, data, pad byte to even length. + public static byte[] Riff(string fourCC, byte[] data) + { + var b = new byte[8 + data.Length + (data.Length & 1)]; + Encoding.Latin1.GetBytes(fourCC).CopyTo(b, 0); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), (uint)data.Length); + data.CopyTo(b, 8); + return b; + } + + /// PNG chunk with a real CRC. + public static byte[] Png(string type, byte[] data) + { + var b = new byte[12 + data.Length]; + BinaryPrimitives.WriteUInt32BigEndian(b, (uint)data.Length); + Encoding.Latin1.GetBytes(type).CopyTo(b, 4); + data.CopyTo(b, 8); + BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(8 + data.Length), Core.Hashing.Crc32.Compute(b.AsSpan(4, 4 + data.Length))); + return b; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs b/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs new file mode 100644 index 00000000..01e3b644 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/Fixtures.cs @@ -0,0 +1,417 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Synthetic files for every container Titano reads. The canonical camera values below are what the tests +/// expect back; each RAW-like fixture also exercises its vendor MakerNote and preview layout. +internal static class Fixtures +{ + public const string Make = "TestCam"; + public const string Model = "TC-1"; + public const string Xmp = """ + + + + + Red + + + + + """; + + public static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48"); + public static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16"); + + /// 12:34:56.123 +02:00 on 2024-05-01. + public static readonly DateTime Captured = new DateTime(2024, 5, 1, 12, 34, 56, DateTimeKind.Unspecified).AddTicks(1_230_000); + + public static IfdSpec Ifd0(string make = Make, string model = Model, ushort orientation = 6) => new IfdSpec() + .Ascii(TiffTags.Make, make) + .Ascii(TiffTags.Model, model) + .Short(TiffTags.Orientation, orientation) + .Ascii(TiffTags.Software, "fw 1.0") + .Ascii(TiffTags.Artist, "Ada") + .Ascii(TiffTags.Copyright, "(c) Ada") + .Short(TiffTags.Rating, 3); + + /// Every standard Exif field Titano reads; adds body serial and lens model. + public static IfdSpec ExifIfd(bool identity = true, ushort iso = 400) + { + var exif = new IfdSpec() + .Rational(TiffTags.ExposureTime, (1, 250)) + .Rational(TiffTags.FNumber, (56, 10)) + .Ascii(TiffTags.DateTimeOriginal, "2024:05:01 12:34:56") + .Ascii(TiffTags.SubSecTimeOriginal, "123") + .Ascii(TiffTags.OffsetTimeOriginal, "+02:00") + .Ascii(TiffTags.DateTimeDigitized, "2024:05:01 12:34:57") + .Rational(TiffTags.FocalLength, (35, 1)) + .Short(TiffTags.FocalLengthIn35mmFilm, 52) + .SRational(TiffTags.ExposureBiasValue, -2, 3) + .Short(TiffTags.ExposureProgram, 3) + .Short(TiffTags.MeteringMode, 5) + .Short(TiffTags.WhiteBalance, 1) + .Short(TiffTags.Flash, 16) + .Long(TiffTags.PixelXDimension, 4000) + .Long(TiffTags.PixelYDimension, 3000); + if (iso > 0) exif.Short(TiffTags.IsoSpeedRatings, iso); + if (identity) exif.Ascii(TiffTags.BodySerialNumber, "SN123").Ascii(TiffTags.LensModel, "TestLens 35mm"); + return exif; + } + + /// 45.5° N, 9.26° W, 120.5 m, 2024-05-01 10:34:56 UTC. + public static IfdSpec GpsIfd() => new IfdSpec() + .Bytes(TiffTags.GpsVersionId, 2, 3, 0, 0) + .Ascii(TiffTags.GpsLatitudeRef, "N") + .Rational(TiffTags.GpsLatitude, (45, 1), (30, 1), (0, 1)) + .Ascii(TiffTags.GpsLongitudeRef, "W") + .Rational(TiffTags.GpsLongitude, (9, 1), (15, 1), (3600, 100)) + .Bytes(TiffTags.GpsAltitudeRef, 0) + .Rational(TiffTags.GpsAltitude, (1205, 10)) + .Rational(TiffTags.GpsTimeStamp, (10, 1), (34, 1), (56, 1)) + .Ascii(TiffTags.GpsDateStamp, "2024:05:01"); + + /// Canonical Exif TIFF block; IFD1 carries a 160×120 JPEG thumbnail. + public static byte[] ExifTiff(bool littleEndian = true, IfdSpec? exif = null, IfdSpec? ifd0 = null) + { + var root = (ifd0 ?? Ifd0()).Child(TiffTags.ExifIfd, exif ?? ExifIfd()).Child(TiffTags.GpsIfd, GpsIfd()); + root.Next = new IfdSpec() + .Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120)); + return TiffFile.Build(root, littleEndian); + } + + /// 4000×3000 JPEG: Exif (+thumbnail), XMP, MPF with a 1920×1440 large thumbnail and a disparity image + /// (not a preview). + public static byte[] Jpeg(bool littleEndian = true) => new JpegBuilder() + .Segment(0xE0, [.. "JFIF\0"u8, 1, 2, 0, 0, 1, 0, 1, 0, 0]) + .Exif(ExifTiff(littleEndian)) + .Xmp(Xmp) + .Mpf((JpegBuilder.Minimal(1920, 1440), 0x00010002), (JpegBuilder.Minimal(640, 480), 0x00020002)) + .Build(4000, 3000); + + /// CR2: "CR" marker, IFD0 full-size JPEG strip (6720×4480), IFD1 thumbnail, IFD2 RGB, IFD3 lossless + /// raw (SOF3, 14-bit); Canon MakerNote supplies serial, lens, IS and colour temperature. + public static byte[] Cr2() + { + var makerNote = new IfdSpec() + .Short(0x0001, [.. Enumerable.Range(0, 40).Select(i => (ushort)(i == 34 ? 1 : 0))]) + .Long(0x000C, 123456) + .Long(0x0010, 0x80000349) + .Ascii(0x0095, "EF24-70mm f/2.8L II USM") + .Short(0x00AE, 5200); + var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true); + var ifd0 = Ifd0("Canon", "Canon EOS 5D Mark IV", 1) + .Long(TiffTags.ImageWidth, 6720).Long(TiffTags.ImageLength, 4480) + .Short(TiffTags.BitsPerSample, 8, 8, 8) + .Short(TiffTags.Compression, 6) + .Strip(JpegBuilder.Minimal(6720, 4480)) + .Child(TiffTags.ExifIfd, exif); + var ifd1 = new IfdSpec().Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120)); + var ifd2 = new IfdSpec().Long(TiffTags.ImageWidth, 592).Long(TiffTags.ImageLength, 395) + .Short(TiffTags.BitsPerSample, 16, 16, 16).Short(TiffTags.Compression, 1).Strip(new byte[64]); + var ifd3 = new IfdSpec().Short(TiffTags.Compression, 6).Strip(JpegBuilder.Minimal(2784, 3708, 0xC3, 14)); + ifd0.Next = ifd1; + ifd1.Next = ifd2; + ifd2.Next = ifd3; + return TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]); + } + + /// Big-endian NEF: IFD0 RGB thumbnail; SubIFDs JpgFromRaw (8256×5504) and 14-bit CFA raw (8288×5520); + /// Nikon type-3 MakerNote (serial, shutter count, lens, VR, ISO used because Exif ISO is absent). + public static byte[] Nef() + { + var nikon = new IfdSpec() + .Short(0x0002, 0, 64) + .Ascii(0x001D, "3001234") + .Undefined(0x001F, [.. "0100"u8, 1, 0, 0, 0]) + .Rational(0x0084, (24, 1), (70, 1), (28, 10), (28, 10)) + .Long(0x00A7, 12345); + var exif = ExifIfd(identity: false, iso: 0) + .Undefined(TiffTags.MakerNote, [.. "Nikon\0"u8, 2, 0x11, 0, 0, .. TiffFile.Build(nikon, littleEndian: false)]); + var jpgFromRaw = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(8256, 5504)); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 8288).Long(TiffTags.ImageLength, 5520) + .Short(TiffTags.BitsPerSample, 14).Short(TiffTags.Compression, 34713) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[128]); + var ifd0 = Ifd0("NIKON CORPORATION", "NIKON D850", 1) + .Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 160).Long(TiffTags.ImageLength, 120) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Strip(new byte[96]) + .Child(TiffTags.SubIfds, jpgFromRaw, raw) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, littleEndian: false); + } + + /// DNG: IFD0 thumbnail with CameraSerialNumber; SubIFDs 16-bit CFA raw (4032×3024, lossless JPEG strip, + /// excluded as CFA) and a 1024×768 YCbCr JPEG preview (NewSubfileType 1). + public static byte[] Dng() + { + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 4032).Long(TiffTags.ImageLength, 3024) + .Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(JpegBuilder.Minimal(2016, 3024, 0xC3, 12)); + var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 1024).Long(TiffTags.ImageLength, 768) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 7) + .Short(TiffTags.PhotometricInterpretation, 6).Strip(JpegBuilder.Minimal(1024, 768)); + var ifd0 = Ifd0("Google", "Pixel 8", 1) + .Long(TiffTags.NewSubfileType, 1) + .Long(TiffTags.ImageWidth, 256).Long(TiffTags.ImageLength, 192) + .Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Short(TiffTags.PhotometricInterpretation, 2) + .Strip(new byte[48]) + .Bytes(TiffTags.DngVersion, 1, 4, 0, 0) + .Ascii(TiffTags.CameraSerialNumber, "DNGSER1") + .Child(TiffTags.SubIfds, raw, preview) + .Child(TiffTags.ExifIfd, ExifIfd(identity: false)); + return TiffFile.Build(ifd0); + } + + /// ARW: IFD0 is a 1616×1080 JPEG preview, SubIFD the 12-bit raw; "SONY DSC" MakerNote with LensSpec. + public static byte[] Arw() + { + var sony = new IfdSpec() + .Long(0xB021, 5600) + .Long(0xB026, 1) + .Undefined(0xB02A, [0x00, 0x00, 0x24, 0x00, 0x70, 0x28, 0x28, 0x00]); + var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "SONY DSC \0\0\0"u8], sony, relativeToTiff: true, littleEndian: true); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, 6048).Long(TiffTags.ImageLength, 4024) + .Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 32767) + .Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[64]); + var ifd0 = Ifd0("SONY", "ILCE-7M3", 1) + .Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6) + .Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(1616, 1080)) + .Child(TiffTags.SubIfds, raw) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0); + } + + /// ORF ("IIRO"): raw in IFD0; "OM SYSTEM" MakerNote with Equipment (serial, lens) and CameraSettings + /// (3200×2400 preview at a MakerNote-relative offset, IS on). + public static byte[] Orf() + { + var equipment = new IfdSpec().Ascii(0x0101, "BHX123").Ascii(0x0203, "M.Zuiko 12-40mm F2.8"); + var settings = new IfdSpec().Long(0x0100, 1).Blob(0x0101, 0x0102, JpegBuilder.Minimal(3200, 2400)).Long(0x0604, 1); + var olympus = new IfdSpec().Child(0x2010, equipment).Child(0x2020, settings); + var exif = ExifIfd(identity: false) + .Embedded(TiffTags.MakerNote, [.. "OM SYSTEM\0\0\0II"u8, 4, 0], olympus, relativeToTiff: false, littleEndian: true); + var ifd0 = Ifd0("OM Digital Solutions", "OM-1", 1) + .Long(TiffTags.ImageWidth, 5240).Long(TiffTags.ImageLength, 3912) + .Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 1).Strip(new byte[64]) + .Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, magic: "IIRO"); + } + + /// RW2 ("IIU\0"): sensor borders give 5776×4344, 12-bit, ISO 800; JpgFromRaw (1920×1440) carries the Exif + /// block with a Panasonic MakerNote (internal serial, lens type, IS, colour temperature). + public static byte[] Rw2() + { + var panasonic = new IfdSpec() + .Short(0x001A, 2) + .Undefined(0x0025, [.. "F541504040123"u8, 0, 0, 0]) + .Short(0x0044, 5000) + .Ascii(0x0051, "LUMIX G VARIO 12-60mm"); + var exif = ExifIfd(identity: false, iso: 800) + .Embedded(TiffTags.MakerNote, [.. "Panasonic\0\0\0"u8], panasonic, relativeToTiff: true, littleEndian: true); + var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("Panasonic", "DC-GH6", 1))).Build(1920, 1440); + var ifd0 = new IfdSpec() + .Short(0x0002, 5800).Short(0x0003, 4360) + .Short(0x0004, 8).Short(0x0005, 12).Short(0x0006, 4352).Short(0x0007, 5788) + .Short(0x000A, 12).Short(0x0017, 800) + .Undefined(0x002E, jpeg) + .Ascii(TiffTags.Make, "Panasonic").Ascii(TiffTags.Model, "DC-GH6").Short(TiffTags.Orientation, 1); + return TiffFile.Build(ifd0, magic: "IIU\0"); + } + + /// CR3: CMT1–4 + THMB in the Canon uuid, PRVW in the preview uuid, track 1 full-size JPEG (8192×5464), + /// track 2 raw with CMP1 (8352×5586, 14-bit); mdat comes last. + public static byte[] Cr3() => Cr3(out _); + + public static byte[] Cr3(out int mdatStart) + { + var full = JpegBuilder.Minimal(8192, 5464); + var canonMakerNote = TiffFile.Build(new IfdSpec().Long(0x000C, 98765).Ascii(0x0095, "RF24-105mm F4 L IS USM")); + var cmt2 = new IfdSpec() + .Rational(TiffTags.ExposureTime, (1, 100)).Rational(TiffTags.FNumber, (4, 1)).Short(TiffTags.IsoSpeedRatings, 100) + .Ascii(TiffTags.DateTimeOriginal, "2024:06:01 08:00:00").Ascii(TiffTags.SubSecTimeOriginal, "50") + .Ascii(TiffTags.OffsetTimeOriginal, "-04:00"); + var thumb = JpegBuilder.Minimal(160, 120); + var canon = Box.Uuid(CanonUuid, + Box.Make("CNCV", Box.Ascii("CanonCR3_001/00.09.00/00.00.00")), + Box.Make("CMT1", TiffFile.Build(Ifd0("Canon", "Canon EOS R5", 8).Long(TiffTags.ImageWidth, 8192).Long(TiffTags.ImageLength, 5464))), + Box.Make("CMT2", TiffFile.Build(cmt2)), + Box.Make("CMT3", canonMakerNote), + Box.Make("CMT4", TiffFile.Build(GpsIfd())), + Box.Make("THMB", [0, 0, 0, 0], Box.U16(160), Box.U16(120), Box.U32((uint)thumb.Length), Box.U16(0xFF), Box.U16(0xFF), thumb)); + var prvwJpeg = JpegBuilder.Minimal(1620, 1080); + var preview = Box.Uuid(PreviewUuid, Box.U64(0), + Box.Make("PRVW", Box.U32(0), Box.U16(1), Box.U16(1620), Box.U16(1080), Box.U16(1), Box.U32((uint)prvwJpeg.Length), prvwJpeg)); + + byte[] Build(uint jpegOffset) + { + var moov = Box.Make("moov", canon, Box.Make("mvhd", Box.Zeros(100)), + Track(Box.Make("JPEG", Box.Zeros(4)), Box.U32(0), Box.U32(1), Box.U32((uint)full.Length), jpegOffset, 8192, 5464), + Track(Box.Make("CMP1", Box.U16(0), Box.U16(0x30), Box.U32(0x100), Box.U32(8352), Box.U32(5586), Box.U32(512), Box.U32(512), [14, 0x11, 0, 0]), + Box.U32(0), Box.U32(1), Box.U32(1000), jpegOffset + (uint)full.Length, 8352, 5586)); + return [.. Box.Make("ftyp", Box.Ascii("crx "), Box.U32(1), Box.Ascii("crx isom")), .. moov, .. preview]; + } + + var head = Build(0); + var offset = (uint)(head.Length + 8); + head = Build(offset); + mdatStart = head.Length; + var mdat = new byte[8 + full.Length + 1000]; + BinaryPrimitives.WriteUInt32BigEndian(mdat, (uint)mdat.Length); + "mdat"u8.CopyTo(mdat.AsSpan(4)); + full.CopyTo(mdat, 8); + return [.. head, .. mdat]; + + static byte[] Track(byte[] entryChild, byte[] sampleSize, byte[] sampleCount, byte[] firstSize, uint chunkOffset, ushort width, ushort height) + { + var craw = Box.Make("CRAW", Box.Zeros(6), Box.U16(1), Box.Zeros(16), Box.U16(width), Box.U16(height), + Box.U32(0x00480000), Box.U32(0x00480000), Box.U32(0), Box.U16(1), Box.Zeros(32), Box.U16(24), Box.U16(0xFFFF), entryChild); + var stbl = Box.Make("stbl", + Box.Full("stsd", 0, 0, Box.U32(1), craw), + Box.Full("stsz", 0, 0, sampleSize, sampleCount, firstSize), + Box.Full("stco", 0, 0, Box.U32(1), Box.U32(chunkOffset))); + return Box.Make("trak", Box.Make("mdia", Box.Make("minf", stbl))); + } + } + + /// HEIC: primary hvc1 item 4032×3024 (ispe), 10-bit pixi, irot 1 (+ imir axis 1 when ), + /// Exif item (orientation 6, ignored when transforms exist) and a two-extent XMP item. + public static byte[] Heic(bool rotate = true, bool mirror = false, string major = "heic") + { + var exifPayload = (byte[])[.. Box.U32(6), .. "Exif\0\0"u8, .. ExifTiff()]; + var xmp = Encoding.UTF8.GetBytes(Xmp); + var split = xmp.Length / 2; + var codec = major == "avif" ? "av01" : "hvc1"; + + byte[] Build(uint mdatData) + { + var exifAt = mdatData + 64; + var xmpAt = exifAt + (uint)exifPayload.Length; + var properties = new List { Box.Full("ispe", 0, 0, Box.U32(4032), Box.U32(3024)), Box.Full("pixi", 0, 0, [3, 10, 10, 10]) }; + if (rotate) properties.Add(Box.Make("irot", [1])); + if (mirror) properties.Add(Box.Make("imir", [1])); + var associations = Enumerable.Range(1, properties.Count).Select(i => (byte)(0x80 | i)).ToArray(); + var meta = Box.Full("meta", 0, 0, + Box.Full("hdlr", 0, 0, Box.U32(0), Box.Ascii("pict"), Box.Zeros(12), [0]), + Box.Full("pitm", 0, 0, Box.U16(1)), + Box.Full("iinf", 0, 0, Box.U16(3), + Box.Full("infe", 2, 0, Box.U16(1), Box.U16(0), Box.Ascii(codec), [0]), + Box.Full("infe", 2, 0, Box.U16(2), Box.U16(0), Box.Ascii("Exif"), [0]), + Box.Full("infe", 2, 0, Box.U16(3), Box.U16(0), Box.Ascii("mime"), [0], Box.Ascii("application/rdf+xml"), [0])), + Box.Full("iloc", 1, 0, [0x44, 0x00], Box.U16(3), + Box.U16(1), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(mdatData), Box.U32(64), + Box.U16(2), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(exifAt), Box.U32((uint)exifPayload.Length), + Box.U16(3), Box.U16(0), Box.U16(0), Box.U16(2), Box.U32(xmpAt), Box.U32((uint)split), Box.U32(xmpAt + (uint)split), Box.U32((uint)(xmp.Length - split))), + Box.Make("iprp", + Box.Make("ipco", [.. properties.SelectMany(p => p)]), + Box.Full("ipma", 0, 0, Box.U32(1), Box.U16(1), [(byte)associations.Length], associations))); + return [.. Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii("mif1"), Box.Ascii(major)), .. meta]; + } + + var head = Build(0); + var data = (uint)(head.Length + 8); + head = Build(data); + return [.. head, .. Box.Make("mdat", Box.Zeros(64), exifPayload, xmp)]; + } + + /// RAF: big-endian directory; embedded 1920×1280 JPEG with Exif and a Fujifilm MakerNote; RAF records give + /// 7752×5178 (cropped) and the FujiIFD 14-bit. + public static byte[] Raf() + { + var fuji = new IfdSpec().Ascii(0x0010, "FF02B1234567").Short(0x1005, 6100).Short(0x1422, 2, 1, 0); + var exif = ExifIfd(identity: false) + .Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true); + var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("FUJIFILM", "X-T5", 1))).Build(1920, 1280); + var records = (byte[])[.. Box.U32(2), .. Box.U16(0x0100), .. Box.U16(4), .. Box.U16(5280), .. Box.U16(7920), + .. Box.U16(0x0111), .. Box.U16(4), .. Box.U16(5178), .. Box.U16(7752)]; + var fujiIfd = TiffFile.Build(new IfdSpec().Child(0xF000, new IfdSpec().Long(0xF001, 7920).Long(0xF002, 5280).Long(0xF003, 14)), littleEndian: false); + var jpegOffset = 0x6C; + var recordsOffset = jpegOffset + jpeg.Length; + var cfaOffset = recordsOffset + records.Length; + var header = new byte[0x6C]; + "FUJIFILMCCD-RAW 0201FF129502"u8.CopyTo(header); + "X-T5"u8.CopyTo(header.AsSpan(0x1C)); + "0100"u8.CopyTo(header.AsSpan(0x3C)); + uint[] directory = [(uint)jpegOffset, (uint)jpeg.Length, (uint)recordsOffset, (uint)records.Length, (uint)cfaOffset, (uint)fujiIfd.Length]; + for (var i = 0; i < directory.Length; i++) BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(0x54 + 4 * i), directory[i]); + return [.. header, .. jpeg, .. records, .. fujiIfd]; + } + + /// WebP with VP8X canvas 3000×2000, a VP8L bitstream, EXIF (no prefix) and XMP chunks. + public static byte[] WebP() + { + byte[] vp8x = [0x0C, 0, 0, 0, .. UInt24(2999), .. UInt24(1999)]; + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8X", vp8x), .. Box.Riff("VP8L", Vp8L(3000, 2000)), + .. Box.Riff("EXIF", ExifTiff(false)), .. Box.Riff("XMP ", Encoding.UTF8.GetBytes(Xmp))]; + return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body]; + } + + /// Simple lossy WebP (VP8 key frame) without metadata. + public static byte[] WebPLossy(int width, int height) + { + byte[] frame = [0x10, 0x02, 0x00, 0x9D, 0x01, 0x2A, (byte)width, (byte)(width >> 8), (byte)height, (byte)(height >> 8), 0, 0]; + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8 ", frame)]; + return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body]; + } + + public static byte[] Vp8L(int width, int height) + { + var bits = (uint)(width - 1) | (uint)(height - 1) << 14; + return [0x2F, .. LittleEndian32((int)bits), 0]; + } + + /// PNG 2048×1536 16-bit RGB with eXIf (big-endian TIFF), iTXt XMP (zlib-compressed when asked), IDAT, IEND. + public static byte[] Png(bool compressedXmp = false) + { + var ihdr = (byte[])[.. Box.U32(2048), .. Box.U32(1536), 16, 2, 0, 0, 0]; + var xmp = Encoding.UTF8.GetBytes(Xmp); + if (compressedXmp) + { + using var output = new MemoryStream(); + using (var z = new System.IO.Compression.ZLibStream(output, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true)) z.Write(xmp); + xmp = output.ToArray(); + } + var itxt = (byte[])[.. "XML:com.adobe.xmp\0"u8, compressedXmp ? (byte)1 : (byte)0, 0, 0, 0, .. xmp]; + return [0x89, .. "PNG\r\n\u001a\n"u8, .. Box.Png("IHDR", ihdr), .. Box.Png("eXIf", ExifTiff(false)), + .. Box.Png("iTXt", itxt), .. Box.Png("IDAT", new byte[32]), .. Box.Png("IEND", [])]; + } + + /// Every fixture by name, for table-driven and fuzz tests. + public static byte[] ByName(string name) => name switch + { + "jpeg" => Jpeg(), + "jpeg-be" => Jpeg(false), + "cr2" => Cr2(), + "nef" => Nef(), + "dng" => Dng(), + "arw" => Arw(), + "orf" => Orf(), + "rw2" => Rw2(), + "cr3" => Cr3(), + "heic" => Heic(), + "avif" => Heic(major: "avif"), + "raf" => Raf(), + "webp" => WebP(), + "png" => Png(), + "png-z" => Png(compressedXmp: true), + _ => throw new ArgumentException(name), + }; + + private static byte[] UInt24(int v) => [(byte)v, (byte)(v >> 8), (byte)(v >> 16)]; + + private static byte[] LittleEndian32(int v) + { + var b = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(b, v); + return b; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs new file mode 100644 index 00000000..393cbfc0 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs @@ -0,0 +1,276 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Declarative IFD for synthetic test files: typed values, child-IFD pointers, data blobs and embedded +/// (MakerNote-style) IFDs. Serialised by in either byte order. +internal sealed class IfdSpec +{ + internal abstract record Entry(ushort Tag); + + internal sealed record ValueEntry(ushort Tag, TiffType Type, object Data) : Entry(Tag); + + internal sealed record ChildrenEntry(ushort Tag, IfdSpec[] Children) : Entry(Tag); + + internal sealed record BlobEntry(ushort Tag, byte[] Data) : Entry(Tag); + + internal sealed record EmbeddedEntry(ushort Tag, byte[] Prefix, IfdSpec Ifd, bool RelativeToTiff, bool LittleEndian) : Entry(Tag); + + public List Entries { get; } = []; + + /// Next IFD in the chain (IFD1 after IFD0…). + public IfdSpec? Next { get; set; } + + public IfdSpec Ascii(ushort tag, string value) => Add(new ValueEntry(tag, TiffType.Ascii, value)); + + public IfdSpec Short(ushort tag, params ushort[] values) => Add(new ValueEntry(tag, TiffType.Short, values)); + + public IfdSpec Long(ushort tag, params uint[] values) => Add(new ValueEntry(tag, TiffType.Long, values)); + + public IfdSpec Rational(ushort tag, params (uint, uint)[] values) => Add(new ValueEntry(tag, TiffType.Rational, values)); + + public IfdSpec SRational(ushort tag, int numerator, int denominator) => Add(new ValueEntry(tag, TiffType.SRational, new[] { (numerator, denominator) })); + + public IfdSpec Undefined(ushort tag, byte[] data) => Add(new ValueEntry(tag, TiffType.Undefined, data)); + + public IfdSpec Bytes(ushort tag, params byte[] data) => Add(new ValueEntry(tag, TiffType.Byte, data)); + + /// LONG pointer(s) to child IFDs (Exif, GPS, SubIFDs, MakerNote sub-directories). + public IfdSpec Child(ushort tag, params IfdSpec[] children) => Add(new ChildrenEntry(tag, children)); + + /// LONG offset to (placed after all IFDs) plus an optional LONG length tag. + public IfdSpec Blob(ushort offsetTag, ushort? lengthTag, byte[] data) + { + Add(new BlobEntry(offsetTag, data)); + return lengthTag is { } t ? Long(t, (uint)data.Length) : this; + } + + public IfdSpec Strip(byte[] data) => Blob(TiffTags.StripOffsets, TiffTags.StripByteCounts, data); + + /// UNDEFINED value made of and an IFD whose offsets are relative to the TIFF base + /// () or to the start of the value itself. + public IfdSpec Embedded(ushort tag, byte[] prefix, IfdSpec ifd, bool relativeToTiff, bool littleEndian) => + Add(new EmbeddedEntry(tag, prefix, ifd, relativeToTiff, littleEndian)); + + public IfdSpec Without(params ushort[] tags) + { + Entries.RemoveAll(e => tags.Contains(e.Tag)); + return this; + } + + private IfdSpec Add(Entry entry) + { + Entries.RemoveAll(e => e.Tag == entry.Tag); + Entries.Add(entry); + return this; + } +} + +/// Serialises trees: IFDs in depth-first order, each followed by its values, blobs last. +internal static class TiffFile +{ + /// A complete TIFF file/block with header ( overrides "II*\0"/"MM\0*", e.g. "IIRO"); + /// follows the 8-byte header (the CR2 "CR" marker block). + public static byte[] Build(IfdSpec ifd0, bool littleEndian = true, string? magic = null, byte[]? headerExtra = null) + { + var w = new IfdWriter(littleEndian, 0); + w.Raw(Encoding.Latin1.GetBytes(magic ?? (littleEndian ? "II*\0" : "MM\0*"))); + w.Raw(new byte[4]); + if (headerExtra is not null) w.Raw(headerExtra); + w.PatchU32(4, (uint)w.WriteChain(ifd0)); + w.FlushBlobs(); + return w.ToArray(); + } + + /// An IFD and its values laid out as if placed at relative to the offset base. + public static byte[] Block(IfdSpec ifd, bool littleEndian, int origin) + { + var w = new IfdWriter(littleEndian, origin); + w.WriteChain(ifd); + w.FlushBlobs(); + return w.ToArray(); + } + + private sealed class IfdWriter(bool le, int origin) + { + private readonly List _b = []; + private readonly List<(int Patch, byte[] Data)> _blobs = []; + + public byte[] ToArray() => _b.ToArray(); + + public void Raw(byte[] bytes) => _b.AddRange(bytes); + + public int WriteChain(IfdSpec spec) + { + var position = WriteIfd(spec, out var nextPatch); + if (spec.Next is { } next) PatchU32(nextPatch, (uint)WriteChain(next)); + return position; + } + + public void FlushBlobs() + { + foreach (var (patch, data) in _blobs) + { + Align(); + PatchU32(patch, (uint)(origin + _b.Count)); + _b.AddRange(data); + } + _blobs.Clear(); + } + + public void PatchU32(int at, uint value) + { + Span s = stackalloc byte[4]; + if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, value); + else BinaryPrimitives.WriteUInt32BigEndian(s, value); + for (var i = 0; i < 4; i++) _b[at + i] = s[i]; + } + + private void PatchU16(int at, ushort value) + { + Span s = stackalloc byte[2]; + if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, value); + else BinaryPrimitives.WriteUInt16BigEndian(s, value); + _b[at] = s[0]; + _b[at + 1] = s[1]; + } + + private void Align() + { + if ((origin + _b.Count) % 2 != 0) _b.Add(0); + } + + private int WriteIfd(IfdSpec spec, out int nextPatch) + { + Align(); + var start = _b.Count; + var entries = spec.Entries.OrderBy(e => e.Tag).ToList(); + _b.AddRange(new byte[2 + 12 * entries.Count + 4]); + PatchU16(start, (ushort)entries.Count); + nextPatch = start + 2 + 12 * entries.Count; + var children = new List<(int Patch, IfdSpec Child)>(); + for (var i = 0; i < entries.Count; i++) + { + var at = start + 2 + 12 * i; + var e = entries[i]; + PatchU16(at, e.Tag); + switch (e) + { + case IfdSpec.ValueEntry v: + var (bytes, count) = Encode(v); + PutValue(at, v.Type, count, bytes); + break; + case IfdSpec.ChildrenEntry c: + PatchU16(at + 2, (ushort)TiffType.Long); + PatchU32(at + 4, (uint)c.Children.Length); + if (c.Children.Length == 1) + { + children.Add((at + 8, c.Children[0])); + } + else + { + Align(); + PatchU32(at + 8, (uint)(origin + _b.Count)); + for (var k = 0; k < c.Children.Length; k++) + { + children.Add((_b.Count, c.Children[k])); + _b.AddRange(new byte[4]); + } + } + break; + case IfdSpec.BlobEntry blob: + PatchU16(at + 2, (ushort)TiffType.Long); + PatchU32(at + 4, 1); + _blobs.Add((at + 8, blob.Data)); + break; + case IfdSpec.EmbeddedEntry m: + Align(); + var position = origin + _b.Count; + var block = Block(m.Ifd, m.LittleEndian, m.RelativeToTiff ? position + m.Prefix.Length : m.Prefix.Length); + PatchU16(at + 2, (ushort)TiffType.Undefined); + PatchU32(at + 4, (uint)(m.Prefix.Length + block.Length)); + PatchU32(at + 8, (uint)position); + _b.AddRange(m.Prefix); + _b.AddRange(block); + break; + } + } + foreach (var (patch, child) in children) PatchU32(patch, (uint)WriteChain(child)); + return origin + start; + } + + private void PutValue(int at, TiffType type, uint count, byte[] bytes) + { + PatchU16(at + 2, (ushort)type); + PatchU32(at + 4, count); + if (bytes.Length <= 4) + { + for (var i = 0; i < bytes.Length; i++) _b[at + 8 + i] = bytes[i]; + return; + } + Align(); + PatchU32(at + 8, (uint)(origin + _b.Count)); + _b.AddRange(bytes); + } + + private (byte[] Bytes, uint Count) Encode(IfdSpec.ValueEntry v) + { + switch (v.Data) + { + case string s: + var ascii = Encoding.UTF8.GetBytes(s + "\0"); + return (ascii, (uint)ascii.Length); + case byte[] raw: + return (raw, (uint)raw.Length); + case ushort[] shorts: + { + var b = new byte[2 * shorts.Length]; + for (var i = 0; i < shorts.Length; i++) Write16(b.AsSpan(2 * i), shorts[i]); + return (b, (uint)shorts.Length); + } + case uint[] longs: + { + var b = new byte[4 * longs.Length]; + for (var i = 0; i < longs.Length; i++) Write32(b.AsSpan(4 * i), longs[i]); + return (b, (uint)longs.Length); + } + case (uint, uint)[] rationals: + { + var b = new byte[8 * rationals.Length]; + for (var i = 0; i < rationals.Length; i++) + { + Write32(b.AsSpan(8 * i), rationals[i].Item1); + Write32(b.AsSpan(8 * i + 4), rationals[i].Item2); + } + return (b, (uint)rationals.Length); + } + case (int, int)[] signed: + { + var b = new byte[8 * signed.Length]; + for (var i = 0; i < signed.Length; i++) + { + Write32(b.AsSpan(8 * i), (uint)signed[i].Item1); + Write32(b.AsSpan(8 * i + 4), (uint)signed[i].Item2); + } + return (b, (uint)signed.Length); + } + default: + throw new InvalidOperationException("Unsupported test value " + v.Data.GetType()); + } + } + + private void Write16(Span s, ushort v) + { + if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, v); + else BinaryPrimitives.WriteUInt16BigEndian(s, v); + } + + private void Write32(Span s, uint v) + { + if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, v); + else BinaryPrimitives.WriteUInt32BigEndian(s, v); + } + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs b/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs new file mode 100644 index 00000000..04a3b1bd --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/JpegBuilder.cs @@ -0,0 +1,149 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Core.Tests.Metadata.Builders; + +/// Synthetic JPEG: SOI, arbitrary segments/raw bytes, an optional APP2 MPF index of appended secondary +/// images, SOFn, SOS with a fake scan, EOI. No real entropy data: parsers stop at SOS. +internal sealed class JpegBuilder +{ + public const string XmpSignature = "http://ns.adobe.com/xap/1.0/\0"; + public const string ExtendedXmpSignature = "http://ns.adobe.com/xmp/extension/\0"; + + private readonly List _parts = []; + private readonly List<(byte[] Jpeg, uint Type)> _secondary = []; + private int _mpfPart = -1; + + /// A minimal JPEG with just a frame header (used as embedded previews). + public static byte[] Minimal(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32) => + new JpegBuilder().Build(width, height, sofMarker, precision, scanBytes); + + public JpegBuilder Segment(byte marker, byte[] payload) + { + var s = new byte[4 + payload.Length]; + s[0] = 0xFF; + s[1] = marker; + BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2)); + payload.CopyTo(s, 4); + _parts.Add(s); + return this; + } + + /// Bytes inserted verbatim (fill bytes, garbage). + public JpegBuilder Raw(params byte[] bytes) + { + _parts.Add(bytes); + return this; + } + + public JpegBuilder Exif(byte[] tiff) => Segment(0xE1, [.. "Exif\0\0"u8, .. tiff]); + + public JpegBuilder Xmp(string packet) => Segment(0xE1, [.. Encoding.ASCII.GetBytes(XmpSignature), .. Encoding.UTF8.GetBytes(packet)]); + + /// Extended XMP split into -byte APP1 segments (written in reverse order to prove + /// reassembly uses offsets). + public JpegBuilder ExtendedXmp(string guid, string packet, int chunk) + { + var data = Encoding.UTF8.GetBytes(packet); + var segments = new List(); + for (var offset = 0; offset < data.Length; offset += chunk) + { + var piece = data.AsSpan(offset, Math.Min(chunk, data.Length - offset)); + var payload = new byte[ExtendedXmpSignature.Length + 32 + 8 + piece.Length]; + Encoding.ASCII.GetBytes(ExtendedXmpSignature).CopyTo(payload, 0); + Encoding.ASCII.GetBytes(guid).CopyTo(payload, ExtendedXmpSignature.Length); + BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 32), (uint)data.Length); + BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 36), (uint)offset); + piece.CopyTo(payload.AsSpan(ExtendedXmpSignature.Length + 40)); + segments.Add(payload); + } + segments.Reverse(); + foreach (var s in segments) Segment(0xE1, s); + return this; + } + + /// APP2 MPF index; each secondary JPEG is appended after the primary's EOI with the given MP type code. + public JpegBuilder Mpf(params (byte[] Jpeg, uint Type)[] secondary) + { + _secondary.AddRange(secondary); + _mpfPart = _parts.Count; + _parts.Add([]); + return this; + } + + public byte[] Build(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32) + { + var tail = new List(); + tail.AddRange(SegmentBytes(sofMarker, [(byte)precision, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1])); + tail.AddRange(SegmentBytes(0xDA, [3, 1, 0, 2, 0x11, 3, 0x11, 0, 0x3F, 0])); + for (var i = 0; i < scanBytes; i++) tail.Add((byte)(i * 37 % 255)); + tail.AddRange([0xFF, 0xD9]); + + if (_mpfPart >= 0) _parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(new uint[_secondary.Count], 0)); + var headLength = 2 + _parts.Sum(p => p.Length); + var primaryLength = headLength + tail.Count; + if (_mpfPart >= 0) + { + var mpHeader = 2 + _parts.Take(_mpfPart).Sum(p => p.Length) + 4 + 4; + var offsets = new uint[_secondary.Count]; + var at = primaryLength; + for (var i = 0; i < offsets.Length; i++) + { + offsets[i] = (uint)(at - mpHeader); + at += _secondary[i].Jpeg.Length; + } + _parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(offsets, primaryLength)); + } + + var file = new List(primaryLength); + file.AddRange([0xFF, 0xD8]); + foreach (var p in _parts) file.AddRange(p); + file.AddRange(tail); + foreach (var (jpeg, _) in _secondary) file.AddRange(jpeg); + return file.ToArray(); + + byte[] MpfPayload(uint[] offsets, int primarySize) + { + // "MPF\0", big-endian MP header, index IFD (version, count, entries), then 16-byte MP entries. + var n = offsets.Length + 1; + var b = new byte[4 + 8 + 2 + 3 * 12 + 4 + 16 * n]; + var s = b.AsSpan(); + "MPF\0MM\0*"u8.CopyTo(s); + BinaryPrimitives.WriteUInt32BigEndian(s[8..], 8); + var ifd = s[12..]; + BinaryPrimitives.WriteUInt16BigEndian(ifd, 3); + WriteEntry(ifd[2..], 0xB000, 7, 4, BinaryPrimitives.ReadUInt32BigEndian("0100"u8)); + WriteEntry(ifd[14..], 0xB001, 4, 1, (uint)n); + WriteEntry(ifd[26..], 0xB002, 7, (uint)(16 * n), 8 + 2 + 36 + 4); + var entries = s[(4 + 8 + 2 + 36 + 4)..]; + BinaryPrimitives.WriteUInt32BigEndian(entries, 0x20030000); + BinaryPrimitives.WriteUInt32BigEndian(entries[4..], (uint)primarySize); + for (var i = 0; i < offsets.Length; i++) + { + var e = entries[(16 * (i + 1))..]; + BinaryPrimitives.WriteUInt32BigEndian(e, _secondary[i].Type); + BinaryPrimitives.WriteUInt32BigEndian(e[4..], (uint)_secondary[i].Jpeg.Length); + BinaryPrimitives.WriteUInt32BigEndian(e[8..], offsets[i]); + } + return b; + } + } + + private static void WriteEntry(Span s, ushort tag, ushort type, uint count, uint value) + { + BinaryPrimitives.WriteUInt16BigEndian(s, tag); + BinaryPrimitives.WriteUInt16BigEndian(s[2..], type); + BinaryPrimitives.WriteUInt32BigEndian(s[4..], count); + BinaryPrimitives.WriteUInt32BigEndian(s[8..], value); + } + + private static byte[] SegmentBytes(byte marker, byte[] payload) + { + var s = new byte[4 + payload.Length]; + s[0] = 0xFF; + s[1] = marker; + BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2)); + payload.CopyTo(s, 4); + return s; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs b/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs new file mode 100644 index 00000000..e11ae79c --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/Builders/TestStreams.cs @@ -0,0 +1,86 @@ +namespace Titano.Core.Tests.Metadata.Builders; + +/// Read-only seekable stream: prefix bytes followed by zeros up to length. Simulates a large +/// RAW (image data never materialised) for I/O-bound tests. +internal sealed class SparseStream(byte[] prefix, long length) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => _position; + set => _position = value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = (int)Math.Max(0, Math.Min(buffer.Length, length - _position)); + for (var i = 0; i < n; i++) + { + var p = _position + i; + buffer[i] = p < prefix.Length ? prefix[p] : (byte)0; + } + _position += n; + return n; + } + + public override long Seek(long offset, SeekOrigin origin) => _position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => length + offset, + }; + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// Counts the bytes returned by of the wrapped stream. +internal sealed class CountingStream(Stream inner) : Stream +{ + public long BytesRead { get; private set; } + public int ReadCalls { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => inner.Length; + + public override long Position + { + get => inner.Position; + set => inner.Position = value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = inner.Read(buffer); + BytesRead += n; + ReadCalls++; + return n; + } + + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} From f68eae03c521c279609d7a3bde65f998a66d23d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:02:03 +0000 Subject: [PATCH 067/188] test(metadata): cover signatures, Exif, XMP and TIFF RAWs Signature table for every format and tie-break; every FrameMetadata field from JPEG in both byte orders; timestamp fallbacks (digitized, XMP, GPS, file time), sub-seconds and offsets, orientation, ISO and APEX rules, GPS validation; XMP attribute/element forms, priority, DTD refusal, size cap and extended-XMP reassembly; CR2/NEF/DNG/ARW/ORF/RW2 main-image selection, previews with real sizes and MakerNote fallbacks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Core.Tests/Metadata/ExifTests.cs | 278 ++++++++++++++++++ .../Metadata/ImageSignatureTests.cs | 112 +++++++ .../Metadata/MetadataTestHelpers.cs | 25 ++ .../Metadata/RawContainerTests.cs | 190 ++++++++++++ tests/Titano.Core.Tests/Metadata/XmpTests.cs | 196 ++++++++++++ 5 files changed, 801 insertions(+) create mode 100644 tests/Titano.Core.Tests/Metadata/ExifTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs create mode 100644 tests/Titano.Core.Tests/Metadata/RawContainerTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/XmpTests.cs diff --git a/tests/Titano.Core.Tests/Metadata/ExifTests.cs b/tests/Titano.Core.Tests/Metadata/ExifTests.cs new file mode 100644 index 00000000..b990d65e --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ExifTests.cs @@ -0,0 +1,278 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ExifTests +{ + [Theory] + [Case(true)] + [Case(false)] + public void ReadsEveryFieldFromJpeg(bool littleEndian) + { + var m = Read(Fixtures.Jpeg(littleEndian), "IMG_0001.JPG"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Jpeg, m.Format); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Model, m.Model); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + Assert.Equal("fw 1.0", m.Software); + Assert.Equal("Ada", m.Artist); + Assert.Equal("(c) Ada", m.Copyright); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind); + Assert.Equal(120, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(1 / 250.0, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(5.6, m.FNumber!.Value, 1e-12); + Assert.Equal(400, m.Iso); + Assert.Approximately(35, m.FocalLength!.Value, 1e-12); + Assert.Approximately(52, m.FocalLength35!.Value, 1e-12); + Assert.Approximately(-2 / 3.0, m.ExposureBias!.Value, 1e-12); + Assert.Equal(3, m.ExposureProgram); + Assert.Equal(5, m.MeteringMode); + Assert.Equal(1, m.WhiteBalanceMode); + Assert.Equal(16, m.Flash); + Assert.Null(m.ColorTemperature); + Assert.Equal(6, m.Orientation); + Assert.Equal(4000, m.Width); + Assert.Equal(3000, m.Height); + Assert.Equal((3000, 4000), m.OrientedSize); + Assert.Equal(8, m.BitsPerSample); + var gps = Assert.NotNull(m.Gps); + Assert.Approximately(45.5, gps.Latitude, 1e-9); + Assert.Approximately(-9.26, gps.Longitude, 1e-9); + Assert.Approximately(120.5, gps.Altitude!.Value, 1e-9); + Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56, DateTimeKind.Utc), gps.UtcTimestamp); + Assert.Equal(4, m.Rating); + Assert.Equal("Red", m.Label); + AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + } + + [Test] + public void PreviewOffsetsPointAtJpegData() + { + var bytes = Fixtures.Jpeg(); + var m = Read(bytes); + foreach (var p in m.Previews) + { + Assert.Equal(0xFF, bytes[p.Offset]); + Assert.Equal(0xD8, bytes[p.Offset + 1]); + Assert.Equal(0xD9, bytes[p.Offset + p.Length - 1]); + } + } + + [Test] + public void FallsBackToDigitizedTime() + { + var m = ReadWithExif(Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal)); + Assert.Equal(TimestampSource.ExifCreate, m.TimestampSource); + Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 57), m.CapturedAt); + } + + [Test] + public void FallsBackToXmpTime() + { + var xmp = """ + + + + """; + var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized); + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48); + var m = Read(jpeg); + Assert.Equal(TimestampSource.Xmp, m.TimestampSource); + Assert.Equal(new DateTime(2023, 12, 31, 23, 59, 58, 250), m.CapturedAt); + Assert.Equal(-300, m.UtcOffsetMinutes); + } + + [Test] + public void FallsBackToGpsTime() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized); + var m = ReadWithExif(exif); + Assert.Equal(TimestampSource.Gps, m.TimestampSource); + Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56), m.CapturedAt); + Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind); + Assert.Equal(0, m.UtcOffsetMinutes); + } + + [Theory] + [Case(DateTimeKind.Utc, 0)] + [Case(DateTimeKind.Unspecified, null)] + public void FallsBackToFileTime(DateTimeKind kind, int? expectedOffset) + { + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0())).Build(64, 48); + var modified = new DateTime(2022, 2, 3, 4, 5, 6, kind); + var m = Read(jpeg, null, modified); + Assert.Equal(TimestampSource.FileSystem, m.TimestampSource); + Assert.Equal(new DateTime(2022, 2, 3, 4, 5, 6), m.CapturedAt); + Assert.Equal(expectedOffset, m.UtcOffsetMinutes); + } + + [Test] + public void LocalFileTimeCarriesLocalOffset() + { + var modified = new DateTime(2022, 7, 3, 4, 5, 6, DateTimeKind.Local); + var m = Read(JpegBuilder.Minimal(8, 8), null, modified); + Assert.Equal((int)TimeZoneInfo.Local.GetUtcOffset(modified).TotalMinutes, m.UtcOffsetMinutes); + } + + [Test] + public void NoTimeAtAllIsUnknown() + { + var m = Read(JpegBuilder.Minimal(8, 8)); + Assert.Equal(TimestampSource.Unknown, m.TimestampSource); + Assert.Null(m.CapturedAt); + } + + [Theory] + [Case("5", "+05:30", 5_000_000L, 330)] + [Case("123456789", "-03:00", 1_234_567L, -180)] + [Case("007", "+0100", 70_000L, 60)] + [Case("", "Z", 0L, 0)] + [Case(" ", " : ", 0L, null)] + [Case("12x", "+25:00", 1_200_000L, null, Name = "trailing junk, offset out of range")] + public void ParsesSubSecondsAndOffsets(string subSec, string offset, long ticks, int? minutes) + { + var exif = Fixtures.ExifIfd().Ascii(TiffTags.SubSecTimeOriginal, subSec).Ascii(TiffTags.OffsetTimeOriginal, offset); + var m = ReadWithExif(exif); + Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(ticks), m.CapturedAt); + Assert.Equal(minutes, m.UtcOffsetMinutes); + } + + [Test] + public void OffsetTimeIsTheFallbackOffset() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.OffsetTimeOriginal).Ascii(TiffTags.OffsetTime, "-07:00"); + Assert.Equal(-420, ReadWithExif(exif).UtcOffsetMinutes); + } + + [Theory] + [Case("0000:00:00 00:00:00")] + [Case(" : : : : ")] + [Case("2024:13:01 10:00:00")] + [Case("2024:02:30 10:00:00")] + [Case("2024:05")] + public void RejectsInvalidDates(string value) + { + var exif = Fixtures.ExifIfd().Ascii(TiffTags.DateTimeOriginal, value); + Assert.Equal(TimestampSource.ExifCreate, ReadWithExif(exif).TimestampSource); + } + + [Theory] + [Case((ushort)1, 1)] + [Case((ushort)3, 3)] + [Case((ushort)5, 5)] + [Case((ushort)8, 8)] + [Case((ushort)0, 1)] + [Case((ushort)9, 1)] + public void ValidatesOrientation(ushort value, int expected) + { + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0(orientation: value))).Build(64, 48)); + Assert.Equal(expected, m.Orientation); + if (value is 0 or 9) Assert.Contains($"Invalid orientation {value} ignored", m.Warnings); + } + + [Test] + public void XmpOrientationAppliesWithoutExif() + { + var xmp = """3"""; + Assert.Equal(3, Read(new JpegBuilder().Xmp(xmp).Build(64, 48)).Orientation); + } + + [Theory] + [Case((ushort)65535, 102400u, 102400)] + [Case((ushort)65535, 0u, 65535, Name = "saturated without REI")] + [Case((ushort)0, 51200u, 51200, Name = "ISO absent")] + [Case((ushort)3200, 6400u, 3200, Name = "ISO wins when valid")] + public void ResolvesIso(ushort iso, uint rei, int expected) + { + var exif = Fixtures.ExifIfd(iso: iso); + if (rei > 0) exif.Long(TiffTags.RecommendedExposureIndex, rei); + Assert.Equal(expected, ReadWithExif(exif).Iso); + } + + [Test] + public void UsesStandardOutputSensitivityWhenIsoMissing() + { + var exif = Fixtures.ExifIfd(iso: 0).Long(TiffTags.StandardOutputSensitivity, 250); + Assert.Equal(250, ReadWithExif(exif).Iso); + } + + [Test] + public void DerivesExposureFromApexValues() + { + var exif = Fixtures.ExifIfd().Without(TiffTags.FNumber, TiffTags.ExposureTime) + .SRational(TiffTags.ShutterSpeedValue, 8, 1) + .Rational(TiffTags.ApertureValue, (5, 1)); + var m = ReadWithExif(exif); + Assert.Approximately(1 / 256.0, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(Math.Pow(2, 2.5), m.FNumber!.Value, 1e-12); + } + + [Test] + public void IgnoresVoidGpsFix() + { + var gps = Fixtures.GpsIfd().Ascii(TiffTags.GpsStatus, "V"); + var tiff = TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Null(m.Gps); + Assert.Equal(TimestampSource.Gps, m.TimestampSource); + } + + [Test] + public void RejectsOutOfRangeCoordinates() + { + var gps = Fixtures.GpsIfd().Rational(TiffTags.GpsLatitude, (95, 1), (0, 1), (0, 1)); + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps))).Build(64, 48)); + Assert.Null(m.Gps); + } + + [Test] + public void ToleratesFillBytesAndGarbageBetweenSegments() + { + var jpeg = new JpegBuilder() + .Raw(0xFF, 0xFF, 0xFF) + .Exif(Fixtures.ExifTiff()) + .Raw(0x00, 0x13, 0x37, 0xFF) + .Segment(0xFE, "comment"u8.ToArray()) + .Build(1234, 567); + var m = Read(jpeg); + Assert.Equal(1234, m.Width); + Assert.Equal(567, m.Height); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Contains("JPEG: garbage between segments skipped", m.Warnings); + } + + [Theory] + [Case((byte)0xC2, 8)] + [Case((byte)0xC1, 12)] + public void ReadsProgressiveAndExtendedFrames(byte sof, int precision) + { + var m = Read(JpegBuilder.Minimal(800, 600, sof, precision)); + Assert.Equal((800, 600), (m.Width, m.Height)); + Assert.Equal(precision, m.BitsPerSample); + } + + [Test] + public void TruncatedExifKeepsWhatWasRead() + { + var full = Fixtures.Jpeg(); + var cut = full.AsSpan(0, 140).ToArray(); + var m = Read(cut); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Jpeg, m.Format); + Assert.NotEmpty(m.Warnings); + } + + private static FrameMetadata ReadWithExif(IfdSpec exif) => + Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif).Child(TiffTags.GpsIfd, Fixtures.GpsIfd()))).Build(64, 48)); +} diff --git a/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs b/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs new file mode 100644 index 00000000..d45c472d --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ImageSignatureTests.cs @@ -0,0 +1,112 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ImageSignatureTests +{ + [Theory] + [Case("jpeg", "a.jpg", ImageFileFormat.Jpeg)] + [Case("jpeg", "a.png", ImageFileFormat.Jpeg, Name = "extension never overrides the signature")] + [Case("png", null, ImageFileFormat.Png)] + [Case("webp", null, ImageFileFormat.WebP)] + [Case("raf", "a.jpg", ImageFileFormat.Raf)] + [Case("cr2", "a.tif", ImageFileFormat.Cr2, Name = "CR marker beats .tif")] + [Case("cr3", null, ImageFileFormat.Cr3)] + [Case("heic", null, ImageFileFormat.Heif)] + [Case("avif", null, ImageFileFormat.Avif)] + [Case("nef", null, ImageFileFormat.Nef)] + [Case("nef", "x.NRW", ImageFileFormat.Nrw)] + [Case("nef", "x.tif", ImageFileFormat.Tiff, Name = "Nikon-made TIFF")] + [Case("arw", "x.arw", ImageFileFormat.Arw)] + [Case("arw", "x.sr2", ImageFileFormat.Sr2)] + [Case("arw", "x.srf", ImageFileFormat.Srf)] + [Case("dng", "x.dng", ImageFileFormat.Dng)] + [Case("dng", "x.gpr", ImageFileFormat.Gpr)] + [Case("dng", "x.tif", ImageFileFormat.Dng, Name = "DNGVersion beats .tif")] + [Case("orf", null, ImageFileFormat.Orf)] + [Case("rw2", null, ImageFileFormat.Rw2)] + [Case("rw2", "x.rwl", ImageFileFormat.Rwl)] + [Case("rw2", "x.raw", ImageFileFormat.Raw)] + public void DetectsFixtures(string fixture, string? fileName, ImageFileFormat expected) => + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(Fixtures.ByName(fixture)), fileName)); + + [Theory] + [Case("PENTAX Corporation", null, ImageFileFormat.Pef)] + [Case("RICOH IMAGING COMPANY, LTD.", null, ImageFileFormat.Pef)] + [Case("SAMSUNG", null, ImageFileFormat.Srw)] + [Case("Hasselblad", null, ImageFileFormat.ThreeFr)] + [Case("Hasselblad", "x.fff", ImageFileFormat.Fff)] + [Case("Phase One", null, ImageFileFormat.Iiq)] + [Case("Leaf", null, ImageFileFormat.Iiq)] + [Case("Canon", "x.cr2", ImageFileFormat.Cr2, Name = "Canon without CR marker, .cr2")] + [Case("Canon", null, ImageFileFormat.Tiff)] + [Case("OLYMPUS", "x.orf", ImageFileFormat.Orf)] + [Case("Scanner Inc", "x.pef", ImageFileFormat.Pef, Name = "unknown make, raw extension breaks the tie")] + [Case("Scanner Inc", null, ImageFileFormat.Tiff)] + [Case("SAMSUNG", "x.tiff", ImageFileFormat.Tiff, Name = ".tiff keeps a camera-made TIFF a TIFF")] + public void RefinesTiffByMake(string make, string? fileName, ImageFileFormat expected) + { + var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make).Long(TiffTags.ImageWidth, 8), littleEndian: false); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(tiff), fileName)); + } + + [Theory] + [Case("LEICA CAMERA AG", null, ImageFileFormat.Rwl)] + [Case("Panasonic", null, ImageFileFormat.Rw2)] + public void PanasonicHeaderUsesMake(string make, string? fileName, ImageFileFormat expected) + { + var rw = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make), magic: "IIU\0"); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(rw), fileName)); + } + + [Theory] + [Case("mif1", "heic", ImageFileFormat.Heif)] + [Case("mif1", "avif", ImageFileFormat.Avif)] + [Case("msf1", "hevc", ImageFileFormat.Heif)] + [Case("heix", "mif1", ImageFileFormat.Heif)] + [Case("avis", "msf1", ImageFileFormat.Avif)] + [Case("qt ", "qt ", ImageFileFormat.Unknown, Name = "QuickTime movie")] + [Case("isom", "mp41", ImageFileFormat.Unknown, Name = "MP4 video")] + public void ClassifiesFtypBrands(string major, string compatible, ImageFileFormat expected) + { + var ftyp = Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii(compatible)); + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream([.. ftyp, .. Box.Make("free")]), null)); + } + + [Theory] + [Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)] + [Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'7', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)] + [Case(new byte[] { 0xFF, 0x0A, 0x7F, 0 }, ImageFileFormat.JpegXl)] + [Case(new byte[] { 0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A }, ImageFileFormat.JpegXl)] + [Case(new byte[] { (byte)'I', (byte)'I', 0xBC, 0x01, 8, 0, 0, 0 }, ImageFileFormat.JpegXr)] + [Case(new byte[] { (byte)'I', (byte)'I', 0x1A, 0, 0, 0, (byte)'H', (byte)'E', (byte)'A', (byte)'P', (byte)'C', (byte)'C', (byte)'D', (byte)'R' }, ImageFileFormat.Crw)] + [Case(new byte[] { (byte)'M', (byte)'M', (byte)'O', (byte)'R', 0, 0, 0, 8 }, ImageFileFormat.Orf)] + [Case(new byte[] { 0xFF, 0xD8, 0xFF, 0xE1 }, ImageFileFormat.Jpeg)] + [Case(new byte[] { 0xFF, 0xD8 }, ImageFileFormat.Unknown, Name = "two bytes of SOI only")] + [Case(new byte[] { (byte)'B', (byte)'M', 0, 0 }, ImageFileFormat.Unknown, Name = "BM without a DIB header")] + [Case(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, ImageFileFormat.Unknown)] + [Case(new byte[0], ImageFileFormat.Unknown)] + public void DetectsMagicBytes(byte[] head, ImageFileFormat expected) => + Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(head), "file.jpg")); + + [Test] + public void DetectsBmpWithInfoHeader() + { + var bmp = new byte[54]; + "BM"u8.CopyTo(bmp); + bmp[14] = 40; + Assert.Equal(ImageFileFormat.Bmp, ImageSignature.Detect(new MemoryStream(bmp), null)); + } + + [Test] + public void RestoresStreamPosition() + { + var stream = new MemoryStream(Fixtures.Nef()) { Position = 5 }; + ImageSignature.Detect(stream, null); + Assert.Equal(5L, stream.Position); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs b/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs new file mode 100644 index 00000000..4bf6ea89 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/MetadataTestHelpers.cs @@ -0,0 +1,25 @@ +using Titano.Core.Metadata; +using Titano.Testing; + +namespace Titano.Core.Tests.Metadata; + +internal static class MetadataTestHelpers +{ + public static FrameMetadata Read(byte[] data, string? fileName = null, DateTime? modified = null) => + MetadataReader.Read(new MemoryStream(data, writable: false), fileName, modified); + + /// The reader's safety net turns parser defects into "Parser fault" warnings; tests require none. + public static void AssertNoFault(FrameMetadata m) + { + foreach (var w in m.Warnings) + { + if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail(w); + } + } + + public static void AssertPreviews(FrameMetadata m, params (int Width, int Height, PreviewKind Kind)[] expected) + { + Assert.SequenceEqual(expected, m.Previews.Select(p => (p.Width, p.Height, p.Kind)), "previews"); + foreach (var p in m.Previews) Assert.True(p.Offset > 0 && p.Length > 0, $"preview at {p.Offset} length {p.Length}"); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs b/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs new file mode 100644 index 00000000..e8fff67d --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/RawContainerTests.cs @@ -0,0 +1,190 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// TIFF-based RAWs: main-image selection across IFDs/SubIFDs, embedded previews and MakerNote fallbacks. +public sealed class RawContainerTests +{ + [Test] + public void Cr2() + { + var m = Read(Fixtures.Cr2(), "IMG_0001.CR2"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Cr2, m.Format); + Assert.Equal("Canon", m.Make); + Assert.Equal((6720, 4480), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (6720, 4480, PreviewKind.FullSize), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("0000123456", m.BodySerial); + Assert.Equal("EF24-70mm f/2.8L II USM", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(5200, m.ColorTemperature); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(1, m.Orientation); + } + + [Test] + public void Nef() + { + var m = Read(Fixtures.Nef(), "DSC_0001.NEF"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Nef, m.Format); + Assert.Equal("NIKON CORPORATION", m.Make); + Assert.Equal((8288, 5520), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (8256, 5504, PreviewKind.FullSize)); + Assert.Equal("3001234", m.BodySerial); + Assert.Equal(12345L, m.ShutterCount); + Assert.Equal("24-70mm f/2.8", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(64, m.Iso); + } + + [Test] + public void Dng() + { + var m = Read(Fixtures.Dng(), "PXL_0001.dng"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Dng, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + AssertPreviews(m, (1024, 768, PreviewKind.Preview)); + Assert.Equal("DNGSER1", m.BodySerial); + Assert.Equal("Pixel 8", m.Model); + } + + [Test] + public void Arw() + { + var m = Read(Fixtures.Arw(), "DSC00001.ARW"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Arw, m.Format); + Assert.Equal((6048, 4024), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + AssertPreviews(m, (1616, 1080, PreviewKind.Preview)); + Assert.Equal("24-70mm F2.8", m.LensModel); + Assert.Equal(5600, m.ColorTemperature); + Assert.Equal(true, m.ImageStabilization); + } + + [Test] + public void Orf() + { + var m = Read(Fixtures.Orf(), "P0000001.ORF"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Orf, m.Format); + Assert.Equal((5240, 3912), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + AssertPreviews(m, (3200, 2400, PreviewKind.Preview)); + Assert.Equal("BHX123", m.BodySerial); + Assert.Equal("M.Zuiko 12-40mm F2.8", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + } + + [Test] + public void Rw2() + { + var m = Read(Fixtures.Rw2(), "P1000001.RW2"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Rw2, m.Format); + Assert.Equal("Panasonic", m.Make); + Assert.Equal("DC-GH6", m.Model); + Assert.Equal((5776, 4344), (m.Width, m.Height)); + Assert.Equal(12, m.BitsPerSample); + Assert.Equal(800, m.Iso); + AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("F541504040123", m.BodySerial); + Assert.Equal("LUMIX G VARIO 12-60mm", m.LensModel); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(5000, m.ColorTemperature); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Equal(1, m.Orientation); + } + + [Test] + public void StandardTagsBeatMakerNote() + { + var makerNote = new IfdSpec().Long(0x000C, 42).Ascii(0x0095, "MakerNote Lens"); + var exif = Fixtures.ExifIfd().Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + } + + [Theory] + [Case("Canon EOS-1D X Mark III", "042000")] + [Case("Canon EOS R6", "0000042000")] + public void FormatsCanonSerialByModel(string model, string expected) + { + var makerNote = new IfdSpec().Long(0x000C, 42000); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: false); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", model).Child(TiffTags.ExifIfd, exif), littleEndian: false); + Assert.Equal(expected, Read(new JpegBuilder().Exif(tiff).Build(64, 48)).BodySerial); + } + + [Test] + public void ReadsHeaderlessNikonMakerNote() + { + var nikon = new IfdSpec().Ascii(0x001D, "TYPE2").Long(0x00A7, 7); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], nikon, relativeToTiff: true, littleEndian: true); + var tiff = TiffFile.Build(Fixtures.Ifd0("NIKON", "E5700").Child(TiffTags.ExifIfd, exif)); + var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48)); + Assert.Equal("TYPE2", m.BodySerial); + Assert.Equal(7L, m.ShutterCount); + } + + [Test] + public void ReadsLegacyOlympusAndFujifilmMakerNotes() + { + var olympus = new IfdSpec().Child(0x2010, new IfdSpec().Ascii(0x0101, "OLD-SN")); + var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "OLYMP\0"u8, 1, 0], olympus, relativeToTiff: true, littleEndian: true); + var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("OLYMPUS", "E-1").Child(TiffTags.ExifIfd, exif))).Build(64, 48)); + Assert.Equal("OLD-SN", m.BodySerial); + + var fuji = new IfdSpec().Short(0x1422, 0, 0, 0); + exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true); + m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("FUJIFILM", "X100V").Child(TiffTags.ExifIfd, exif), littleEndian: false)).Build(64, 48)); + Assert.Equal(false, m.ImageStabilization); + } + + [Test] + public void MakerNoteOutsideFileIsReported() + { + var exif = Fixtures.ExifIfd(identity: false).Undefined(TiffTags.MakerNote, new byte[64]); + var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif)); + var cut = tiff.AsSpan(0, tiff.Length - 40).ToArray(); + var m = Read(cut, "a.tif"); + AssertNoFault(m); + Assert.Contains("MakerNote outside the file", m.Warnings); + } + + [Test] + public void SubIfdLoopsAreBroken() + { + // IFD0's SubIFDs entry points back at IFD0 itself. + var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, "Loop").Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10).Long(TiffTags.SubIfds, 8)); + var m = Read(tiff, "loop.tif"); + AssertNoFault(m); + Assert.Equal((10, 10), (m.Width, m.Height)); + Assert.Contains("IFD loop at 8", m.Warnings); + } + + [Test] + public void PlainTiffUsesLargestFullResolutionIfd() + { + var reduced = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 9000).Long(TiffTags.ImageLength, 9000); + var ifd0 = new IfdSpec().Long(TiffTags.ImageWidth, 3000).Long(TiffTags.ImageLength, 2000).Short(TiffTags.BitsPerSample, 16, 16, 16); + ifd0.Next = reduced; + var m = Read(TiffFile.Build(ifd0, littleEndian: false), "scan.tif"); + Assert.Equal(ImageFileFormat.Tiff, m.Format); + Assert.Equal((3000, 2000), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/XmpTests.cs b/tests/Titano.Core.Tests/Metadata/XmpTests.cs new file mode 100644 index 00000000..5dfda915 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/XmpTests.cs @@ -0,0 +1,196 @@ +using System.Text; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Metadata.Xmp; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class XmpTests +{ + private const string Head = """"""; + private const string Tail = ""; + private const string Namespaces = """ + xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:exif="http://ns.adobe.com/exif/1.0/" + xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" + xmlns:aux="http://ns.adobe.com/exif/1.0/aux/" xmlns:exifEX="http://cipa.jp/exif/1.0/" + xmlns:xmpNote="http://ns.adobe.com/xmp/note/" + """; + + [Test] + public void ReadsAttributeForm() + { + var v = Parse($""" + {Head}{Tail} + """); + Assert.Equal(5, v.Rating); + Assert.Equal("Green", v.Label); + Assert.Equal(new DateTime(2024, 3, 4, 5, 6, 7, 500), v.DateTimeOriginal!.Value.Value); + Assert.Equal(60, v.DateTimeOriginal!.Value.OffsetMinutes); + Assert.Equal(8, v.Orientation); + Assert.Equal("BODY1", v.BodySerial); + Assert.Equal("CipaLens", v.Lens); + } + + [Test] + public void ReadsElementForm() + { + var v = Parse($""" + {Head} + -1 + + 2021-01-02T03:04Z + 2020-01-01T00:00:00 + 2 + AUX2 + Nested Lens + {Tail} + """); + Assert.Equal(-1, v.Rating); + Assert.Equal("Purple", v.Label); + Assert.Equal(new DateTime(2021, 1, 2, 3, 4, 0), v.CaptureTime!.Value.Value); + Assert.Equal(0, v.CaptureTime!.Value.OffsetMinutes); + Assert.Equal(2, v.Orientation); + Assert.Equal("AUX2", v.BodySerial); + Assert.Equal("Nested Lens", v.Lens); + } + + [Theory] + [Case("exif:DateTimeOriginal=\"2001-01-01T01:01:01\" photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2001)] + [Case("photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2002)] + [Case("xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003)] + [Case("photoshop:DateCreated=\"2002-02-02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003, Name = "date-only values are not capture times")] + public void CaptureTimeFollowsMwgOrder(string attributes, int year) => + Assert.Equal(year, Parse($"{Head}{Tail}").CaptureTime!.Value.Value.Year); + + [Test] + public void FirstPacketWins() + { + var v = new XmpValues(); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}{Tail}"), v)); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}{Tail}"), v)); + Assert.Equal(2, v.Rating); + Assert.Equal("Blue", v.Label); + } + + [Test] + public void RefusesDtdsAndEntities() + { + var packet = $"""]>{Head}{Tail}"""; + var v = new XmpValues(); + var problem = XmpParser.Parse(Encoding.UTF8.GetBytes(packet), v); + Assert.NotNull(problem); + Assert.Null(v.Label); + } + + [Test] + public void MalformedPacketKeepsEarlierValues() + { + var v = new XmpValues(); + var problem = XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}Yel"), v); + Assert.Contains("Malformed XMP", problem); + Assert.Equal(3, v.Rating); + } + + [Test] + public void RejectsPacketsOverFourMegabytes() + { + var packet = new byte[XmpParser.MaxPacketBytes + 1]; + packet.AsSpan().Fill((byte)' '); + Assert.Equal("XMP packet larger than 4 MB ignored", XmpParser.Parse(packet, new XmpValues())); + } + + [Test] + public void IgnoresTrailingNulPaddingAndInvalidValues() + { + var v = new XmpValues(); + var bytes = Encoding.UTF8.GetBytes($"{Head}{Tail}\0\0\0"); + Assert.Null(XmpParser.Parse(bytes, v)); + Assert.Null(v.Rating); + Assert.Null(v.Orientation); + Assert.Null(v.CreateDate); + } + + [Test] + public void ReassemblesExtendedXmpInJpeg() + { + const string guid = "0123456789ABCDEF0123456789ABCDEF"; + var main = $"{Head}{Tail}"; + var extended = $"{Head}{Tail}"; + var jpeg = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 200).Build(64, 48); + var m = Read(jpeg); + AssertNoFault(m); + Assert.Equal(1, m.Rating); + Assert.Equal(TimestampSource.Xmp, m.TimestampSource); + Assert.Equal(new DateTime(2019, 9, 9, 9, 9, 9), m.CapturedAt); + Assert.Contains("Extended Lens", m.LensModel); + } + + [Test] + public void IgnoresUnreferencedOrIncompleteExtendedXmp() + { + const string guid = "0123456789ABCDEF0123456789ABCDEF"; + var extended = $"{Head}{Tail}"; + var unreferenced = Read(new JpegBuilder().ExtendedXmp(guid, extended, 64).Build(64, 48)); + Assert.Null(unreferenced.Label); + Assert.Contains("Extended XMP present but not referenced by the main packet", unreferenced.Warnings); + + var main = $"{Head}{Tail}"; + var builder = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 64); + var bytes = builder.Build(64, 48); + var withoutFirstChunk = Read(RemoveFirstExtendedChunk(bytes)); + Assert.Null(withoutFirstChunk.Label); + Assert.Contains("Extended XMP incomplete", withoutFirstChunk.Warnings); + } + + [Test] + public void SuppliesSerialAndLensFallbacks() + { + var xmp = $"{Head}{Tail}"; + var exif = Fixtures.ExifIfd(identity: false); + var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48); + var m = Read(jpeg); + Assert.Equal("XMPSN", m.BodySerial); + Assert.Equal("XMP Lens", m.LensModel); + } + + [Test] + public void ExifIdentityBeatsXmp() + { + var xmp = $"{Head}{Tail}"; + var m = Read(new JpegBuilder().Exif(Fixtures.ExifTiff()).Xmp(xmp).Build(64, 48)); + Assert.Equal("SN123", m.BodySerial); + Assert.Equal("TestLens 35mm", m.LensModel); + } + + [Test] + public void ReadsXmpTagInTiff() + { + var xmp = Encoding.UTF8.GetBytes($"{Head}{Tail}"); + var tiff = TiffFile.Build(Fixtures.Ifd0().Undefined(TiffTags.Xmp, xmp).Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10)); + Assert.Equal("FromTiff", Read(tiff, "a.tif").Label); + } + + private static XmpValues Parse(string packet) + { + var values = new XmpValues(); + Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes(packet), values)); + return values; + } + + /// Drops the extended-XMP segment holding offset 0 (written last by ). + private static byte[] RemoveFirstExtendedChunk(byte[] jpeg) + { + var signature = Encoding.ASCII.GetBytes(JpegBuilder.ExtendedXmpSignature); + var last = -1; + for (var i = 0; i + signature.Length < jpeg.Length; i++) + { + if (jpeg.AsSpan(i).StartsWith(signature)) last = i - 4; + } + var length = jpeg[last + 2] << 8 | jpeg[last + 3]; + return [.. jpeg.AsSpan(0, last), .. jpeg.AsSpan(last + 2 + length)]; + } +} From 484bfa9dd55fcfcda3173dbd5c9f53b3059602bf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:02:13 +0000 Subject: [PATCH 068/188] test(metadata): cover BMFF, RAF, PNG, WebP, ExifWriter, fuzzing CR3 and HEIC/AVIF parsing (irot/imir orientation table, multi-extent XMP), the box walker's edge cases, RAF/WebP/PNG/GIF/BMP/JPEG XL/JPEG XR, ExifWriter round trips through MetadataReader, and robustness: 200 truncations plus 500 seeded corruptions per fixture with no exception or parser fault, previews always inside the file, 50 MB DNG and CR3 read with well under 512 KB, 2,000 JPEG headers under 2 s, cancellation and shared file access. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Core.Tests/Metadata/BmffTests.cs | 127 +++++++++++ .../Metadata/ExifWriterTests.cs | 147 +++++++++++++ .../Metadata/OtherFormatTests.cs | 202 ++++++++++++++++++ .../Metadata/RobustnessTests.cs | 189 ++++++++++++++++ 4 files changed, 665 insertions(+) create mode 100644 tests/Titano.Core.Tests/Metadata/BmffTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs create mode 100644 tests/Titano.Core.Tests/Metadata/RobustnessTests.cs diff --git a/tests/Titano.Core.Tests/Metadata/BmffTests.cs b/tests/Titano.Core.Tests/Metadata/BmffTests.cs new file mode 100644 index 00000000..c122240f --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/BmffTests.cs @@ -0,0 +1,127 @@ +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Bmff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class BmffTests +{ + [Test] + public void Cr3() + { + var m = Read(Fixtures.Cr3(), "IMG_0001.CR3"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Cr3, m.Format); + Assert.Equal("Canon", m.Make); + Assert.Equal("Canon EOS R5", m.Model); + Assert.Equal(8, m.Orientation); + Assert.Equal((8352, 5586), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (8192, 5464, PreviewKind.FullSize), (1620, 1080, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal(new DateTime(2024, 6, 1, 8, 0, 0, 500), m.CapturedAt); + Assert.Equal(-240, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(0.01, m.ExposureTime!.Value, 1e-12); + Assert.Approximately(4, m.FNumber!.Value, 1e-12); + Assert.Equal(100, m.Iso); + Assert.Equal("0000098765", m.BodySerial); + Assert.Equal("RF24-105mm F4 L IS USM", m.LensModel); + Assert.Approximately(-9.26, m.Gps!.Longitude, 1e-9); + } + + [Test] + public void Cr3FullSizeJpegIsTrackOneSample() + { + var bytes = Fixtures.Cr3(out var mdatStart); + var full = Read(bytes).Previews[0]; + Assert.Equal(mdatStart + 8L, full.Offset); + Assert.Equal(0xFF, bytes[full.Offset]); + Assert.Equal(0xD9, bytes[full.Offset + full.Length - 1]); + } + + [Theory] + [Case(false, false, 6, Name = "no transforms: Exif orientation applies")] + [Case(true, false, 8, Name = "irot 90° anticlockwise")] + [Case(true, true, 7, Name = "irot then imir left-right")] + [Case(false, true, 2, Name = "imir left-right only")] + public void HeifTransformsOverrideExifOrientation(bool rotate, bool mirror, int expected) => + Assert.Equal(expected, Read(Fixtures.Heic(rotate, mirror), "IMG_0001.HEIC").Orientation); + + [Test] + public void Heic() + { + var m = Read(Fixtures.Heic(), "IMG_0001.HEIC"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Heif, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal(10, m.BitsPerSample); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(400, m.Iso); + Assert.Equal(4, m.Rating); + Assert.Equal("Red", m.Label); + AssertPreviews(m, (160, 120, PreviewKind.Thumbnail)); + } + + [Test] + public void Avif() + { + var m = Read(Fixtures.Heic(major: "avif"), "a.avif"); + Assert.Equal(ImageFileFormat.Avif, m.Format); + Assert.Equal((4032, 3024), (m.Width, m.Height)); + Assert.Equal("Red", m.Label); + } + + [Test] + public void WalksLargeSizeToEndAndUuidBoxes() + { + var guid = Guid.NewGuid(); + byte[] large = [.. Box.U32(1), .. Box.Ascii("free"), .. Box.U64(20), 1, 2, 3, 4]; + byte[] data = [.. Box.Make("ftyp", Box.Ascii("heic")), .. large, .. Box.Uuid(guid, [9, 9]), .. Box.U32(0), .. Box.Ascii("mdat"), 7, 7, 7]; + var boxes = BmffReader.ReadChildren(new MemoryStream(data), 0, data.Length); + Assert.Equal(4, boxes.Count); + Assert.True(boxes[1].Is("free")); + Assert.Equal(16, boxes[1].HeaderSize); + Assert.Equal(20L, boxes[1].Size); + Assert.Equal(guid, boxes[2].UserType); + Assert.Equal(24, boxes[2].HeaderSize); + Assert.True(boxes[3].Is("mdat")); + Assert.Equal((long)data.Length, boxes[3].End); + } + + [Test] + public void StopsAtMalformedAndClampsTruncatedBoxes() + { + var warnings = new List(); + byte[] truncated = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(1000), .. Box.Ascii("moov"), 0, 0]; + var boxes = BmffReader.ReadChildren(new MemoryStream(truncated), 0, truncated.Length, warnings); + Assert.Equal(2, boxes.Count); + Assert.Equal((long)truncated.Length, boxes[1].End); + Assert.Contains("Box 'moov' at 12 runs past its container", warnings); + + byte[] malformed = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(4), .. Box.Ascii("bad!"), .. Box.Make("free")]; + Assert.Equal(1, BmffReader.ReadChildren(new MemoryStream(malformed), 0, malformed.Length).Count); + } + + [Test] + public void FindPathIsDepthLimited() + { + var box = new BmffBox(FourCC.From("moov"), 0, 8, 8, Guid.Empty); + Assert.Throws(() => BmffReader.FindPath(new MemoryStream(new byte[8]), box, [.. Enumerable.Repeat("trak", BmffReader.MaxDepth + 1)])); + Assert.Null(BmffReader.FindPath(new MemoryStream(new byte[8]), box, "trak", "mdia")); + } + + [Test] + public void FourCCRoundTrips() + { + Assert.Equal(0x66747970u, FourCC.From("ftyp")); + Assert.Equal("ftyp", FourCC.Format(0x66747970)); + Assert.Equal("?abc", FourCC.Format(0x01616263)); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs b/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs new file mode 100644 index 00000000..3e962e5c --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/ExifWriterTests.cs @@ -0,0 +1,147 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +public sealed class ExifWriterTests +{ + private static readonly FrameMetadata Sample = new() + { + Make = "TestCam", + Model = "TC-1 Mark II", + Orientation = 8, + Software = "Titano 1.0", + Artist = "Ada Lovelace", + Copyright = "© 2024 Ada", + CapturedAt = new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(1_234_500), + UtcOffsetMinutes = -330, + ExposureTime = 1 / 8000.0, + FNumber = 2.8, + Iso = 3200, + FocalLength = 23.5, + FocalLength35 = 35, + ExposureBias = -1 / 3.0, + BodySerial = "BODY-42", + LensModel = "XF23mmF1.4 R", + Gps = new GpsPosition(-33.8567844, 151.2152967, -12.25, new DateTime(2024, 5, 1, 2, 4, 56, 500, DateTimeKind.Utc)), + }; + + [Test] + public void RoundTripsThroughMetadataReader() + { + var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample))); + AssertNoFault(m); + Assert.Equal(Sample.Make, m.Make); + Assert.Equal(Sample.Model, m.Model); + Assert.Equal(8, m.Orientation); + Assert.Equal(Sample.Software, m.Software); + Assert.Equal(Sample.Artist, m.Artist); + Assert.Equal(Sample.Copyright, m.Copyright); + Assert.Equal(Sample.CapturedAt, m.CapturedAt); + Assert.Equal(-330, m.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource); + Assert.Approximately(Sample.ExposureTime!.Value, m.ExposureTime!.Value, 1e-15); + Assert.Approximately(2.8, m.FNumber!.Value, 1e-12); + Assert.Equal(3200, m.Iso); + Assert.Approximately(23.5, m.FocalLength!.Value, 1e-12); + Assert.Approximately(35, m.FocalLength35!.Value, 1e-12); + Assert.Approximately(-1 / 3.0, m.ExposureBias!.Value, 1e-4); + Assert.Equal(Sample.BodySerial, m.BodySerial); + Assert.Equal(Sample.LensModel, m.LensModel); + var gps = Assert.NotNull(m.Gps); + Assert.Approximately(-33.8567844, gps.Latitude, 1e-7); + Assert.Approximately(151.2152967, gps.Longitude, 1e-7); + Assert.Approximately(-12.25, gps.Altitude!.Value, 1e-9); + Assert.Equal(Sample.Gps!.UtcTimestamp, gps.UtcTimestamp); + } + + [Test] + public void App1SegmentIsWellFormed() + { + var app1 = ExifWriter.BuildJpegApp1(Sample); + Assert.Equal(0xFF, app1[0]); + Assert.Equal(0xE1, app1[1]); + Assert.Equal(app1.Length - 2, BinaryPrimitives.ReadUInt16BigEndian(app1.AsSpan(2))); + Assert.True(app1.AsSpan(4).StartsWith("Exif\0\0II*\0"u8)); + } + + [Test] + public void TiffIsSortedAndPointersResolve() + { + var tiff = ExifWriter.BuildTiff(Sample); + var reader = Assert.NotNull(TiffReader.Open(new MemoryStream(tiff))); + Assert.True(reader.LittleEndian); + var chain = reader.ReadChain(); + Assert.Equal(1, chain.Count); + var ifd0 = chain[0]; + AssertSorted(reader, ifd0); + var exif = Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)); + AssertSorted(reader, exif); + Assert.Equal("0232", reader.GetString(exif, TiffTags.ExifVersion)); + Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value)); + Assert.Empty(reader.Warnings); + } + + [Test] + public void OmitsUnknownValuesAndGps() + { + var tiff = ExifWriter.BuildTiff(new FrameMetadata { Make = "Only" }); + var reader = TiffReader.Open(new MemoryStream(tiff))!; + var ifd0 = reader.ReadChain()[0]; + Assert.False(ifd0.Has(TiffTags.GpsIfd)); + Assert.False(ifd0.Has(TiffTags.DateTime)); + Assert.Equal((ushort)1, (ushort)reader.GetUInt(ifd0, TiffTags.Orientation)!.Value); + var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!; + Assert.False(exif.Has(TiffTags.ExposureTime)); + Assert.False(exif.Has(TiffTags.SubSecTimeOriginal)); + Assert.False(exif.Has(TiffTags.OffsetTimeOriginal)); + } + + [Test] + public void HighIsoUsesRecommendedExposureIndex() + { + var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample with { Iso = 204800 }))); + Assert.Equal(204800, m.Iso); + } + + [Theory] + [Case(1 / 8000.0, 1u, 8000u)] + [Case(0.3, 3u, 10u)] + [Case(2.8, 14u, 5u)] + [Case(30.0, 30u, 1u)] + public void EncodesExposureRationals(double seconds, uint numerator, uint denominator) + { + var tiff = ExifWriter.BuildTiff(new FrameMetadata { ExposureTime = seconds }); + var reader = TiffReader.Open(new MemoryStream(tiff))!; + var exif = reader.ReadIfd(reader.GetUInt(reader.ReadChain()[0], TiffTags.ExifIfd)!.Value)!; + var raw = reader.ReadBytes(exif.Entries[TiffTags.ExposureTime])!; + Assert.Equal(numerator, BinaryPrimitives.ReadUInt32LittleEndian(raw)); + Assert.Equal(denominator, BinaryPrimitives.ReadUInt32LittleEndian(raw.AsSpan(4))); + } + + [Test] + public void TruncatesLongStringsOnCharacterBoundaries() + { + var longText = new string('é', ExifWriter.MaxStringBytes); + var app1 = ExifWriter.BuildJpegApp1(new FrameMetadata { Artist = longText, Copyright = longText, Make = longText, Model = longText, Software = longText, BodySerial = longText, LensModel = longText }); + Assert.Less(app1.Length, 65535); + var m = Read(Wrap(app1)); + Assert.Equal(ExifWriter.MaxStringBytes / 2, m.Artist!.Length); + Assert.True(m.Artist.All(c => c == 'é')); + } + + /// SOI + APP1 + a minimal 64×48 frame. + private static byte[] Wrap(byte[] app1) => [0xFF, 0xD8, .. app1, .. Builders.JpegBuilder.Minimal(64, 48).AsSpan(2)]; + + private static void AssertSorted(TiffReader reader, Ifd ifd) + { + var count = BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position, 2)!); + var tags = new List(); + for (var i = 0; i < count; i++) tags.Add(BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position + 2 + 12 * i, 2)!)); + Assert.Monotonic(tags, strict: true); + } +} diff --git a/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs b/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs new file mode 100644 index 00000000..e7f3ec0f --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/OtherFormatTests.cs @@ -0,0 +1,202 @@ +using System.Buffers.Binary; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// RAF, WebP, PNG and the minimal formats (GIF, BMP, JPEG XL, JPEG XR). +public sealed class OtherFormatTests +{ + [Test] + public void Raf() + { + var m = Read(Fixtures.Raf(), "DSCF0001.RAF"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Raf, m.Format); + Assert.Equal("FUJIFILM", m.Make); + Assert.Equal("X-T5", m.Model); + Assert.Equal((7752, 5178), (m.Width, m.Height)); + Assert.Equal(14, m.BitsPerSample); + AssertPreviews(m, (1920, 1280, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail)); + Assert.Equal("FF02B1234567", m.BodySerial); + Assert.Equal(6100, m.ColorTemperature); + Assert.Equal(true, m.ImageStabilization); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + } + + [Test] + public void RafHeaderModelIsTheFallback() + { + var raf = Fixtures.Raf(); + BinaryPrimitives.WriteUInt32BigEndian(raf.AsSpan(0x54), 0); + var m = Read(raf); + Assert.Equal("FUJIFILM", m.Make); + Assert.Equal("X-T5", m.Model); + Assert.Equal((7752, 5178), (m.Width, m.Height)); + Assert.Contains("RAF embedded JPEG missing", m.Warnings); + } + + [Test] + public void WebPWithVp8xExifAndXmp() + { + var m = Read(Fixtures.WebP(), "a.webp"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.WebP, m.Format); + Assert.Equal((3000, 2000), (m.Width, m.Height)); + Assert.Equal(8, m.BitsPerSample); + Assert.Equal(Fixtures.Make, m.Make); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + Assert.Equal(4, m.Rating); + Assert.Equal(6, m.Orientation); + } + + [Test] + public void WebPSimpleFormats() + { + Assert.Equal((640, 480), Size(Read(Fixtures.WebPLossy(640, 480)))); + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(400, 300))]; + Assert.Equal((400, 300), Size(Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body]))); + } + + [Test] + public void WebPExifWithPrefix() + { + var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(8, 8)), .. Box.Riff("EXIF", [.. "Exif\0\0"u8, .. Fixtures.ExifTiff()])]; + Assert.Equal(Fixtures.Model, Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body]).Model); + } + + [Theory] + [Case(false)] + [Case(true)] + public void Png(bool compressedXmp) + { + var m = Read(Fixtures.Png(compressedXmp), "a.png"); + AssertNoFault(m); + Assert.Empty(m.Warnings); + Assert.Equal(ImageFileFormat.Png, m.Format); + Assert.Equal((2048, 1536), (m.Width, m.Height)); + Assert.Equal(16, m.BitsPerSample); + Assert.Equal(Fixtures.Model, m.Model); + Assert.Equal(400, m.Iso); + Assert.Equal("Red", m.Label); + } + + [Test] + public void Gif() => Assert.Equal((320, 200), Size(Read([.. "GIF89a"u8, 0x40, 0x01, 0xC8, 0x00, 0, 0, 0]))); + + [Theory] + [Case(40, 640, -480)] + [Case(124, 1024, 768)] + public void Bmp(int headerSize, int width, int height) + { + var bmp = new byte[54]; + "BM"u8.CopyTo(bmp); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(14), headerSize); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(18), width); + BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(22), height); + Assert.Equal((width, Math.Abs(height)), Size(Read(bmp))); + } + + [Test] + public void BmpCoreHeader() + { + var bmp = new byte[26]; + "BM"u8.CopyTo(bmp); + bmp[14] = 12; + BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(18), 300); + BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(20), 200); + Assert.Equal((300, 200), Size(Read(bmp))); + } + + [Theory] + [Case(256, 128)] + [Case(1000, 750, Name = "4:3 ratio")] + [Case(1921, 1081)] + [Case(300000, 270000, Name = "two 30-bit sizes (68-bit header)")] + public void JpegXlCodestream(int width, int height) + { + var m = Read(BuildJpegXlCodestream(width, height), "a.jxl"); + Assert.Equal(ImageFileFormat.JpegXl, m.Format); + Assert.Equal((width, height), Size(m)); + } + + [Test] + public void JpegXlContainer() + { + byte[] file = [.. Box.Make("JXL ", [0x0D, 0x0A, 0x87, 0x0A]), .. Box.Make("ftyp", Box.Ascii("jxl "), Box.U32(0), Box.Ascii("jxl ")), + .. Box.Make("Exif", Box.U32(0), Fixtures.ExifTiff()), .. Box.Make("jxlp", Box.U32(0), BuildJpegXlCodestream(512, 384))]; + var m = Read(file); + Assert.Equal(ImageFileFormat.JpegXl, m.Format); + Assert.Equal((512, 384), Size(m)); + Assert.Equal(Fixtures.Make, m.Make); + } + + [Test] + public void JpegXr() + { + var ifd = new IfdSpec().Ascii(TiffTags.Make, "Microsoft").Long(0xBC80, 1600).Long(0xBC81, 900); + var m = Read(TiffFile.Build(ifd, magic: "II¼\u0001"), "a.jxr"); + Assert.Equal(ImageFileFormat.JpegXr, m.Format); + Assert.Equal((1600, 900), Size(m)); + Assert.Equal("Microsoft", m.Make); + } + + [Test] + public void UnknownFilesYieldAWarning() + { + var m = Read("hello world, not an image"u8.ToArray(), "notes.jpg"); + Assert.Equal(ImageFileFormat.Unknown, m.Format); + Assert.Contains("Unrecognised file signature", m.Warnings); + } + + private static (int, int) Size(FrameMetadata m) => (m.Width, m.Height); + + private static byte[] LittleEndian(int v) + { + var b = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(b, v); + return b; + } + + /// FF 0A + SizeHeader (ISO/IEC 18181-1): small multiples of 8 or U32 distributions; a 4:3 ratio when exact. + private static byte[] BuildJpegXlCodestream(int width, int height) + { + var bits = new List(); + void Put(ulong value, int count) + { + for (var i = 0; i < count; i++) bits.Add(((value >> i) & 1) != 0); + } + void PutU32(int value) + { + var v = (ulong)(value - 1); + var (selector, n) = v < 1 << 9 ? (0, 9) : v < 1 << 13 ? (1, 13) : v < 1 << 18 ? (2, 18) : (3, 30); + Put((ulong)selector, 2); + Put(v, n); + } + var small = width % 8 == 0 && height % 8 == 0 && width <= 256 && height <= 256; + Put(small ? 1UL : 0UL, 1); + if (small) Put((ulong)(height / 8 - 1), 5); + else PutU32(height); + var ratio = height * 4 / 3 == width && height % 3 == 0 ? 3 : 0; + Put((ulong)ratio, 3); + if (ratio == 0) + { + if (small) Put((ulong)(width / 8 - 1), 5); + else PutU32(width); + } + var bytes = new byte[2 + (bits.Count + 7) / 8 + 8]; + bytes[0] = 0xFF; + bytes[1] = 0x0A; + for (var i = 0; i < bits.Count; i++) + { + if (bits[i]) bytes[2 + i / 8] |= (byte)(1 << (i % 8)); + } + return bytes; + } +} diff --git a/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs b/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs new file mode 100644 index 00000000..bead02a9 --- /dev/null +++ b/tests/Titano.Core.Tests/Metadata/RobustnessTests.cs @@ -0,0 +1,189 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Model; +using Titano.Core.Tests.Metadata.Builders; +using Titano.Testing; +using static Titano.Core.Tests.Metadata.MetadataTestHelpers; + +namespace Titano.Core.Tests.Metadata; + +/// Fuzzing, I/O bounds, speed, cancellation and file access. +public sealed class RobustnessTests(TestContext context) +{ + private const int Truncations = 200; + private const int Corruptions = 500; + private const long FiftyMegabytes = 50L * 1024 * 1024; + private const long ReadBudget = 512 * 1024; + + [Theory] + [Case("jpeg")] + [Case("jpeg-be")] + [Case("cr2")] + [Case("nef")] + [Case("dng")] + [Case("arw")] + [Case("orf")] + [Case("rw2")] + [Case("cr3")] + [Case("heic")] + [Case("avif")] + [Case("raf")] + [Case("webp")] + [Case("png")] + [Case("png-z")] + [Timeout(5000)] + public void SurvivesTruncationAndCorruption(string fixture) + { + var original = Fixtures.ByName(fixture); + var random = new Random(fixture.Aggregate(0x5EED, (seed, c) => seed * 31 + c)); + var parses = 0; + for (var i = 0; i < Truncations; i++) + { + var length = (int)((long)original.Length * i / Truncations) + random.Next(0, 3); + Check(original.AsSpan(0, Math.Min(length, original.Length)).ToArray(), $"truncated at {length}"); + parses++; + } + var buffer = new byte[original.Length]; + for (var i = 0; i < Corruptions; i++) + { + original.CopyTo(buffer, 0); + var flips = random.Next(1, 9); + for (var f = 0; f < flips; f++) buffer[random.Next(buffer.Length)] = (byte)random.Next(256); + Check(buffer, $"corruption {i}"); + parses++; + } + Assert.Equal(Truncations + Corruptions, parses); + } + + [Test] + public void FuzzedFieldsStaySane() + { + var random = new Random(7); + var original = Fixtures.Jpeg(); + for (var i = 0; i < 300; i++) + { + var bytes = (byte[])original.Clone(); + for (var f = 0; f < 6; f++) bytes[random.Next(bytes.Length)] ^= (byte)(1 << random.Next(8)); + var m = Read(bytes, "fuzz.jpg"); + Assert.InRange(m.Orientation, 1, 8); + Assert.True(m.Width >= 0 && m.Height >= 0); + foreach (var p in m.Previews) Assert.True(p.Offset >= 0 && p.Offset + p.Length <= bytes.Length, "preview inside file"); + } + } + + [Test] + public void LargeDngReadsWellUnderHalfAMegabyte() + { + var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 4000).Long(TiffTags.ImageLength, 3000) + .Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 6) + .Strip(JpegBuilder.Minimal(4000, 3000, scanBytes: 1_500_000)); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0).Long(TiffTags.ImageWidth, 8000).Long(TiffTags.ImageLength, 6000) + .Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 32803) + .Long(TiffTags.StripOffsets, 2_000_000).Long(TiffTags.StripByteCounts, 48_000_000); + var ifd0 = Fixtures.Ifd0("Leica Camera AG", "M11", 1).Long(TiffTags.NewSubfileType, 1).Bytes(TiffTags.DngVersion, 1, 6, 0, 0) + .Child(TiffTags.SubIfds, raw, preview).Child(TiffTags.ExifIfd, Fixtures.ExifIfd()).Child(TiffTags.GpsIfd, Fixtures.GpsIfd()); + var bytes = TiffFile.Build(ifd0); + Assert.Less(bytes.Length, 2_000_000); + using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes)); + var m = MetadataReader.Read(stream, "L1000001.DNG"); + AssertNoFault(m); + Assert.Equal(ImageFileFormat.Dng, m.Format); + Assert.Equal((8000, 6000), (m.Width, m.Height)); + AssertPreviews(m, (4000, 3000, PreviewKind.Preview)); + Assert.Equal(Fixtures.Captured, m.CapturedAt); + context.Log($"DNG: {stream.BytesRead} bytes in {stream.ReadCalls} reads"); + Assert.Less(stream.BytesRead, ReadBudget); + } + + [Test] + public void LargeCr3ReadsWellUnderHalfAMegabyte() + { + var bytes = Fixtures.Cr3(out var mdatStart); + BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(mdatStart), (uint)(FiftyMegabytes - mdatStart)); + using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes)); + var m = MetadataReader.Read(stream, "IMG_0001.CR3"); + AssertNoFault(m); + Assert.Equal((8352, 5586), (m.Width, m.Height)); + Assert.Count(3, m.Previews); + context.Log($"CR3: {stream.BytesRead} bytes in {stream.ReadCalls} reads"); + Assert.Less(stream.BytesRead, ReadBudget); + } + + [Test] + public void ParsesTwoThousandJpegHeadersQuickly() + { + var jpeg = Fixtures.Jpeg(); + Read(jpeg); + var watch = Stopwatch.StartNew(); + for (var i = 0; i < 2000; i++) + { + var m = MetadataReader.Read(new MemoryStream(jpeg, writable: false), "IMG.JPG"); + if (m.Width != 4000) Assert.Fail("unexpected width"); + } + watch.Stop(); + context.Log($"2000 JPEG headers in {watch.ElapsedMilliseconds} ms"); + Assert.Less(watch.Elapsed.TotalSeconds, 2.0); + } + + [Test] + public void HonoursCancellation() + { + using var cts = new CancellationTokenSource(); + cts.Cancel(); + Assert.Throws(() => MetadataReader.Read(new MemoryStream(Fixtures.Nef()), "a.nef", null, cts.Token)); + } + + [Test] + public void RejectsNonSeekableStreams() + { + Assert.Throws(() => MetadataReader.Read(new NonSeekable(), null)); + Assert.Throws(() => ImageSignature.Detect(new NonSeekable(), null)); + } + + [Test] + public void ReadsFilesSharedWithAWriter() + { + var path = Path.Combine(context.CreateTempDirectory(), "IMG_0002.JPG"); + File.WriteAllBytes(path, JpegBuilder.Minimal(320, 240)); + var modified = new DateTime(2021, 6, 7, 8, 9, 10, DateTimeKind.Local); + File.SetLastWriteTime(path, modified); + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) + { + var m = MetadataReader.Read(path); + Assert.Equal((320, 240), (m.Width, m.Height)); + Assert.Equal(TimestampSource.FileSystem, m.TimestampSource); + Assert.Equal(new DateTime(2021, 6, 7, 8, 9, 10), m.CapturedAt); + } + } + + private static void Check(byte[] bytes, string what) + { + FrameMetadata m; + try + { + m = MetadataReader.Read(new MemoryStream(bytes, writable: false), "fuzz"); + } + catch (Exception ex) + { + Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}"); + return; + } + foreach (var w in m.Warnings) + { + if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail($"{what}: {w}"); + } + foreach (var p in m.Previews) + { + if (p.Offset < 0 || p.Length <= 0 || p.Offset + p.Length > bytes.Length) Assert.Fail($"{what}: preview {p} outside the file"); + } + if (m.Orientation is < 1 or > 8 || m.Width < 0 || m.Height < 0) Assert.Fail($"{what}: invalid geometry"); + } + + private sealed class NonSeekable : MemoryStream + { + public override bool CanSeek => false; + } +} From 6d9ede0c47becf7342b16d21e06a0343ad1dc368 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:02:27 +0000 Subject: [PATCH 069/188] feat(codecs): add TIFF raster reader and TIFF writer TiffImageReader decodes strips and tiles (chunky or planar) with none, LZW (old-style bit order tolerated), Deflate, PackBits and JPEG compression (JPEGTables, YCbCr or RGB, lossless SOF3 tiles reshaped as DNG writes them), predictors 2/3 and the DNG x2/x4 variants, 1-16 bit integer and 16/32-bit float samples; tiles decode in parallel. Output is a raw TiffRaster or a linear ImageBuffer. JPEG strips match libtiff bit for bit. TiffWriter writes 8/16-bit gray/RGB/RGBA, uncompressed or Deflate with horizontal predictor, and embeds capture metadata from an Exif block. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs | 9 + .../Codecs/Tiff/TiffDecompressors.cs | 121 +++++ src/Titano.Core/Codecs/Tiff/TiffDirectory.cs | 189 ++++++++ .../Codecs/Tiff/TiffImageReader.cs | 425 ++++++++++++++++++ src/Titano.Core/Codecs/Tiff/TiffWriter.cs | 222 +++++++++ .../Codecs/TiffTestEncoders.cs | 127 ++++++ tests/Titano.Core.Tests/Codecs/TiffTests.cs | 315 +++++++++++++ tests/fixtures/codecs/make-fixtures.sh | 1 + tests/fixtures/codecs/tiff/jpeg-rgb.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm | Bin 0 -> 8248 bytes 10 files changed, 1409 insertions(+) create mode 100644 src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffDirectory.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffImageReader.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffWriter.cs create mode 100644 tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs create mode 100644 tests/Titano.Core.Tests/Codecs/TiffTests.cs create mode 100644 tests/fixtures/codecs/tiff/jpeg-rgb.ppm create mode 100644 tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm diff --git a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs index 00f32884..63afe5c9 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs @@ -44,6 +44,15 @@ public static class JpegDecoder return new JpegRenderer(parser).RenderLinear(expandGray); } + /// Decodes a TIFF/DNG tile: lossless streams return raw samples (any component count), DCT streams pixels. + internal static (JpegImage? Image, JpegLosslessImage Raw) DecodeTile(ReadOnlySpan data, JpegDecodeOptions options) + { + var parser = Parse(data, options); + return parser.Frame!.Process == JpegProcess.Lossless + ? (null, JpegLosslessDecoder.Finish(parser)) + : (new JpegRenderer(parser).RenderInterleaved(parser.Info()), default); + } + private static JpegParser Parse(ReadOnlySpan data, JpegDecodeOptions? options) { var parser = new JpegParser(options ?? JpegDecodeOptions.Default); diff --git a/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs b/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs new file mode 100644 index 00000000..da328f6f --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs @@ -0,0 +1,121 @@ +using System.IO.Compression; + +namespace Titano.Core.Codecs.Tiff; + +/// +/// Strip/tile decompressors. Each fills exactly output.Length bytes when the data allows and returns the number +/// of bytes produced; damaged data ends early instead of throwing out of range. +/// +internal static class TiffDecompressors +{ + /// TIFF LZW (MSB-first codes, "early change"). Old-style streams (pre-6.0 libtiff, LSB-first codes, + /// no early change) are recognised by their first byte as libtiff does. + public static int Lzw(ReadOnlySpan input, Span output) + { + const int clear = 256, eoi = 257, maxCodes = 4096; + var oldStyle = input.Length >= 2 && input[0] == 0 && (input[1] & 1) != 0; + Span prefix = stackalloc ushort[maxCodes]; + Span suffix = stackalloc byte[maxCodes]; + Span first = stackalloc byte[maxCodes]; + Span length = stackalloc ushort[maxCodes]; + for (var i = 0; i < 256; i++) + { + suffix[i] = first[i] = (byte)i; + length[i] = 1; + } + int next = 258, width = 9, old = -1, written = 0, inPos = 0, bits = 0; + uint acc = 0; + var early = oldStyle ? 0 : 1; + while (written < output.Length) + { + while (bits < width && inPos < input.Length) + { + if (oldStyle) acc |= (uint)input[inPos++] << bits; + else acc = acc << 8 | input[inPos++]; + bits += 8; + } + if (bits < width) break; + int code; + if (oldStyle) + { + code = (int)(acc & ((1u << width) - 1)); + acc >>= width; + } + else + { + code = (int)(acc >> (bits - width)) & ((1 << width) - 1); + } + bits -= width; + if (code == eoi) break; + if (code == clear) + { + next = 258; + width = 9; + old = -1; + continue; + } + if (old < 0) + { + if (code > 255) break; // the first code after a clear must be a literal + } + else + { + if (code > next || next >= maxCodes && code == next) break; // corrupt: code beyond the table + if (next < maxCodes) + { + // New entry: old string + first byte of the current string (KwKwK when code == next). + prefix[next] = (ushort)old; + suffix[next] = code < next ? first[code] : first[old]; + first[next] = first[old]; + length[next] = (ushort)Math.Min(ushort.MaxValue, length[old] + 1); + next++; + } + } + // Strings are prefix chains: write back to front, clipped to the output. + var len = length[code]; + var end = Math.Min(written + len, output.Length); + var c = code; + for (var p = written + len - 1; p >= written; p--) + { + if (p < end) output[p] = suffix[c]; + c = prefix[c]; + } + written = end; + old = code; + if (next + early >= 1 << width && width < 12) width++; + } + return written; + } + + /// Macintosh PackBits run-length decoding. + public static int PackBits(ReadOnlySpan input, Span output) + { + int i = 0, o = 0; + while (i < input.Length && o < output.Length) + { + var n = (sbyte)input[i++]; + if (n >= 0) + { + var count = Math.Min(n + 1, Math.Min(input.Length - i, output.Length - o)); + input.Slice(i, count).CopyTo(output[o..]); + i += n + 1; + o += count; + } + else if (n != -128) + { + if (i >= input.Length) break; + var count = Math.Min(1 - n, output.Length - o); + output.Slice(o, count).Fill(input[i++]); + o += count; + } + } + return o; + } + + /// zlib (Adobe Deflate, TIFF compression 8/32946). + public static int Deflate(byte[] input, Span output) + { + using var z = new ZLibStream(new MemoryStream(input, writable: false), CompressionMode.Decompress); + return z.ReadAtLeast(output, output.Length, throwOnEndOfStream: false); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs b/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs new file mode 100644 index 00000000..05fb8c80 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs @@ -0,0 +1,189 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// +/// A little-endian IFD under construction for and the DNG writer: entries kept sorted by +/// tag, values ≤ 4 bytes inline, larger ones word-aligned after the entry table, child IFDs (Exif, GPS, Interop) +/// laid out after their parent. +/// +internal sealed class TiffDirectory +{ + private readonly SortedDictionary _entries = []; + private readonly SortedDictionary _children = []; + private long _offset = -1; + + public bool Has(ushort tag) => _entries.ContainsKey(tag) || _children.ContainsKey(tag); + + /// Adds an entry whose value bytes are already little-endian. + public void Add(ushort tag, TiffType type, int count, byte[] value) => _entries[tag] = (type, count, value); + + public void Short(ushort tag, params ReadOnlySpan values) + { + var b = new byte[values.Length * 2]; + for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(b.AsSpan(2 * i), values[i]); + Add(tag, TiffType.Short, values.Length, b); + } + + public void Long(ushort tag, params ReadOnlySpan values) + { + var b = new byte[values.Length * 4]; + for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4 * i), values[i]); + Add(tag, TiffType.Long, values.Length, b); + } + + public void Rational(ushort tag, params ReadOnlySpan<(uint Numerator, uint Denominator)> values) + { + var b = new byte[values.Length * 8]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator); + } + Add(tag, TiffType.Rational, values.Length, b); + } + + public void SRational(ushort tag, params ReadOnlySpan<(int Numerator, int Denominator)> values) + { + var b = new byte[values.Length * 8]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator); + } + Add(tag, TiffType.SRational, values.Length, b); + } + + public void Ascii(ushort tag, string value) + { + var b = Encoding.UTF8.GetBytes(value + "\0"); + Add(tag, TiffType.Ascii, b.Length, b); + } + + public void Bytes(ushort tag, params ReadOnlySpan values) => Add(tag, TiffType.Byte, values.Length, values.ToArray()); + + /// Links a sub-IFD through a LONG pointer entry (resolved during ). + public void Child(ushort tag, TiffDirectory child) => _children[tag] = child; + + private int OwnSize + { + get + { + var size = 2 + 12 * (_entries.Count + _children.Count) + 4; + foreach (var (_, (_, _, value)) in _entries) + { + if (value.Length > 4) size += (value.Length + 1) & ~1; + } + return size; + } + } + + /// Assigns file offsets to this directory and its children (depth first); returns the end offset. + public long Layout(long offset) + { + _offset = (offset + 1) & ~1L; + var end = _offset + OwnSize; + foreach (var child in _children.Values) end = child.Layout(end); + if (end > uint.MaxValue) throw new InvalidOperationException("TIFF exceeds 4 GB"); + return end; + } + + /// Writes this directory and its children at the offsets chosen by . + /// Positioned at or before this directory's offset. + public void Write(Stream output) + { + if (_offset < 0) throw new InvalidOperationException("Layout must run before Write"); + while (output.Position < _offset) output.WriteByte(0); + var buffer = new byte[OwnSize]; + var count = _entries.Count + _children.Count; + BinaryPrimitives.WriteUInt16LittleEndian(buffer, (ushort)count); + var valueAt = 2 + 12 * count + 4; + var e = 2; + var all = _entries.Select(kv => (kv.Key, kv.Value.Type, kv.Value.Count, kv.Value.Value, Child: (TiffDirectory?)null)) + .Concat(_children.Select(kv => (kv.Key, TiffType.Long, 1, Array.Empty(), Child: (TiffDirectory?)kv.Value))) + .OrderBy(x => x.Key); + foreach (var (tag, type, n, value, child) in all) + { + var entry = buffer.AsSpan(e, 12); + BinaryPrimitives.WriteUInt16LittleEndian(entry, tag); + BinaryPrimitives.WriteUInt16LittleEndian(entry[2..], (ushort)type); + BinaryPrimitives.WriteUInt32LittleEndian(entry[4..], (uint)n); + if (child is not null) + { + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)child._offset); + } + else if (value.Length <= 4) + { + value.CopyTo(entry[8..]); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)(_offset + valueAt)); + value.CopyTo(buffer.AsSpan(valueAt)); + valueAt += (value.Length + 1) & ~1; + } + e += 12; + } + output.Write(buffer); + foreach (var child in _children.Values) child.Write(output); + } + + /// + /// Copies capture metadata from a TIFF-structured Exif block (a JPEG APP1 payload, with or without the + /// "Exif\0\0" prefix): IFD0 descriptive tags plus the Exif (with Interop) and GPS sub-IFDs, converted to + /// little-endian. Maker notes are copied as opaque bytes (offsets inside them are not rebased). + /// + public void AttachExif(byte[] exif) + { + var start = exif.AsSpan().StartsWith("Exif\0\0"u8) ? 6 : 0; + using var stream = new MemoryStream(exif, start, exif.Length - start, writable: false); + var reader = TiffReader.Open(stream) ?? throw new ArgumentException("Exif block is not TIFF-structured", nameof(exif)); + var chain = reader.ReadChain(); + if (chain.Count == 0) throw new ArgumentException("Exif block has no IFD", nameof(exif)); + var ifd0 = chain[0]; + foreach (var tag in (ReadOnlySpan)[TiffTags.ImageDescription, TiffTags.Make, TiffTags.Model, TiffTags.DateTime, TiffTags.Artist, TiffTags.Copyright]) + { + if (!Has(tag) && ifd0.Entries.TryGetValue(tag, out var entry)) CopyEntry(reader, entry); + } + var visited = new HashSet { ifd0.Position }; + foreach (var pointer in (ReadOnlySpan)[TiffTags.ExifIfd, TiffTags.GpsIfd]) + { + if (reader.GetUInt(ifd0, pointer) is { } offset && reader.ReadIfd(offset, visited) is { } sub) Child(pointer, CopyDirectory(reader, sub, visited, 0)); + } + } + + private static TiffDirectory CopyDirectory(TiffReader reader, Ifd source, HashSet visited, int depth) + { + var copy = new TiffDirectory(); + foreach (var entry in source.Entries.Values) + { + if (entry.Tag == TiffTags.InteropIfd) + { + if (depth < 2 && reader.GetUInts(entry) is [var offset, ..] && reader.ReadIfd(offset, visited) is { } interop) + copy.Child(entry.Tag, CopyDirectory(reader, interop, visited, depth + 1)); + continue; + } + copy.CopyEntry(reader, entry); + } + return copy; + } + + private void CopyEntry(TiffReader reader, IfdEntry entry) + { + if (reader.ReadBytes(entry) is not { } value) return; + if (!reader.LittleEndian) + { + var size = entry.Type switch + { + TiffType.Short or TiffType.SShort => 2, + TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd or TiffType.Rational or TiffType.SRational => 4, + TiffType.Double => 8, + _ => 1, + }; + for (var i = 0; size > 1 && i + size <= value.Length; i += size) value.AsSpan(i, size).Reverse(); + } + Add(entry.Tag, entry.Type, (int)entry.Count, value); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs new file mode 100644 index 00000000..09e8f367 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs @@ -0,0 +1,425 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// TIFF SampleFormat values handled by . +public enum TiffSampleFormat +{ + UnsignedInteger = 1, + Float = 3, +} + +/// Decoded samples of one IFD: chunky (interleaved), top-down, cropped to the image size. +public sealed class TiffRaster +{ + internal TiffRaster(int width, int height, int samplesPerPixel, int bitsPerSample, TiffSampleFormat format, int photometric, ushort[]? samples, float[]? floats, IReadOnlyList warnings) + { + Width = width; + Height = height; + SamplesPerPixel = samplesPerPixel; + BitsPerSample = bitsPerSample; + SampleFormat = format; + Photometric = photometric; + Samples = samples; + FloatSamples = floats; + Warnings = warnings; + } + + public int Width { get; } + public int Height { get; } + public int SamplesPerPixel { get; } + + /// Significant bits per sample (integer samples are 0..2^bits−1; JPEG tiles report their precision). + public int BitsPerSample { get; } + + public TiffSampleFormat SampleFormat { get; } + + /// PhotometricInterpretation of the samples as returned (JPEG-coded YCbCr is delivered as RGB = 2). + public int Photometric { get; } + + /// Integer samples (). + public ushort[]? Samples { get; } + + /// Floating-point samples (16/32-bit float TIFF and DNG). + public float[]? FloatSamples { get; } + + /// Recoverable problems (missing or truncated strips/tiles, JPEG warnings). + public IReadOnlyList Warnings { get; } +} + +/// Options for . +public sealed record TiffDecodeOptions +{ + public static TiffDecodeOptions Default { get; } = new(); + + /// Integer samples are linear light (otherwise sRGB-encoded is assumed; LinearRaw is always linear). + public bool AssumeLinear { get; init; } + + /// Upper bound on width × height × samples per pixel, checked before allocation. + public long MaxSamples { get; init; } = 1L << 29; + + /// Worker limit for strip/tile decoding (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// TIFF/DNG pixel data on top of : strips and tiles, chunky and planar, compression none / LZW +/// (old-style bit order tolerated) / Deflate / PackBits / JPEG (with JPEGTables; YCbCr or RGB; lossless SOF3 for DNG, +/// including tiles whose JPEG frame is laid out as e.g. 2 components × width/2), predictors 2 and 3 (and the DNG ×2/×4 +/// variants), 1–16-bit integer and 16/32-bit float samples. Strips and tiles decode in parallel. +/// +public static class TiffImageReader +{ + private const int CompressionNone = 1, CompressionLzw = 5, CompressionJpeg = 7, CompressionDeflate = 8; + private const int CompressionAdobeDeflate = 32946, CompressionPackBits = 32773, CompressionLossyJpeg = 34892; + private const int PhotometricMinIsWhite = 0, PhotometricRgb = 2, PhotometricPalette = 3, PhotometricYCbCr = 6; + private const int PhotometricCfa = 32803, PhotometricLinearRaw = 34892; + + /// Decodes the first full-resolution image of a TIFF (or a DNG whose main image is not CFA). + public static ImageBuffer Decode(Stream stream, TiffDecodeOptions? options = null) + { + var reader = TiffReader.Open(stream) ?? throw new InvalidDataException("TIFF: missing header"); + var chain = reader.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("TIFF: no image directory"); + var ifd = chain.FirstOrDefault(i => ((reader.GetUInt(i, TiffTags.NewSubfileType) ?? 0) & 1) == 0) ?? chain[0]; + var o = options ?? TiffDecodeOptions.Default; + return ToImageBuffer(ReadRaster(reader, ifd, o), o); + } + + public static ImageBuffer Decode(byte[] data, TiffDecodeOptions? options = null) => Decode(new MemoryStream(data, writable: false), options); + + /// Converts a gray/RGB raster to linear light (min-is-white inverted; extra samples dropped). + public static ImageBuffer ToImageBuffer(TiffRaster raster, TiffDecodeOptions? options = null) + { + var o = options ?? TiffDecodeOptions.Default; + if (raster.Photometric is PhotometricCfa or PhotometricPalette) + throw new InvalidDataException($"TIFF: photometric {raster.Photometric} needs colour reconstruction (CFA/palette) not done here"); + int w = raster.Width, h = raster.Height, spp = raster.SamplesPerPixel; + var colour = spp >= 3 && raster.Photometric is PhotometricRgb or PhotometricLinearRaw; + var channels = colour ? 3 : 1; + if (raster.FloatSamples is { } floats) + { + var image = new ImageBuffer(w, h, channels, clear: false); + for (var c = 0; c < channels; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = floats[i * spp + c]; + } + return image; + } + var samples = raster.Samples!; + var max = (1 << raster.BitsPerSample) - 1; + var packedChannels = colour ? Math.Min(spp, 4) : Math.Min(spp, 2); + if (raster.Photometric == PhotometricMinIsWhite || packedChannels != spp) + { + var packed = new ushort[w * h * packedChannels]; + var invert = raster.Photometric == PhotometricMinIsWhite; + for (var i = 0; i < w * h; i++) + { + for (var c = 0; c < packedChannels; c++) + { + var v = samples[i * spp + c]; + packed[i * packedChannels + c] = invert && c == 0 ? (ushort)(max - v) : v; + } + } + samples = packed; + } + var transfer = o.AssumeLinear || raster.Photometric == PhotometricLinearRaw ? TransferFunction.Linear : TransferFunction.Srgb; + return PixelConvert.FromInterleaved16(samples, w, h, packedChannels, transfer, max, channels); + } + + /// Decodes every strip or tile of into one raster. + /// Missing or inconsistent layout tags, or an unsupported encoding. + public static TiffRaster ReadRaster(TiffReader reader, Ifd ifd, TiffDecodeOptions? options = null) + { + var o = options ?? TiffDecodeOptions.Default; + var g = Geometry.Read(reader, ifd, o); + var warnings = new List(); + var count = g.ChunksPerPlane * g.Planes; + var offsets = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets) ?? throw new InvalidDataException("TIFF: missing strip/tile offsets"); + var counts = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts); + if (counts is null && count == 1 && g.Compression == CompressionNone) counts = [(uint)Math.Min(int.MaxValue, g.RowBytes * (long)g.ChunkHeight)]; + if (counts is null) throw new InvalidDataException("TIFF: missing strip/tile byte counts"); + if (offsets.Length < count || counts.Length < count) warnings.Add($"TIFF: {count} strips/tiles expected, {Math.Min(offsets.Length, counts.Length)} present"); + + // I/O is sequential (one stream); decoding is parallel. + var chunks = new byte[]?[count]; + for (var i = 0; i < Math.Min(count, Math.Min(offsets.Length, counts.Length)); i++) + { + if (counts[i] == 0) continue; + chunks[i] = reader.ReadRelative(offsets[i], (int)Math.Min(counts[i], int.MaxValue)); + if (chunks[i] is null) warnings.Add($"TIFF: strip/tile {i} lies outside the file"); + } + var tables = g.Compression is CompressionJpeg or CompressionLossyJpeg && ifd.Entries.TryGetValue(TiffTags.JpegTables, out var t) ? reader.ReadBytes(t) : null; + + var total = (long)g.Width * g.Height * g.Spp; + var ints = g.Format == TiffSampleFormat.UnsignedInteger ? new ushort[total] : null; + var floats = ints is null ? new float[total] : null; + var bits = g.Bps; + var gate = new Lock(); + Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }, i => + { + if (chunks[i] is not { } data) return; + try + { + var decoded = DecodeChunk(g, i, data, tables, ints, floats, reader.LittleEndian); + if (decoded.Warning is { } warning) + { + lock (gate) warnings.Add(warning); + } + if (decoded.Bits > 0) bits = decoded.Bits; + } + catch (InvalidDataException ex) + { + lock (gate) warnings.Add($"TIFF: strip/tile {i}: {ex.Message}"); + } + }); + var photometric = g.Photometric == PhotometricYCbCr && g.IsJpeg ? PhotometricRgb : g.Photometric; + return new TiffRaster(g.Width, g.Height, g.Spp, bits, g.Format, photometric, ints, floats, warnings); + } + + /// Layout of the image data of one IFD. + private sealed class Geometry + { + public int Width, Height, Spp, Bps, Compression, Photometric, Planes, ChunkSpp, Predictor, PredictorStride; + public int ChunkWidth, ChunkHeight, Across, ChunksPerPlane; + public long RowBytes; + public bool Tiled, FloatPredictor; + public TiffSampleFormat Format; + public bool IsJpeg => Compression is CompressionJpeg or CompressionLossyJpeg; + + public static Geometry Read(TiffReader r, Ifd ifd, TiffDecodeOptions o) + { + var g = new Geometry + { + Width = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageWidth) ?? 0, int.MaxValue), + Height = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageLength) ?? 0, int.MaxValue), + Spp = (int)Math.Min(r.GetUInt(ifd, TiffTags.SamplesPerPixel) ?? 1, 64), + Compression = (int)(r.GetUInt(ifd, TiffTags.Compression) ?? CompressionNone), + Predictor = (int)(r.GetUInt(ifd, TiffTags.Predictor) ?? 1), + }; + if (g.Width == 0 || g.Height == 0 || g.Spp == 0) throw new InvalidDataException("TIFF: missing or zero image size"); + if ((long)g.Width * g.Height * g.Spp > o.MaxSamples) throw new InvalidDataException($"TIFF: {g.Width}x{g.Height}x{g.Spp} exceeds the sample limit"); + var bps = r.GetUInts(ifd, TiffTags.BitsPerSample) ?? [1]; + if (bps.Length == 0 || bps.Any(b => b != bps[0])) throw new InvalidDataException("TIFF: mixed bits per sample are not supported"); + g.Bps = (int)Math.Min(bps[0], 64); + g.Format = (r.GetUInt(ifd, TiffTags.SampleFormat) ?? 1) switch + { + 1 => TiffSampleFormat.UnsignedInteger, + 3 => TiffSampleFormat.Float, + var f => throw new InvalidDataException($"TIFF: sample format {f} is not supported"), + }; + if (g.Format == TiffSampleFormat.Float ? g.Bps is not (16 or 32) : g.Bps is < 1 or > 16) + throw new InvalidDataException($"TIFF: {g.Bps}-bit {g.Format} samples are not supported"); + if (g.Compression is not (CompressionNone or CompressionLzw or CompressionJpeg or CompressionDeflate or CompressionAdobeDeflate or CompressionPackBits or CompressionLossyJpeg)) + throw new InvalidDataException($"TIFF: compression {g.Compression} is not supported"); + if (g.IsJpeg && g.Format == TiffSampleFormat.Float) throw new InvalidDataException("TIFF: JPEG-compressed float data"); + g.Photometric = (int)(r.GetUInt(ifd, TiffTags.PhotometricInterpretation) ?? (uint)(g.Spp >= 3 ? PhotometricRgb : 1)); + if (g.Photometric == PhotometricYCbCr && !g.IsJpeg) throw new InvalidDataException("TIFF: uncompressed YCbCr is not supported"); + + // Predictor 2/3 and the DNG 1.4 ×2/×4 variants (34892–34895) differ only in the differencing stride. + (g.FloatPredictor, var factor) = g.Predictor switch + { + 1 => (false, 0), + 2 => (false, 1), + 3 => (true, 1), + 34892 => (false, 2), + 34893 => (false, 4), + 34894 => (true, 2), + 34895 => (true, 4), + var p => throw new InvalidDataException($"TIFF: predictor {p} is not supported"), + }; + if (factor > 0 && g.FloatPredictor != (g.Format == TiffSampleFormat.Float)) throw new InvalidDataException("TIFF: predictor does not match the sample format"); + g.Planes = (r.GetUInt(ifd, TiffTags.PlanarConfiguration) ?? 1) == 2 ? g.Spp : 1; + g.ChunkSpp = g.Planes == 1 ? g.Spp : 1; + g.PredictorStride = g.ChunkSpp * factor; + + g.Tiled = ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets); + if (g.Tiled) + { + g.ChunkWidth = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileWidth) ?? 0, 1 << 16); + g.ChunkHeight = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileLength) ?? 0, 1 << 16); + if (g.ChunkWidth == 0 || g.ChunkHeight == 0) throw new InvalidDataException("TIFF: zero tile size"); + g.Across = (g.Width + g.ChunkWidth - 1) / g.ChunkWidth; + g.ChunksPerPlane = checked(g.Across * ((g.Height + g.ChunkHeight - 1) / g.ChunkHeight)); + } + else + { + g.ChunkWidth = g.Width; + g.ChunkHeight = (int)Math.Clamp(r.GetUInt(ifd, TiffTags.RowsPerStrip) ?? (uint)g.Height, 1, (uint)g.Height); + g.Across = 1; + g.ChunksPerPlane = (g.Height + g.ChunkHeight - 1) / g.ChunkHeight; + } + g.RowBytes = ((long)g.ChunkWidth * g.ChunkSpp * g.Bps + 7) / 8; + if (g.RowBytes * g.ChunkHeight > TiffReader.MaxValueBytes * 4) throw new InvalidDataException("TIFF: strip/tile too large"); + return g; + } + } + + private readonly record struct ChunkResult(string? Warning, int Bits); + + private static ChunkResult DecodeChunk(Geometry g, int index, byte[] data, byte[]? tables, ushort[]? ints, float[]? floats, bool littleEndian) + { + var plane = index / g.ChunksPerPlane; + var local = index % g.ChunksPerPlane; + var x0 = local % g.Across * g.ChunkWidth; + var y0 = local / g.Across * g.ChunkHeight; + var rows = g.Tiled ? g.ChunkHeight : Math.Min(g.ChunkHeight, g.Height - y0); + var validW = Math.Min(g.ChunkWidth, g.Width - x0); + var validH = Math.Min(rows, g.Height - y0); + if (g.IsJpeg) return DecodeJpegChunk(g, data, tables, ints!, x0, y0, validW, validH, plane); + + var expected = (int)(g.RowBytes * rows); + var raw = new byte[expected]; + var produced = g.Compression switch + { + CompressionNone => Copy(data, raw), + CompressionLzw => TiffDecompressors.Lzw(data, raw), + CompressionPackBits => TiffDecompressors.PackBits(data, raw), + _ => TiffDecompressors.Deflate(data, raw), + }; + var rowBytes = (int)g.RowBytes; + var rowSamples = g.ChunkWidth * g.ChunkSpp; + var ushorts = ints is null ? null : new ushort[rowSamples]; + var singles = floats is null ? null : new float[rowSamples]; + for (var r = 0; r < validH; r++) + { + var row = raw.AsSpan(r * rowBytes, rowBytes); + if (ushorts is not null) + { + UnpackIntegers(row, g.Bps, littleEndian, ushorts); + if (g.PredictorStride > 0) + { + var mask = (1 << g.Bps) - 1; + for (var i = g.PredictorStride; i < rowSamples; i++) ushorts[i] = (ushort)((ushorts[i] + ushorts[i - g.PredictorStride]) & mask); + } + Place(ushorts, ints!, g, x0, y0 + r, validW, plane); + } + else + { + UnpackFloats(row, g, littleEndian, singles!); + Place(singles!, floats!, g, x0, y0 + r, validW, plane); + } + } + return new ChunkResult(produced < expected ? $"TIFF: strip/tile {index} truncated ({produced}/{expected} bytes)" : null, 0); + } + + private static int Copy(byte[] data, byte[] raw) + { + var n = Math.Min(data.Length, raw.Length); + data.AsSpan(0, n).CopyTo(raw); + return n; + } + + private static void Place(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane) + { + if (g.Planes == 1) + { + row.AsSpan(0, validW * g.Spp).CopyTo(target.AsSpan((int)(((long)y * g.Width + x0) * g.Spp))); + return; + } + var start = (int)(((long)y * g.Width + x0) * g.Spp + plane); + for (var x = 0; x < validW; x++) target[start + x * g.Spp] = row[x]; + } + + /// MSB-first unpacking of 1–16-bit samples (8/16-bit in file byte order). + private static void UnpackIntegers(ReadOnlySpan row, int bps, bool littleEndian, ushort[] dst) + { + switch (bps) + { + case 8: + for (var i = 0; i < dst.Length; i++) dst[i] = row[i]; + return; + case 16: + for (var i = 0; i < dst.Length; i++) + { + dst[i] = littleEndian ? (ushort)(row[2 * i] | row[2 * i + 1] << 8) : (ushort)(row[2 * i] << 8 | row[2 * i + 1]); + } + return; + } + long bit = 0; + for (var i = 0; i < dst.Length; i++) + { + var v = 0; + for (var b = 0; b < bps; b++, bit++) v = v << 1 | (row[(int)(bit >> 3)] >> (7 - (int)(bit & 7)) & 1); + dst[i] = (ushort)v; + } + } + + /// 16/32-bit floats; the floating-point predictor stores byte planes MSB-first after byte differencing. + private static void UnpackFloats(Span row, Geometry g, bool littleEndian, float[] dst) + { + var size = g.Bps / 8; + var count = dst.Length; + if (g.PredictorStride > 0) + { + for (var i = g.PredictorStride; i < row.Length; i++) row[i] += row[i - g.PredictorStride]; + for (var i = 0; i < count; i++) + { + uint bits = 0; + for (var k = 0; k < size; k++) bits = bits << 8 | row[k * count + i]; + dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits); + } + return; + } + for (var i = 0; i < count; i++) + { + uint bits = 0; + for (var k = 0; k < size; k++) bits = bits << 8 | row[i * size + (littleEndian ? size - 1 - k : k)]; + dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits); + } + } + + private static ChunkResult DecodeJpegChunk(Geometry g, byte[] data, byte[]? tables, ushort[] ints, int x0, int y0, int validW, int validH, int plane) + { + var options = new JpegDecodeOptions + { + Tables = tables, + MaxDegreeOfParallelism = 1, + ColorTransform = g.Photometric switch + { + PhotometricYCbCr => JpegColorTransform.YCbCr, + PhotometricRgb when g.Compression == CompressionJpeg => JpegColorTransform.None, + _ => JpegColorTransform.Auto, + }, + }; + var (image, raw) = JpegDecoder.DecodeTile(data, options); + string? warning = null; + if (image is not null) + { + var comps = Math.Min(image.Components, g.ChunkSpp); + var w = Math.Min(validW, image.Width); + for (var r = 0; r < Math.Min(validH, image.Height); r++) + { + for (var x = 0; x < w; x++) + { + var src = (r * image.Width + x) * image.Components; + var dst = ((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane; + for (var c = 0; c < comps; c++) ints[dst + c] = image.Pixels8 is { } p8 ? p8[src + c] : image.Pixels16![src + c]; + } + } + if (image.Warnings.Count > 0) warning = "TIFF: " + image.Warnings[0]; + return new ChunkResult(warning, image.BitDepth); + } + + // Lossless: the JPEG frame may be shaped differently from the tile (DNG writes e.g. 2 components × width/2), + // but the sample stream order is the same, so samples map back linearly. + var samples = raw.Samples; + var perRow = g.ChunkWidth * g.ChunkSpp; + var tileSamples = (long)perRow * g.ChunkHeight; + if (samples.Length != tileSamples) warning = $"TIFF: lossless JPEG holds {samples.Length} samples, tile needs {tileSamples}"; + var n = (int)Math.Min(samples.Length, tileSamples); + for (var k = 0; k < n; k++) + { + var r = k / perRow; + var rem = k - r * perRow; + var x = rem / g.ChunkSpp; + if (r >= validH) break; + if (x >= validW) continue; + ints[((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane + rem % g.ChunkSpp] = samples[k]; + } + return new ChunkResult(warning, raw.Precision); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffWriter.cs b/src/Titano.Core/Codecs/Tiff/TiffWriter.cs new file mode 100644 index 00000000..9e8c6051 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffWriter.cs @@ -0,0 +1,222 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// Compression written by . +public enum TiffCompression +{ + None = 1, + Deflate = 8, +} + +/// Options for . +public sealed record TiffWriteOptions +{ + public static TiffWriteOptions Default { get; } = new(); + + /// 8 or 16. + public int BitsPerSample { get; init; } = 16; + + public TiffCompression Compression { get; init; } = TiffCompression.Deflate; + + /// Horizontal differencing (Predictor = 2) before Deflate; ignored when uncompressed. + public bool Predictor { get; init; } = true; + + /// Encoding of input: sRGB (display-ready) or linear light. + public TransferFunction Transfer { get; init; } = TransferFunction.Srgb; + + public CompressionLevel Level { get; init; } = CompressionLevel.Optimal; + + /// TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded. + public byte[]? Exif { get; init; } + + /// Worker limit for strip encoding (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// Little-endian baseline TIFF writer: 8/16-bit gray, RGB or RGBA (unassociated alpha), uncompressed or Deflate with +/// optional horizontal predictor, optional embedded Exif. Strips are encoded in parallel and written in order. +/// +public static class TiffWriter +{ + private const int TargetStripBytes = 256 * 1024; + + public static byte[] Write(ImageBuffer image, TiffWriteOptions? options = null) + { + using var ms = new MemoryStream(); + Write(ms, image, options); + return ms.ToArray(); + } + + /// Writes a linear-light buffer (1 channel → gray, 3 → RGB, 4 → RGBA). + public static void Write(Stream output, ImageBuffer image, TiffWriteOptions? options = null) + { + var o = options ?? TiffWriteOptions.Default; + var channels = image.Channels; + Write(output, image.Width, image.Height, channels, o, (y, row) => + { + if (o.BitsPerSample == 16) + { + PixelConvert.EncodeRow16(image, y, row, channels, o.Transfer); + return; + } + var buffer = ArrayPool.Shared.Rent(row.Length); + PixelConvert.EncodeRow8(image, y, buffer.AsSpan(0, row.Length), channels, o.Transfer, dither: false); + for (var i = 0; i < row.Length; i++) row[i] = buffer[i]; + ArrayPool.Shared.Return(buffer); + }); + } + + /// Writes interleaved, already-encoded samples (values below 2^). + public static unsafe void Write(Stream output, ReadOnlySpan samples, int width, int height, int channels, TiffWriteOptions? options = null) + { + if (samples.Length < (long)width * height * channels) throw new ArgumentException("Sample buffer too small", nameof(samples)); + fixed (ushort* p = samples) + { + var ptr = (nint)p; + Write(output, width, height, channels, options ?? TiffWriteOptions.Default, + (y, row) => new ReadOnlySpan((ushort*)ptr + (long)y * width * channels, width * channels).CopyTo(row)); + } + } + + private delegate void RowSource(int y, Span row); + + private static void Write(Stream output, int width, int height, int channels, TiffWriteOptions o, RowSource source) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (channels is < 1 or > 4 or 2) throw new ArgumentOutOfRangeException(nameof(channels), "1, 3 or 4 channels"); + if (o.BitsPerSample is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(o), "8 or 16 bits per sample"); + if (!output.CanSeek) + { + using var buffer = new MemoryStream(); + Write(buffer, width, height, channels, o, source); + buffer.Position = 0; + buffer.CopyTo(output); + return; + } + + var start = output.Position; + output.Write("II*\0\0\0\0\0"u8); + var bytesPerSample = o.BitsPerSample / 8; + var rowBytes = (long)width * channels * bytesPerSample; + var rowsPerStrip = (int)Math.Clamp(TargetStripBytes / rowBytes, 1, height); + var strips = (height + rowsPerStrip - 1) / rowsPerStrip; + var deflate = o.Compression == TiffCompression.Deflate; + var predictor = deflate && o.Predictor; + var offsets = new uint[strips]; + var counts = new uint[strips]; + var batch = Math.Max(1, Environment.ProcessorCount * 2); + var encoded = new byte[batch][]; + var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }; + for (var first = 0; first < strips; first += batch) + { + var n = Math.Min(batch, strips - first); + Parallel.For(0, n, parallel, k => + { + var s = first + k; + var y0 = s * rowsPerStrip; + var rows = Math.Min(rowsPerStrip, height - y0); + var raw = new byte[rowBytes * rows]; + var row = new ushort[width * channels]; + for (var r = 0; r < rows; r++) + { + source(y0 + r, row); + if (predictor) + { + var mask = (1 << o.BitsPerSample) - 1; + for (var i = row.Length - 1; i >= channels; i--) row[i] = (ushort)((row[i] - row[i - channels]) & mask); + } + var dst = raw.AsSpan((int)(r * rowBytes), (int)rowBytes); + if (bytesPerSample == 2) + { + for (var i = 0; i < row.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(dst[(2 * i)..], row[i]); + } + else + { + for (var i = 0; i < row.Length; i++) dst[i] = (byte)row[i]; + } + } + encoded[k] = deflate ? Deflate(raw, o.Level) : raw; + }); + for (var k = 0; k < n; k++) + { + if (output.Position - start > uint.MaxValue - (long)encoded[k].Length) throw new InvalidOperationException("TIFF exceeds 4 GB"); + offsets[first + k] = (uint)(output.Position - start); + counts[first + k] = (uint)encoded[k].Length; + output.Write(encoded[k]); + } + } + + var ifd = new TiffDirectory(); + ifd.Long(TiffTags.NewSubfileType, 0); + ifd.Long(TiffTags.ImageWidth, (uint)width); + ifd.Long(TiffTags.ImageLength, (uint)height); + ifd.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)o.BitsPerSample, channels).ToArray()); + ifd.Short(TiffTags.Compression, (ushort)o.Compression); + ifd.Short(TiffTags.PhotometricInterpretation, channels == 1 ? (ushort)1 : (ushort)2); + ifd.Long(TiffTags.StripOffsets, offsets); + ifd.Short(TiffTags.SamplesPerPixel, (ushort)channels); + ifd.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip); + ifd.Long(TiffTags.StripByteCounts, counts); + ifd.Rational(TiffTags.XResolution, (72u, 1u)); + ifd.Rational(TiffTags.YResolution, (72u, 1u)); + ifd.Short(TiffTags.PlanarConfiguration, 1); + ifd.Short(TiffTags.ResolutionUnit, 2); + ifd.Ascii(TiffTags.Software, "Titano"); + if (predictor) ifd.Short(TiffTags.Predictor, 2); + if (channels == 4) ifd.Short(TiffTags.ExtraSamples, 2); + if (o.Exif is { } exif) ifd.AttachExif(exif); + WriteDirectory(output, start, ifd); + } + + /// Appends (and its children) and points the header at it. + internal static void WriteDirectory(Stream output, long start, TiffDirectory ifd) + { + var at = output.Position - start; + ifd.Layout(at); + var origin = new OffsetStream(output, start); + ifd.Write(origin); + var end = output.Position; + output.Position = start + 4; + Span pointer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(pointer, (uint)((at + 1) & ~1L)); + output.Write(pointer); + output.Position = end; + } + + internal static byte[] Deflate(byte[] raw, CompressionLevel level) + { + using var ms = new MemoryStream(raw.Length / 2 + 64); + using (var z = new ZLibStream(ms, level, leaveOpen: true)) z.Write(raw); + return ms.ToArray(); + } + + /// View of a stream whose Position is relative to the TIFF header (files may start mid-stream). + private sealed class OffsetStream(Stream inner, long origin) : Stream + { + public override bool CanRead => false; + public override bool CanSeek => true; + public override bool CanWrite => true; + public override long Length => inner.Length - origin; + + public override long Position + { + get => inner.Position - origin; + set => inner.Position = value + origin; + } + + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + public override void Write(ReadOnlySpan buffer) => inner.Write(buffer); + public override void WriteByte(byte value) => inner.WriteByte(value); + public override void Flush() => inner.Flush(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin seekOrigin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} diff --git a/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs b/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs new file mode 100644 index 00000000..d49c57c1 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs @@ -0,0 +1,127 @@ +using Titano.Core.Codecs.Tiff; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Codecs; + +/// Test-side encoders for TIFF compressions the product never writes (LZW, PackBits) and a raw TIFF builder. +internal static class TiffTestEncoders +{ + /// TIFF LZW; writes LSB-first codes switching width one code late (pre-6.0 libtiff). + public static byte[] Lzw(ReadOnlySpan data, bool oldStyle = false) + { + var output = new List(); + uint acc = 0; + var bits = 0; + var width = 9; + void Put(int code) + { + if (oldStyle) + { + acc |= (uint)code << bits; + bits += width; + while (bits >= 8) + { + output.Add((byte)acc); + acc >>= 8; + bits -= 8; + } + } + else + { + acc = acc << width | (uint)code; + bits += width; + while (bits >= 8) + { + output.Add((byte)(acc >> (bits - 8))); + bits -= 8; + } + } + } + var table = new Dictionary<(int, byte), int>(); + var next = 258; + Put(256); + if (data.Length == 0) + { + Put(257); + } + else + { + int current = data[0]; + for (var i = 1; i < data.Length; i++) + { + var c = data[i]; + if (table.TryGetValue((current, c), out var code)) + { + current = code; + continue; + } + Put(current); + table[(current, c)] = next++; + current = c; + if (next == 4094) + { + Put(256); + table.Clear(); + next = 258; + width = 9; + } + else if (next >= (1 << width) + (oldStyle ? 1 : 0)) + { + width++; + } + } + Put(current); + // libtiff's LZWPostEncode counts the final code too, so EOI uses the decoder's width. + if (++next >= (1 << width) + (oldStyle ? 1 : 0) && width < 12) width++; + Put(257); + } + if (bits > 0) output.Add(oldStyle ? (byte)acc : (byte)(acc << (8 - bits))); + return [.. output]; + } + + /// PackBits with both literal and replicate runs. + public static byte[] PackBits(ReadOnlySpan data) + { + var output = new List(); + var i = 0; + while (i < data.Length) + { + var run = 1; + while (i + run < data.Length && run < 128 && data[i + run] == data[i]) run++; + if (run >= 3) + { + output.Add((byte)(sbyte)(1 - run)); + output.Add(data[i]); + i += run; + continue; + } + var start = i; + while (i < data.Length && i - start < 128 && !(i + 2 < data.Length && data[i] == data[i + 1] && data[i] == data[i + 2])) i++; + output.Add((byte)(i - start - 1)); + for (var k = start; k < i; k++) output.Add(data[k]); + } + return [.. output]; + } + + /// Builds a little-endian TIFF from pre-encoded strips or tiles plus layout tags. + public static byte[] Build(Action tags, IReadOnlyList chunks, bool tiled) + { + using var ms = new MemoryStream(); + ms.Write("II*\0\0\0\0\0"u8); + var offsets = new uint[chunks.Count]; + var counts = new uint[chunks.Count]; + for (var i = 0; i < chunks.Count; i++) + { + offsets[i] = (uint)ms.Position; + counts[i] = (uint)chunks[i].Length; + ms.Write(chunks[i]); + if ((ms.Position & 1) != 0) ms.WriteByte(0); + } + var ifd = new TiffDirectory(); + tags(ifd); + ifd.Long(tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets, offsets); + ifd.Long(tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts, counts); + TiffWriter.WriteDirectory(ms, 0, ifd); + return ms.ToArray(); + } +} diff --git a/tests/Titano.Core.Tests/Codecs/TiffTests.cs b/tests/Titano.Core.Tests/Codecs/TiffTests.cs new file mode 100644 index 00000000..92777536 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/TiffTests.cs @@ -0,0 +1,315 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +public sealed class TiffTests(TestContext context) +{ + private static TiffRaster Raster(byte[] tiff, TiffDecodeOptions? options = null) + { + var reader = TiffReader.Open(new MemoryStream(tiff)) ?? throw new InvalidDataException("not a TIFF"); + return TiffImageReader.ReadRaster(reader, reader.ReadChain()[0], options); + } + + [Theory] + [Case("tiff/lzw-pred.tif")] + [Case("tiff/packbits.tif")] + [Case("tiff/none-strips.tif")] + [Case("tiff/lzw-tiled.tif")] + [Case("tiff/planar-zip.tif")] + public void EightBitLayoutsMatchSource(string name) + { + var raster = Raster(Fixture(name)); + Assert.Empty(raster.Warnings); + Assert.Equal(3, raster.SamplesPerPixel); + Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Words, raster.Samples!); + } + + [Test] + public void SixteenBitDeflatePredictorMatchesSource() + { + var raster = Raster(Fixture("tiff/deflate16-pred.tif")); + Assert.Equal(16, raster.BitsPerSample); + Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, raster.Samples!); + } + + [Test] + public void FloatingPointPredictorMatchesSource() + { + var raster = Raster(Fixture("tiff/float32-pred3.tif")); + Assert.Equal(TiffSampleFormat.Float, raster.SampleFormat); + var source = ReadPnm(Fixture("src16.ppm")).Samples; + for (var i = 0; i < source.Length; i++) Assert.Approximately(source[i] / 65535.0, raster.FloatSamples![i], 1e-6); + using var image = TiffImageReader.Decode(Fixture("tiff/float32-pred3.tif")); + Assert.Approximately(source[3 * 100 + 1] / 65535.0, image[1, 100 % 61, 100 / 61], 1e-6); + } + + [Theory] + [Case("tiff/jpeg-ycbcr")] + [Case("tiff/jpeg-rgb")] + public void JpegCompressedStripsMatchLibtiff(string name) + { + var raster = Raster(Fixture(name + ".tif")); + Assert.Equal(2, raster.Photometric); + Assert.Empty(raster.Warnings); + var diff = MaxAbsDiff(raster.Samples!.Select(s => (byte)s).ToArray(), ReadPnm(Fixture(name + ".ppm")).Samples); + context.Log($"{name}: max |diff| vs libtiff {diff}"); + Assert.LessOrEqual(diff, 2); + } + + [Test] + public void MinIsWhiteIsInverted() + { + // The raster keeps stored values; the image inverts them (0 = white), as libtiff readers do. + var file = Fixture("tiff/gray-miniswhite.tif"); + var raster = Raster(file); + Assert.Equal(0, raster.Photometric); + using var image = TiffImageReader.Decode(file); + Assert.Equal(1, image.Channels); + for (var i = 0; i < image.PlaneLength; i++) Assert.Equal(ColorSpace.Linear8((byte)(255 - raster.Samples![i])), image.Plane(0)[i]); + } + + [Theory] + [Case(false)] + [Case(true)] + public void LzwBothBitOrdersAndTableResets(bool oldStyle) + { + const int w = 70, h = 64; + var pixels = new byte[w * h * 3]; + new Random(3).NextBytes(pixels.AsSpan(0, pixels.Length / 2)); + for (var i = pixels.Length / 2; i < pixels.Length; i++) pixels[i] = (byte)(i / 50); + var strips = new List(); + for (var y = 0; y < h; y += 32) strips.Add(TiffTestEncoders.Lzw(pixels.AsSpan(y * w * 3, Math.Min(32, h - y) * w * 3), oldStyle)); + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 3, 8, compression: 5, rowsPerStrip: 32), strips, tiled: false); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.SequenceEqual(pixels.Select(b => (ushort)b), raster.Samples!); + } + + [Test] + public void PackBitsSixteenBitPlanarTiles() + { + const int w = 40, h = 24, tile = 16; + var samples = new ushort[w * h * 3]; + for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 7 == 0 ? 60000 : i * 13); + var chunks = new List(); + for (var plane = 0; plane < 3; plane++) + { + for (var ty = 0; ty < h; ty += tile) + { + for (var tx = 0; tx < w; tx += tile) + { + var raw = new byte[tile * tile * 2]; + for (var y = 0; y < tile; y++) + { + for (var x = 0; x < tile; x++) + { + var v = ty + y < h && tx + x < w ? samples[((ty + y) * w + tx + x) * 3 + plane] : (ushort)0; + BinaryPrimitives.WriteUInt16LittleEndian(raw.AsSpan((y * tile + x) * 2), v); + } + } + chunks.Add(TiffTestEncoders.PackBits(raw)); + } + } + } + var tiff = TiffTestEncoders.Build(d => + { + Layout(d, w, h, 3, 16, compression: 32773); + d.Short(TiffTags.PlanarConfiguration, 2); + d.Long(TiffTags.TileWidth, tile); + d.Long(TiffTags.TileLength, tile); + }, chunks, tiled: true); + Assert.SequenceEqual(samples, Raster(tiff).Samples!); + } + + [Test] + public void PackedTwelveBitSamplesUnpack() + { + const int w = 5, h = 3; + var values = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 273 % 4096)).ToArray(); + var stride = (w * 12 + 7) / 8; + var raw = new byte[stride * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + for (var b = 0; b < 12; b++) + { + if ((values[y * w + x] >> (11 - b) & 1) != 0) raw[y * stride + (x * 12 + b) / 8] |= (byte)(0x80 >> ((x * 12 + b) % 8)); + } + } + } + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 12, compression: 1), [raw], tiled: false); + var raster = Raster(tiff); + Assert.Equal(12, raster.BitsPerSample); + Assert.SequenceEqual(values, raster.Samples!); + } + + [Test] + public void DngStyleLosslessTilesMapBackFromReshapedFrames() + { + // A CFA-like 1-sample tile of 32×8 stored as a 2-component, 16-wide lossless JPEG frame (as DNG writers do). + const int w = 48, h = 8, tile = 32; + var samples = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 977 % 16384)).ToArray(); + var chunks = new List(); + for (var tx = 0; tx < w; tx += tile) + { + var t = new ushort[tile * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < tile; x++) t[y * tile + x] = tx + x < w ? samples[y * w + tx + x] : (ushort)0; + } + chunks.Add(JpegLosslessEncoder.Encode(t, tile / 2, h, 2, 14, predictor: 1)); + } + var tiff = TiffTestEncoders.Build(d => + { + Layout(d, w, h, 1, 16, compression: 7); + d.Short(TiffTags.PhotometricInterpretation, 32803); + d.Long(TiffTags.TileWidth, tile); + d.Long(TiffTags.TileLength, h); + }, chunks, tiled: true); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.Equal(14, raster.BitsPerSample); + Assert.SequenceEqual(samples, raster.Samples!); + Assert.Throws(() => TiffImageReader.ToImageBuffer(raster)); + } + + [Theory] + [Case(8, 1, TiffCompression.None, false)] + [Case(8, 3, TiffCompression.Deflate, true)] + [Case(16, 3, TiffCompression.Deflate, true)] + [Case(16, 3, TiffCompression.Deflate, false)] + [Case(16, 4, TiffCompression.None, false)] + [Case(16, 1, TiffCompression.Deflate, true)] + public void WriterRoundTrips(int bits, int channels, TiffCompression compression, bool predictor) + { + const int w = 123, h = 77; + var samples = new ushort[w * h * channels]; + var rng = new Random(bits + channels); + for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 3 == 0 ? rng.Next(1 << bits) : (i / channels * 31) & ((1 << bits) - 1)); + var options = new TiffWriteOptions { BitsPerSample = bits, Compression = compression, Predictor = predictor }; + using var ms = new MemoryStream(); + TiffWriter.Write(ms, samples, w, h, channels, options); + var raster = Raster(ms.ToArray()); + Assert.Equal(channels, raster.SamplesPerPixel); + Assert.Equal(bits, raster.BitsPerSample); + Assert.SequenceEqual(samples, raster.Samples!); + } + + [Test] + public void ImageBufferRoundTripAndExifEmbedding() + { + using var image = new ImageBuffer(300, 1100); + for (var c = 0; c < 3; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 2) % 1000) / 999f; + } + var tiff = TiffWriter.Write(image, new TiffWriteOptions { Exif = ExifBlock() }); + using var back = TiffImageReader.Decode(tiff); + for (var i = 0; i < image.Data.Length; i += 101) Assert.Approximately(image.Data[i], back.Data[i], 2e-4); + AssertExif(tiff); + Assert.True(Raster(tiff).Warnings.Count == 0); + } + + [Theory] + [Case("tiff/lzw-pred.tif")] + [Case("tiff/lzw-tiled.tif")] + [Case("tiff/planar-zip.tif")] + [Case("tiff/jpeg-ycbcr.tif")] + [Case("tiff/float32-pred3.tif")] + public void FuzzedInputOnlyThrowsInvalidData(string name) + { + int ok = 0, rejected = 0; + var options = new TiffDecodeOptions { MaxSamples = 1 << 22 }; + foreach (var input in Corruptions(Fixture(name), 120, seed: name.Length * 31)) + { + try + { + using var image = TiffImageReader.Decode(input, options); + ok++; + } + catch (InvalidDataException) + { + rejected++; + } + } + context.Log($"{name}: {ok} decoded, {rejected} rejected"); + } + + internal static void Layout(TiffDirectory d, int w, int h, int spp, int bits, int compression, int rowsPerStrip = 0) + { + d.Long(TiffTags.ImageWidth, (uint)w); + d.Long(TiffTags.ImageLength, (uint)h); + d.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)bits, spp).ToArray()); + d.Short(TiffTags.Compression, (ushort)compression); + d.Short(TiffTags.PhotometricInterpretation, spp >= 3 ? (ushort)2 : (ushort)1); + d.Short(TiffTags.SamplesPerPixel, (ushort)spp); + if (rowsPerStrip > 0) d.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip); + } + + /// A big-endian Exif APP1 payload: IFD0 Make/Model/Orientation, Exif IFD (exposure, ISO, Interop), GPS IFD. + internal static byte[] ExifBlock() + { + var ms = new MemoryStream(); + var w = new BinaryWriter(ms); + void U16(int v) => w.Write(BinaryPrimitives.ReverseEndianness((ushort)v)); + void U32(uint v) => w.Write(BinaryPrimitives.ReverseEndianness(v)); + void Entry(int tag, int type, uint count, uint value) + { + U16(tag); + U16(type); + U32(count); + U32(value); + } + w.Write("Exif\0\0MM\0*"u8); + U32(8); + // IFD0 at 8: 5 entries → 2 + 60 + 4 = 66 bytes → data area at 74. + U16(5); + Entry(0x010F, 2, 6, 74); // Make "Canon\0" at 74 + Entry(0x0110, 2, 4, 0x45_4F_53_00); // Model "EOS\0" inline + Entry(0x0112, 3, 1, 6u << 16); // Orientation (not copied) + Entry(0x8769, 4, 1, 80); // Exif IFD at 80 + Entry(0x8825, 4, 1, 148); // GPS IFD at 148 + U32(0); + w.Write("Canon\0"u8); + // Exif IFD at 80: 3 entries → 2 + 36 + 4 = 42 → rational at 122. + U16(3); + Entry(0x829A, 5, 1, 122); // ExposureTime 1/250 + Entry(0x8827, 3, 1, 400u << 16); // ISO 400 + Entry(0xA005, 4, 1, 130); // Interop IFD at 130 + U32(0); + U32(1); + U32(250); + // Interop IFD at 130: 2 + 12 + 4 = 18 bytes → GPS IFD at 148. + U16(1); + Entry(0x0001, 2, 4, 0x52_39_38_00); // InteroperabilityIndex "R98" + U32(0); + U16(1); + Entry(0x0001, 2, 2, 0x4E_00_00_00); // GPSLatitudeRef "N" + U32(0); + return ms.ToArray(); + } + + internal static void AssertExif(byte[] file) + { + var reader = TiffReader.Open(new MemoryStream(file))!; + var ifd0 = reader.ReadChain()[0]; + Assert.Equal("Canon", reader.GetString(ifd0, TiffTags.Make)); + Assert.Equal("EOS", reader.GetString(ifd0, TiffTags.Model)); + Assert.False(ifd0.Has(TiffTags.Orientation) && reader.GetUInt(ifd0, TiffTags.Orientation) == 6, "orientation must not be copied"); + var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!; + Assert.Approximately(1 / 250.0, reader.GetDouble(exif, TiffTags.ExposureTime)!.Value, 1e-9); + Assert.Equal(400u, reader.GetUInt(exif, TiffTags.IsoSpeedRatings)); + var interop = reader.ReadIfd(reader.GetUInt(exif, TiffTags.InteropIfd)!.Value)!; + Assert.Equal("R98", reader.GetString(interop, 0x0001)); + var gps = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value)!; + Assert.Equal("N", reader.GetString(gps, TiffTags.GpsLatitudeRef)); + } +} diff --git a/tests/fixtures/codecs/make-fixtures.sh b/tests/fixtures/codecs/make-fixtures.sh index a2aea85c..f499e9f5 100755 --- a/tests/fixtures/codecs/make-fixtures.sh +++ b/tests/fixtures/codecs/make-fixtures.sh @@ -70,6 +70,7 @@ convert src16.ppm -depth 16 -compress Zip -define tiff:predictor=2 tiff/deflate1 convert src.ppm -compress LZW -define tiff:tile-geometry=16x16 tiff/lzw-tiled.tif tiffcp -p separate -c zip src.ppm.tmp.tif tiff/planar-zip.tif 2>/dev/null || { convert src.ppm -compress None tiff/_tmp.tif; tiffcp -p separate -c zip tiff/_tmp.tif tiff/planar-zip.tif; rm tiff/_tmp.tif; } convert src.ppm -compress None tiff/_tmp.tif && tiffcp -c jpeg:90 -r 16 tiff/_tmp.tif tiff/jpeg-ycbcr.tif && tiffcp -c jpeg:r:90 -r 16 tiff/_tmp.tif tiff/jpeg-rgb.tif && rm tiff/_tmp.tif +convert tiff/jpeg-ycbcr.tif tiff/jpeg-ycbcr.ppm && convert tiff/jpeg-rgb.tif tiff/jpeg-rgb.ppm convert src16.ppm -define quantum:format=floating-point -depth 32 -compress Zip -define tiff:predictor=3 tiff/float32-pred3.tif convert src.ppm -colorspace Gray -define tiff:photometric=min-is-white -compress None tiff/gray-miniswhite.tif ls -l jpeg png tiff diff --git a/tests/fixtures/codecs/tiff/jpeg-rgb.ppm b/tests/fixtures/codecs/tiff/jpeg-rgb.ppm new file mode 100644 index 0000000000000000000000000000000000000000..78d88fd00bfdf91f839f049ac658ee8642675c61 GIT binary patch literal 8248 zcmeHpi&qp^w*IN^20?{LK|kuz4;l&-RDuLc1r-&Qw4kD*p%qkOP%*7h5{Y7B=Z2X$ z8L~zpOeBdW*a=BAq65*+gcuSr_M@sFDBKBYQTkQY-Owmzf{r-Utz>>{{c_j3_Yb&h z&FQnw+I_0_sqcK}JA3c7b0^QuR6UhFc}{lrWB_p@XgnGki-GRPK_g-)ghGA=YAb=xl|rrMP)h}Lx)N%xf|~Y0$E%_G z8t7OpRHuiI)&Ol|YQ0ZByqzx+WfC`OJK_`^o1?63X za?B7(Ls?EJqYp~!hf)S0wHs0}5E6pKBT(EZ6f*`zjYGl-2m&xCg2$ubu^9M%96Tb1 zLn!Q5z#cU`kOKFo!@U`>GYh6k*qjS@=fPe1aAyH*EP~sM;kFX^Tq)dI4!2amrz_#+ zD!6GMe7qX2uYr%%!gYH1XdQgy7+g~iSD%3QHo;ZRaOEku;tX8Y3YVUROWNS#4!F<= z7j(k;U2xttIL8c=G@RvxGy34PemG?SR=Z&Z10x|=JOam!!ZBlT)Hp1hfFVF|B4Rw6 z7>gn9#}Ol9B7_ot1>sQ>11Us*I?nBnM2(_C~Fa#1J#3Mx9C=oM8M2!=| z2?7EnCnCqA$*~ynejGU>CPOIcSCAexIgmp3r<1)Iq%(`8Nz$B4cIS~@`DAASX)Ge! zi^;YU@?0s|T28i9kf$rj<|?vjA9=i*tgj)D)sl63@@O4-O`)=HM1B}>}K;tsOVNEURG`CVk*H8RIc@?Xkwk{NwuT0faGK&suOf+3L*DIOu? zM#-2lGHRR@PLL4La3alkv}PpaIbEq~uF^E^(;TnX)YoW^)oSYWnxl1^BgZr~ z^_uDvn!Qb$s%A~)DNV&0O<+O`tyxl(OwxwfT3d%9BFT%~Q=r#)V+ zt*_A@tJT)&wMXl;M~-Q0>b2D;w0oPhRn6MUQ`(9%+Ok${=~-<_o3^+^TWHi4bZYav zw0YOGIc6?sTQDxk}fxPj|dpS6`z$R;#Pi>yFmxjvUj~)a$BG==L`0s+x6`r*su(bY-o& z(zCjfHeGRtuF$9}=+xzR>GH1Wa?CoC)@3<$8GX96eqG9dPVLqy7#$MQiAQvCqq>+e zUDUWvIH7}po)hWEqxEAk`ulPE5wSjm>ir76N39=7(f6n8do%RTEIm!?&AIySJbhQb zzOz7YEYi0Z>)T57=Suah<@%Ni{pm`5bCtenpZ<8YzP?6(tX5yA*B`CZA33J4sn=JZ z(C=;1S2gP^Pw6Yp=*wF5rDydeZTjL4eW6ib(5cVw(&t^%=a}^*t!Ww8a~rDoY~sYQql0iuHz^79BaMG#-AlvHDMqy0;svnj0%mH*P)CSl-&W<+Fy8^G!wV zCkih&tn56o;@jiPzHeM$emk3P$aFMh_BKrKZy;_rBzhX;Yy&pbAPYCZqYbfR4N>C_ zLaqS<22N;r9A$Vg)$r3a!@UH25*w#R*K<=bi>UIgCom8lLm8+p?i_x+vSE! z1%~g63>S(GZ6${DrG~R*hEKK`nzvo};Nbhmp8u?&`jbB%K2!H<%WHKX*6Kew`ljK9 zw+u&47^<2KRn3Oorwo;649|XSC^_G{;o?W@zGzwdW$VhXKU?%|%aZTUW|`k#L>r!R z7&3YdsXrK|-!h~Q8gQRM$r@ru4Nv@JnEKE#>9IjLVSpgxgvdA^Z5)d+j>5(fi7|*7 zeG22C+BiTMe@rv>&Ne!;j5KL9=Nh{g8@uw2R|<@m3XSKAjbD@)Kh_#QEH|FnZan?m z#dmkMzf<|wcWT;xf8ek6FMa)o*Nm_J{?f~D7!SW`Jn$#uu14ejlg5hojb$yytsfaT zpS`&0ym58=m#Z!t3%+W9y6dalYi%n`T~FDJvz^AwKI6=OW6Eu#++$R+#wS8Xe8dQk z8e@MpMn5t}{L?4^CQe{_JjwK6s_Ca`rn?EIA;iSsCQp*-R;uZTbkofzO^&Bb)I5`E zq3LR#>6_)IZwgEuMW#!|rVATQXSJpaTTN#wOsDoxO}ia`K45*TnyRm{{NX>od-WB| z>w5FiH%%|UW!l?d+V_rW_j{)2J}~Y6$W-=;>6vqu4Q-a*Y^uuSC_lKDsX*Wyg2 zT^kLqt>;`D+xj=O-zqe^mwk0-X;kYZqm4DeH);c~*M@&r z7pOh__ust{e({gt{l~*qP2qj-hO0gZS9}!S@kx07r{N8shgbh4RCt*!>KZi0Bj6pC) zfihB*kztGqXFMpwqAY_mKBdPkV*}DaNa6PSaNLKWenk3GQKm2ibcFWxyLUF zF>)^>3;3l0zl>#gCkFL1N`?`$48}52hLJH0!aoQwK0m|y8NTtuFCG0~+b{V3hyMTO z5R}1w^PEAMUpm6FnBV^|n;(DU&uCVR(Z_$0EPZ@_yLA7W>uUC)r={ z{`dC3qW%r0{|5fwu>Z~W{};_~l=xf0{97dd7Rmn=ksvY@mtzVHm7$nSj$twhj>{1l zF852MtU}J`ngA;CDNr^+?#B>T>c{x_D+}<6MuqzmBrJ;h_-UVv2`NHe)H@^#{hBJ= zK8y{rxYRF4+)`v1Mg3AFphWx_9+Kkx+kRPK7-hT)zh6AWAYK*^czx0U%V!yc^`agY z3xs3=ALeKIJQVb?elNp@e11Rc_4)&$0E;LPi5Qc?VqA_Q3KW%Lav6rnRR|iy(SR($ zi{POIwHuQJRdSyc@yc1Lg25$jsWgbm2c>9G&Zj**IE3Hvi9_y{6jSjO%jG=RGE^={a49a4p%R(Itw?62d~(Np z3M3$w1f-Z>iSlG(s1H{%N_h}X@XJvaNpg!}uTM6_ss@9|a7Yqxqf7wfL4{bK1arqr zf2k5AvO%SC7!?N-5EfGoN`gUYkX3}(*gIZT;I`B^jD!L~Nr06N`!FAa@C5inxO-SS zbSE(oWZfhFz_8za%RS^~+#^0d+s9*kH6lU8GDRY;kRVbCrjjS1GNn`*#-H#i5*P_G zf?|UzEGWZ=#HdH*kx5t_y(Nnap(z1G>Q%_XGMpX4SfAAESNMI1pOO25acn?wH^?Gr z2v@OkSx_$ZN^vG0A5x(MO38@C>sQ|KV*#IXD2%grF|Qj5`uKvxs~lvp+kP3pr6D&m z@Jk@vOF|QK$`x8TK{GeYs#KgNjVqT!ZQP_8fQK z(2q02E}x(E2fTqhezz~o_(T4XuQSo|5o-6W?h{5pSsIW$6FNP~V$ZjqilCC`fk;>| zc~Zpnr>+k_Z)uHp$Z(LqHfn1v_|N5*t~m~_wp%0;mAoKOslnMe`onnBSL&W;c1DOX z@Kh1Fv+71y#`lgD^kg9rMTz3o;PyJ_wcNfA!n~*u%vvDCuW z$P_@Vj&kIf`wHm`$+QT7nezn1Y;d!{@u=23u-=iC4=q^-R;&@8oO=Diej8h1+x!Ap zUl}<)Q}F$~>mS9^t~IviXv?&zf@uhVCE(i`mXlL@nuYW<7>bI4lGDMd2xIX`$ue;U0Pg zJ?#l-UOof_pl6wL{6DCls;HG(fF*-uLUbYC7Tjf{7h2bD7pi6f{xt9IpdY_#yZgLl z-FCr-ePBg7xQJSu`8`)N%m5MsA*4u!{(@1jyY>a3-7A=#EBMb1w&5K&KA3DN*a)`l2Wxf$UnSi)-_a_z74HD}Ot5he zczD#_HOF>sj=k)NaP1}_hJis$or|+Re9>N92@;+VY}hLpKV-XIa^ve+maJmHpI1~g z_~%jj$6|+Lsjd7dAm)Iw7eRQpy%n={Dea0Bp%@4AS3(`B4pX-E<7t+%S0ExCWabE# ztPyac|RXQ3BTU6MpEtH)rYK?XL<26U%S$f+cAP@sw4w|P}{N+?fa&H_A(zBq_ zgW%q?^yMV}bM&smAiDsp*a%vu*iJ=J{oDFx%>lw_=-FCP|2oIrXC3cPp-c9H$x}e_ zOTdz4=_Dw+sQ1}}0K=gtVgQv-waKY7@unClXo;fFBaTaiL!Bxr+y*HKaC3Rzd4%f9 zumJ$nGxz~8+vuJG$Hi%M=3-EK5Q>z7ySsY3N$UC%%ch-R=3Fp$5nwjb6Gt4KGacGJ zqWsNJ-a2r7PTyCvsSl%UQ(-V^5_ozmIET}piybX-bmQ58|3mM1T;m{Dim)W8vIcyi?)y5EIwi2p$bd4JLJJo~T#(sJi|JD$sy)d( zDHckbCzvdP-Uc>f3Uygw&shtyas}(Q3i>xv?q{rH`<>IXfI3aE>t*n%nDTG6-dRI~ zNYR>|f-TjcXC2LMrG|H#W2ZoK3j}i)LSdaP@EkR=+rF#-l)NM;C>1c9sPnk>bfj~# z6e#Bio|poLbX4C;>)+PXOIL~3Y!FOe4&H(2;VR0v&AezKl<~A6Z#`s)w)x7bi@0^t z)CdFx1>3+U3ffm@dtB@2TSBMK1{rg~(o(?gvAEXU=r6VjrwS5c1Tr;XD(s!ptoZw&4<<}9QUeeu^jBI0ooey(Im_F3vPs}Y!!OJ z>`Z|o60BUJ7ZAdUr@D~01P*$uI_(cSjU0y1!3ZC|YV~Su4-eSnY7vnEre^}~RjPL# z)iuL8Yd(-EpsCT&2UF?ro}SAJ%l0F`1S@&6fL>(z9I;)QO>ftO&3nNHozS()`tu>% zgTuD$B_d53h>8HW$|)O3xyzh+ML;nf5(uFOuh5^y_FP?PNlOKaSzu+EVB(;qBgr(bUnbIzYOjAXt>>vcuwXUVvPaO4)9tDD zc7-)%HXk9u_9M{nF6-zE^m~FEA_%M~jVwC=s9f8PRn}90o}LMnza-eS2ZW!ex!UXP z>Yk}lAT9x9FB9AfxzdRS7Z|2;UW1tc&PtS&pqQ zgLqg(%;d3A?}?mUIrN5YP+=JmMt~0{**}a5I;A)1YJ<)dcDM#;O zbNNA#kO)@q0L&KWh|bKEQ!Ca3EES|o2iNBFciGl5m6l=9>I#um0a~JMr=y%VpSGzp zBPtGpjn#n9uxFKy4%5>cn=+|I8v(!6+U;QIdE2ekwoj(frB!^6 z7R}2C-_NtTwayC?8%ji=3NQ@?_jR@#D;-y6n|a2zALaD}E~GezpEbL*_UB#(lVYHm z3qfFq^S+My$A0U{Np>t*1jj_g$Aia*ss0tz_(4ZfDkwiFN}dZkNsC%Rn*nym!*<1)@zl=$j`^{{;o7v#9_8 literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm b/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm new file mode 100644 index 0000000000000000000000000000000000000000..16a511195d4d3bfb7855f3f6748ef6a028815e37 GIT binary patch literal 8248 zcmXY!byQS~|Fw?-CKAKsnPh@)n4mjm=u%(+K~b(!Vjzg5q)4M;p;9IWC}3T$O(=>= z*VLJ!&FhUX?{I(bT6@i!KcBPb`RubMfU${TPO_qJvY^v90V>}Cm2ZkDsVr?$o>Ns4 z!HXdQBV9c)?|CQ??HD{Wa& z+VE9L`G*qlrxLJ6^DkxCul2A$H^aWEYc3%)=Ri#<0VW`8PU^sh4K+WS!Uilgdsv#U z?KECFX+Cq-dgKQ09=~fjJ=e5)S1#1&t~$Sa&>nizIs<6!p|qRf)Yk3P z#vQbVU9=0kX=nE8oJ`TFJg8H8M5iD}CpTXwqgXffglazxJgtKh(XdhqI8VWRAtS$& z)qhde|4Uu7LIc*(e{Q7z*v$B*PG3S;EuiT#0v*z3@Tv3(UB-wJW5|s8!HV9`V)WQD zUOO_MxiOx2GP=DP_x+i7gIR4`Sy#hZm!qsN#9E)-ZGCDlvo?iUafnrNgjtZyJeJQq zTEse7#!9Yc{dStU>%3Kbqt(t9I`J1w_8!yq9x?R(Y{GeO$$87<^gD1~daxgQdv*A*+x0~V2Q8Iiqq zkuN+Wy8XgC{KDJ)xwiu&Z-hj*Zrgq-GWyKU=(;^ol_}g4hqxu_+~Tb8!kmbr{P1H% z5!t2O^h$1O9d~bi_}&ZQyBot}S|cK^b3@v=zU^Gk2VCc85!SE6S$$jW2e#UN2(ujI z8h++dMqJ)nUi-Iu?LQ>429wN(k_|`p(I)nhcqv3EnIKKVFC<}> zl3+iQH~hH|_$L)mKDx3#Yh`oxzv@{(w6d4b*>m`8iFS^VnmwbNJz< z@^bTXvrDp%mgl5Z=j}b2A6K8Z{X%Z^<=oij+?cDmkvDQf@8o%R<+(o2vwx9m_bS`2 zH{1SQw)J2R{bR1taGuV1K4~ToFUrHoaxinb@GrS)Kl4=n&IkU<2b8N#p;7e#Y}jm2J-{$Nn1I!5aFMuL;?&gb+I-)mwbT2`y?`rsLz>&dnp&e9FYmm3es9y+y$#jL7mug4 zR%Bi|k=a_3d8H`3Ij6KSy{0ksRLkDetvkyja_rl`O{Pv~@x8gvbrcD=Xk>|u32x9fWB*wyLOb>F@F zzHe7YP}l8k_pU{>H*Rmgw5z=#`9b4vck5C+Pp5U)9cV93?>Kh!etuqOc5z2q`Mm?x zovA0g5>9u=p6`shbT6uy1m0jy&uhbdaZh2u=<|Z_I11Tc6+?(@P2bU@b!(bSFMpRn_^#G-rds} z_p)Kv%d;tc4g22I9eQ;``>C%3pStE?}htT(Nq=U{Db>goR7=lf%u`(v*6McsT8 z((%Tp>y69Pe%C*GoL}@hKYL~K{F(X3KIU+*=}-@KxCcMchvxMop?;*a4?f?kx!j}r zy?4W}UZsEg)~p*@SvUIc#`AbyctbtH$ zBodhl#O4C2C4Y`Sv%s2JwBao{@Z~Oi$U`vW1%2QwJm$>b447{XUuue8yc9Keo;!Du zJKxM*x*7fTE?0i_x7jOcvlosC%8v_+&q2~_uTp<@=YG9&_MeW1 znaX$LB~yc0GoNyVLs`P1gTjw#(htX%1{>#kZq2>vTIlco^0|Fsv_Uj-_}kZ=!g+_8 zuNE^uj08VT_&-dA-x$yrC+S!J`LEo?<(TEAn6Jyx-;M-Vz?lU&GXN(R z;9w8fdH}3oz$YEx90NSd0gr0HtqyRl0bHwrpgrXGS*WQH?4&OXFCz+_JpA}?_LYJ!w=1A$zBpe&etD%|Y?H~!4F z{q+&4HPJiDV?9o!P(;Ild=Y(YmiBpxIJ7|eJVza#HJMy+l6;F?{3~VoN80j_^l#tN zzyC=4^ZP+8h{l3Q5UcfHkXQ_eM-!1+96b3hoHzz2PQi#XaJ(3am0{7d>ntwX^u!TG zXi$X1OSFl65{_r3F%v~tZX`%Xi2QjSzMRGv5TI$Nk%7|tow*+Ful30?Py@nfNbwi} zhB$*}PQaq)sF!89PZEq20wD;?SL7|L{^vm4%p6iA-vlWl)e=jwkeI;Zac1Wq2_<5I zWL_wqmx-iukys)Yfglb9K|BVnh=Li5!Qs&a6pTaEzK6umAP7?kJP&~rqd^%CEn8=C zf!P~JfIzeugO}oo0vwKSp)tcHEngx?J`?$~6rogGCj2MIEVXy)$W|f(U z60ftYx9s1Ik$@6tHk}Y#Gi^<9St|wXUelPUQ#Aq@fO@?q( z5r`CE4FAKvJc}Kap`@$WNbxL6{K@L;95RJ(gO@AQnZc63XoXos@oW`vej9u z{y3}{L`pzVhR2FPjL=k#7l!|O4xD|9l!#C=v6lS5w#TRQI$s}g4}Y#_1!2fS6h(ri z3P5lMG@8)jE>Ih!ggyy&MxloUgcOp0u)6$rUjif{OCf@y>O}#1Nr+iky%Nvm`8K)a zvrIZH7f;LyMKY0GAqR1MAg+0R8Ln7vO{tM*fc8_^U5jBqc*)oK%dS6@l|2{G5O!netkmzolT7NQY&T ziFu)5P9TS%c??byh1Wvjk#Ia3i32epj)WwF3b%>(upm!SxPlg;umQjNMak*{vu6)U zKqLqV+7OW_0I>pN4PFT8%V~uqc%eWW;*+3hf_TDd^lf2x#}T&sa|0TL#fXsP)wZ!{ z9>!>ONhmE6{Ez@E72sFNACK`a7;1yNWWQeg-dRA6H@e5iy@1@@{TI1v)77{Jv4^mCT|@i+)e z5Q1b#u_XV8y;XbpjJD)0Ng$$#gxVqn_L$RXe_{9SBW#!FhExT%5KWNa$Pfk;te)h5 z*tih^Rw43?B8s*L=$HTL-vP$&9Lq2ow>9#3K|-LVyQS2oFFEA43wLhyoZ2B2vC-p!k5zX~WOkHRKwg429++ ziBb}hZ>AVP?S+dvl40Vsln9COa>WYpnVy4p_7{pA& zH03zL5}qoCn+xEP^OSQCc94e@%Wx2co{?fj9~tLX`gbhKFnqqcObSW`ASA#F#6-T- zXMXXPSUkQUpXE=>g#1NFy3Ct}NFW2PP9`ID&vA`1$vYhQE4u3Ph-- z1zpiJa#4U6f+{`ItZqNyW=D-m-`Q*Wt~gQ`0WH_T%o7n(6h?|B&LWUJz^vAyZ#Pk-F5G#K3+@Kv{Q644{p{x*SM zp296d*x4S_(<|>2#1f)#1~(58=K1RXEMR7NFtNaO=~wr(e0oYOoSXk5n~}?fa`BQx z7o;N96o;s%fgx{1q0|W|1QD)@vB%SH!jK~byaa<1fmjHI7SKowD(2_SdlIlBvf{O_ zEy60^@<_h1`qVc3Y&{n0SG;Qwa>1ne$VdCFY6Te1RzKE7*C6fyapT$!HD^q_qvd*5cEWWY-8XVYU z<3zAGCS(xfANl{DNGoHZ<5X1iHv;+>wmt0GCrve}r)_bhhwBF)v^{yKyd)y;Zp)bs zAYikHuA+ktb3etkYB&&nDl{w}Ag(oHGuu+HTyrmf9975!04o4s1FHP^OK;pOTO9Ka z5JGn%S>XVEF##G6m}s>;mq7CLcT`S^1)pYQHgIA;oUf*;0#+74oFB2+GW(Wq=OL@; zFs4axuy(ME-uvta56wH?hrj8HzZGHTW@)i5Ineog=JZ>;=dX7?Cjl5gAA4U%hNPrV zl>GLbdxZ~FfQ8W?J=!bHo6L8}Gz36~hKik%>LZ`)y}>VP9E*v-I&-tNR$Ear~YAV8G zec@ISINwam1DO_kP6sFYYy|TiV{8FThNbUd#odOT7c2qB4vL>Xu(5ep!Tai~?<&t8 zpu4%N=&{vVSsqFEvKyOrS7q47aa1i?Yr(F{%HF0^&uWX(99;_B_8hW^FLujl-g%}f z;Dj+?Yyg-9toJLlPfD^kEe;Cv({LO-{#sD+eC&9ary7%?Ot)X_mO;<0w5_@m*OC{o z`>=Od5Q5p2+R}6M$x(W0ym?@zclaSEug5vnx8qOeu=c0h?D5fJq%ng=YVJ0Mlw1hR zJs!AYpS_O-KuKq&lv!sCAAfYjeH&}jmTYJCL`~b%Lum-0;dI_aI!SDC7Kb1kj?&e5%rr=LZ34`x2!9~@|Js1;+*Y>O^`Kf!e7Uq7;kBK(HD{=LVM@sGsGd~uX9Hy>Y=V*X21U6i7E~vqj_r^Rq!tu%o zSNvT>y-0c36ZW~xta49~PwtLw`s~G9+(OyKu!|yDvS+QSO-uZO6%@m z*WKJ+n&BDXu7?iL(|eiHI-T?4jNjpOudPuWJFcD0?Z~PIm%?PTa6LeS2mlE-z9+2n zY8ll>j1T3w?Mn{``^}DB<5gVaP+H459E!0pTe~F$N59~lyHqjq@x)_R?YaQmhME+1;)^#l)I&rz!&gXGcKN03aQm+U9t>!lrnqevp@e zMS@Gf(_M}4<2yyiKYFXNOmG^ddw;9YKQtcq@^Nw_MX@A4W=A4?AICQE4!wAte$hf% z*@>meHp6{7cyBE6)$3yqxOC305Vu%+=l+zJr;X308)i@e&xc^Div-`g_ z#G5-uJJCaQjdF0?M-!htIeabD#EHYy4`9~`l8q zUh$+Qu9B@`9znHAHe>gscXY;Fd6II&2tZl`+MXLto~O6fxt3guXfpszX#mznS?BkI z*PbL@eQ@x)+a`+$ea8?2{aS2MhH>yv^>xLp6@>W~g@hh8i@p|K_o}F)ARx`3;NYTa zmS>+hQ1Y;pb9lSHuK|Dx)!__Q4yPF(94x;Vt!;jk)|F;pza>&h*%EL^o%jlS39K*aXlTseS%9sdccp+ikNU8)hD)=E$oV zc)YXaj8|?Tn&q&`%oMObY+5*&GkDx7r!Y9#T2>AkS6%oNbo z)&wXjDjaqDY{RVcR!uebRe_fD#4yE!$6fL{)9ulEKje%P7GXt(lK{dA_mgwE^Th_4 z93!J(7n5vGY$-FN*}AEgdEA{ya533(EG%%a_@*drBpY`C3jpD6rg`4pw;~Ik1$XA_ z9=0RFlXtL=_VL|;x{O>_?_3$-$k^%XK?XJ%1K75x*87p&b-uN9I6jC$CjnaL z1FG)@Uy@Yz?x5Qp3<>4noQvG@>#U3TRsC@`UJN*b3ar1%t$e@#`DOoVJ2h+=-MlDd zdy&hYEd0TXUZ;b|HnFxg?wiyG@-Ouyw6}(wVyYoCxB+hJsQ$dxCg&5i%=`nkG1eNS zY`^HHorM*wj1%^0o&@T4d%F_9gZUPRZ~C;<+T|S!j4)UO7z6N3qogbBi=RthCiuJd zCUi+E24-p>aMZQ+*RRV6-TwR0oBMTlbRM|qx<%IxMR3v5Eum*-5f7bYmwIZLW^NCp z0)VLUQ=LU=Lr7^ZJ38Lg(vM8c(2c(r)^kxP+Y5V_D1L>S2Q_kx5Xi@%Ur3b z$>?T*Nht+DJJ^Czo;G)!ueKRoZw;@GvbGKN)!X6fJdrXv7&umJnswA8+CfLvUsv~* z$F-^WnKJuKeL&riu*G1VhVZ~puix`J|0;X3{(=2AZicG$7DeJc)6aKbs|??b(gfVh z5T6gd{+Tekls9uZVmW Date: Fri, 2 Oct 2026 10:02:27 +0000 Subject: [PATCH 070/188] feat(codecs): add linear DNG writer 16-bit LinearRaw DNG 1.4 with tiles (lossless JPEG or uncompressed), ColorMatrix1 = XYZ(D65) to linear sRGB, ForwardMatrix1 to XYZ(D50), D65 illuminant, neutral AsShotNeutral, WhiteLevel 65535 and optional Exif. LibRaw renders test patches back to the exact source values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Dng/LinearDngWriter.cs | 155 ++++++++++++++++++ .../Codecs/LinearDngWriterTests.cs | 124 ++++++++++++++ 2 files changed, 279 insertions(+) create mode 100644 src/Titano.Core/Codecs/Dng/LinearDngWriter.cs create mode 100644 tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs diff --git a/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs b/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs new file mode 100644 index 00000000..8e112346 --- /dev/null +++ b/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs @@ -0,0 +1,155 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Dng; + +/// Tile compression of a linear DNG. +public enum DngCompression +{ + Uncompressed = 1, + + /// Lossless JPEG (SOF3, predictor 1) per tile, DNG Compression = 7. + LosslessJpeg = 7, +} + +/// Options for . +public sealed record LinearDngOptions +{ + public static LinearDngOptions Default { get; } = new(); + + public DngCompression Compression { get; init; } = DngCompression.LosslessJpeg; + + /// UniqueCameraModel (and Model): raw editors key their profiles on it. + public string UniqueCameraModel { get; init; } = "Titano"; + + /// TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded. + public byte[]? Exif { get; init; } + + /// Tile edge in pixels (multiple of 16). + public int TileSize { get; init; } = 256; + + /// Worker limit for tile encoding (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// Writes linear Rec.709/sRGB-primaries RGB as a 16-bit LinearRaw DNG 1.4 that raw editors render with correct +/// colours: ColorMatrix1 = XYZ(D65) → linear sRGB, ForwardMatrix1 = linear sRGB → XYZ(D50), illuminant D65, +/// AsShotNeutral 1/1/1, WhiteLevel 65535, BaselineExposure 0. Values above 1.0 are clipped. +/// +public static class LinearDngWriter +{ + /// XYZ (D65) → linear sRGB, i.e. the inverse of the sRGB → XYZ matrix (IEC 61966-2-1). + internal static readonly double[] XyzToLinearSrgb = + [ + 3.2404542, -1.5371385, -0.4985314, + -0.9692660, 1.8760108, 0.0415560, + 0.0556434, -0.2040259, 1.0572252, + ]; + + /// Linear sRGB → XYZ (D50), Bradford-adapted: neutral (1,1,1) maps to the D50 white point. + internal static readonly double[] LinearSrgbToXyzD50 = + [ + 0.4360747, 0.3850649, 0.1430804, + 0.2225045, 0.7168786, 0.0606169, + 0.0139322, 0.0971045, 0.7141733, + ]; + + public static byte[] Write(ImageBuffer image, LinearDngOptions? options = null) + { + using var ms = new MemoryStream(); + Write(ms, image, options); + return ms.ToArray(); + } + + /// Writes a linear-light buffer (gray is stored as neutral RGB; alpha is dropped). + public static void Write(Stream output, ImageBuffer image, LinearDngOptions? options = null) + { + var o = options ?? LinearDngOptions.Default; + if (o.TileSize is < 16 or > 4096 || o.TileSize % 16 != 0) throw new ArgumentOutOfRangeException(nameof(options), "Tile size must be a multiple of 16 in 16..4096"); + if (!output.CanSeek) + { + using var buffer = new MemoryStream(); + Write(buffer, image, o); + buffer.Position = 0; + buffer.CopyTo(output); + return; + } + int w = image.Width, h = image.Height, t = o.TileSize; + int across = (w + t - 1) / t, down = (h + t - 1) / t; + var offsets = new uint[across * down]; + var counts = new uint[across * down]; + var start = output.Position; + output.Write("II*\0\0\0\0\0"u8); + var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }; + var band = new ushort[w * t * 3]; + var tiles = new byte[across][]; + for (var ty = 0; ty < down; ty++) + { + var y0 = ty * t; + var rows = Math.Min(t, h - y0); + Parallel.For(0, rows, parallel, r => PixelConvert.EncodeRow16(image, y0 + r, band.AsSpan(r * w * 3, w * 3), 3, TransferFunction.Linear)); + Parallel.For(0, across, parallel, tx => tiles[tx] = EncodeTile(band, w, rows, tx * t, t, o.Compression)); + for (var tx = 0; tx < across; tx++) + { + if (output.Position - start > uint.MaxValue - (long)tiles[tx].Length) throw new InvalidOperationException("DNG exceeds 4 GB"); + offsets[ty * across + tx] = (uint)(output.Position - start); + counts[ty * across + tx] = (uint)tiles[tx].Length; + output.Write(tiles[tx]); + } + } + + var ifd = new TiffDirectory(); + // Capture metadata first, so the source camera's Make/Model win; UniqueCameraModel still keys the profile. + if (o.Exif is { } exif) ifd.AttachExif(exif); + if (!ifd.Has(TiffTags.Make)) ifd.Ascii(TiffTags.Make, "Titano"); + if (!ifd.Has(TiffTags.Model)) ifd.Ascii(TiffTags.Model, o.UniqueCameraModel); + ifd.Long(TiffTags.NewSubfileType, 0); + ifd.Long(TiffTags.ImageWidth, (uint)w); + ifd.Long(TiffTags.ImageLength, (uint)h); + ifd.Short(TiffTags.BitsPerSample, 16, 16, 16); + ifd.Short(TiffTags.Compression, (ushort)o.Compression); + ifd.Short(TiffTags.PhotometricInterpretation, 34892); + ifd.Short(TiffTags.Orientation, 1); + ifd.Short(TiffTags.SamplesPerPixel, 3); + ifd.Short(TiffTags.PlanarConfiguration, 1); + ifd.Ascii(TiffTags.Software, "Titano"); + ifd.Long(TiffTags.TileWidth, (uint)t); + ifd.Long(TiffTags.TileLength, (uint)t); + ifd.Long(TiffTags.TileOffsets, offsets); + ifd.Long(TiffTags.TileByteCounts, counts); + ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0); + ifd.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0); + ifd.Ascii(TiffTags.UniqueCameraModel, o.UniqueCameraModel); + ifd.SRational(TiffTags.ColorMatrix1, Rationals(XyzToLinearSrgb)); + ifd.SRational(TiffTags.ForwardMatrix1, Rationals(LinearSrgbToXyzD50)); + ifd.Short(TiffTags.CalibrationIlluminant1, 21); // D65 + ifd.Rational(TiffTags.AsShotNeutral, (1u, 1u), (1u, 1u), (1u, 1u)); + ifd.SRational(TiffTags.BaselineExposure, (0, 1)); + ifd.Long(TiffTags.WhiteLevel, 65535, 65535, 65535); + TiffWriter.WriteDirectory(output, start, ifd); + } + + /// One t×t tile from a band of rows; pixels beyond the image repeat the edge (better compression). + private static byte[] EncodeTile(ushort[] band, int width, int rows, int x0, int t, DngCompression compression) + { + var tile = new ushort[t * t * 3]; + for (var y = 0; y < t; y++) + { + var src = band.AsSpan(Math.Min(y, rows - 1) * width * 3, width * 3); + var dst = tile.AsSpan(y * t * 3, t * 3); + var valid = Math.Min(t, width - x0); + src.Slice(x0 * 3, valid * 3).CopyTo(dst); + for (var x = valid; x < t; x++) src.Slice((width - 1) * 3, 3).CopyTo(dst[(x * 3)..]); + } + if (compression == DngCompression.LosslessJpeg) return JpegLosslessEncoder.Encode(tile, t, t, 3, 16); + var bytes = new byte[tile.Length * 2]; + for (var i = 0; i < tile.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), tile[i]); + return bytes; + } + + private static (int, int)[] Rationals(double[] matrix) => matrix.Select(v => ((int)Math.Round(v * 10000), 10000)).ToArray(); +} diff --git a/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs b/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs new file mode 100644 index 00000000..b9d00ecb --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs @@ -0,0 +1,124 @@ +using Titano.Core.Codecs.Dng; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; +using Titano.Testing; + +namespace Titano.Core.Tests.Codecs; + +public sealed class LinearDngWriterTests +{ + private static ImageBuffer Scene(int w, int h) + { + var image = new ImageBuffer(w, h); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + image[0, x, y] = x / (float)(w - 1); + image[1, x, y] = y / (float)(h - 1) * 0.6f; + image[2, x, y] = (x * y % 97) / 96f; + } + } + image[0, 0, 0] = 1.7f; // highlight above white: clipped + return image; + } + + [Theory] + [Case(DngCompression.LosslessJpeg)] + [Case(DngCompression.Uncompressed)] + public void PixelsRoundTripThroughTheTiffReader(DngCompression compression) + { + using var image = Scene(300, 70); + var dng = LinearDngWriter.Write(image, new LinearDngOptions { Compression = compression, TileSize = 128 }); + var reader = TiffReader.Open(new MemoryStream(dng))!; + var raster = TiffImageReader.ReadRaster(reader, reader.ReadChain()[0]); + Assert.Empty(raster.Warnings); + Assert.Equal(34892, raster.Photometric); + Assert.SequenceEqual(PixelConvert.ToInterleaved16(image, 3, TransferFunction.Linear), raster.Samples!); + using var back = TiffImageReader.Decode(dng); + Assert.Approximately(1.0, back[0, 0, 0], 1e-6); + for (var i = 1; i < image.Data.Length; i += 37) + { + Assert.Approximately(Math.Clamp(image.Data[i], 0, 1), back.Data[i], 1.0 / 65535); + } + } + + [Test] + public void TagsDescribeLinearRec709() + { + using var image = Scene(40, 30); + var dng = LinearDngWriter.Write(image); + var r = TiffReader.Open(new MemoryStream(dng))!; + Assert.True(r.LittleEndian); + var ifd = r.ReadChain()[0]; + Assert.SequenceEqual(new uint[] { 1, 4, 0, 0 }, r.GetUInts(ifd, TiffTags.DngVersion)!); + Assert.Equal(0u, r.GetUInt(ifd, TiffTags.NewSubfileType)); + Assert.Equal(34892u, r.GetUInt(ifd, TiffTags.PhotometricInterpretation)); + Assert.Equal(3u, r.GetUInt(ifd, TiffTags.SamplesPerPixel)); + Assert.SequenceEqual(new uint[] { 16, 16, 16 }, r.GetUInts(ifd, TiffTags.BitsPerSample)!); + Assert.Equal(7u, r.GetUInt(ifd, TiffTags.Compression)); + Assert.Equal("Titano", r.GetString(ifd, TiffTags.UniqueCameraModel)); + Assert.Equal(21u, r.GetUInt(ifd, TiffTags.CalibrationIlluminant1)); + Assert.SequenceEqual(new[] { 1.0, 1.0, 1.0 }, r.GetDoubles(ifd, TiffTags.AsShotNeutral)!); + Assert.Equal(0.0, r.GetDouble(ifd, TiffTags.BaselineExposure)); + Assert.SequenceEqual(new uint[] { 65535, 65535, 65535 }, r.GetUInts(ifd, TiffTags.WhiteLevel)!); + Assert.True(ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets) && ifd.Has(TiffTags.TileByteCounts)); + + // ColorMatrix1 maps XYZ to camera space: D65 white must land on the camera neutral (1, 1, 1), + // and its product with sRGB → XYZ(D65) must be the identity (camera space = linear sRGB). + var cm = r.GetDoubles(ifd, TiffTags.ColorMatrix1)!; + Assert.Equal(9, cm.Length); + double[] d65 = [0.95047, 1.0, 1.08883]; + double[] srgbToXyz = [0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041]; + for (var row = 0; row < 3; row++) + { + Assert.Approximately(1.0, cm[row * 3] * d65[0] + cm[row * 3 + 1] * d65[1] + cm[row * 3 + 2] * d65[2], 2e-3); + for (var col = 0; col < 3; col++) + { + var p = 0.0; + for (var k = 0; k < 3; k++) p += cm[row * 3 + k] * srgbToXyz[k * 3 + col]; + Assert.Approximately(row == col ? 1 : 0, p, 2e-4); + } + } + // ForwardMatrix1 maps the white-balanced neutral to D50 (the DNG SDK's xy 0.3457, 0.3585). + var fm = r.GetDoubles(ifd, TiffTags.ForwardMatrix1)!; + double[] d50 = [0.3457 / 0.3585, 1.0, (1 - 0.3457 - 0.3585) / 0.3585]; + for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4); + } + + [Test] + public void GrayInputExifAndNonSeekableOutput() + { + using var gray = new ImageBuffer(33, 20, 1); + for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = i / (float)gray.PlaneLength; + using var sink = new MemoryStream(); + LinearDngWriter.Write(new ForwardOnlyStream(sink), gray, new LinearDngOptions { Exif = TiffTests.ExifBlock() }); + var dng = sink.ToArray(); + TiffTests.AssertExif(dng); + using var back = TiffImageReader.Decode(dng); + Assert.Equal(3, back.Channels); + Assert.Approximately(gray[0, 20, 10], back[2, 20, 10], 1.0 / 65535); + } + + /// A write-only, non-seekable stream (pipes, network) to exercise the buffering path. + private sealed class ForwardOnlyStream(Stream inner) : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + public override void Flush() => inner.Flush(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} From ec6e43d531bd182848270009254bc486073f840b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:02:33 +0000 Subject: [PATCH 071/188] style: apply whitespace formatting to motion tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Geometry/GeometryStageTests.cs | 12 +++++----- .../Motion/MotionBlurTests.cs | 24 +++++++++---------- .../Motion/OpticalFlowTests.cs | 10 ++++---- .../Titano.Core.Tests/Motion/PlaneOpsTests.cs | 8 +++---- .../Motion/StabilizerTests.cs | 4 ++-- .../Motion/TemporalStackerTests.cs | 4 ++-- 6 files changed, 31 insertions(+), 31 deletions(-) diff --git a/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs b/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs index 4d98c6c9..df87e2ec 100644 --- a/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs +++ b/tests/Titano.Core.Tests/Geometry/GeometryStageTests.cs @@ -44,8 +44,8 @@ public sealed class GeometryStageTests { using var ramp = new ImageBuffer(64, 64, 1); for (var y = 0; y < 64; y++) - for (var x = 0; x < 64; x++) - ramp[0, x, y] = 0.01f * x + 0.005f * y; + for (var x = 0; x < 64; x++) + ramp[0, x, y] = 0.01f * x + 0.005f * y; using var output = new ImageBuffer(64, 64, 1); var map = Affine2D.About(Affine2D.Similarity(0.8, 0.2, 0, 0), 32, 32); GeometryStage.Warp(ramp, output, map); @@ -110,13 +110,13 @@ public sealed class GeometryStageTests { using var checker = new ImageBuffer(256, 256, 1); for (var y = 0; y < 256; y++) - for (var x = 0; x < 256; x++) - checker[0, x, y] = (x + y) % 2 == 0 ? 1f : 0f; + for (var x = 0; x < 256; x++) + checker[0, x, y] = (x + y) % 2 == 0 ? 1f : 0f; using var small = GeometryStage.Apply(checker, new GeometrySettings { OutputWidth = 64 }); Assert.Equal(64, small.Height); for (var y = 2; y < 62; y++) - for (var x = 2; x < 62; x++) - Assert.Approximately(0.5, small[0, x, y], 0.02); + for (var x = 2; x < 62; x++) + Assert.Approximately(0.5, small[0, x, y], 0.02); } [Test] diff --git a/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs index 731d49dd..9d14b267 100644 --- a/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs +++ b/tests/Titano.Core.Tests/Motion/MotionBlurTests.cs @@ -74,13 +74,13 @@ public sealed class MotionBlurTests using var source = Texture(); using var motion = new MotionField(Size, Size, 2); for (var j = 0; j < motion.Rows; j++) - for (var i = 0; i < motion.Columns; i++) - { - // A smooth swirl: magnitude up to ~6 px. - var k = j * motion.Columns + i; - motion.U[k] = (float)(6 * double.Sin(j * 0.1)); - motion.V[k] = (float)(4 * double.Cos(i * 0.08)); - } + for (var i = 0; i < motion.Columns; i++) + { + // A smooth swirl: magnitude up to ~6 px. + var k = j * motion.Columns + i; + motion.U[k] = (float)(6 * double.Sin(j * 0.1)); + motion.V[k] = (float)(4 * double.Cos(i * 0.08)); + } using var output = new ImageBuffer(Size, Size); new MotionBlurRenderer().Render(source, motion, 1.0, output); for (var c = 0; c < 3; c++) @@ -98,11 +98,11 @@ public sealed class MotionBlurTests double sum = 0; var n = 0; for (var y = margin; y < Size - margin; y++) - for (var x = margin; x < Size - margin; x++) - { - sum += plane[y * Size + x]; - n++; - } + for (var x = margin; x < Size - margin; x++) + { + sum += plane[y * Size + x]; + n++; + } return sum / n; } diff --git a/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs b/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs index e9a0518d..7e2d2c84 100644 --- a/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs +++ b/tests/Titano.Core.Tests/Motion/OpticalFlowTests.cs @@ -85,11 +85,11 @@ public sealed class OpticalFlowTests Assert.Equal(3, field.Columns); Assert.Equal(2, field.Rows); for (var j = 0; j < field.Rows; j++) - for (var i = 0; i < field.Columns; i++) - { - field.U[j * field.Columns + i] = i; - field.V[j * field.Columns + i] = 2 * j; - } + for (var i = 0; i < field.Columns; i++) + { + field.U[j * field.Columns + i] = i; + field.V[j * field.Columns + i] = 2 * j; + } var (u, v) = field.Sample(6, 2); Assert.Approximately(1.5, u, 1e-6); Assert.Approximately(1, v, 1e-6); diff --git a/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs b/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs index 959fab08..aaa44998 100644 --- a/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs +++ b/tests/Titano.Core.Tests/Motion/PlaneOpsTests.cs @@ -22,8 +22,8 @@ public sealed class PlaneOpsTests { var window = new List(); for (var dy = -radius; dy <= radius; dy++) - for (var dx = -radius; dx <= radius; dx++) - window.Add(source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]); + for (var dx = -radius; dx <= radius; dx++) + window.Add(source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]); window.Sort(); Assert.Equal(window[window.Count / 2], output[y * Width + x]); } @@ -44,8 +44,8 @@ public sealed class PlaneOpsTests { double sum = 0; for (var dy = -radius; dy <= radius; dy++) - for (var dx = -radius; dx <= radius; dx++) - sum += source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]; + for (var dx = -radius; dx <= radius; dx++) + sum += source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]; Assert.Approximately(sum / ((2 * radius + 1) * (2 * radius + 1)), output[y * Width + x], 1e-5); } } diff --git a/tests/Titano.Core.Tests/Motion/StabilizerTests.cs b/tests/Titano.Core.Tests/Motion/StabilizerTests.cs index aedd1119..1b437a2e 100644 --- a/tests/Titano.Core.Tests/Motion/StabilizerTests.cs +++ b/tests/Titano.Core.Tests/Motion/StabilizerTests.cs @@ -158,8 +158,8 @@ public sealed class StabilizerTests private static IEnumerable<(double X, double Y)> GridPoints() { for (var j = 1; j <= 3; j++) - for (var i = 1; i <= 3; i++) - yield return (Width * i / 4.0, Height * j / 4.0); + for (var i = 1; i <= 3; i++) + yield return (Width * i / 4.0, Height * j / 4.0); } private static double Gaussian(Random random) diff --git a/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs b/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs index 44950896..6dc36279 100644 --- a/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs +++ b/tests/Titano.Core.Tests/Motion/TemporalStackerTests.cs @@ -76,8 +76,8 @@ public sealed class TemporalStackerTests { // An aircraft light streak crossing one frame. for (var c = 0; c < 3; c++) - for (var x = 10; x < 80; x++) - frame[c, x, 40 + x / 8] = 5f; + for (var x = 10; x < 80; x++) + frame[c, x, 40 + x / 8] = 5f; } stacker.Push(frame); } From 661be6c94bb7dd5de938b9b8ded6e4e9a9db5658 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:03:20 +0000 Subject: [PATCH 072/188] feat(ui-visuals): add layout, scale, decimation, viewport and curve math kernels WPF-free geometry behind the visual controls: wrapped-grid layout with O(1) index/offset mapping and keyboard targets, nice axis ticks, min/max decimation, zoom/pan transforms, monotone curve editing rules, filmstrip and heatmap cell layout, an LRU cache and device-pixel snapping, with tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Ui/Visuals/CurveMath.cs | 77 ++++++++ src/Titano.Ui/Visuals/LruCache.cs | 81 ++++++++ src/Titano.Ui/Visuals/MinMaxDecimator.cs | 80 ++++++++ src/Titano.Ui/Visuals/NiceScale.cs | 91 +++++++++ src/Titano.Ui/Visuals/PixelGrid.cs | 32 ++++ src/Titano.Ui/Visuals/StripLayout.cs | 123 ++++++++++++ src/Titano.Ui/Visuals/ViewportMath.cs | 70 +++++++ src/Titano.Ui/Visuals/WrapLayout.cs | 180 ++++++++++++++++++ .../Visuals/CurveMathTests.cs | 85 +++++++++ .../Titano.App.Tests/Visuals/LruCacheTests.cs | 59 ++++++ .../Visuals/MinMaxDecimatorTests.cs | 106 +++++++++++ .../Visuals/NiceScaleTests.cs | 91 +++++++++ .../Visuals/PixelGridTests.cs | 34 ++++ .../Visuals/StripLayoutTests.cs | 85 +++++++++ .../Visuals/ViewportMathTests.cs | 72 +++++++ .../Visuals/WrapLayoutTests.cs | 144 ++++++++++++++ 16 files changed, 1410 insertions(+) create mode 100644 src/Titano.Ui/Visuals/CurveMath.cs create mode 100644 src/Titano.Ui/Visuals/LruCache.cs create mode 100644 src/Titano.Ui/Visuals/MinMaxDecimator.cs create mode 100644 src/Titano.Ui/Visuals/NiceScale.cs create mode 100644 src/Titano.Ui/Visuals/PixelGrid.cs create mode 100644 src/Titano.Ui/Visuals/StripLayout.cs create mode 100644 src/Titano.Ui/Visuals/ViewportMath.cs create mode 100644 src/Titano.Ui/Visuals/WrapLayout.cs create mode 100644 tests/Titano.App.Tests/Visuals/CurveMathTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/LruCacheTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/NiceScaleTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/PixelGridTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/StripLayoutTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/ViewportMathTests.cs create mode 100644 tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs diff --git a/src/Titano.Ui/Visuals/CurveMath.cs b/src/Titano.Ui/Visuals/CurveMath.cs new file mode 100644 index 00000000..846ce462 --- /dev/null +++ b/src/Titano.Ui/Visuals/CurveMath.cs @@ -0,0 +1,77 @@ +namespace Titano.Ui.Visuals; + +/// +/// Editing rules of in normalised [0, 1]² space: control points stay ordered by X with +/// a minimum gap, optionally with the end points pinned to X = 0 and X = 1 (time remap). +/// +public static class CurveMath +{ + /// Default minimum X distance between two control points. + public const double DefaultMinGap = 0.001; + + /// + /// X the point may take when dragged to : strictly between its + /// neighbours (by at least ), inside [0, 1], and fixed at 0 or 1 for the end points + /// when . + /// + public static double ConstrainX(ReadOnlySpan xs, int index, double proposedX, double minGap, bool pinEnds) + { + var n = xs.Length; + if (index < 0 || index >= n) throw new ArgumentOutOfRangeException(nameof(index)); + if (pinEnds && n > 1) + { + if (index == 0) return 0; + if (index == n - 1) return 1; + } + var gap = Math.Max(0, minGap); + var low = index > 0 ? xs[index - 1] + gap : 0; + var high = index < n - 1 ? xs[index + 1] - gap : 1; + low = Math.Max(0, low); + high = Math.Min(1, high); + if (low > high) return Math.Clamp((low + high) / 2, 0, 1); + return Math.Clamp(double.IsNaN(proposedX) ? xs[index] : proposedX, low, high); + } + + /// Clamps a Y value to [0, 1]. + public static double ConstrainY(double y) => double.IsNaN(y) ? 0 : Math.Clamp(y, 0, 1); + + /// + /// Index at which a new point at keeps ascending, or −1 when it would + /// sit closer than to an existing point, outside [0, 1], or outside the pinned ends. + /// + public static int InsertionIndex(ReadOnlySpan xs, double x, double minGap, bool pinEnds) + { + if (double.IsNaN(x) || x < 0 || x > 1) return -1; + var gap = Math.Max(0, minGap); + var index = 0; + while (index < xs.Length && xs[index] < x) index++; + if (index > 0 && x - xs[index - 1] < gap) return -1; + if (index < xs.Length && xs[index] - x < gap) return -1; + if (pinEnds && xs.Length >= 2 && (index == 0 || index == xs.Length)) return -1; + return index; + } + + /// Whether point may be deleted: two points always remain and pinned ends stay. + public static bool CanRemove(int count, int index, bool pinEnds) => + count > 2 && index >= 0 && index < count && (!pinEnds || (index > 0 && index < count - 1)); + + /// Index of the point nearest to (, ) within , or −1; coordinates in one space. + public static int HitTest(ReadOnlySpan xs, ReadOnlySpan ys, double x, double y, double radius) + { + var best = -1; + var bestDistance = radius * radius; + var n = Math.Min(xs.Length, ys.Length); + for (var i = 0; i < n; i++) + { + var dx = xs[i] - x; + var dy = ys[i] - y; + var d = dx * dx + dy * dy; + if (d <= bestDistance) + { + bestDistance = d; + best = i; + } + } + return best; + } +} diff --git a/src/Titano.Ui/Visuals/LruCache.cs b/src/Titano.Ui/Visuals/LruCache.cs new file mode 100644 index 00000000..49d43d35 --- /dev/null +++ b/src/Titano.Ui/Visuals/LruCache.cs @@ -0,0 +1,81 @@ +namespace Titano.Ui.Visuals; + +/// Fixed-capacity map that evicts the least recently used entry (decoded thumbnails). +public sealed class LruCache + where TKey : notnull +{ + private readonly Dictionary>> _map; + private readonly LinkedList> _order = new(); + private int _capacity; + + public LruCache(int capacity) + { + ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1); + _capacity = capacity; + _map = new Dictionary>>(capacity); + } + + public int Count => _map.Count; + + /// Maximum entries; lowering it evicts the oldest entries at once. + public int Capacity + { + get => _capacity; + set + { + ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); + _capacity = value; + Trim(); + } + } + + /// Looks up and marks it as the most recently used. + public bool TryGet(TKey key, out TValue value) + { + if (_map.TryGetValue(key, out var node)) + { + _order.Remove(node); + _order.AddFirst(node); + value = node.Value.Value; + return true; + } + value = default!; + return false; + } + + /// Inserts or replaces as the most recently used entry. + public void Set(TKey key, TValue value) + { + if (_map.TryGetValue(key, out var node)) + { + _order.Remove(node); + node.Value = new KeyValuePair(key, value); + _order.AddFirst(node); + return; + } + _map[key] = _order.AddFirst(new KeyValuePair(key, value)); + Trim(); + } + + public bool Remove(TKey key) + { + if (!_map.Remove(key, out var node)) return false; + _order.Remove(node); + return true; + } + + public void Clear() + { + _map.Clear(); + _order.Clear(); + } + + private void Trim() + { + while (_map.Count > _capacity && _order.Last is { } oldest) + { + _order.RemoveLast(); + _map.Remove(oldest.Value.Key); + } + } +} diff --git a/src/Titano.Ui/Visuals/MinMaxDecimator.cs b/src/Titano.Ui/Visuals/MinMaxDecimator.cs new file mode 100644 index 00000000..4152d027 --- /dev/null +++ b/src/Titano.Ui/Visuals/MinMaxDecimator.cs @@ -0,0 +1,80 @@ +namespace Titano.Ui.Visuals; + +/// +/// Reduces a long series to at most two samples per pixel column (its minimum and maximum, in index order) so a +/// line over 100k+ points draws in time proportional to the plot width while every spike stays visible. +/// +public static class MinMaxDecimator +{ + /// Index written to the output where the line must break (a run without finite samples). + public const int Gap = -1; + + /// Output capacity needed for samples over columns. + public static int Capacity(int count, int columns) => Math.Max(0, Math.Min(count, 2 * Math.Max(1, columns))); + + /// + /// Writes ascending sample indices to draw into and returns how many were written. + /// When the series has at most two samples per column every finite sample is kept; otherwise each column + /// keeps the indices of its minimum and maximum. Non-finite samples are skipped and a run of them (or a + /// column without any finite sample) becomes one entry. + /// + public static int Decimate(ReadOnlySpan values, int columns, Span output) + { + columns = Math.Max(1, columns); + var n = values.Length; + if (output.Length < Capacity(n, columns)) + throw new ArgumentException("Output span is smaller than Capacity(count, columns).", nameof(output)); + + var written = 0; + if (n <= 2 * columns) + { + for (var i = 0; i < n; i++) + { + if (double.IsFinite(values[i])) output[written++] = i; + else if (written > 0 && output[written - 1] != Gap) output[written++] = Gap; + } + return Trim(output, written); + } + + for (var c = 0; c < columns; c++) + { + var start = (int)((long)c * n / columns); + var end = (int)((long)(c + 1) * n / columns); + int minIndex = -1, maxIndex = -1; + double min = double.PositiveInfinity, max = double.NegativeInfinity; + for (var i = start; i < end; i++) + { + var v = values[i]; + if (!double.IsFinite(v)) continue; + if (v < min) + { + min = v; + minIndex = i; + } + if (v > max) + { + max = v; + maxIndex = i; + } + } + if (minIndex < 0) + { + if (written > 0 && output[written - 1] != Gap) output[written++] = Gap; + continue; + } + if (minIndex == maxIndex) + { + output[written++] = minIndex; + } + else + { + output[written++] = Math.Min(minIndex, maxIndex); + output[written++] = Math.Max(minIndex, maxIndex); + } + } + return Trim(output, written); + } + + /// A trailing gap carries no information. + private static int Trim(Span output, int written) => written > 0 && output[written - 1] == Gap ? written - 1 : written; +} diff --git a/src/Titano.Ui/Visuals/NiceScale.cs b/src/Titano.Ui/Visuals/NiceScale.cs new file mode 100644 index 00000000..64c0648f --- /dev/null +++ b/src/Titano.Ui/Visuals/NiceScale.cs @@ -0,0 +1,91 @@ +namespace Titano.Ui.Visuals; + +/// Evenly spaced axis ticks: , + , … up to . +public readonly record struct AxisTicks(double First, double Last, double Step) +{ + /// Number of ticks (0 when the scale is empty). + public int Count => Step > 0 && Last >= First ? (int)Math.Round((Last - First) / Step) + 1 : 0; + + /// Value of tick , computed from integer multiples of the step to limit drift. + public double this[int i] => (Math.Round(First / Step) + i) * Step; +} + +/// "Nice" numbers for axes (1, 2, 5 × 10ⁿ), padded data ranges and tick placement. +public static class NiceScale +{ + /// + /// Heckbert's nice number: the 1/2/5 × 10ⁿ value closest to when + /// , otherwise the smallest one that is ≥ . + /// + public static double NiceNumber(double value, bool round) + { + if (!double.IsFinite(value) || value <= 0) return 1; + var exponent = Math.Floor(Math.Log10(value)); + var magnitude = Math.Pow(10, exponent); + var fraction = value / magnitude; + double nice; + if (round) + nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10; + else + nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; + return nice * magnitude; + } + + /// Nice tick step giving at most (≥ 2) ticks inside [min, max]. + public static double Step(double min, double max, int maxTicks) + { + var span = max - min; + if (!double.IsFinite(span) || span <= 0) return 1; + var intervals = Math.Max(2, maxTicks) - 1; + var step = NiceNumber(NiceNumber(span, false) / intervals, true); + // Rounding the step down can overshoot the budget (e.g. 1/7 → 0.1); climb the 1-2-5 ladder until it fits. + while (span / step > intervals + 1e-9) step = NextNice(step); + return step; + } + + /// Ticks inside [min, max] (none outside), for gridlines over a fixed data range. + public static AxisTicks Inner(double min, double max, int maxTicks) + { + if (!double.IsFinite(min) || !double.IsFinite(max) || max <= min) return default; + var step = Step(min, max, maxTicks); + var first = Math.Ceiling(min / step - 1e-9) * step; + var last = Math.Floor(max / step + 1e-9) * step; + return last < first ? default : new AxisTicks(first, last, step); + } + + /// Range widened outward to whole steps, for axes that should start and end on a tick (e.g. bars from zero). + public static AxisTicks Outer(double min, double max, int maxTicks) + { + if (!double.IsFinite(min) || !double.IsFinite(max)) return default; + if (max <= min) (min, max) = Expand(min); + var step = Step(min, max, maxTicks); + return new AxisTicks(Math.Floor(min / step + 1e-9) * step, Math.Ceiling(max / step - 1e-9) * step, step); + } + + /// + /// Data range padded by of its span on both sides; a flat range is widened around + /// its value so the line sits in the middle. + /// + public static (double Min, double Max) Pad(double min, double max, double fraction) + { + if (!double.IsFinite(min) || !double.IsFinite(max)) return (0, 1); + if (max < min) (min, max) = (max, min); + if (max == min) return Expand(min); + var pad = (max - min) * Math.Max(0, fraction); + return (min - pad, max + pad); + } + + /// The next value of the 1-2-5 ladder above . + private static double NextNice(double step) + { + var magnitude = Math.Pow(10, Math.Floor(Math.Log10(step))); + var fraction = step / magnitude; + return (fraction < 1.5 ? 2 : fraction < 3.5 ? 5 : 10) * magnitude; + } + + private static (double Min, double Max) Expand(double v) + { + var half = v == 0 ? 1 : Math.Abs(v) * 0.1; + return (v - half, v + half); + } +} diff --git a/src/Titano.Ui/Visuals/PixelGrid.cs b/src/Titano.Ui/Visuals/PixelGrid.cs new file mode 100644 index 00000000..99ce0114 --- /dev/null +++ b/src/Titano.Ui/Visuals/PixelGrid.cs @@ -0,0 +1,32 @@ +namespace Titano.Ui.Visuals; + +/// Device-pixel alignment for drawn lines and edges (scale = device pixels per DIP). +public static class PixelGrid +{ + /// Rounds to the nearest device-pixel boundary. + public static double Snap(double value, double scale) + { + if (!(scale > 0) || !double.IsFinite(value)) return value; + return Math.Round(value * scale) / scale; + } + + /// + /// Position of the centre of a line DIPs wide drawn at so it + /// covers whole device pixels: odd pixel widths sit on pixel centres, even ones on pixel boundaries. + /// + public static double SnapLine(double value, double thickness, double scale) + { + if (!(scale > 0) || !double.IsFinite(value)) return value; + var pixels = Math.Max(1, Math.Round(thickness * scale)); + var device = value * scale; + var snapped = pixels % 2 == 1 ? Math.Floor(device) + 0.5 : Math.Round(device); + return snapped / scale; + } + + /// Line thickness in DIPs that renders as whole device pixels (at least one). + public static double SnapThickness(double thickness, double scale) + { + if (!(scale > 0)) return thickness; + return Math.Max(1, Math.Round(thickness * scale)) / scale; + } +} diff --git a/src/Titano.Ui/Visuals/StripLayout.cs b/src/Titano.Ui/Visuals/StripLayout.cs new file mode 100644 index 00000000..80d554d1 --- /dev/null +++ b/src/Titano.Ui/Visuals/StripLayout.cs @@ -0,0 +1,123 @@ +namespace Titano.Ui.Visuals; + +/// +/// Cells of a filmstrip: as many cells of about the target width as fit, each standing for a contiguous run of +/// frames and showing the frame in the middle of its run; X positions map continuously to frames for seeking. +/// +public readonly struct StripLayout +{ + public StripLayout(double width, double targetCellWidth, double gap, int frameCount) + { + Width = double.IsFinite(width) ? Math.Max(0, width) : 0; + Gap = double.IsFinite(gap) ? Math.Max(0, gap) : 0; + FrameCount = Math.Max(0, frameCount); + var target = double.IsFinite(targetCellWidth) && targetCellWidth > 1 ? targetCellWidth : 1; + CellCount = FrameCount == 0 || Width <= 0 + ? 0 + : (int)Math.Min(FrameCount, Math.Max(1, Math.Floor((Width + Gap) / (target + Gap)))); + CellWidth = CellCount == 0 ? 0 : Math.Max(0, (Width - Gap * (CellCount - 1)) / CellCount); + } + + public double Width { get; } + + public double Gap { get; } + + public int FrameCount { get; } + + public int CellCount { get; } + + public double CellWidth { get; } + + public double CellLeft(int cell) => cell * (CellWidth + Gap); + + /// Cell whose run contains . + public int CellForFrame(int frame) + { + if (CellCount == 0) return -1; + return (int)((long)Math.Clamp(frame, 0, FrameCount - 1) * CellCount / FrameCount); + } + + /// Frame shown by : the middle of the frames that map to it. + public int FrameForCell(int cell) + { + if (CellCount == 0) return -1; + cell = Math.Clamp(cell, 0, CellCount - 1); + var first = FirstFrame(cell); + var last = FirstFrame(cell + 1) - 1; + return first + (last - first) / 2; + } + + /// Frame under (continuous across cells and gaps), clamped to the sequence. + public int FrameAt(double x) + { + if (FrameCount == 0 || Width <= 0) return -1; + return (int)Math.Clamp(Math.Floor(x / Width * FrameCount), 0, FrameCount - 1); + } + + /// Centre X of on the continuous frame axis. + public double XForFrame(double frame) => FrameCount == 0 ? 0 : (frame + 0.5) / FrameCount * Width; + + /// Smallest frame f with CellForFrame(f) = cell, i.e. ⌈cell · frames / cells⌉. + private int FirstFrame(int cell) => (int)(((long)cell * FrameCount + CellCount - 1) / CellCount); +} + +/// A grid of square cells with gaps (heatmap): cell origins and hit testing that excludes the gaps. +public readonly struct CellGridLayout +{ + public CellGridLayout(double left, double top, int rows, int columns, double cellSize, double gap) + { + Left = left; + Top = top; + Rows = Math.Max(0, rows); + Columns = Math.Max(0, columns); + CellSize = Math.Max(0, cellSize); + Gap = Math.Max(0, gap); + } + + public double Left { get; } + + public double Top { get; } + + public int Rows { get; } + + public int Columns { get; } + + public double CellSize { get; } + + public double Gap { get; } + + public double Pitch => CellSize + Gap; + + public double Width => Columns == 0 ? 0 : Columns * Pitch - Gap; + + public double Height => Rows == 0 ? 0 : Rows * Pitch - Gap; + + public (double X, double Y) CellOrigin(int row, int column) => (Left + column * Pitch, Top + row * Pitch); + + /// Largest square cell (≤ ) letting the grid fit in width × height. + public static double FitCellSize(double width, double height, int rows, int columns, double gap, double maxCell) + { + if (rows <= 0 || columns <= 0) return 0; + var byWidth = double.IsFinite(width) ? (width - gap * (columns - 1)) / columns : double.PositiveInfinity; + var byHeight = double.IsFinite(height) ? (height - gap * (rows - 1)) / rows : double.PositiveInfinity; + var size = Math.Min(Math.Min(byWidth, byHeight), maxCell); + return double.IsFinite(size) ? Math.Max(0, size) : Math.Max(0, maxCell); + } + + /// Cell under (, ); false over gaps and outside the grid. + public bool TryHit(double x, double y, out int row, out int column) + { + row = column = -1; + if (Rows == 0 || Columns == 0 || CellSize <= 0) return false; + var dx = x - Left; + var dy = y - Top; + if (dx < 0 || dy < 0) return false; + var c = (int)Math.Floor(dx / Pitch); + var r = (int)Math.Floor(dy / Pitch); + if (c >= Columns || r >= Rows) return false; + if (dx - c * Pitch > CellSize || dy - r * Pitch > CellSize) return false; + row = r; + column = c; + return true; + } +} diff --git a/src/Titano.Ui/Visuals/ViewportMath.cs b/src/Titano.Ui/Visuals/ViewportMath.cs new file mode 100644 index 00000000..3a5c67f6 --- /dev/null +++ b/src/Titano.Ui/Visuals/ViewportMath.cs @@ -0,0 +1,70 @@ +namespace Titano.Ui.Visuals; + +/// Uniform scale and translation from image pixels to view units: view = image × + offset. +public readonly record struct ViewTransform(double Scale, double OffsetX, double OffsetY) +{ + public (double X, double Y) ToView(double x, double y) => (x * Scale + OffsetX, y * Scale + OffsetY); + + public (double X, double Y) ToImage(double x, double y) => ((x - OffsetX) / Scale, (y - OffsetY) / Scale); +} + +/// Zoom and pan math of the preview: fit, zoom around a fixed point, panning limits and pixel alignment. +public static class ViewportMath +{ + /// Largest scale at which the whole image fits the view (0 when either is empty). + public static double FitScale(double imageWidth, double imageHeight, double viewWidth, double viewHeight) + { + if (!(imageWidth > 0) || !(imageHeight > 0) || !(viewWidth > 0) || !(viewHeight > 0)) return 0; + return Math.Min(viewWidth / imageWidth, viewHeight / imageHeight); + } + + /// The image at , centred in the view. + public static ViewTransform Centered(double scale, double imageWidth, double imageHeight, double viewWidth, double viewHeight) => + new(scale, (viewWidth - imageWidth * scale) / 2, (viewHeight - imageHeight * scale) / 2); + + /// + /// Changes the scale to keeping the image point under (, + /// ) where it is. + /// + public static ViewTransform ZoomAt(ViewTransform t, double scale, double viewX, double viewY) + { + if (!(t.Scale > 0) || !(scale > 0)) return t; + var k = scale / t.Scale; + return new ViewTransform(scale, viewX - (viewX - t.OffsetX) * k, viewY - (viewY - t.OffsetY) * k); + } + + /// + /// Keeps the image covering the view on each axis where it is larger than the view, and centred on each axis + /// where it is smaller, so panning can never lose the picture. + /// + public static ViewTransform Clamp(ViewTransform t, double imageWidth, double imageHeight, double viewWidth, double viewHeight) => + t with + { + OffsetX = ClampAxis(t.OffsetX, imageWidth * t.Scale, viewWidth), + OffsetY = ClampAxis(t.OffsetY, imageHeight * t.Scale, viewHeight), + }; + + /// Moves the offset by (, ) view units. + public static ViewTransform Pan(ViewTransform t, double dx, double dy) => t with { OffsetX = t.OffsetX + dx, OffsetY = t.OffsetY + dy }; + + /// Rounds the offset to whole device pixels ( device pixels per view unit) so 1:1 shows raw pixels. + public static ViewTransform SnapOffset(ViewTransform t, double pixelsPerUnit) + { + if (!(pixelsPerUnit > 0)) return t; + return t with + { + OffsetX = Math.Round(t.OffsetX * pixelsPerUnit) / pixelsPerUnit, + OffsetY = Math.Round(t.OffsetY * pixelsPerUnit) / pixelsPerUnit, + }; + } + + /// Next zoom level for a wheel movement of (positive = in), by a factor of 1.25 per notch. + public static double WheelZoom(double scale, double notches, double minScale, double maxScale) => + Math.Clamp(scale * Math.Pow(1.25, notches), minScale, maxScale); + + private static double ClampAxis(double offset, double size, double view) + { + if (size <= view) return (view - size) / 2; + return Math.Clamp(offset, view - size, 0); + } +} diff --git a/src/Titano.Ui/Visuals/WrapLayout.cs b/src/Titano.Ui/Visuals/WrapLayout.cs new file mode 100644 index 00000000..52a26cab --- /dev/null +++ b/src/Titano.Ui/Visuals/WrapLayout.cs @@ -0,0 +1,180 @@ +namespace Titano.Ui.Visuals; + +/// Keyboard steps inside a wrapped grid. +public enum WrapStep +{ + Left, + Right, + Up, + Down, + PageUp, + PageDown, + First, + Last, +} + +/// +/// Geometry of a grid of fixed-size items wrapped into rows: O(1) mapping between item index, row, column and +/// pixel offset, visible ranges, minimal scroll to reveal an item and keyboard navigation targets. +/// +public readonly struct WrapLayout +{ + private const double Epsilon = 1e-9; + + /// Number of items. + /// Width available for the rows; infinite puts every item on one row. + /// Slot width of one item. + /// Slot height of one item. + /// Gap between columns and between rows. + /// Spread the leftover width over the column gaps so the grid spans the viewport. + public WrapLayout(int itemCount, double viewportWidth, double itemWidth, double itemHeight, double spacing, bool justify = false) + { + ItemCount = Math.Max(0, itemCount); + ItemWidth = Positive(itemWidth); + ItemHeight = Positive(itemHeight); + Spacing = double.IsFinite(spacing) ? Math.Max(0, spacing) : 0; + var finiteWidth = double.IsFinite(viewportWidth); + Columns = finiteWidth ? ColumnsFor(viewportWidth, ItemWidth, Spacing) : Math.Max(1, ItemCount); + Rows = ItemCount == 0 ? 0 : (ItemCount + Columns - 1) / Columns; + RowPitch = ItemHeight + Spacing; + ColumnPitch = justify && finiteWidth && Columns > 1 + ? Math.Max(ItemWidth + Spacing, (viewportWidth - ItemWidth) / (Columns - 1)) + : ItemWidth + Spacing; + } + + public int ItemCount { get; } + + public double ItemWidth { get; } + + public double ItemHeight { get; } + + public double Spacing { get; } + + public int Columns { get; } + + public int Rows { get; } + + /// Distance between the tops of two consecutive rows. + public double RowPitch { get; } + + /// Distance between the left edges of two consecutive columns. + public double ColumnPitch { get; } + + /// Height of all rows, without a trailing gap. + public double ExtentHeight => Rows == 0 ? 0 : Rows * RowPitch - Spacing; + + /// Width spanned by the columns, without a trailing gap. + public double ExtentWidth => ItemCount == 0 ? 0 : (Math.Min(Columns, ItemCount) - 1) * ColumnPitch + ItemWidth; + + /// Columns that fit in (at least one). + public static int ColumnsFor(double width, double itemWidth, double spacing) + { + if (!double.IsFinite(width) || width <= 0) return 1; + var pitch = Positive(itemWidth) + Math.Max(0, spacing); + return Math.Max(1, (int)Math.Floor((width + Math.Max(0, spacing)) / pitch + Epsilon)); + } + + public int RowOf(int index) => index / Columns; + + public int ColumnOf(int index) => index % Columns; + + public double LeftOf(int index) => ColumnOf(index) * ColumnPitch; + + public double TopOf(int index) => RowOf(index) * RowPitch; + + /// Row whose slot band [top, top + pitch) contains , clamped to the rows. + public int RowAt(double y) + { + if (Rows == 0) return -1; + if (!(y > 0)) return 0; + return (int)Math.Min(Rows - 1, Math.Floor(y / RowPitch)); + } + + /// + /// First and last item index whose slot intersects [offset, offset + viewportHeight), widened by + /// rows on each side. Returns (0, −1) when nothing is visible. + /// + public (int First, int Last) VisibleRange(double offset, double viewportHeight, int cacheRows = 0) + { + if (Rows == 0 || !(viewportHeight > 0)) return (0, -1); + if (double.IsInfinity(viewportHeight)) return (0, ItemCount - 1); + // Row r occupies [r·pitch, r·pitch + itemHeight): visible when it starts before the bottom edge and ends after the top edge. + var firstRow = (long)Math.Floor((offset - ItemHeight) / RowPitch + Epsilon) + 1; + var lastRow = (long)Math.Ceiling((offset + viewportHeight) / RowPitch - Epsilon) - 1; + firstRow = Math.Max(0, firstRow - Math.Max(0, cacheRows)); + lastRow = Math.Min(Rows - 1, lastRow + Math.Max(0, cacheRows)); + if (firstRow > lastRow) return (0, -1); + var first = (int)(firstRow * Columns); + var last = (int)Math.Min(ItemCount - 1, (lastRow + 1) * Columns - 1); + return (first, last); + } + + /// Clamps a vertical offset to [0, extent − viewport]. + public double ClampOffset(double offset, double viewportHeight) + { + var max = Math.Max(0, ExtentHeight - Math.Max(0, viewportHeight)); + return double.IsNaN(offset) ? 0 : Math.Clamp(offset, 0, max); + } + + /// Smallest change of that shows [top, top + height) fully; a band taller than the viewport is aligned to its top. + public static double OffsetToReveal(double top, double height, double offset, double viewportHeight) + { + if (top < offset || height >= viewportHeight) return top; + if (top + height > offset + viewportHeight) return top + height - viewportHeight; + return offset; + } + + /// Clamped offset that shows item fully with the least scrolling. + public double OffsetToReveal(int index, double offset, double viewportHeight) + { + if (index < 0 || index >= ItemCount) return ClampOffset(offset, viewportHeight); + return ClampOffset(OffsetToReveal(TopOf(index), ItemHeight, offset, viewportHeight), viewportHeight); + } + + /// Whole rows that fit in the viewport (at least one): the PageUp/PageDown step. + public int PageRows(double viewportHeight) => + double.IsFinite(viewportHeight) ? Math.Max(1, (int)Math.Floor((viewportHeight + Spacing) / RowPitch + Epsilon)) : Math.Max(1, Rows); + + /// + /// Target of a keyboard step from . Left/Right walk the reading order (wrapping across + /// rows); Up/Down keep the column; Down from a row above a shorter last row lands on the last item; page steps + /// move rows in the same column. Returns −1 when there are no items. + /// + public int Navigate(int index, WrapStep step, int pageRows) + { + if (ItemCount == 0) return -1; + index = Math.Clamp(index, 0, ItemCount - 1); + var last = ItemCount - 1; + var page = Math.Max(1, pageRows); + switch (step) + { + case WrapStep.Left: + return Math.Max(0, index - 1); + case WrapStep.Right: + return Math.Min(last, index + 1); + case WrapStep.Up: + return index >= Columns ? index - Columns : index; + case WrapStep.Down: + if (index + Columns <= last) return index + Columns; + return RowOf(index) < Rows - 1 ? last : index; + case WrapStep.PageUp: + { + var row = Math.Max(0, RowOf(index) - page); + return row * Columns + ColumnOf(index); + } + case WrapStep.PageDown: + { + var row = Math.Min(Rows - 1, RowOf(index) + page); + return Math.Min(last, row * Columns + ColumnOf(index)); + } + case WrapStep.First: + return 0; + case WrapStep.Last: + return last; + default: + return index; + } + } + + private static double Positive(double v) => double.IsFinite(v) && v > 0 ? v : 1; +} diff --git a/tests/Titano.App.Tests/Visuals/CurveMathTests.cs b/tests/Titano.App.Tests/Visuals/CurveMathTests.cs new file mode 100644 index 00000000..ee5b9abf --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/CurveMathTests.cs @@ -0,0 +1,85 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class CurveMathTests +{ + private const double Gap = CurveMath.DefaultMinGap; + + [Test] + public void DraggedPointCannotPassItsNeighbours() + { + double[] xs = [0, 0.3, 0.6, 1]; + Assert.Approximately(0.6 - Gap, CurveMath.ConstrainX(xs, 1, 0.9, Gap, pinEnds: true), 1e-12); + Assert.Approximately(0 + Gap, CurveMath.ConstrainX(xs, 1, -0.4, Gap, pinEnds: true), 1e-12); + Assert.Approximately(0.45, CurveMath.ConstrainX(xs, 1, 0.45, Gap, pinEnds: true), 1e-12); + } + + [Test] + public void PinnedEndsStayAtZeroAndOne() + { + double[] xs = [0, 0.5, 1]; + Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, 0.2, Gap, pinEnds: true), 0); + Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 0.7, Gap, pinEnds: true), 0); + } + + [Test] + public void FreeEndsMoveInsideTheUnitInterval() + { + double[] xs = [0.1, 0.5, 0.9]; + Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, -3, Gap, pinEnds: false), 0); + Assert.Approximately(0.5 - Gap, CurveMath.ConstrainX(xs, 0, 0.8, Gap, pinEnds: false), 1e-12); + Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 4, Gap, pinEnds: false), 0); + } + + [Test] + public void AnySequenceOfDragsKeepsXStrictlyIncreasing() + { + var random = new Random(11); + double[] xs = [0, 0.2, 0.4, 0.6, 0.8, 1]; + for (var step = 0; step < 10_000; step++) + { + var i = random.Next(xs.Length); + xs[i] = CurveMath.ConstrainX(xs, i, random.NextDouble() * 1.4 - 0.2, Gap, pinEnds: true); + for (var k = 1; k < xs.Length; k++) Assert.True(xs[k] - xs[k - 1] >= Gap - 1e-12, $"x[{k - 1}]={xs[k - 1]} x[{k}]={xs[k]}"); + Assert.Approximately(0, xs[0], 0); + Assert.Approximately(1, xs[^1], 0); + } + } + + [Test] + public void InsertionKeepsOrderAndRespectsGapAndPins() + { + double[] xs = [0, 0.5, 1]; + Assert.Equal(1, CurveMath.InsertionIndex(xs, 0.25, Gap, pinEnds: true)); + Assert.Equal(2, CurveMath.InsertionIndex(xs, 0.75, Gap, pinEnds: true)); + Assert.Equal(-1, CurveMath.InsertionIndex(xs, 0.5 + Gap / 2, Gap, pinEnds: true)); + Assert.Equal(-1, CurveMath.InsertionIndex(xs, 1.2, Gap, pinEnds: false)); + + double[] free = [0.2, 0.6]; + Assert.Equal(0, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: false)); + Assert.Equal(2, CurveMath.InsertionIndex(free, 0.9, Gap, pinEnds: false)); + Assert.Equal(-1, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: true)); + } + + [Test] + public void RemovalKeepsTwoPointsAndPinnedEnds() + { + Assert.False(CurveMath.CanRemove(2, 1, pinEnds: false)); + Assert.True(CurveMath.CanRemove(3, 0, pinEnds: false)); + Assert.False(CurveMath.CanRemove(3, 0, pinEnds: true)); + Assert.True(CurveMath.CanRemove(3, 1, pinEnds: true)); + Assert.False(CurveMath.CanRemove(3, 2, pinEnds: true)); + } + + [Test] + public void HitTestPicksTheNearestPointWithinRadius() + { + double[] xs = [10, 50, 54]; + double[] ys = [10, 10, 10]; + Assert.Equal(2, CurveMath.HitTest(xs, ys, 53, 11, 6)); + Assert.Equal(1, CurveMath.HitTest(xs, ys, 51, 10, 6)); + Assert.Equal(-1, CurveMath.HitTest(xs, ys, 30, 10, 6)); + } +} diff --git a/tests/Titano.App.Tests/Visuals/LruCacheTests.cs b/tests/Titano.App.Tests/Visuals/LruCacheTests.cs new file mode 100644 index 00000000..21186f4f --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/LruCacheTests.cs @@ -0,0 +1,59 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class LruCacheTests +{ + [Test] + public void EvictsTheLeastRecentlyUsedEntry() + { + var cache = new LruCache(2); + cache.Set(1, "a"); + cache.Set(2, "b"); + Assert.True(cache.TryGet(1, out _)); + cache.Set(3, "c"); + Assert.False(cache.TryGet(2, out _)); + Assert.True(cache.TryGet(1, out var one)); + Assert.Equal("a", one); + Assert.True(cache.TryGet(3, out _)); + Assert.Equal(2, cache.Count); + } + + [Test] + public void ReplacingAValueRefreshesItsRecency() + { + var cache = new LruCache(2); + cache.Set(1, "a"); + cache.Set(2, "b"); + cache.Set(1, "a2"); + cache.Set(3, "c"); + Assert.True(cache.TryGet(1, out var value)); + Assert.Equal("a2", value); + Assert.False(cache.TryGet(2, out _)); + } + + [Test] + public void ShrinkingCapacityEvictsOldestFirst() + { + var cache = new LruCache(10); + for (var i = 0; i < 10; i++) cache.Set(i, i); + cache.Capacity = 3; + Assert.Equal(3, cache.Count); + for (var i = 0; i < 7; i++) Assert.False(cache.TryGet(i, out _)); + for (var i = 7; i < 10; i++) Assert.True(cache.TryGet(i, out _)); + } + + [Test] + public void RemoveAndClear() + { + var cache = new LruCache(4); + cache.Set("x", 1); + cache.Set("y", 2); + Assert.True(cache.Remove("x")); + Assert.False(cache.Remove("x")); + cache.Clear(); + Assert.Equal(0, cache.Count); + Assert.Throws(() => _ = new LruCache(0)); + } +} diff --git a/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs b/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs new file mode 100644 index 00000000..ba7df1d9 --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs @@ -0,0 +1,106 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class MinMaxDecimatorTests +{ + [Test] + public void ShortSeriesKeepsEverySample() + { + double[] values = [3, 1, 4, 1, 5]; + var output = new int[MinMaxDecimator.Capacity(values.Length, 10)]; + var n = MinMaxDecimator.Decimate(values, 10, output); + Assert.SequenceEqual([0, 1, 2, 3, 4], output[..n]); + } + + [Test] + public void LongSeriesKeepsAtMostTwoSamplesPerColumn() + { + var values = Noise(200_000, seed: 1); + const int columns = 800; + var output = new int[MinMaxDecimator.Capacity(values.Length, columns)]; + var n = MinMaxDecimator.Decimate(values, columns, output); + Assert.LessOrEqual(n, 2 * columns); + Assert.Monotonic(output[..n].Select(i => (double)i), strict: true); + } + + [Test] + public void EveryColumnPreservesItsMinimumAndMaximum() + { + var values = Noise(123_457, seed: 2); + // Plant spikes that a naive stride sampler would miss. + values[50_001] = 1000; + values[99_999] = -1000; + const int columns = 640; + var output = new int[MinMaxDecimator.Capacity(values.Length, columns)]; + var n = MinMaxDecimator.Decimate(values, columns, output); + var kept = output[..n]; + + for (var c = 0; c < columns; c++) + { + var start = (int)((long)c * values.Length / columns); + var end = (int)((long)(c + 1) * values.Length / columns); + double min = double.PositiveInfinity, max = double.NegativeInfinity; + double keptMin = double.PositiveInfinity, keptMax = double.NegativeInfinity; + for (var i = start; i < end; i++) + { + min = Math.Min(min, values[i]); + max = Math.Max(max, values[i]); + } + foreach (var i in kept) + { + if (i < start || i >= end) continue; + keptMin = Math.Min(keptMin, values[i]); + keptMax = Math.Max(keptMax, values[i]); + } + Assert.Equal(min, keptMin, $"column {c} min"); + Assert.Equal(max, keptMax, $"column {c} max"); + } + Assert.Contains(50_001, kept); + Assert.Contains(99_999, kept); + } + + [Test] + public void NonFiniteRunsBecomeSingleGaps() + { + double[] values = [1, double.NaN, double.NaN, 2, double.PositiveInfinity, 3, double.NaN]; + var output = new int[values.Length]; + var n = MinMaxDecimator.Decimate(values, 100, output); + Assert.SequenceEqual([0, MinMaxDecimator.Gap, 3, MinMaxDecimator.Gap, 5], output[..n]); + } + + [Test] + public void EmptyColumnsBreakTheLineInDecimatedMode() + { + var values = new double[1000]; + for (var i = 0; i < values.Length; i++) values[i] = i < 400 || i >= 600 ? i : double.NaN; + var output = new int[MinMaxDecimator.Capacity(values.Length, 10)]; + var n = MinMaxDecimator.Decimate(values, 10, output); + // Columns 4 and 5 (indices 400–599) hold no finite sample: exactly one gap between columns 3 and 6. + Assert.SequenceEqual([0, 99, 100, 199, 200, 299, 300, 399, MinMaxDecimator.Gap, 600, 699, 700, 799, 800, 899, 900, 999], output[..n]); + } + + [Test] + public void FlatColumnsEmitOneSample() + { + var values = Enumerable.Repeat(5.0, 1000).ToArray(); + var output = new int[MinMaxDecimator.Capacity(values.Length, 4)]; + var n = MinMaxDecimator.Decimate(values, 4, output); + Assert.SequenceEqual([0, 250, 500, 750], output[..n]); + } + + [Test] + public void UndersizedOutputIsRejected() + { + Assert.Throws(() => MinMaxDecimator.Decimate(new double[100], 10, new int[5])); + } + + private static double[] Noise(int count, int seed) + { + var random = new Random(seed); + var values = new double[count]; + for (var i = 0; i < count; i++) values[i] = Math.Sin(i * 0.001) + random.NextDouble() * 0.2; + return values; + } +} diff --git a/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs b/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs new file mode 100644 index 00000000..cc83c820 --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs @@ -0,0 +1,91 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class NiceScaleTests +{ + [Theory] + [Case(0.6, true, 0.5)] + [Case(1.2, true, 1.0)] + [Case(2.9, true, 2.0)] + [Case(3.1, true, 5.0)] + [Case(7.5, true, 10.0)] + [Case(1.2, false, 2.0)] + [Case(4.0, false, 5.0)] + [Case(5.0, false, 5.0)] + [Case(1234.0, false, 2000.0)] + [Case(0.025, true, 0.02)] + public void NiceNumbersAreOneTwoOrFiveTimesAPowerOfTen(double value, bool round, double expected) + { + Assert.Approximately(expected, NiceScale.NiceNumber(value, round), expected * 1e-12); + } + + [Test] + public void InnerTicksStayInsideTheRangeOnNiceMultiples() + { + var ticks = NiceScale.Inner(0.13, 0.87, 5); + Assert.Approximately(0.2, ticks.Step, 1e-12); + Assert.Equal(4, ticks.Count); + Assert.Approximately(0.2, ticks[0], 1e-12); + Assert.Approximately(0.8, ticks[3], 1e-12); + for (var i = 0; i < ticks.Count; i++) Assert.InRange(ticks[i], 0.13, 0.87); + } + + [Test] + public void OuterTicksEncloseTheRange() + { + var ticks = NiceScale.Outer(3, 1870, 5); + Assert.Approximately(500, ticks.Step, 1e-9); + Assert.Approximately(0, ticks.First, 1e-9); + Assert.Approximately(2000, ticks.Last, 1e-9); + Assert.Equal(5, ticks.Count); + } + + [Test] + public void TickValuesDoNotDriftOverManySteps() + { + var ticks = NiceScale.Inner(-1e6, 1e6, 11); + Assert.Approximately(200_000, ticks.Step, 1e-6); + Assert.Approximately(0, ticks[5], 1e-6); + Assert.Approximately(1e6, ticks[ticks.Count - 1], 1e-6); + } + + [Test] + public void TickCountNeverExceedsTheRequest() + { + var random = new Random(7); + for (var i = 0; i < 1000; i++) + { + var a = (random.NextDouble() - 0.5) * Math.Pow(10, random.Next(-3, 7)); + var b = a + random.NextDouble() * Math.Pow(10, random.Next(-3, 7)) + 1e-9; + var max = random.Next(2, 12); + var ticks = NiceScale.Inner(a, b, max); + Assert.LessOrEqual(ticks.Count, max); + } + } + + [Test] + public void PadWidensBothSidesAndCentresFlatData() + { + var (min, max) = NiceScale.Pad(10, 20, 0.1); + Assert.Approximately(9, min, 1e-12); + Assert.Approximately(21, max, 1e-12); + + var (flatMin, flatMax) = NiceScale.Pad(5, 5, 0.1); + Assert.Approximately(5, (flatMin + flatMax) / 2, 1e-12); + Assert.Greater(flatMax - flatMin, 0); + + var (zeroMin, zeroMax) = NiceScale.Pad(0, 0, 0.1); + Assert.Approximately(-1, zeroMin, 1e-12); + Assert.Approximately(1, zeroMax, 1e-12); + Assert.Equal((0.0, 1.0), NiceScale.Pad(double.NaN, 3, 0.1)); + } + + [Test] + public void DegenerateRangesGiveNoInnerTicks() + { + Assert.Equal(0, NiceScale.Inner(4, 4, 5).Count); + Assert.Equal(0, NiceScale.Inner(double.NaN, 4, 5).Count); + } +} diff --git a/tests/Titano.App.Tests/Visuals/PixelGridTests.cs b/tests/Titano.App.Tests/Visuals/PixelGridTests.cs new file mode 100644 index 00000000..871fbeb1 --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/PixelGridTests.cs @@ -0,0 +1,34 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class PixelGridTests +{ + [Theory] + [Case(1.0)] + [Case(1.25)] + [Case(1.5)] + [Case(2.0)] + public void HairlinesCoverWholeDevicePixels(double scale) + { + var thickness = PixelGrid.SnapThickness(1, scale); + var devicePixels = thickness * scale; + Assert.Approximately(Math.Round(devicePixels), devicePixels, 1e-9); + for (var v = 0.0; v < 50; v += 0.37) + { + var centre = PixelGrid.SnapLine(v, thickness, scale) * scale; + var left = centre - devicePixels / 2; + Assert.Approximately(Math.Round(left), left, 1e-9, $"v={v}"); + Assert.LessOrEqual(Math.Abs(centre - v * scale), 1); + } + } + + [Test] + public void SnapRoundsToDevicePixelBoundaries() + { + Assert.Approximately(10, PixelGrid.Snap(10.2, 1), 1e-12); + Assert.Approximately(10 + 2 / 3.0, PixelGrid.Snap(10.6, 1.5), 1e-12); + Assert.Approximately(3.3, PixelGrid.Snap(3.3, 0), 0); + } +} diff --git a/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs b/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs new file mode 100644 index 00000000..030a191a --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs @@ -0,0 +1,85 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class StripLayoutTests +{ + [Test] + public void CellsFillTheWidthExactly() + { + var strip = new StripLayout(898, 36, 2, 3600); + Assert.Equal(23, strip.CellCount); + Assert.Approximately(898, strip.CellLeft(strip.CellCount - 1) + strip.CellWidth, 1e-9); + } + + [Test] + public void ShortSequencesGetOneCellPerFrame() + { + var strip = new StripLayout(898, 36, 2, 5); + Assert.Equal(5, strip.CellCount); + for (var c = 0; c < 5; c++) Assert.Equal(c, strip.FrameForCell(c)); + } + + [Theory] + [Case(3600, 23)] + [Case(5, 4)] + [Case(7, 7)] + [Case(1001, 24)] + [Case(24, 23)] + public void EachCellShowsAFrameFromItsOwnRun(int frames, int cells) + { + var strip = new StripLayout(cells * 40 - 2, 38, 2, frames); + Assert.Equal(Math.Min(cells, frames), strip.CellCount); + var previous = -1; + for (var c = 0; c < strip.CellCount; c++) + { + var frame = strip.FrameForCell(c); + Assert.Equal(c, strip.CellForFrame(frame)); + Assert.Greater(frame, previous); + previous = frame; + } + } + + [Test] + public void SeekingMapsXToFramesContinuously() + { + var strip = new StripLayout(900, 36, 2, 3600); + Assert.Equal(0, strip.FrameAt(-5)); + Assert.Equal(0, strip.FrameAt(0)); + Assert.Equal(1800, strip.FrameAt(450)); + Assert.Equal(3599, strip.FrameAt(900)); + Assert.Equal(3599, strip.FrameAt(5000)); + Assert.Equal(412, strip.FrameAt(strip.XForFrame(412))); + } + + [Test] + public void EmptyStripHasNoCells() + { + var strip = new StripLayout(900, 36, 2, 0); + Assert.Equal(0, strip.CellCount); + Assert.Equal(-1, strip.FrameAt(10)); + Assert.Equal(-1, strip.FrameForCell(0)); + } + + [Test] + public void HeatmapHitTestExcludesGaps() + { + var grid = new CellGridLayout(30, 20, 8, 12, 16, 3); + Assert.True(grid.TryHit(30 + 19 * 2 + 5, 20 + 19 * 7 + 15.5, out var row, out var column)); + Assert.Equal(7, row); + Assert.Equal(2, column); + Assert.False(grid.TryHit(30 + 16.5, 25, out _, out _)); + Assert.False(grid.TryHit(29, 25, out _, out _)); + Assert.False(grid.TryHit(30 + grid.Width + 1, 25, out _, out _)); + Assert.Approximately(12 * 19 - 3, grid.Width, 1e-12); + } + + [Test] + public void HeatmapCellsFitTheSmallerAxis() + { + Assert.Approximately(16, CellGridLayout.FitCellSize(500, 149, 8, 12, 3, 24), 1e-9); + Assert.Approximately(24, CellGridLayout.FitCellSize(5000, 5000, 8, 12, 3, 24), 1e-9); + Assert.Approximately((260 - 33) / 12.0, CellGridLayout.FitCellSize(260, double.PositiveInfinity, 8, 12, 3, 24), 1e-9); + } +} diff --git a/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs b/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs new file mode 100644 index 00000000..cea6efe8 --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs @@ -0,0 +1,72 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class ViewportMathTests +{ + [Test] + public void FitUsesTheLimitingAxisAndCentres() + { + // 8192×5464 into 900×430: height limits. + var scale = ViewportMath.FitScale(8192, 5464, 900, 430); + Assert.Approximately(430.0 / 5464, scale, 1e-12); + var t = ViewportMath.Centered(scale, 8192, 5464, 900, 430); + Assert.Approximately(0, t.OffsetY, 1e-9); + Assert.Approximately((900 - 8192 * scale) / 2, t.OffsetX, 1e-9); + Assert.Approximately(0, ViewportMath.FitScale(0, 100, 900, 430), 0); + } + + [Test] + public void ZoomAtKeepsThePointUnderTheCursorFixed() + { + var t = new ViewTransform(0.25, 37, -12); + var (ix, iy) = t.ToImage(410, 220); + var zoomed = ViewportMath.ZoomAt(t, 1.7, 410, 220); + var (vx, vy) = zoomed.ToView(ix, iy); + Assert.Within(410, 220, vx, vy, 1e-9); + Assert.Approximately(1.7, zoomed.Scale, 0); + } + + [Test] + public void WheelZoomStepsGeometricallyAndClamps() + { + Assert.Approximately(1.25, ViewportMath.WheelZoom(1, 1, 0.01, 32), 1e-12); + Assert.Approximately(1 / 1.5625, ViewportMath.WheelZoom(1, -2, 0.01, 32), 1e-12); + Assert.Approximately(32, ViewportMath.WheelZoom(30, 3, 0.01, 32), 0); + } + + [Test] + public void ClampCentresSmallImagesAndCoversWithLargeOnes() + { + // Image 400×300 at scale 1 inside 900×430: centred on both axes whatever the offset. + var small = ViewportMath.Clamp(new ViewTransform(1, -500, 999), 400, 300, 900, 430); + Assert.Approximately(250, small.OffsetX, 1e-9); + Assert.Approximately(65, small.OffsetY, 1e-9); + + // Image 4000×3000 at scale 1: the view must stay covered. + var large = ViewportMath.Clamp(new ViewTransform(1, 100, -5000), 4000, 3000, 900, 430); + Assert.Approximately(0, large.OffsetX, 1e-9); + Assert.Approximately(430 - 3000, large.OffsetY, 1e-9); + } + + [Test] + public void PanMovesAndRoundTripsThroughImageCoordinates() + { + var t = ViewportMath.Pan(new ViewTransform(2, 10, 20), -4, 6); + Assert.Approximately(6, t.OffsetX, 0); + Assert.Approximately(26, t.OffsetY, 0); + var (x, y) = t.ToView(123.5, 77.25); + var (ix, iy) = t.ToImage(x, y); + Assert.Within(123.5, 77.25, ix, iy, 1e-12); + } + + [Test] + public void SnapOffsetAlignsToDevicePixels() + { + // 150 % DPI: 1.5 device pixels per DIP. + var t = ViewportMath.SnapOffset(new ViewTransform(1, 10.4, -3.1), 1.5); + Assert.Approximately(Math.Round(10.4 * 1.5), t.OffsetX * 1.5, 1e-9); + Assert.Approximately(Math.Round(-3.1 * 1.5), t.OffsetY * 1.5, 1e-9); + } +} diff --git a/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs b/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs new file mode 100644 index 00000000..2492e1e2 --- /dev/null +++ b/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs @@ -0,0 +1,144 @@ +using Titano.Testing; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Visuals; + +public sealed class WrapLayoutTests +{ + [Theory] + [Case(0.0, 1)] + [Case(235.0, 1)] + [Case(236.0, 1)] + [Case(487.0, 1)] + [Case(488.0, 2)] + [Case(1252.0, 5)] + [Case(1255.0, 5)] + public void ColumnsCountWholeItemsWithGapsBetween(double width, int expected) + { + // 236-px cards with 16-px gaps: n columns need n·236 + (n−1)·16 px. + Assert.Equal(expected, WrapLayout.ColumnsFor(width, 236, 16)); + } + + [Test] + public void RowsAndExtentLeaveNoTrailingGap() + { + var layout = new WrapLayout(11, 1252, 236, 208, 16); + Assert.Equal(5, layout.Columns); + Assert.Equal(3, layout.Rows); + Assert.Approximately(3 * 224 - 16, layout.ExtentHeight, 1e-9); + Assert.Approximately(5 * 236 + 4 * 16, layout.ExtentWidth, 1e-9); + Assert.Approximately(0, new WrapLayout(0, 1252, 236, 208, 16).ExtentHeight, 1e-9); + } + + [Test] + public void IndexMapsToRowColumnAndPixelOrigin() + { + var layout = new WrapLayout(500_000, 1252, 236, 208, 16); + Assert.Equal(1234, layout.RowOf(6172)); + Assert.Equal(2, layout.ColumnOf(6172)); + Assert.Approximately(2 * 252, layout.LeftOf(6172), 1e-9); + Assert.Approximately(1234 * 224, layout.TopOf(6172), 1e-6); + Assert.Equal(100_000, layout.Rows); + } + + [Test] + public void VisibleRangeIsConstantTimeAndCoversPartialRows() + { + var layout = new WrapLayout(500_000, 1252, 236, 208, 16); + // Offset in the middle of row 50 000's gap: row 50 000 has ended, row 50 001 starts at 50 001·224. + var offset = 50_000 * 224.0 + 210; + var (first, last) = layout.VisibleRange(offset, 600); + Assert.Equal(50_001 * 5, first); + // Bottom edge at offset + 600 = 50 000·224 + 810 → rows up to 50 003 (starts at +672) are visible. + Assert.Equal(50_004 * 5 - 1, last); + + var (cachedFirst, cachedLast) = layout.VisibleRange(offset, 600, cacheRows: 1); + Assert.Equal(first - 5, cachedFirst); + Assert.Equal(last + 5, cachedLast); + } + + [Test] + public void VisibleRangeExcludesRowStartingAtBottomEdge() + { + var layout = new WrapLayout(100, 1252, 236, 208, 16); + var (first, last) = layout.VisibleRange(0, 224); + Assert.Equal(0, first); + Assert.Equal(4, last); + } + + [Test] + public void VisibleRangeClampsToLastPartialRow() + { + var layout = new WrapLayout(12, 1252, 236, 208, 16); + var (first, last) = layout.VisibleRange(0, 10_000, cacheRows: 2); + Assert.Equal(0, first); + Assert.Equal(11, last); + Assert.Equal((0, -1), new WrapLayout(0, 1252, 236, 208, 16).VisibleRange(0, 500)); + } + + [Test] + public void OffsetToRevealScrollsTheLeastAmount() + { + var layout = new WrapLayout(100, 1252, 236, 208, 16); + // Row 3 spans [672, 880): below a viewport [0, 600) → bottom-aligned. + Assert.Approximately(880 - 600, layout.OffsetToReveal(15, 0, 600), 1e-9); + // Already visible → unchanged. + Assert.Approximately(300, layout.OffsetToReveal(15, 300, 600), 1e-9); + // Above the viewport → top-aligned. + Assert.Approximately(224, layout.OffsetToReveal(5, 1000, 600), 1e-9); + // Taller than the viewport → top-aligned. + Assert.Approximately(672, WrapLayout.OffsetToReveal(672, 208, 0, 100), 1e-9); + } + + [Test] + public void ClampOffsetKeepsViewportInsideExtent() + { + var layout = new WrapLayout(10, 1252, 236, 208, 16); + Assert.Approximately(432 - 300, layout.ClampOffset(5000, 300), 1e-9); + Assert.Approximately(0, layout.ClampOffset(-20, 300), 1e-9); + Assert.Approximately(0, layout.ClampOffset(50, 1000), 1e-9); + } + + [Test] + public void JustifySpreadsLeftoverWidthOverGaps() + { + var layout = new WrapLayout(10, 1300, 236, 208, 16, justify: true); + Assert.Equal(5, layout.Columns); + Assert.Approximately(1300, layout.LeftOf(4) + 236, 1e-9); + Assert.Approximately(1300, layout.ExtentWidth, 1e-9); + } + + [Theory] + [Case(7, WrapStep.Left, 6)] + [Case(5, WrapStep.Left, 4)] + [Case(0, WrapStep.Left, 0)] + [Case(4, WrapStep.Right, 5)] + [Case(11, WrapStep.Right, 11)] + [Case(7, WrapStep.Up, 2)] + [Case(2, WrapStep.Up, 2)] + [Case(2, WrapStep.Down, 7)] + [Case(9, WrapStep.Down, 11)] + [Case(11, WrapStep.Down, 11)] + [Case(7, WrapStep.First, 0)] + [Case(7, WrapStep.Last, 11)] + public void KeyboardStepsFollowReadingOrderAndColumns(int from, WrapStep step, int expected) + { + // 12 items in rows of 5: 0–4, 5–9, 10–11. + var layout = new WrapLayout(12, 1252, 236, 208, 16); + Assert.Equal(expected, layout.Navigate(from, step, pageRows: 2)); + } + + [Test] + public void PageStepsMoveWholeViewportRowsInTheSameColumn() + { + var layout = new WrapLayout(1000, 1252, 236, 208, 16); + var pageRows = layout.PageRows(700); + Assert.Equal(3, pageRows); + Assert.Equal(2 + 3 * 5, layout.Navigate(2, WrapStep.PageDown, pageRows)); + Assert.Equal(2, layout.Navigate(2 + 3 * 5, WrapStep.PageUp, pageRows)); + Assert.Equal(3, layout.Navigate(8, WrapStep.PageUp, pageRows)); + // From row 198 a page down is clamped to the last row, same column. + Assert.Equal(999, layout.Navigate(994, WrapStep.PageDown, pageRows)); + Assert.Equal(-1, new WrapLayout(0, 1252, 236, 208, 16).Navigate(0, WrapStep.Down, 1)); + } +} From 45518e8e4e068a72788d91925b0be754006e701a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:05:36 +0000 Subject: [PATCH 073/188] feat(windows): add Media Foundation encoder provider/session and DXGI adapter enumeration Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core.Windows/Dxgi/GpuAdapters.cs | 131 ++++ src/Titano.Core.Windows/Interop/ComObjects.cs | 60 ++ .../MediaFoundationEncoderProvider.cs | 124 ++++ .../MediaFoundationEncoderSession.cs | 640 ++++++++++++++++++ .../MediaFoundationEncoders.cs | 95 +++ .../MediaFoundation/MediaFoundationRuntime.cs | 44 ++ .../MediaFoundation/MfInterop.cs | 314 +++++++++ .../MediaFoundation/GpuAdaptersTests.cs | 18 + .../MediaFoundationEncoderTests.cs | 153 +++++ 9 files changed, 1579 insertions(+) create mode 100644 src/Titano.Core.Windows/Dxgi/GpuAdapters.cs create mode 100644 src/Titano.Core.Windows/Interop/ComObjects.cs create mode 100644 src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderProvider.cs create mode 100644 src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs create mode 100644 src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoders.cs create mode 100644 src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs create mode 100644 src/Titano.Core.Windows/MediaFoundation/MfInterop.cs create mode 100644 tests/Titano.Core.Windows.Tests/MediaFoundation/GpuAdaptersTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs diff --git a/src/Titano.Core.Windows/Dxgi/GpuAdapters.cs b/src/Titano.Core.Windows/Dxgi/GpuAdapters.cs new file mode 100644 index 00000000..ae6aaa28 --- /dev/null +++ b/src/Titano.Core.Windows/Dxgi/GpuAdapters.cs @@ -0,0 +1,131 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using Titano.Core.Diagnostics; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Dxgi; + +/// A graphics adapter as reported by DXGI (shown next to the encoders in Settings › Rendering). +/// PCI vendor id (0x10DE NVIDIA, 0x8086 Intel, 0x1002 AMD…). +/// The Microsoft Basic Render Driver or another software adapter. +public sealed record GpuAdapterInfo(string Description, uint VendorId, uint DeviceId, ulong DedicatedVideoMemory, ulong SharedSystemMemory, bool IsSoftware); + +/// Enumerates graphics adapters with CreateDXGIFactory1 → EnumAdapters1 → GetDesc1. +public static partial class GpuAdapters +{ + private const int NotFound = unchecked((int)0x887A0002); // DXGI_ERROR_NOT_FOUND + private const uint SoftwareFlag = 2; // DXGI_ADAPTER_FLAG_SOFTWARE + + /// All adapters in DXGI order (the primary adapter first); empty when DXGI is unavailable. + public static IReadOnlyList Enumerate() + { + var adapters = new List(); + if (!OperatingSystem.IsWindows()) return adapters; + IDXGIFactory1? factory = null; + try + { + ComObjects.Check(CreateDXGIFactory1(typeof(IDXGIFactory1).GUID, out var pointer), "CreateDXGIFactory1"); + factory = ComObjects.Attach(pointer); + for (uint index = 0; ; index++) + { + var hr = factory.EnumAdapters1(index, out var adapterPointer); + if (hr == NotFound) break; + ComObjects.Check(hr, "IDXGIFactory1.EnumAdapters1"); + var adapter = ComObjects.Attach(adapterPointer); + try + { + ComObjects.Check(adapter.GetDesc1(out var desc), "IDXGIAdapter1.GetDesc1"); + adapters.Add(desc.ToInfo()); + } + finally + { + ComObjects.Release(adapter); + } + } + } + catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException) + { + Log.Warning("Dxgi", "Graphics adapters could not be enumerated", ex); + } + finally + { + ComObjects.Release(factory); + } + return adapters; + } + + [LibraryImport("dxgi.dll")] + private static partial int CreateDXGIFactory1(in Guid iid, out nint factory); + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct AdapterDesc1 + { + public fixed char Description[128]; + public uint VendorId; + public uint DeviceId; + public uint SubSysId; + public uint Revision; + public nuint DedicatedVideoMemory; + public nuint DedicatedSystemMemory; + public nuint SharedSystemMemory; + public uint AdapterLuidLow; + public int AdapterLuidHigh; + public uint Flags; + + public readonly GpuAdapterInfo ToInfo() + { + fixed (char* text = Description) + { + var description = new string(text, 0, new ReadOnlySpan(text, 128).IndexOf('\0') is var n and >= 0 ? n : 128); + return new GpuAdapterInfo(description, VendorId, DeviceId, DedicatedVideoMemory, SharedSystemMemory, (Flags & SoftwareFlag) != 0); + } + } + } +} + +// DXGI interfaces in vtable order (dxgi.h); unused slots keep their real signatures with raw pointers. + +[GeneratedComInterface] +[Guid("aec22fb8-76f3-4639-9be0-28eb43a67a2e")] +internal partial interface IDXGIObject +{ + [PreserveSig] int SetPrivateData(in Guid name, uint size, nint data); + [PreserveSig] int SetPrivateDataInterface(in Guid name, nint unknown); + [PreserveSig] int GetPrivateData(in Guid name, ref uint size, nint data); + [PreserveSig] int GetParent(in Guid iid, out nint parent); +} + +[GeneratedComInterface] +[Guid("7b7166ec-21c7-44ae-b21a-c9ae321ae369")] +internal partial interface IDXGIFactory : IDXGIObject +{ + [PreserveSig] int EnumAdapters(uint index, out nint adapter); + [PreserveSig] int MakeWindowAssociation(nint window, uint flags); + [PreserveSig] int GetWindowAssociation(out nint window); + [PreserveSig] int CreateSwapChain(nint device, nint description, out nint swapChain); + [PreserveSig] int CreateSoftwareAdapter(nint module, out nint adapter); +} + +[GeneratedComInterface] +[Guid("770aae78-f26f-4dba-a829-253c83d1b387")] +internal partial interface IDXGIFactory1 : IDXGIFactory +{ + [PreserveSig] int EnumAdapters1(uint index, out nint adapter); + [PreserveSig] int IsCurrent(); +} + +[GeneratedComInterface] +[Guid("2411e7e1-12ac-4ccf-bd14-9798e8534dc0")] +internal partial interface IDXGIAdapter : IDXGIObject +{ + [PreserveSig] int EnumOutputs(uint index, out nint output); + [PreserveSig] int GetDesc(nint description); + [PreserveSig] int CheckInterfaceSupport(in Guid iid, out long umdVersion); +} + +[GeneratedComInterface] +[Guid("29038f61-3839-4626-91fd-086879011a05")] +internal partial interface IDXGIAdapter1 : IDXGIAdapter +{ + [PreserveSig] int GetDesc1(out GpuAdapters.AdapterDesc1 description); +} diff --git a/src/Titano.Core.Windows/Interop/ComObjects.cs b/src/Titano.Core.Windows/Interop/ComObjects.cs new file mode 100644 index 00000000..db6a7bc6 --- /dev/null +++ b/src/Titano.Core.Windows/Interop/ComObjects.cs @@ -0,0 +1,60 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; + +namespace Titano.Core.Windows.Interop; + +/// +/// Lifetime helpers for source-generated COM interop. Interface pointers received as out nint are wrapped in +/// unique runtime-callable wrappers so they can be released deterministically (Media Foundation encoders recycle a +/// small pool of samples and stall when references linger until finalization). +/// +internal static class ComObjects +{ + private static readonly StrategyBasedComWrappers Wrappers = new(); + + /// Wraps an owned interface pointer; the caller's reference is released (the wrapper holds its own). + public static T Attach(nint pointer) where T : class + { + if (pointer == 0) throw new ArgumentNullException(nameof(pointer)); + try + { + return (T)Wrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.UniqueInstance); + } + finally + { + Marshal.Release(pointer); + } + } + + /// Like but returns null for a null pointer. + public static T? AttachOrNull(nint pointer) where T : class => pointer == 0 ? null : Attach(pointer); + + /// An AddRef'ed pointer of a wrapper, for structures; release it with . + public static unsafe nint GetPointer(T wrapper) where T : class => (nint)ComInterfaceMarshaller.ConvertToUnmanaged(wrapper); + + /// Releases the COM object behind a wrapper created by now rather than at finalization. + public static void Release(object? wrapper) + { + if (wrapper is ComObject com) com.FinalRelease(); + } + + /// Throws a naming the operation when is a failure code. + public static void Check(int hr, string operation) + { + if (hr < 0) throw new COMException($"{operation} failed with HRESULT 0x{hr:X8}", hr); + } + + /// Reads and frees a CoTaskMem-allocated UTF-16 string. + public static string? TakeString(nint pointer) + { + if (pointer == 0) return null; + try + { + return Marshal.PtrToStringUni(pointer); + } + finally + { + Marshal.FreeCoTaskMem(pointer); + } + } +} diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderProvider.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderProvider.cs new file mode 100644 index 00000000..d7bc3752 --- /dev/null +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderProvider.cs @@ -0,0 +1,124 @@ +using System.Runtime.InteropServices; +using Titano.Core.Diagnostics; +using Titano.Core.Video; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.MediaFoundation; + +/// +/// H.264, HEVC and AV1 encoding through Media Foundation MFTs (BRIEF §11.3): hardware encoders (NVENC, Quick Sync, +/// AMF…) first, the Microsoft software encoder as the H.264 fallback; HEVC and AV1 are offered only with hardware. +/// Codecs without a usable encoder are absent from . +/// +public sealed class MediaFoundationEncoderProvider : IVideoEncoderProvider +{ + private const string LogCategory = MediaFoundationEncoders.LogCategory; + private const int SoftwareH264MaxWidth = 4096, SoftwareH264MaxHeight = 2304; // Microsoft H.264 encoder, level 5.2 + private readonly Lazy> _capabilities = new(BuildCapabilities); + + public string Name => "Media Foundation"; + + public IReadOnlyList Capabilities => _capabilities.Value; + + public bool CanEncode(EncodeSettings settings) + { + if (!SettingsSupported(settings)) return false; + foreach (var c in Capabilities) + { + if (Fits(c.Codec, c.Name, c.Hardware, c.SupportsTenBit, settings) && settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight) return true; + } + return false; + } + + public IVideoEncoderSession Open(EncodeSettings settings) + { + if (!SettingsSupported(settings)) throw new NotSupportedException($"Media Foundation cannot encode {settings.Codec} {settings.Width}×{settings.Height} {settings.BitDepth}-bit"); + var runtime = MediaFoundationRuntime.Acquire(); + var candidates = new List<(MediaFoundationEncoderInfo Info, IMFActivate Activate)>(); + try + { + foreach (var (info, activate) in MediaFoundationEncoders.Find(settings.Codec)) + { + if (Fits(info.Codec, info.Name, info.IsHardware, info.SupportsTenBit, settings)) candidates.Add((info, activate)); + else ComObjects.Release(activate); + } + // Named encoder first, then the preferred kind; MFTEnumEx merit order otherwise. + var ordered = candidates + .OrderByDescending(c => settings.EncoderName is not null && c.Info.Name == settings.EncoderName) + .ThenByDescending(c => c.Info.IsHardware == settings.PreferHardware) + .ToList(); + Exception? failure = null; + for (var i = 0; i < ordered.Count; i++) + { + var (info, activate) = ordered[i]; + try + { + var session = MediaFoundationEncoderSession.Open(settings, info, activate, runtime); + for (var j = i + 1; j < ordered.Count; j++) ComObjects.Release(ordered[j].Activate); + candidates.Clear(); + return session; + } + catch (Exception ex) when (ex is COMException or NotSupportedException or InvalidCastException) + { + Log.Warning(LogCategory, $"\"{info.Name}\" could not be configured for {settings.Codec} {settings.Width}×{settings.Height}: {ex.Message}"); + candidates.Remove(ordered[i]); + activate.ShutdownObject(); + ComObjects.Release(activate); + failure = ex; + } + } + throw new NotSupportedException($"No Media Foundation encoder accepted {settings.Codec} {settings.Width}×{settings.Height} {settings.BitDepth}-bit", failure); + } + catch + { + foreach (var (_, activate) in candidates) ComObjects.Release(activate); + runtime.Dispose(); + throw; + } + } + + private static bool SettingsSupported(EncodeSettings s) => + s.Codec is VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 + && s.Width > 0 && s.Height > 0 && s.Width % 2 == 0 && s.Height % 2 == 0 + && s.FrameRate.Numerator > 0 && s.FrameRate.Denominator > 0 + && (s.BitDepth == 8 || (s.BitDepth == 10 && s.Codec != VideoCodec.H264)); + + /// §11.3: HEVC and AV1 only in hardware; 10-bit needs P010 input; a named encoder must match. + private static bool Fits(VideoCodec codec, string name, bool hardware, bool tenBit, EncodeSettings s) => + codec == s.Codec + && (hardware || codec == VideoCodec.H264) + && (s.BitDepth == 8 || tenBit) + && (s.EncoderName is null || s.EncoderName == name); + + private static IReadOnlyList BuildCapabilities() + { + var capabilities = new List(); + try + { + foreach (var info in MediaFoundationEncoders.Enumerate()) + { + if (!info.IsHardware && info.Codec != VideoCodec.H264) continue; + var (width, height) = info.IsHardware ? (info.Codec == VideoCodec.H264 ? (4096, 4096) : (8192, 8192)) : (SoftwareH264MaxWidth, SoftwareH264MaxHeight); + capabilities.Add(new EncoderCapability(info.Codec, info.Name, info.IsHardware, width, height, + info.SupportsTenBit && info.Codec != VideoCodec.H264, VendorName(info.VendorId))); + Log.Info(LogCategory, $"{info.Codec} encoder \"{info.Name}\" ({(info.IsHardware ? "hardware" : "software")}{(info.SupportsTenBit ? ", 10-bit" : string.Empty)})"); + } + } + catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException or PlatformNotSupportedException) + { + Log.Warning(LogCategory, "Media Foundation encoders could not be enumerated", ex); + } + return capabilities; + } + + /// Readable vendor for PCI vendor ids reported as "VEN_xxxx". + internal static string? VendorName(string? vendorId) => vendorId?.ToUpperInvariant() switch + { + null => null, + "VEN_10DE" => "NVIDIA", + "VEN_8086" => "Intel", + "VEN_1002" or "VEN_1022" => "AMD", + "VEN_5143" or "VEN_4D4F4351" => "Qualcomm", + var other => other, + }; +} diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs new file mode 100644 index 00000000..f82354aa --- /dev/null +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs @@ -0,0 +1,640 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.IO; +using Titano.Core.Video; +using Titano.Core.Video.Bitstream; +using Titano.Core.Video.Mp4; +using Titano.Core.Video.Yuv; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.MediaFoundation; + +/// +/// One encode through a Media Foundation encoder MFT driven directly (no SinkWriter): output type first, then NV12/P010 +/// input, ICodecAPI rate control/GOP/B-frames, synchronous ProcessInput/ProcessOutput or the asynchronous event loop of +/// hardware MFTs, and Annex-B/OBU output muxed by into a temporary file that +/// commits. Disposing without completing deletes the partial file. +/// +public sealed class MediaFoundationEncoderSession : IVideoEncoderSession +{ + private const string LogCategory = MediaFoundationEncoders.LogCategory; + + private readonly EncodeSettings _settings; + private readonly IDisposable _runtime; + private readonly IMFActivate _activate; + private readonly IMFTransform _transform; + private readonly IMFMediaEventGenerator? _events; + private readonly bool _tenBit; + private readonly string _tempPath; + private readonly FileStream _file; + private readonly Mp4Muxer _muxer; + private readonly Dictionary _ticksByHns = []; + private readonly Dictionary _durationByTicks = []; + private readonly Queue _inputStarts = new(); + private bool _providesSamples; + private uint _outputBufferSize; + private int _needInput; + private bool _drained; + private long _time; + private Encoded? _pending; + private int _framesIn; + private int _framesOut; + private bool _completed; + private bool _released; + private bool _disposed; + + private MediaFoundationEncoderSession(EncodeSettings settings, MediaFoundationEncoderInfo info, IMFActivate activate, IMFTransform transform, IDisposable runtime) + { + _settings = settings; + _activate = activate; + _transform = transform; + _runtime = runtime; + _tenBit = settings.BitDepth == 10; + EncoderName = info.Name; + IsHardware = info.IsHardware; + + if (UnlockAsync(transform)) + _events = transform as IMFMediaEventGenerator ?? throw new NotSupportedException("Asynchronous MFT without an event generator"); + if (transform as ICodecAPI is { } codecApi) ApplyCodecSettings(codecApi); + SetOutputType(); + SetInputType(); + ReadOutputStreamInfo(); + Message(MfNative.MessageNotifyBeginStreaming); + Message(MfNative.MessageNotifyStartOfStream); + + _tempPath = AtomicFile.TempPathFor(settings.OutputPath); + _file = new FileStream(_tempPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 1 << 20); + try + { + _muxer = new Mp4Muxer(_file, new VideoTrackConfig { Codec = settings.Codec, Width = settings.Width, Height = settings.Height, FastStart = true }); + ReadSequenceHeader(); + } + catch + { + _file.Dispose(); + File.Delete(_tempPath); + throw; + } + Log.Info(LogCategory, $"Encoding {settings.Codec} {settings.Width}×{settings.Height} {settings.BitDepth}-bit with \"{info.Name}\" ({(info.IsHardware ? "hardware" : "software")}, {(_events is null ? "sync" : "async")})"); + } + + public string EncoderName { get; } + + public bool IsHardware { get; } + + /// Activates the MFT behind and configures it; the session then owns the activate and the runtime lease. + internal static MediaFoundationEncoderSession Open(EncodeSettings settings, MediaFoundationEncoderInfo info, IMFActivate activate, IDisposable runtime) + { + ComObjects.Check(activate.ActivateObject(MfGuids.IidTransform, out var pointer), "IMFActivate.ActivateObject"); + var transform = ComObjects.Attach(pointer); + try + { + return new MediaFoundationEncoderSession(settings, info, activate, transform, runtime); + } + catch + { + ComObjects.Release(transform); + throw; + } + } + + public void WriteFrame(ImageBuffer frame, long duration90k) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_completed) throw new InvalidOperationException("The session is complete"); + if (frame.Width != _settings.Width || frame.Height != _settings.Height) throw new ArgumentException("Frame size differs from the encode size", nameof(frame)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration90k); + + var start = _time; + _time += duration90k; + var hns = ToHns(start); + _ticksByHns[hns] = start; + _durationByTicks[start] = duration90k; + _inputStarts.Enqueue(start); + var sample = CreateInputSample(frame, hns, ToHns(_time) - hns); + try + { + if (_events is not null) + { + Pump(() => _needInput > 0); + _needInput--; + ComObjects.Check(_transform.ProcessInput(0, sample, 0), "ProcessInput"); + } + else + { + SubmitSync(sample); + } + } + finally + { + ComObjects.Release(sample); + } + _framesIn++; + } + + public void Complete() + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_completed) throw new InvalidOperationException("The session is already complete"); + if (_framesIn == 0) throw new InvalidOperationException("No frames were written"); + Message(MfNative.MessageNotifyEndOfStream); + Message(MfNative.MessageCommandDrain); + if (_events is not null) Pump(() => _drained); + else while (ProcessOutput()) { } + if (_pending is { } last) + { + // The last decoded picture keeps the duration of its own presentation slot. + WritePending(last, _durationByTicks.GetValueOrDefault(last.Pts, 1)); + _pending = null; + } + Message(MfNative.MessageNotifyEndStreaming); + ReleaseEncoder(); + + _muxer.Complete(); + _file.Flush(flushToDisk: true); + _file.Dispose(); + AtomicFile.Commit(_tempPath, _settings.OutputPath); + _completed = true; + Log.Info(LogCategory, $"\"{EncoderName}\" encoded {_framesIn} frames into {_framesOut} samples: {_settings.OutputPath}"); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + if (!_completed) + { + _file.Dispose(); + try + { + File.Delete(_tempPath); + } + catch (IOException ex) + { + Log.Warning(LogCategory, "Could not delete the partial output " + _tempPath, ex); + } + } + ReleaseEncoder(); + _runtime.Dispose(); + } + + private sealed record Encoded(byte[] Data, long Pts, long Dts, bool Key); + + private static bool UnlockAsync(IMFTransform transform) + { + if (transform.GetAttributes(out var pointer) < 0 || pointer == 0) return false; + var attributes = ComObjects.Attach(pointer); + try + { + if (attributes.GetUINT32(MfGuids.TransformAsync, out var isAsync) < 0 || isAsync == 0) return false; + ComObjects.Check(attributes.SetUINT32(MfGuids.TransformAsyncUnlock, 1), "MF_TRANSFORM_ASYNC_UNLOCK"); + return true; + } + finally + { + ComObjects.Release(attributes); + } + } + + private void ApplyCodecSettings(ICodecAPI api) + { + var mode = _settings.RateControl switch + { + RateControl.Cbr => MfNative.RateControlCbr, + RateControl.Quality => MfNative.RateControlQuality, + _ => MfNative.RateControlUnconstrainedVbr, + }; + SetCodecValue(api, MfGuids.CodecRateControlMode, ComVariant.Create(mode), "RateControlMode"); + if (_settings.RateControl == RateControl.Quality) + SetCodecValue(api, MfGuids.CodecQuality, ComVariant.Create((uint)Math.Clamp(_settings.Quality, 1, 100)), "Quality"); + else + SetCodecValue(api, MfGuids.CodecMeanBitRate, ComVariant.Create(BitRate), "MeanBitRate"); + var gop = _settings.GopLength > 0 ? _settings.GopLength : (int)Math.Max(1, Math.Round(_settings.FrameRate.Value)); + SetCodecValue(api, MfGuids.CodecGopSize, ComVariant.Create((uint)gop), "GOPSize"); + var bFrames = _settings.Profile == CodecProfile.H264Baseline ? 0 : Math.Max(0, _settings.BFrames); + SetCodecValue(api, MfGuids.CodecBPictureCount, ComVariant.Create((uint)bFrames), "BPictureCount"); + SetCodecValue(api, MfGuids.CodecLowLatencyMode, ComVariant.Create(false), "LowLatencyMode"); + } + + private static unsafe void SetCodecValue(ICodecAPI api, in Guid property, ComVariant value, string name) + { + if (api.IsSupported(property) != 0) + { + Log.Debug(LogCategory, $"ICodecAPI {name} not supported by the encoder"); + return; + } + var hr = api.SetValue(property, (nint)(&value)); + if (hr < 0) Log.Debug(LogCategory, $"ICodecAPI {name} rejected (0x{hr:X8})"); + } + + /// Requested bit rate, or the preset density (§11.4: 0.10/0.07/0.05 bits per pixel per frame) when unset. + private uint BitRate + { + get + { + if (_settings.BitRate > 0) return (uint)Math.Min(uint.MaxValue, _settings.BitRate); + var bpp = _settings.Codec switch { VideoCodec.H264 => 0.10, VideoCodec.Hevc => 0.07, _ => 0.05 }; + return (uint)Math.Min(uint.MaxValue, _settings.Width * (double)_settings.Height * _settings.FrameRate.Value * bpp); + } + } + + private void SetOutputType() + { + var level = CodecLimits.Check(_settings.Codec, _settings.Width, _settings.Height, _settings.FrameRate.Value, BitRate, _settings.Profile).Level; + var hr = TrySetOutputType(level); + if (hr < 0 && level is not null) + { + Log.Debug(LogCategory, $"Output type with level {level} rejected (0x{hr:X8}); letting the encoder choose"); + hr = TrySetOutputType(null); + } + ComObjects.Check(hr, "SetOutputType"); + } + + private int TrySetOutputType(CodecLevel? level) + { + var type = CreateMediaType(); + try + { + ComObjects.Check(type.SetGUID(MfGuids.Subtype, MediaFoundationEncoders.Subtype(_settings.Codec)), "MF_MT_SUBTYPE"); + ComObjects.Check(type.SetUINT32(MfGuids.AverageBitrate, BitRate), "MF_MT_AVG_BITRATE"); + SetVideoFormat(type); + var profile = Profile(); + if (profile > 0) ComObjects.Check(type.SetUINT32(MfGuids.Mpeg2Profile, profile), "MF_MT_MPEG2_PROFILE"); + if (level is { } l && _settings.Codec != VideoCodec.Av1) + { + var idc = _settings.Codec == VideoCodec.H264 ? l.H264LevelIdc : l.HevcLevelIdc; + ComObjects.Check(type.SetUINT32(MfGuids.Mpeg2Level, (uint)idc), "MF_MT_MPEG2_LEVEL"); + } + return _transform.SetOutputType(0, type, 0); + } + finally + { + ComObjects.Release(type); + } + } + + /// eAVEncH264VProfile / eAVEncH265VProfile value; AV1 encoders derive the profile from the input format. + private uint Profile() => _settings.Codec switch + { + VideoCodec.H264 => _settings.Profile switch + { + CodecProfile.H264Baseline => 66u, + CodecProfile.H264Main => 77u, + _ => 100u, + }, + VideoCodec.Hevc => _tenBit ? 2u : 1u, + _ => 0u, + }; + + private void SetInputType() + { + var subtype = _tenBit ? MfGuids.FormatP010 : MfGuids.FormatNv12; + var type = CreateMediaType(); + int hr; + try + { + ComObjects.Check(type.SetGUID(MfGuids.Subtype, subtype), "MF_MT_SUBTYPE"); + ComObjects.Check(type.SetUINT32(MfGuids.DefaultStride, (uint)(_settings.Width * (_tenBit ? 2 : 1))), "MF_MT_DEFAULT_STRIDE"); + SetVideoFormat(type); + hr = _transform.SetInputType(0, type, 0); + } + finally + { + ComObjects.Release(type); + } + + // Some encoders only accept their own enumerated input types: complete one with our format. + for (uint index = 0; hr < 0; index++) + { + var available = _transform.GetInputAvailableType(0, index, out var pointer); + if (available < 0) break; + var candidate = ComObjects.Attach(pointer); + try + { + if (candidate.GetGUID(MfGuids.Subtype, out var s) < 0 || s != subtype) continue; + SetVideoFormat(candidate); + hr = _transform.SetInputType(0, candidate, 0); + } + finally + { + ComObjects.Release(candidate); + } + } + ComObjects.Check(hr, $"SetInputType ({(_tenBit ? "P010" : "NV12")})"); + } + + private static IMFMediaType CreateMediaType() + { + ComObjects.Check(MfNative.MFCreateMediaType(out var pointer), "MFCreateMediaType"); + var type = ComObjects.Attach(pointer); + ComObjects.Check(type.SetGUID(MfGuids.MajorType, MfGuids.MediaTypeVideo), "MF_MT_MAJOR_TYPE"); + return type; + } + + /// Frame size and rate, square pixels, progressive, BT.709 limited range. + private void SetVideoFormat(IMFMediaType type) + { + ComObjects.Check(type.SetUINT64(MfGuids.FrameSize, Pack(_settings.Width, _settings.Height)), "MF_MT_FRAME_SIZE"); + ComObjects.Check(type.SetUINT64(MfGuids.FrameRate, Pack(_settings.FrameRate.Numerator, _settings.FrameRate.Denominator)), "MF_MT_FRAME_RATE"); + ComObjects.Check(type.SetUINT64(MfGuids.PixelAspectRatio, Pack(1, 1)), "MF_MT_PIXEL_ASPECT_RATIO"); + ComObjects.Check(type.SetUINT32(MfGuids.InterlaceMode, MfNative.InterlaceProgressive), "MF_MT_INTERLACE_MODE"); + type.SetUINT32(MfGuids.NominalRange, MfNative.NominalRange16To235); + type.SetUINT32(MfGuids.VideoPrimaries, MfNative.PrimariesBt709); + type.SetUINT32(MfGuids.TransferFunction, MfNative.TransferBt709); + type.SetUINT32(MfGuids.YuvMatrix, MfNative.MatrixBt709); + } + + private static ulong Pack(int high, int low) => (ulong)(uint)high << 32 | (uint)low; + + private void ReadOutputStreamInfo() + { + ComObjects.Check(_transform.GetOutputStreamInfo(0, out var info), "GetOutputStreamInfo"); + _providesSamples = (info.Flags & (MfNative.OutputStreamProvidesSamples | MfNative.OutputStreamCanProvideSamples)) != 0; + _outputBufferSize = Math.Max(info.Size, (uint)(_settings.Width * _settings.Height * 3 / 2)); + } + + /// Hands MF_MT_MPEG_SEQUENCE_HEADER (parameter sets / sequence header OBU) of the current output type to the muxer. + private void ReadSequenceHeader() + { + if (_transform.GetOutputCurrentType(0, out var pointer) < 0) return; + var type = ComObjects.Attach(pointer); + try + { + if (type.GetAllocatedBlob(MfGuids.MpegSequenceHeader, out var blob, out var size) < 0) return; + try + { + var bytes = new byte[size]; + Marshal.Copy(blob, bytes, 0, (int)size); + _muxer.AddParameterSets(bytes); + } + finally + { + Marshal.FreeCoTaskMem(blob); + } + } + finally + { + ComObjects.Release(type); + } + } + + private unsafe IMFSample CreateInputSample(ImageBuffer frame, long time, long duration) + { + var fourCc = _tenBit ? 0x30313050u : 0x3231564Eu; // 'P010' / 'NV12' + ComObjects.Check(MfNative.MFCreate2DMediaBuffer((uint)_settings.Width, (uint)_settings.Height, fourCc, false, out var bufferPointer), "MFCreate2DMediaBuffer"); + var buffer = ComObjects.Attach(bufferPointer); + try + { + var buffer2D = buffer as IMF2DBuffer ?? throw new NotSupportedException("Media buffer without IMF2DBuffer"); + ComObjects.Check(buffer2D.Lock2D(out var scanline0, out var pitch), "IMF2DBuffer.Lock2D"); + try + { + if (pitch <= 0) throw new NotSupportedException("Bottom-up input buffers are not supported"); + var rows = _settings.Height * 3 / 2; + if (_tenBit) Nv12Converter.ToP010(frame, new Span((void*)scanline0, pitch / 2 * rows), ChromaSiting.Left, pitch / 2); + else Nv12Converter.ToNv12(frame, new Span((void*)scanline0, pitch * rows), ChromaSiting.Left, pitch); + } + finally + { + buffer2D.Unlock2D(); + } + // 2D buffers report their contiguous size; setting it explicitly helps encoders that read the plain length. + if (buffer2D.GetContiguousLength(out var length) >= 0 && buffer.SetCurrentLength(length) < 0) + Log.Debug(LogCategory, "SetCurrentLength on the 2D input buffer was rejected"); + + ComObjects.Check(MfNative.MFCreateSample(out var samplePointer), "MFCreateSample"); + var sample = ComObjects.Attach(samplePointer); + try + { + ComObjects.Check(sample.AddBuffer(buffer), "AddBuffer"); + ComObjects.Check(sample.SetSampleTime(time), "SetSampleTime"); + ComObjects.Check(sample.SetSampleDuration(duration), "SetSampleDuration"); + return sample; + } + catch + { + ComObjects.Release(sample); + throw; + } + } + finally + { + ComObjects.Release(buffer); + } + } + + private void SubmitSync(IMFSample sample) + { + while (true) + { + var hr = _transform.ProcessInput(0, sample, 0); + if (hr != MfNative.NotAccepting) + { + ComObjects.Check(hr, "ProcessInput"); + break; + } + // Full: collect output first; an encoder that neither accepts input nor yields output is stuck. + if (!ProcessOutput()) throw new COMException("Encoder refuses input without producing output", hr); + while (ProcessOutput()) { } + } + while (ProcessOutput()) { } + } + + /// Runs the asynchronous MFT event loop until holds. + private void Pump(Func done) + { + while (!done()) + { + ComObjects.Check(_events!.GetEvent(0, out var pointer), "IMFMediaEventGenerator.GetEvent"); + var mediaEvent = ComObjects.Attach(pointer); + uint type; + int status; + try + { + ComObjects.Check(mediaEvent.GetEventType(out type), "IMFMediaEvent.GetType"); + ComObjects.Check(mediaEvent.GetStatus(out status), "IMFMediaEvent.GetStatus"); + } + finally + { + ComObjects.Release(mediaEvent); + } + if (status < 0 || type == MfNative.EventError) throw new COMException($"Encoder reported event {type} with failure", status); + switch (type) + { + case MfNative.EventNeedInput: + _needInput++; + break; + case MfNative.EventHaveOutput: + ProcessOutput(); + break; + case MfNative.EventDrainComplete: + _drained = true; + break; + } + } + } + + /// Pulls one output sample; false when the encoder needs more input. + private bool ProcessOutput() + { + IMFSample? own = null; + nint ownPointer = 0; + var data = new MftOutputDataBuffer(); + if (!_providesSamples) + { + own = CreateOutputSample(); + data.Sample = ownPointer = ComObjects.GetPointer(own); + } + int hr; + try + { + hr = _transform.ProcessOutput(0, 1, ref data, out _); + } + finally + { + if (data.Events != 0) Marshal.Release(data.Events); + if (ownPointer != 0) Marshal.Release(ownPointer); + } + + if (hr < 0) + { + ComObjects.Release(own); + if (hr == MfNative.TransformNeedMoreInput) return false; + if (hr == MfNative.TransformStreamChange) + { + Renegotiate(); + return true; + } + ComObjects.Check(hr, "ProcessOutput"); + } + + var output = own ?? ComObjects.AttachOrNull(data.Sample); + if (output is null) return true; + try + { + Deliver(output); + } + finally + { + ComObjects.Release(output); + } + return true; + } + + private IMFSample CreateOutputSample() + { + ComObjects.Check(MfNative.MFCreateMemoryBuffer(_outputBufferSize, out var bufferPointer), "MFCreateMemoryBuffer"); + var buffer = ComObjects.Attach(bufferPointer); + try + { + ComObjects.Check(MfNative.MFCreateSample(out var samplePointer), "MFCreateSample"); + var sample = ComObjects.Attach(samplePointer); + ComObjects.Check(sample.AddBuffer(buffer), "AddBuffer"); + return sample; + } + finally + { + ComObjects.Release(buffer); + } + } + + /// MF_E_TRANSFORM_STREAM_CHANGE: adopt the encoder's new output type and its sequence header. + private void Renegotiate() + { + ComObjects.Check(_transform.GetOutputAvailableType(0, 0, out var pointer), "GetOutputAvailableType"); + var type = ComObjects.Attach(pointer); + try + { + ComObjects.Check(_transform.SetOutputType(0, type, 0), "SetOutputType (stream change)"); + } + finally + { + ComObjects.Release(type); + } + ReadOutputStreamInfo(); + ReadSequenceHeader(); + Log.Debug(LogCategory, $"\"{EncoderName}\" renegotiated its output type"); + } + + private void Deliver(IMFSample sample) + { + ComObjects.Check(sample.GetSampleTime(out var pts), "GetSampleTime"); + bool? cleanPoint = sample.GetUINT32(MfGuids.SampleCleanPoint, out var clean) >= 0 ? clean != 0 : null; + long? dts = sample.GetUINT64(MfGuids.SampleDecodeTimestamp, out var decode) >= 0 ? (long)decode : null; + ComObjects.Check(sample.ConvertToContiguousBuffer(out var bufferPointer), "ConvertToContiguousBuffer"); + var buffer = ComObjects.Attach(bufferPointer); + byte[] bytes; + try + { + ComObjects.Check(buffer.Lock(out var data, out _, out var length), "IMFMediaBuffer.Lock"); + try + { + bytes = new byte[length]; + Marshal.Copy(data, bytes, 0, (int)length); + } + finally + { + buffer.Unlock(); + } + } + finally + { + ComObjects.Release(buffer); + } + if (bytes.Length == 0) return; + var key = cleanPoint ?? IsRandomAccess(bytes); + + var ptsTicks = _ticksByHns.Remove(pts, out var exact) ? exact : To90k(pts); + // Without MFSampleExtension_DecodeTimestamp the n-th output decodes at the n-th input's time. + _inputStarts.TryDequeue(out var inputStart); + var dtsTicks = dts is { } d ? To90k(d) : inputStart; + var encoded = new Encoded(bytes, ptsTicks, dtsTicks, key); + if (_pending is { } previous) WritePending(previous, Math.Max(1, encoded.Dts - previous.Dts)); + _pending = encoded; + _framesOut++; + } + + /// Sync detection for encoders that do not set MFSampleExtension_CleanPoint: IDR/IRAP NAL units or an AV1 sequence header. + private bool IsRandomAccess(byte[] data) + { + if (_settings.Codec == VideoCodec.Av1) + { + foreach (var obu in Av1ObuParser.Split(data)) + { + if (obu.Type == Av1ObuType.SequenceHeader) return true; + } + return false; + } + foreach (var unit in AnnexBParser.SplitAccessUnit(data, out _)) + { + var header = data[unit.Offset]; + if (_settings.Codec == VideoCodec.H264 ? AnnexBParser.H264Type(header) == H264NalUnitType.IdrSlice + : AnnexBParser.HevcType(header) is >= HevcNalUnitType.BlaWLp and <= HevcNalUnitType.Cra) + return true; + } + return false; + } + + private void WritePending(Encoded sample, long duration) + { + _muxer.WriteSample(sample.Data, duration, sample.Key, sample.Pts - sample.Dts); + _durationByTicks.Remove(sample.Pts); + } + + private void Message(uint message) => ComObjects.Check(_transform.ProcessMessage(message, 0), $"ProcessMessage(0x{message:X})"); + + private void ReleaseEncoder() + { + if (_released) return; + _released = true; + ComObjects.Release(_transform); + _activate.ShutdownObject(); + ComObjects.Release(_activate); + } + + private static long ToHns(long ticks90k) => (ticks90k * 1000 + 4) / 9; + + private static long To90k(long hns) => (long)Math.Round(hns * 9 / 1000.0); +} diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoders.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoders.cs new file mode 100644 index 00000000..b8a05dc8 --- /dev/null +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoders.cs @@ -0,0 +1,95 @@ +using System.Runtime.InteropServices; +using Titano.Core.Diagnostics; +using Titano.Core.Video; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.MediaFoundation; + +/// A Media Foundation video encoder MFT available on this machine. +/// MFT_FRIENDLY_NAME_Attribute, e.g. "NVIDIA HEVC Encoder MFT". +/// MFT_ENUM_HARDWARE_VENDOR_ID_Attribute of hardware MFTs, e.g. "VEN_10DE". +/// The MFT accepts P010 input (HEVC Main10 / AV1 10-bit). +public sealed record MediaFoundationEncoderInfo(VideoCodec Codec, string Name, bool IsHardware, bool IsAsync, string? VendorId, bool SupportsTenBit); + +/// Discovers H.264, HEVC and AV1 encoder MFTs with MFTEnumEx in the system's merit order (hardware first). +public static class MediaFoundationEncoders +{ + internal const string LogCategory = "MediaFoundation"; + private static readonly VideoCodec[] Codecs = [VideoCodec.H264, VideoCodec.Hevc, VideoCodec.Av1]; + + /// Every encoder MFT for H.264, HEVC and AV1; empty when Media Foundation is unavailable. + public static IReadOnlyList Enumerate() + { + if (!MediaFoundationRuntime.IsAvailable) return []; + using var lease = MediaFoundationRuntime.Acquire(); + var result = new List(); + foreach (var codec in Codecs) + { + foreach (var (info, activate) in Find(codec)) + { + result.Add(info); + ComObjects.Release(activate); + } + } + return result; + } + + /// Encoder activation objects for ; Media Foundation must be started and the caller releases them. + internal static List<(MediaFoundationEncoderInfo Info, IMFActivate Activate)> Find(VideoCodec codec) + { + var tenBit = new HashSet(StringComparer.Ordinal); + if (codec != VideoCodec.H264) + { + foreach (var activate in Activates(codec, MfGuids.FormatP010)) + { + if (FriendlyName(activate) is { } name) tenBit.Add(name); + ComObjects.Release(activate); + } + } + var found = new List<(MediaFoundationEncoderInfo, IMFActivate)>(); + foreach (var activate in Activates(codec, null)) + { + var name = FriendlyName(activate) ?? "Unnamed encoder"; + var flags = activate.GetUINT32(MfGuids.TransformFlags, out var f) >= 0 ? f : 0; + string? vendor = null; + if (activate.GetAllocatedString(MfGuids.HardwareVendorId, out var vendorPointer, out _) >= 0) vendor = ComObjects.TakeString(vendorPointer); + var info = new MediaFoundationEncoderInfo(codec, name, (flags & MfNative.EnumHardware) != 0, (flags & MfNative.EnumAsync) != 0, vendor, tenBit.Contains(name)); + found.Add((info, activate)); + } + return found; + } + + internal static Guid Subtype(VideoCodec codec) => codec switch + { + VideoCodec.H264 => MfGuids.FormatH264, + VideoCodec.Hevc => MfGuids.FormatHevc, + VideoCodec.Av1 => MfGuids.FormatAv1, + _ => throw new ArgumentException($"{codec} has no Media Foundation encoder", nameof(codec)), + }; + + private static string? FriendlyName(IMFActivate activate) => + activate.GetAllocatedString(MfGuids.FriendlyName, out var pointer, out _) >= 0 ? ComObjects.TakeString(pointer) : null; + + private static unsafe List Activates(VideoCodec codec, Guid? inputSubtype) + { + var output = new MftRegisterTypeInfo { MajorType = MfGuids.MediaTypeVideo, Subtype = Subtype(codec) }; + var input = new MftRegisterTypeInfo { MajorType = MfGuids.MediaTypeVideo, Subtype = inputSubtype ?? Guid.Empty }; + const uint flags = MfNative.EnumHardware | MfNative.EnumAsync | MfNative.EnumSync | MfNative.EnumSortAndFilter; + var hr = MfNative.MFTEnumEx(MfGuids.VideoEncoderCategory, flags, inputSubtype.HasValue ? &input : null, &output, out var array, out var count); + var list = new List((int)count); + if (hr < 0) + { + Log.Warning(LogCategory, $"MFTEnumEx for {codec} failed with HRESULT 0x{hr:X8}"); + return list; + } + try + { + for (var i = 0; i < count; i++) list.Add(ComObjects.Attach(Marshal.ReadIntPtr(array, i * IntPtr.Size))); + } + finally + { + Marshal.FreeCoTaskMem(array); + } + return list; + } +} diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs new file mode 100644 index 00000000..a8cfb3a1 --- /dev/null +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs @@ -0,0 +1,44 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.MediaFoundation; + +/// Reference-counted MFStartup/MFShutdown shared by every Media Foundation user in the process. +internal static class MediaFoundationRuntime +{ + private static readonly Lock Gate = new(); + private static int _references; + + /// True when mfplat.dll can be loaded (absent on Windows "N" editions without the Media Feature Pack). + public static bool IsAvailable { get; } = OperatingSystem.IsWindows() && NativeLibrary.TryLoad("mfplat.dll", out _); + + /// Starts Media Foundation for the lifetime of the returned lease. + public static IDisposable Acquire() + { + if (!IsAvailable) throw new PlatformNotSupportedException("Media Foundation is not available on this system"); + lock (Gate) + { + if (_references == 0) ComObjects.Check(MfNative.MFStartup(MfNative.Version, MfNative.StartupLite), "MFStartup"); + _references++; + } + return new Lease(); + } + + private static void Release() + { + lock (Gate) + { + if (--_references == 0) MfNative.MFShutdown(); + } + } + + private sealed class Lease : IDisposable + { + private int _released; + + public void Dispose() + { + if (Interlocked.Exchange(ref _released, 1) == 0) Release(); + } + } +} diff --git a/src/Titano.Core.Windows/MediaFoundation/MfInterop.cs b/src/Titano.Core.Windows/MediaFoundation/MfInterop.cs new file mode 100644 index 00000000..a6ff08f1 --- /dev/null +++ b/src/Titano.Core.Windows/MediaFoundation/MfInterop.cs @@ -0,0 +1,314 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; + +namespace Titano.Core.Windows.MediaFoundation; + +// Media Foundation COM interfaces in vtable order (mfobjects.h, mftransform.h, strmif.h). Every method returns the raw +// HRESULT because MF uses failure codes for flow control (MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_NOTACCEPTING…). +// Interface pointers come back as nint and are wrapped with ComObjects.Attach for deterministic release; VARIANT and +// PROPVARIANT arguments are raw pointers so the assembly keeps runtime marshalling enabled. + +[GeneratedComInterface] +[Guid("2cd2d921-c447-44a7-a13c-4adabfc247e3")] +internal partial interface IMFAttributes +{ + [PreserveSig] int GetItem(in Guid key, nint value); + [PreserveSig] int GetItemType(in Guid key, out int type); + [PreserveSig] int CompareItem(in Guid key, nint value, out int result); + [PreserveSig] int Compare(nint theirs, int matchType, out int result); + [PreserveSig] int GetUINT32(in Guid key, out uint value); + [PreserveSig] int GetUINT64(in Guid key, out ulong value); + [PreserveSig] int GetDouble(in Guid key, out double value); + [PreserveSig] int GetGUID(in Guid key, out Guid value); + [PreserveSig] int GetStringLength(in Guid key, out uint length); + [PreserveSig] int GetString(in Guid key, nint buffer, uint bufferSize, out uint length); + [PreserveSig] int GetAllocatedString(in Guid key, out nint value, out uint length); + [PreserveSig] int GetBlobSize(in Guid key, out uint size); + [PreserveSig] int GetBlob(in Guid key, nint buffer, uint bufferSize, out uint size); + [PreserveSig] int GetAllocatedBlob(in Guid key, out nint buffer, out uint size); + [PreserveSig] int GetUnknown(in Guid key, in Guid iid, out nint value); + [PreserveSig] int SetItem(in Guid key, nint value); + [PreserveSig] int DeleteItem(in Guid key); + [PreserveSig] int DeleteAllItems(); + [PreserveSig] int SetUINT32(in Guid key, uint value); + [PreserveSig] int SetUINT64(in Guid key, ulong value); + [PreserveSig] int SetDouble(in Guid key, double value); + [PreserveSig] int SetGUID(in Guid key, in Guid value); + [PreserveSig] int SetString(in Guid key, nint value); + [PreserveSig] int SetBlob(in Guid key, nint buffer, uint size); + [PreserveSig] int SetUnknown(in Guid key, nint unknown); + [PreserveSig] int LockStore(); + [PreserveSig] int UnlockStore(); + [PreserveSig] int GetCount(out uint count); + [PreserveSig] int GetItemByIndex(uint index, out Guid key, nint value); + [PreserveSig] int CopyAllItems(nint destination); +} + +[GeneratedComInterface] +[Guid("44ae0fa8-ea31-4109-8d2e-4cae4997c555")] +internal partial interface IMFMediaType : IMFAttributes +{ + [PreserveSig] int GetMajorType(out Guid type); + [PreserveSig] int IsCompressedFormat(out int compressed); + [PreserveSig] int IsEqual(nint other, out uint flags); + [PreserveSig] int GetRepresentation(Guid representation, out nint value); + [PreserveSig] int FreeRepresentation(Guid representation, nint value); +} + +[GeneratedComInterface] +[Guid("045fa593-8799-42b8-bc8d-8968c6453507")] +internal partial interface IMFMediaBuffer +{ + [PreserveSig] int Lock(out nint buffer, out uint maxLength, out uint currentLength); + [PreserveSig] int Unlock(); + [PreserveSig] int GetCurrentLength(out uint length); + [PreserveSig] int SetCurrentLength(uint length); + [PreserveSig] int GetMaxLength(out uint length); +} + +[GeneratedComInterface] +[Guid("7dc9d5f9-9ed9-44ec-9bbf-0600bb589fbb")] +internal partial interface IMF2DBuffer +{ + [PreserveSig] int Lock2D(out nint scanline0, out int pitch); + [PreserveSig] int Unlock2D(); + [PreserveSig] int GetScanline0AndPitch(out nint scanline0, out int pitch); + [PreserveSig] int IsContiguousFormat(out int contiguous); + [PreserveSig] int GetContiguousLength(out uint length); + [PreserveSig] int ContiguousCopyTo(nint destination, uint size); + [PreserveSig] int ContiguousCopyFrom(nint source, uint size); +} + +[GeneratedComInterface] +[Guid("c40a00f2-b93a-4d80-ae8c-5a1c634f58e4")] +internal partial interface IMFSample : IMFAttributes +{ + [PreserveSig] int GetSampleFlags(out uint flags); + [PreserveSig] int SetSampleFlags(uint flags); + [PreserveSig] int GetSampleTime(out long time); + [PreserveSig] int SetSampleTime(long time); + [PreserveSig] int GetSampleDuration(out long duration); + [PreserveSig] int SetSampleDuration(long duration); + [PreserveSig] int GetBufferCount(out uint count); + [PreserveSig] int GetBufferByIndex(uint index, out nint buffer); + [PreserveSig] int ConvertToContiguousBuffer(out nint buffer); + [PreserveSig] int AddBuffer(IMFMediaBuffer buffer); + [PreserveSig] int RemoveBufferByIndex(uint index); + [PreserveSig] int RemoveAllBuffers(); + [PreserveSig] int GetTotalLength(out uint length); + [PreserveSig] int CopyToBuffer(IMFMediaBuffer buffer); +} + +[GeneratedComInterface] +[Guid("7fee9e9a-4a89-47a6-899c-b6a53a70fb67")] +internal partial interface IMFActivate : IMFAttributes +{ + [PreserveSig] int ActivateObject(in Guid iid, out nint instance); + [PreserveSig] int ShutdownObject(); + [PreserveSig] int DetachObject(); +} + +[GeneratedComInterface] +[Guid("df598932-f10c-4e39-bba2-c308f101daa3")] +internal partial interface IMFMediaEvent : IMFAttributes +{ + [PreserveSig] int GetEventType(out uint type); + [PreserveSig] int GetExtendedType(out Guid type); + [PreserveSig] int GetStatus(out int status); + [PreserveSig] int GetValue(nint propVariant); +} + +[GeneratedComInterface] +[Guid("2cd0bd52-bcd5-4b89-b62c-eadc0c031e7d")] +internal partial interface IMFMediaEventGenerator +{ + [PreserveSig] int GetEvent(uint flags, out nint mediaEvent); + [PreserveSig] int BeginGetEvent(nint callback, nint state); + [PreserveSig] int EndGetEvent(nint result, out nint mediaEvent); + [PreserveSig] int QueueEvent(uint type, in Guid extendedType, int status, nint value); +} + +[GeneratedComInterface] +[Guid("bf94c121-5b05-4e6f-8000-ba598961414d")] +internal partial interface IMFTransform +{ + [PreserveSig] int GetStreamLimits(out uint inputMinimum, out uint inputMaximum, out uint outputMinimum, out uint outputMaximum); + [PreserveSig] int GetStreamCount(out uint inputStreams, out uint outputStreams); + [PreserveSig] int GetStreamIDs(uint inputSize, nint inputIds, uint outputSize, nint outputIds); + [PreserveSig] int GetInputStreamInfo(uint stream, out MftInputStreamInfo info); + [PreserveSig] int GetOutputStreamInfo(uint stream, out MftOutputStreamInfo info); + [PreserveSig] int GetAttributes(out nint attributes); + [PreserveSig] int GetInputStreamAttributes(uint stream, out nint attributes); + [PreserveSig] int GetOutputStreamAttributes(uint stream, out nint attributes); + [PreserveSig] int DeleteInputStream(uint stream); + [PreserveSig] int AddInputStreams(uint count, nint ids); + [PreserveSig] int GetInputAvailableType(uint stream, uint index, out nint type); + [PreserveSig] int GetOutputAvailableType(uint stream, uint index, out nint type); + [PreserveSig] int SetInputType(uint stream, IMFMediaType? type, uint flags); + [PreserveSig] int SetOutputType(uint stream, IMFMediaType? type, uint flags); + [PreserveSig] int GetInputCurrentType(uint stream, out nint type); + [PreserveSig] int GetOutputCurrentType(uint stream, out nint type); + [PreserveSig] int GetInputStatus(uint stream, out uint flags); + [PreserveSig] int GetOutputStatus(out uint flags); + [PreserveSig] int SetOutputBounds(long lower, long upper); + [PreserveSig] int ProcessEvent(uint stream, nint mediaEvent); + [PreserveSig] int ProcessMessage(uint message, nint parameter); + [PreserveSig] int ProcessInput(uint stream, IMFSample sample, uint flags); + [PreserveSig] int ProcessOutput(uint flags, uint count, ref MftOutputDataBuffer buffers, out uint status); +} + +[GeneratedComInterface] +[Guid("901db4c7-31ce-41a2-85dc-8fa0bf41b8da")] +internal partial interface ICodecAPI +{ + [PreserveSig] int IsSupported(in Guid api); + [PreserveSig] int IsModifiable(in Guid api); + [PreserveSig] int GetParameterRange(in Guid api, nint minimum, nint maximum, nint step); + [PreserveSig] int GetParameterValues(in Guid api, out nint values, out uint count); + [PreserveSig] int GetDefaultValue(in Guid api, nint value); + [PreserveSig] int GetValue(in Guid api, nint value); + + /// Sets a property; points to a VARIANT (a ComVariant). + [PreserveSig] int SetValue(in Guid api, nint value); + [PreserveSig] int RegisterForEvent(in Guid api, nint userData); + [PreserveSig] int UnregisterForEvent(in Guid api); + [PreserveSig] int SetAllDefaults(); + [PreserveSig] int SetValueWithNotify(in Guid api, nint value, out nint changed, out uint count); + [PreserveSig] int SetAllDefaultsWithNotify(out nint changed, out uint count); + [PreserveSig] int GetAllSettings(nint stream); + [PreserveSig] int SetAllSettings(nint stream); + [PreserveSig] int SetAllSettingsWithNotify(nint stream, out nint changed, out uint count); +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MftInputStreamInfo +{ + public long MaxLatency; + public uint Flags; + public uint Size; + public uint MaxLookahead; + public uint Alignment; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MftOutputStreamInfo +{ + public uint Flags; + public uint Size; + public uint Alignment; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MftOutputDataBuffer +{ + public uint StreamId; + public nint Sample; + public uint Status; + public nint Events; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MftRegisterTypeInfo +{ + public Guid MajorType; + public Guid Subtype; +} + +/// mfplat.dll entry points and the constants this assembly uses. +internal static unsafe partial class MfNative +{ + public const uint Version = 0x0002_0070; // MF_SDK_VERSION << 16 | MF_API_VERSION + public const uint StartupLite = 1; // MFSTARTUP_NOSOCKET + + public const uint EnumSync = 0x1, EnumAsync = 0x2, EnumHardware = 0x4, EnumSortAndFilter = 0x40; + + public const uint MessageCommandDrain = 0x1; + public const uint MessageNotifyBeginStreaming = 0x1000_0000; + public const uint MessageNotifyEndStreaming = 0x1000_0001; + public const uint MessageNotifyEndOfStream = 0x1000_0002; + public const uint MessageNotifyStartOfStream = 0x1000_0003; + + public const uint OutputStreamProvidesSamples = 0x100, OutputStreamCanProvideSamples = 0x200; + + public const uint EventError = 1, EventNeedInput = 601, EventHaveOutput = 602, EventDrainComplete = 603; + + public const int TransformNeedMoreInput = unchecked((int)0xC00D6D72); + public const int TransformStreamChange = unchecked((int)0xC00D6D61); + public const int NotAccepting = unchecked((int)0xC00D36B5); + public const int NoMoreTypes = unchecked((int)0xC00D36B9); + + public const uint InterlaceProgressive = 2; + public const uint NominalRange16To235 = 2; + public const uint PrimariesBt709 = 2; + public const uint TransferBt709 = 5; + public const uint MatrixBt709 = 1; + + public const uint RateControlCbr = 0, RateControlUnconstrainedVbr = 2, RateControlQuality = 3; + + [LibraryImport("mfplat.dll")] + public static partial int MFStartup(uint version, uint flags); + + [LibraryImport("mfplat.dll")] + public static partial int MFShutdown(); + + [LibraryImport("mfplat.dll")] + public static partial int MFTEnumEx(Guid category, uint flags, MftRegisterTypeInfo* inputType, MftRegisterTypeInfo* outputType, out nint activates, out uint count); + + [LibraryImport("mfplat.dll")] + public static partial int MFCreateMediaType(out nint mediaType); + + [LibraryImport("mfplat.dll")] + public static partial int MFCreateSample(out nint sample); + + [LibraryImport("mfplat.dll")] + public static partial int MFCreateMemoryBuffer(uint maxLength, out nint buffer); + + [LibraryImport("mfplat.dll")] + public static partial int MFCreate2DMediaBuffer(uint width, uint height, uint fourCc, [MarshalAs(UnmanagedType.Bool)] bool bottomUp, out nint buffer); +} + +/// Media Foundation GUIDs (mfapi.h, mftransform.h, codecapi.h). +internal static class MfGuids +{ + public static readonly Guid VideoEncoderCategory = new("f79eac7d-e545-4387-bdee-d647d7bde42a"); + public static readonly Guid MediaTypeVideo = new("73646976-0000-0010-8000-00aa00389b71"); + public static readonly Guid FormatH264 = new("34363248-0000-0010-8000-00aa00389b71"); + public static readonly Guid FormatHevc = new("43564548-0000-0010-8000-00aa00389b71"); + public static readonly Guid FormatAv1 = new("31305641-0000-0010-8000-00aa00389b71"); + public static readonly Guid FormatNv12 = new("3231564e-0000-0010-8000-00aa00389b71"); + public static readonly Guid FormatP010 = new("30313050-0000-0010-8000-00aa00389b71"); + + public static readonly Guid MajorType = new("48eba18e-f8c9-4687-bf11-0a74c9f96a8f"); + public static readonly Guid Subtype = new("f7e34c9a-42e8-4714-b74b-cb29d72c35e5"); + public static readonly Guid FrameSize = new("1652c33d-d6b2-4012-b834-72030849a37d"); + public static readonly Guid FrameRate = new("c459a2e8-3d2c-4e44-b132-fee5156c7bb0"); + public static readonly Guid PixelAspectRatio = new("c6376a1e-8d0a-4027-be45-6d9a0ad39bb6"); + public static readonly Guid InterlaceMode = new("e2724bb8-e676-4806-b4b2-a8d6efb44ccd"); + public static readonly Guid AverageBitrate = new("20332624-fb0d-4d9e-bd0d-cbf6786c102e"); + public static readonly Guid Mpeg2Profile = new("ad76a80b-2d5c-4e0b-b375-64e520137036"); + public static readonly Guid Mpeg2Level = new("96f66574-11c5-4015-8666-bff516436da7"); + public static readonly Guid MpegSequenceHeader = new("3c036de7-3ad0-4c9e-9216-ee6d6ac21cb3"); + public static readonly Guid DefaultStride = new("644b4e48-1e02-4516-b0eb-c01ca9d49ac6"); + public static readonly Guid NominalRange = new("c21b8ee5-b956-4071-8daf-325edf5cab11"); + public static readonly Guid VideoPrimaries = new("dbfbe4d7-0740-4ee0-8192-850ab0e21935"); + public static readonly Guid TransferFunction = new("5fb0fce9-be5c-4935-a811-ec838f8eed93"); + public static readonly Guid YuvMatrix = new("3e23d450-2c75-4d25-a00e-b91670d12327"); + + public static readonly Guid TransformAsync = new("f81a699a-649a-497d-8c73-29f8fed6ad7a"); + public static readonly Guid TransformAsyncUnlock = new("e5666d6b-3422-4eb6-a421-da7db1f8e207"); + public static readonly Guid TransformFlags = new("9359bb7e-6275-46c4-a025-1c01e45f1a86"); + public static readonly Guid FriendlyName = new("314ffbae-5b41-4c95-9c19-4e7d586face3"); + public static readonly Guid HardwareVendorId = new("3aecb0cc-035b-4bcc-8185-2b8d551ef3af"); + + public static readonly Guid SampleCleanPoint = new("9cdf01d8-a0f0-43ba-b077-eaa06cbd728a"); + public static readonly Guid SampleDecodeTimestamp = new("73a954d4-09e2-4861-befc-94bd97c08e6e"); + + public static readonly Guid CodecRateControlMode = new("1c0608e9-370c-4710-8a58-cb6181c42423"); + public static readonly Guid CodecMeanBitRate = new("f7222374-2144-4815-b550-a37f8e12ee52"); + public static readonly Guid CodecQuality = new("fcbf57a3-7ea5-4b0c-9644-69b40c39c391"); + public static readonly Guid CodecGopSize = new("95f31b26-95a4-41aa-9303-246a7fc6eef1"); + public static readonly Guid CodecBPictureCount = new("8d390aac-dc5c-4200-b57f-814d04babab2"); + public static readonly Guid CodecLowLatencyMode = new("9c27891a-ed7a-40e1-88e8-b22727a024ee"); + + public static readonly Guid IidTransform = typeof(IMFTransform).GUID; +} diff --git a/tests/Titano.Core.Windows.Tests/MediaFoundation/GpuAdaptersTests.cs b/tests/Titano.Core.Windows.Tests/MediaFoundation/GpuAdaptersTests.cs new file mode 100644 index 00000000..a84fee47 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/MediaFoundation/GpuAdaptersTests.cs @@ -0,0 +1,18 @@ +using Titano.Core.Windows.Dxgi; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.MediaFoundation; + +public sealed class GpuAdaptersTests(TestContext context) +{ + [Test] + [WindowsOnly] + public void EnumeratesAtLeastTheBasicRenderDriver() + { + var adapters = GpuAdapters.Enumerate(); + foreach (var a in adapters) + context.Log($"{a.Description} vendor=0x{a.VendorId:X4} device=0x{a.DeviceId:X4} vram={a.DedicatedVideoMemory >> 20} MiB software={a.IsSoftware}"); + Assert.NotEmpty(adapters); + Assert.True(adapters.All(a => a.Description.Length > 0 && !a.Description.Contains('\0'))); + } +} diff --git a/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs b/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs new file mode 100644 index 00000000..7ec92670 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs @@ -0,0 +1,153 @@ +using Titano.Core.Imaging; +using Titano.Core.Video; +using Titano.Core.Windows.MediaFoundation; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.MediaFoundation; + +[Serial] // encoders share GPU sessions and the MF runtime +public sealed class MediaFoundationEncoderTests(TestContext context) +{ + private const long Frame30 = 3000; // 1/30 s at 90 kHz + + [Test] + public void VendorIdsMapToNames() + { + Assert.Equal("NVIDIA", MediaFoundationEncoderProvider.VendorName("VEN_10DE")); + Assert.Equal("Intel", MediaFoundationEncoderProvider.VendorName("ven_8086")); + Assert.Equal("AMD", MediaFoundationEncoderProvider.VendorName("VEN_1002")); + Assert.Equal("VEN_ABCD", MediaFoundationEncoderProvider.VendorName("VEN_ABCD")); + Assert.Null(MediaFoundationEncoderProvider.VendorName(null)); + } + + [Test] + [WindowsOnly] + public void EnumeratesEncodersAndHidesSoftwareHevcAndAv1() + { + RequireMediaFoundation(); + var encoders = MediaFoundationEncoders.Enumerate(); + foreach (var e in encoders) context.Log($"{e.Codec} \"{e.Name}\" hardware={e.IsHardware} async={e.IsAsync} vendor={e.VendorId} 10-bit={e.SupportsTenBit}"); + Assert.True(encoders.All(e => !string.IsNullOrWhiteSpace(e.Name))); + + var capabilities = new MediaFoundationEncoderProvider().Capabilities; + Assert.True(capabilities.All(c => c.Hardware || c.Codec == VideoCodec.H264), "HEVC/AV1 are hardware-only"); + Assert.True(capabilities.All(c => !c.SupportsTenBit || c.Codec != VideoCodec.H264)); + Assert.Equal(encoders.Count(e => e.IsHardware || e.Codec == VideoCodec.H264), capabilities.Count); + } + + [Test] + [WindowsOnly] + [Timeout(60_000)] + public void SoftwareH264EncodeProducesAValidMp4() + { + RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false); + var dir = context.CreateTempDirectory(); + var settings = Settings(Path.Combine(dir, "software.mp4"), VideoCodec.H264, 8) with { PreferHardware = false }; + var provider = new MediaFoundationEncoderProvider(); + Assert.True(provider.CanEncode(settings)); + using (var session = provider.Open(settings)) + { + Assert.False(session.IsHardware); + context.Log("encoder: " + session.EncoderName); + WriteFrames(session, 60, 8); + session.Complete(); + } + + var report = Mp4Inspector.Inspect(settings.OutputPath); + context.Log(report.ToString()); + Assert.True(report.IsValid, string.Join("; ", report.Errors)); + Assert.Equal(VideoCodec.H264, report.Codec); + Assert.Equal(1280, report.Width); + Assert.Equal(720, report.Height); + Assert.Equal(60, report.FrameCount); + Assert.Approximately(2.0, report.Duration.TotalSeconds, 0.034); + Assert.True(report.FastStart); + Assert.Count(1, Directory.GetFiles(dir)); // no temporary file left behind + } + + [Test] + [WindowsOnly] + [Timeout(60_000)] + public void HardwareHevcMain10EncodeWhenAvailable() + { + RequireEncoder(VideoCodec.Hevc, hardware: true, tenBit: true); + var dir = context.CreateTempDirectory(); + var settings = Settings(Path.Combine(dir, "main10.mp4"), VideoCodec.Hevc, 10); + using (var session = new MediaFoundationEncoderProvider().Open(settings)) + { + Assert.True(session.IsHardware); + context.Log("encoder: " + session.EncoderName); + WriteFrames(session, 60, 10); + session.Complete(); + } + var report = Mp4Inspector.Inspect(settings.OutputPath); + context.Log(report.ToString()); + Assert.True(report.IsValid, string.Join("; ", report.Errors)); + Assert.Equal(VideoCodec.Hevc, report.Codec); + Assert.Equal(10, report.BitDepth); + Assert.Equal(60, report.FrameCount); + } + + [Test] + [WindowsOnly] + [Timeout(60_000)] + public void DisposeWithoutCompleteLeavesNoFile() + { + RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false); + var dir = context.CreateTempDirectory(); + var settings = Settings(Path.Combine(dir, "cancelled.mp4"), VideoCodec.H264, 8) with { PreferHardware = false }; + using (var session = new MediaFoundationEncoderProvider().Open(settings)) + { + WriteFrames(session, 5, 8); + } + Assert.Empty(Directory.GetFiles(dir)); + } + + private static EncodeSettings Settings(string path, VideoCodec codec, int bitDepth) => new() + { + OutputPath = path, + Codec = codec, + Width = 1280, + Height = 720, + FrameRate = new Rational(30, 1), + BitDepth = bitDepth, + Profile = codec == VideoCodec.Hevc ? (bitDepth == 10 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain) : CodecProfile.H264High, + BitRate = 4_000_000, + GopLength = 30, + }; + + /// A moving colour ramp with a bright square, distinct per frame. + private static void WriteFrames(IVideoEncoderSession session, int count, int bitDepth) + { + using var frame = new ImageBuffer(1280, 720); + for (var f = 0; f < count; f++) + { + for (var y = 0; y < 720; y++) + { + var r = frame.Row(0, y); + var g = frame.Row(1, y); + var b = frame.Row(2, y); + for (var x = 0; x < 1280; x++) + { + var square = Math.Abs(x - 100 - f * 15) < 60 && Math.Abs(y - 360) < 60; + r[x] = square ? 1f : (float)ColorSpace.SrgbToLinear((x + f * 7) % 1280 / 1280.0); + g[x] = square ? 1f : (float)ColorSpace.SrgbToLinear(y / 720.0); + b[x] = (float)ColorSpace.SrgbToLinear(bitDepth == 10 ? 0.5 + 0.4 * Math.Sin((x + y) * 0.01) : 0.3); + } + } + session.WriteFrame(frame, Frame30); + } + } + + private static void RequireMediaFoundation() + { + if (!MediaFoundationRuntime.IsAvailable) TestContext.Skip("Media Foundation is not installed (Windows N or Server without Media Foundation)"); + } + + private static void RequireEncoder(VideoCodec codec, bool hardware, bool tenBit) + { + RequireMediaFoundation(); + if (!MediaFoundationEncoders.Enumerate().Any(e => e.Codec == codec && e.IsHardware == hardware && (!tenBit || e.SupportsTenBit))) + TestContext.Skip($"No {(hardware ? "hardware" : "software")} {codec}{(tenBit ? " 10-bit" : string.Empty)} encoder on this machine"); + } +} From 8d93abd65bedd1a5861c021d7df5ab80c1c66df7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:05:43 +0000 Subject: [PATCH 074/188] feat(data): add migrations, repositories and TitanoDatabase facade Embedded per-dialect migrations applied in one transaction and recorded in schema_migrations (advisory lock on PostgreSQL, newer schemas refused). Schema for every BRIEF section 5 entity plus import history and uploads. Hand-written repositories for archives, sequences (filters, keyset paging, Archive statistics), frames (bulk insert and updates), renders, jobs (exclusive claiming, checkpoints, crash recovery), media cards, users, tokens, render nodes, settings, tags, audit and uploads. TitanoDatabase opens, migrates and exposes them, also bound to a transaction. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Migrations/MigrationRunner.cs | 90 +++++ .../Migrations/postgres/0001_initial.sql | 250 ++++++++++++ .../Migrations/sqlite/0001_initial.sql | 250 ++++++++++++ .../Repositories/ArchiveRepository.cs | 43 ++ .../Repositories/AuditRepository.cs | 58 +++ src/Titano.Data/Repositories/DbAccess.cs | 145 +++++++ .../Repositories/FrameRepository.cs | 157 ++++++++ src/Titano.Data/Repositories/JobRepository.cs | 142 +++++++ .../Repositories/MediaCardRepository.cs | 125 ++++++ .../Repositories/RenderNodeRepository.cs | 49 +++ .../Repositories/RenderRepository.cs | 62 +++ .../Repositories/SequenceRepository.cs | 369 ++++++++++++++++++ .../Repositories/SettingsRepository.cs | 93 +++++ src/Titano.Data/Repositories/TagRepository.cs | 79 ++++ .../Repositories/TokenRepository.cs | 57 +++ .../Repositories/UploadRepository.cs | 135 +++++++ .../Repositories/UserRepository.cs | 75 ++++ src/Titano.Data/TitanoDatabase.cs | 155 ++++++++ 18 files changed, 2334 insertions(+) create mode 100644 src/Titano.Data/Migrations/MigrationRunner.cs create mode 100644 src/Titano.Data/Migrations/postgres/0001_initial.sql create mode 100644 src/Titano.Data/Migrations/sqlite/0001_initial.sql create mode 100644 src/Titano.Data/Repositories/ArchiveRepository.cs create mode 100644 src/Titano.Data/Repositories/AuditRepository.cs create mode 100644 src/Titano.Data/Repositories/DbAccess.cs create mode 100644 src/Titano.Data/Repositories/FrameRepository.cs create mode 100644 src/Titano.Data/Repositories/JobRepository.cs create mode 100644 src/Titano.Data/Repositories/MediaCardRepository.cs create mode 100644 src/Titano.Data/Repositories/RenderNodeRepository.cs create mode 100644 src/Titano.Data/Repositories/RenderRepository.cs create mode 100644 src/Titano.Data/Repositories/SequenceRepository.cs create mode 100644 src/Titano.Data/Repositories/SettingsRepository.cs create mode 100644 src/Titano.Data/Repositories/TagRepository.cs create mode 100644 src/Titano.Data/Repositories/TokenRepository.cs create mode 100644 src/Titano.Data/Repositories/UploadRepository.cs create mode 100644 src/Titano.Data/Repositories/UserRepository.cs create mode 100644 src/Titano.Data/TitanoDatabase.cs diff --git a/src/Titano.Data/Migrations/MigrationRunner.cs b/src/Titano.Data/Migrations/MigrationRunner.cs new file mode 100644 index 00000000..b100ce03 --- /dev/null +++ b/src/Titano.Data/Migrations/MigrationRunner.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Migrations; + +/// A numbered schema change shipped as Migrations/<dialect>/NNNN_name.sql. +public sealed record Migration(int Version, string Name, string Sql); + +/// +/// Applies the embedded migrations of a dialect at startup (BRIEF §6.1): all pending ones in a single +/// transaction, each recorded in schema_migrations(version, name, applied_at). A database that already +/// holds a version this build does not know is refused with . +/// +public static class MigrationRunner +{ + private const string ResourcePrefix = "Titano.Data.Migrations."; + + /// Serialises concurrent migrators on one PostgreSQL database (several server instances starting). + private const long AdvisoryLockKey = 0x5469_7461_6E6F; + + /// The embedded migrations of , by ascending version. + public static IReadOnlyList Load(Dialect dialect) + { + var folder = ResourcePrefix + (dialect == Dialect.Postgres ? "postgres" : "sqlite"); + var assembly = typeof(MigrationRunner).Assembly; + var migrations = new List(); + foreach (var resource in assembly.GetManifestResourceNames()) + { + // The logical name keeps the folder separator of the build host ('/' or '\'). + if (resource.Length <= folder.Length + 1 || !resource.StartsWith(folder, StringComparison.Ordinal) + || resource[folder.Length] is not ('/' or '\\')) + continue; + var file = resource[(folder.Length + 1)..]; + var underscore = file.IndexOf('_', StringComparison.Ordinal); + if (underscore <= 0 || !file.EndsWith(".sql", StringComparison.Ordinal) + || !int.TryParse(file.AsSpan(0, underscore), NumberStyles.None, CultureInfo.InvariantCulture, out var version)) + throw new InvalidOperationException($"Migration resource '{resource}' is not named NNNN_name.sql."); + using var reader = new StreamReader(assembly.GetManifestResourceStream(resource)!); + migrations.Add(new Migration(version, file[(underscore + 1)..^4], reader.ReadToEnd())); + } + migrations.Sort((a, b) => a.Version.CompareTo(b.Version)); + for (var i = 1; i < migrations.Count; i++) + { + if (migrations[i].Version == migrations[i - 1].Version) + throw new InvalidOperationException($"Two migrations share version {migrations[i].Version}."); + } + return migrations; + } + + /// Migrates to the newest embedded version and returns that version. + public static Task MigrateAsync(IDatabase database, CancellationToken cancellationToken = default) => + MigrateAsync(database, Load(database.Dialect), cancellationToken); + + /// Applies every migration of not yet recorded; returns the resulting version. + public static async Task MigrateAsync(IDatabase database, IReadOnlyList migrations, CancellationToken cancellationToken = default) + { + var postgres = database.Dialect == Dialect.Postgres; + var session = await database.OpenAsync(cancellationToken).ConfigureAwait(false); + await using (session.ConfigureAwait(false)) + { + var transaction = await session.BeginAsync(cancellationToken).ConfigureAwait(false); + await using (transaction.ConfigureAwait(false)) + { + if (postgres) await session.ExecuteAsync("SELECT pg_advisory_xact_lock($1)", [AdvisoryLockKey], cancellationToken).ConfigureAwait(false); + await session.ExecuteScriptAsync(postgres + ? "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, name text NOT NULL, applied_at timestamptz NOT NULL)" + : "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)", + cancellationToken).ConfigureAwait(false); + + var applied = new HashSet(await session.QueryListAsync( + "SELECT version FROM schema_migrations", [], r => r.GetInt32(0), cancellationToken).ConfigureAwait(false)); + var supported = migrations.Count == 0 ? 0 : migrations[^1].Version; + var current = applied.Count == 0 ? 0 : applied.Max(); + if (current > supported) throw new SchemaTooNewException(current, supported); + + foreach (var migration in migrations) + { + if (applied.Contains(migration.Version)) continue; + await session.ExecuteScriptAsync(migration.Sql, cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync( + "INSERT INTO schema_migrations (version, name, applied_at) VALUES ($1, $2, $3)", + [migration.Version, migration.Name, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + Log.Info("Data", $"Applied {database.Dialect} migration {migration.Version:0000} {migration.Name}"); + } + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return supported; + } + } + } +} diff --git a/src/Titano.Data/Migrations/postgres/0001_initial.sql b/src/Titano.Data/Migrations/postgres/0001_initial.sql new file mode 100644 index 00000000..f62a74fd --- /dev/null +++ b/src/Titano.Data/Migrations/postgres/0001_initial.sql @@ -0,0 +1,250 @@ +-- Titano schema v1 (PostgreSQL). Instants are timestamptz, camera wall-clock times timestamp, JSON jsonb. +-- Sort keys use the "C" collation so ordering equals SQLite's binary UTF-8 order. Mirrors sqlite/0001_initial.sql. + +CREATE TABLE archives ( + id uuid NOT NULL PRIMARY KEY, + name text NOT NULL, + root_path text NOT NULL, + folder_template text NOT NULL, + file_template text NOT NULL, + schema_version integer NOT NULL DEFAULT 1, + created timestamptz NOT NULL, + proxy_long_edge integer NOT NULL DEFAULT 1920 +); + +CREATE TABLE users ( + id uuid NOT NULL PRIMARY KEY, + username text NOT NULL, + username_key text NOT NULL UNIQUE, + display_name text, + password_hash text NOT NULL, + role integer NOT NULL, + permissions bigint NOT NULL, + quota_bytes bigint NOT NULL DEFAULT 0, + used_bytes bigint NOT NULL DEFAULT 0, + disabled boolean NOT NULL DEFAULT FALSE, + must_change_password boolean NOT NULL DEFAULT FALSE, + created timestamptz NOT NULL, + last_login timestamptz +); + +CREATE TABLE sequences ( + id uuid NOT NULL PRIMARY KEY, + archive_id uuid NOT NULL REFERENCES archives (id) ON DELETE CASCADE, + title text, + title_key text COLLATE "C" NOT NULL, + search_text text NOT NULL, + folder text NOT NULL, + camera_make text, + camera_model text, + camera_serial text, + lens text, + first_capture timestamp, + last_capture timestamp, + frame_count integer NOT NULL DEFAULT 0, + median_interval double precision, + total_bytes bigint NOT NULL DEFAULT 0, + status integer NOT NULL DEFAULT 0, + rendered_count integer NOT NULL DEFAULT 0, + verified_at timestamptz, + hero_frame_id uuid, + rating integer NOT NULL DEFAULT 0, + notes text, + settings_json jsonb, + analysis_json jsonb, + origin integer NOT NULL DEFAULT 0, + sync_state integer NOT NULL DEFAULT 0, + settings_version integer NOT NULL DEFAULT 0, + frames_version integer NOT NULL DEFAULT 0, + owner_user_id uuid, + warning_count integer NOT NULL DEFAULT 0, + updated_at timestamptz NOT NULL +); +CREATE INDEX ix_sequences_archive_capture ON sequences (archive_id, first_capture, id); +CREATE INDEX ix_sequences_capture ON sequences (first_capture, id); +CREATE INDEX ix_sequences_camera ON sequences (camera_model); + +CREATE TABLE frames ( + id uuid NOT NULL PRIMARY KEY, + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + idx integer NOT NULL, + relative_path text NOT NULL, + file_name text NOT NULL, + original_file_name text, + size bigint NOT NULL DEFAULT 0, + sha256 text, + captured_at timestamp, + utc_offset_minutes integer, + timestamp_source integer NOT NULL DEFAULT 0, + exposure_time double precision, + f_number double precision, + iso integer, + focal_length double precision, + exposure_bias double precision, + white_balance integer, + orientation integer NOT NULL DEFAULT 1, + width integer NOT NULL DEFAULT 0, + height integer NOT NULL DEFAULT 0, + format integer NOT NULL DEFAULT 0, + preview_offset bigint, + preview_length bigint, + mean_log_luminance double precision, + clip_low double precision, + clip_high double precision, + flags integer NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX ux_frames_sequence_idx ON frames (sequence_id, idx); +CREATE INDEX ix_frames_sha256 ON frames (sha256); +CREATE INDEX ix_frames_captured_at ON frames (captured_at); + +CREATE TABLE renders ( + id uuid NOT NULL PRIMARY KEY, + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + preset_name text NOT NULL, + settings_json jsonb, + output_path text NOT NULL, + codec text, + width integer NOT NULL DEFAULT 0, + height integer NOT NULL DEFAULT 0, + fps double precision NOT NULL DEFAULT 0, + duration_seconds double precision NOT NULL DEFAULT 0, + bytes bigint NOT NULL DEFAULT 0, + created timestamptz NOT NULL, + produced_by text +); +CREATE INDEX ix_renders_sequence ON renders (sequence_id, created); + +CREATE TABLE jobs ( + id uuid NOT NULL PRIMARY KEY, + kind integer NOT NULL, + target_ids text NOT NULL DEFAULT '', + target_label text, + parameters_json jsonb, + state integer NOT NULL, + priority integer NOT NULL, + progress_done bigint NOT NULL DEFAULT 0, + progress_total bigint NOT NULL DEFAULT 0, + items_per_second double precision, + eta_seconds double precision, + checkpoint text, + log_tail text, + created_by uuid, + node_id text, + attempts integer NOT NULL DEFAULT 0, + error text, + created timestamptz NOT NULL, + started timestamptz, + finished timestamptz +); +CREATE INDEX ix_jobs_queue ON jobs (state, priority DESC, created, id); +CREATE INDEX ix_jobs_state_created ON jobs (state, created, id); +CREATE INDEX ix_jobs_finished ON jobs (finished); + +CREATE TABLE media_cards ( + id uuid NOT NULL PRIMARY KEY, + identity text NOT NULL UNIQUE, + volume_serial bigint NOT NULL, + label text, + capacity bigint NOT NULL DEFAULT 0, + nickname text, + camera_make text, + camera_model text, + camera_serial text, + profile_json jsonb, + auto_import boolean NOT NULL DEFAULT FALSE, + first_seen timestamptz NOT NULL, + last_seen timestamptz NOT NULL +); + +CREATE TABLE import_history ( + card_id uuid NOT NULL REFERENCES media_cards (id) ON DELETE CASCADE, + path text NOT NULL, + size bigint NOT NULL, + mtime timestamptz NOT NULL, + sha256 text, + frame_id uuid REFERENCES frames (id) ON DELETE SET NULL, + job_id uuid, + imported_at timestamptz NOT NULL, + PRIMARY KEY (card_id, path, size, mtime) +); +CREATE INDEX ix_import_history_frame ON import_history (frame_id); + +CREATE TABLE tokens ( + token_hash text NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name text, + created timestamptz NOT NULL, + expires timestamptz NOT NULL, + last_used timestamptz NOT NULL, + revoked boolean NOT NULL DEFAULT FALSE +); +CREATE INDEX ix_tokens_user ON tokens (user_id); +CREATE INDEX ix_tokens_expires ON tokens (expires); + +CREATE TABLE render_nodes ( + id uuid NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name text NOT NULL, + capabilities_json jsonb, + last_heartbeat timestamptz NOT NULL, + state text NOT NULL +); +CREATE INDEX ix_render_nodes_user ON render_nodes (user_id); +CREATE INDEX ix_render_nodes_heartbeat ON render_nodes (last_heartbeat); + +CREATE TABLE settings ( + scope text NOT NULL, + scope_id text NOT NULL DEFAULT '', + key text NOT NULL, + value_json jsonb NOT NULL, + updated_at timestamptz NOT NULL, + PRIMARY KEY (scope, scope_id, key) +); + +CREATE TABLE tags ( + id uuid NOT NULL PRIMARY KEY, + name text NOT NULL, + name_key text COLLATE "C" NOT NULL UNIQUE +); + +CREATE TABLE sequence_tags ( + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + tag_id uuid NOT NULL REFERENCES tags (id) ON DELETE CASCADE, + PRIMARY KEY (sequence_id, tag_id) +); +CREATE INDEX ix_sequence_tags_tag ON sequence_tags (tag_id); + +CREATE TABLE audit_log ( + id uuid NOT NULL PRIMARY KEY, + at timestamptz NOT NULL, + user_id uuid, + username text, + action text NOT NULL, + target_kind text, + target_id text, + details text, + remote_address text +); +CREATE INDEX ix_audit_log_at ON audit_log (at, id); +CREATE INDEX ix_audit_log_user ON audit_log (user_id, at); + +CREATE TABLE uploads ( + id uuid NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + sequence_id uuid REFERENCES sequences (id) ON DELETE SET NULL, + file_name text NOT NULL, + size bigint NOT NULL, + sha256 text NOT NULL, + captured_at timestamp, + chunk_size integer NOT NULL, + received bytea NOT NULL, + received_count integer NOT NULL DEFAULT 0, + state integer NOT NULL, + frame_id uuid, + created timestamptz NOT NULL, + updated_at timestamptz NOT NULL +); +CREATE INDEX ix_uploads_user ON uploads (user_id, created); +CREATE INDEX ix_uploads_state ON uploads (state, updated_at); +CREATE INDEX ix_uploads_sha256 ON uploads (sha256); +CREATE INDEX ix_uploads_sequence ON uploads (sequence_id); diff --git a/src/Titano.Data/Migrations/sqlite/0001_initial.sql b/src/Titano.Data/Migrations/sqlite/0001_initial.sql new file mode 100644 index 00000000..6d2c442b --- /dev/null +++ b/src/Titano.Data/Migrations/sqlite/0001_initial.sql @@ -0,0 +1,250 @@ +-- Titano schema v1 (SQLite). Ids are UUID text, instants ISO-8601 UTC text ('…Z'), camera wall-clock times +-- ISO-8601 text without zone, JSON as text, booleans as 0/1. Mirrors postgres/0001_initial.sql. + +CREATE TABLE archives ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + root_path TEXT NOT NULL, + folder_template TEXT NOT NULL, + file_template TEXT NOT NULL, + schema_version INTEGER NOT NULL DEFAULT 1, + created TEXT NOT NULL, + proxy_long_edge INTEGER NOT NULL DEFAULT 1920 +); + +CREATE TABLE users ( + id TEXT NOT NULL PRIMARY KEY, + username TEXT NOT NULL, + username_key TEXT NOT NULL UNIQUE, + display_name TEXT, + password_hash TEXT NOT NULL, + role INTEGER NOT NULL, + permissions INTEGER NOT NULL, + quota_bytes INTEGER NOT NULL DEFAULT 0, + used_bytes INTEGER NOT NULL DEFAULT 0, + disabled INTEGER NOT NULL DEFAULT 0, + must_change_password INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL, + last_login TEXT +); + +CREATE TABLE sequences ( + id TEXT NOT NULL PRIMARY KEY, + archive_id TEXT NOT NULL REFERENCES archives (id) ON DELETE CASCADE, + title TEXT, + title_key TEXT NOT NULL, + search_text TEXT NOT NULL, + folder TEXT NOT NULL, + camera_make TEXT, + camera_model TEXT, + camera_serial TEXT, + lens TEXT, + first_capture TEXT, + last_capture TEXT, + frame_count INTEGER NOT NULL DEFAULT 0, + median_interval REAL, + total_bytes INTEGER NOT NULL DEFAULT 0, + status INTEGER NOT NULL DEFAULT 0, + rendered_count INTEGER NOT NULL DEFAULT 0, + verified_at TEXT, + hero_frame_id TEXT, + rating INTEGER NOT NULL DEFAULT 0, + notes TEXT, + settings_json TEXT, + analysis_json TEXT, + origin INTEGER NOT NULL DEFAULT 0, + sync_state INTEGER NOT NULL DEFAULT 0, + settings_version INTEGER NOT NULL DEFAULT 0, + frames_version INTEGER NOT NULL DEFAULT 0, + owner_user_id TEXT, + warning_count INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL +); +CREATE INDEX ix_sequences_archive_capture ON sequences (archive_id, first_capture, id); +CREATE INDEX ix_sequences_capture ON sequences (first_capture, id); +CREATE INDEX ix_sequences_camera ON sequences (camera_model); + +CREATE TABLE frames ( + id TEXT NOT NULL PRIMARY KEY, + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + idx INTEGER NOT NULL, + relative_path TEXT NOT NULL, + file_name TEXT NOT NULL, + original_file_name TEXT, + size INTEGER NOT NULL DEFAULT 0, + sha256 TEXT, + captured_at TEXT, + utc_offset_minutes INTEGER, + timestamp_source INTEGER NOT NULL DEFAULT 0, + exposure_time REAL, + f_number REAL, + iso INTEGER, + focal_length REAL, + exposure_bias REAL, + white_balance INTEGER, + orientation INTEGER NOT NULL DEFAULT 1, + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + format INTEGER NOT NULL DEFAULT 0, + preview_offset INTEGER, + preview_length INTEGER, + mean_log_luminance REAL, + clip_low REAL, + clip_high REAL, + flags INTEGER NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX ux_frames_sequence_idx ON frames (sequence_id, idx); +CREATE INDEX ix_frames_sha256 ON frames (sha256); +CREATE INDEX ix_frames_captured_at ON frames (captured_at); + +CREATE TABLE renders ( + id TEXT NOT NULL PRIMARY KEY, + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + preset_name TEXT NOT NULL, + settings_json TEXT, + output_path TEXT NOT NULL, + codec TEXT, + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + fps REAL NOT NULL DEFAULT 0, + duration_seconds REAL NOT NULL DEFAULT 0, + bytes INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL, + produced_by TEXT +); +CREATE INDEX ix_renders_sequence ON renders (sequence_id, created); + +CREATE TABLE jobs ( + id TEXT NOT NULL PRIMARY KEY, + kind INTEGER NOT NULL, + target_ids TEXT NOT NULL DEFAULT '', + target_label TEXT, + parameters_json TEXT, + state INTEGER NOT NULL, + priority INTEGER NOT NULL, + progress_done INTEGER NOT NULL DEFAULT 0, + progress_total INTEGER NOT NULL DEFAULT 0, + items_per_second REAL, + eta_seconds REAL, + checkpoint TEXT, + log_tail TEXT, + created_by TEXT, + node_id TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + error TEXT, + created TEXT NOT NULL, + started TEXT, + finished TEXT +); +CREATE INDEX ix_jobs_queue ON jobs (state, priority DESC, created, id); +CREATE INDEX ix_jobs_state_created ON jobs (state, created, id); +CREATE INDEX ix_jobs_finished ON jobs (finished); + +CREATE TABLE media_cards ( + id TEXT NOT NULL PRIMARY KEY, + identity TEXT NOT NULL UNIQUE, + volume_serial INTEGER NOT NULL, + label TEXT, + capacity INTEGER NOT NULL DEFAULT 0, + nickname TEXT, + camera_make TEXT, + camera_model TEXT, + camera_serial TEXT, + profile_json TEXT, + auto_import INTEGER NOT NULL DEFAULT 0, + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL +); + +CREATE TABLE import_history ( + card_id TEXT NOT NULL REFERENCES media_cards (id) ON DELETE CASCADE, + path TEXT NOT NULL, + size INTEGER NOT NULL, + mtime TEXT NOT NULL, + sha256 TEXT, + frame_id TEXT REFERENCES frames (id) ON DELETE SET NULL, + job_id TEXT, + imported_at TEXT NOT NULL, + PRIMARY KEY (card_id, path, size, mtime) +); +CREATE INDEX ix_import_history_frame ON import_history (frame_id); + +CREATE TABLE tokens ( + token_hash TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name TEXT, + created TEXT NOT NULL, + expires TEXT NOT NULL, + last_used TEXT NOT NULL, + revoked INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX ix_tokens_user ON tokens (user_id); +CREATE INDEX ix_tokens_expires ON tokens (expires); + +CREATE TABLE render_nodes ( + id TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name TEXT NOT NULL, + capabilities_json TEXT, + last_heartbeat TEXT NOT NULL, + state TEXT NOT NULL +); +CREATE INDEX ix_render_nodes_user ON render_nodes (user_id); +CREATE INDEX ix_render_nodes_heartbeat ON render_nodes (last_heartbeat); + +CREATE TABLE settings ( + scope TEXT NOT NULL, + scope_id TEXT NOT NULL DEFAULT '', + key TEXT NOT NULL, + value_json TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (scope, scope_id, key) +); + +CREATE TABLE tags ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + name_key TEXT NOT NULL UNIQUE +); + +CREATE TABLE sequence_tags ( + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + tag_id TEXT NOT NULL REFERENCES tags (id) ON DELETE CASCADE, + PRIMARY KEY (sequence_id, tag_id) +); +CREATE INDEX ix_sequence_tags_tag ON sequence_tags (tag_id); + +CREATE TABLE audit_log ( + id TEXT NOT NULL PRIMARY KEY, + at TEXT NOT NULL, + user_id TEXT, + username TEXT, + action TEXT NOT NULL, + target_kind TEXT, + target_id TEXT, + details TEXT, + remote_address TEXT +); +CREATE INDEX ix_audit_log_at ON audit_log (at, id); +CREATE INDEX ix_audit_log_user ON audit_log (user_id, at); + +CREATE TABLE uploads ( + id TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + sequence_id TEXT REFERENCES sequences (id) ON DELETE SET NULL, + file_name TEXT NOT NULL, + size INTEGER NOT NULL, + sha256 TEXT NOT NULL, + captured_at TEXT, + chunk_size INTEGER NOT NULL, + received BLOB NOT NULL, + received_count INTEGER NOT NULL DEFAULT 0, + state INTEGER NOT NULL, + frame_id TEXT, + created TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX ix_uploads_user ON uploads (user_id, created); +CREATE INDEX ix_uploads_state ON uploads (state, updated_at); +CREATE INDEX ix_uploads_sha256 ON uploads (sha256); +CREATE INDEX ix_uploads_sequence ON uploads (sequence_id); diff --git a/src/Titano.Data/Repositories/ArchiveRepository.cs b/src/Titano.Data/Repositories/ArchiveRepository.cs new file mode 100644 index 00000000..717eb4f9 --- /dev/null +++ b/src/Titano.Data/Repositories/ArchiveRepository.cs @@ -0,0 +1,43 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Archive roots (BRIEF §5, §7). +public sealed class ArchiveRepository +{ + private const string Columns = "id, name, root_path, folder_template, file_template, schema_version, created, proxy_long_edge"; + + private static readonly string UpsertSql = SqlDialect.Upsert("archives", + ["id", "name", "root_path", "folder_template", "file_template", "schema_version", "created", "proxy_long_edge"], 1); + + private readonly DbAccess _db; + + internal ArchiveRepository(DbAccess db) => _db = db; + + public async Task UpsertAsync(Archive archive, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [archive.Id, archive.Name, archive.RootPath, archive.FolderTemplate, archive.FileTemplate, archive.SchemaVersion, archive.Created, archive.ProxyLongEdge], + cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM archives WHERE id = $1", [id], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM archives ORDER BY name, id", [], Map, cancellationToken); + + /// Deletes the archive and everything indexed under it (the files on disk are untouched). + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM archives WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static Archive Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Name = r.GetString(1), + RootPath = r.GetString(2), + FolderTemplate = r.GetString(3), + FileTemplate = r.GetString(4), + SchemaVersion = r.GetInt32(5), + Created = r.GetDateTimeOffset(6), + ProxyLongEdge = r.GetInt32(7), + }; +} diff --git a/src/Titano.Data/Repositories/AuditRepository.cs b/src/Titano.Data/Repositories/AuditRepository.cs new file mode 100644 index 00000000..46e13c31 --- /dev/null +++ b/src/Titano.Data/Repositories/AuditRepository.cs @@ -0,0 +1,58 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Append-only record of who did what (BRIEF §5 AuditLog, §14.2). +public sealed class AuditRepository +{ + private const string Columns = "id, at, user_id, username, action, target_kind, target_id, details, remote_address"; + + private readonly DbAccess _db; + + internal AuditRepository(DbAccess db) => _db = db; + + public async Task AppendAsync(AuditEntry entry, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync($"INSERT INTO audit_log ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + [entry.Id, entry.At, entry.UserId, entry.Username, entry.Action, entry.TargetKind, entry.TargetId, entry.Details, entry.RemoteAddress], + cancellationToken).ConfigureAwait(false); + + /// Entries newest first, optionally of one user. + public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = new List(); + if (userId is { } user) where.Add($"user_id = {p.Add(user)}"); + if (cursor is not null) + { + var (value, id) = Cursor.Decode("audit", cursor); + where.Add(Cursor.After("at", "id", descending: true, value, id, p.Add)); + } + var take = Cursor.ClampLimit(limit); + var sql = $"SELECT {Columns} FROM audit_log{(where.Count > 0 ? " WHERE " + string.Join(" AND ", where) : string.Empty)} " + + $"ORDER BY at DESC, id DESC LIMIT {p.Add(take + 1)}"; + return _db.RunAsync(async session => + { + var entries = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false); + string? next = null; + if (entries.Count > take) + { + entries.RemoveAt(take); + next = Cursor.Encode("audit", entries[^1].At, entries[^1].Id); + } + return new Page(entries, next); + }, cancellationToken); + } + + private static AuditEntry Map(DbRow r) => new() + { + Id = r.GetGuid(0), + At = r.GetDateTimeOffset(1), + UserId = r.GetGuidOrNull(2), + Username = r.GetStringOrNull(3), + Action = r.GetString(4), + TargetKind = r.GetStringOrNull(5), + TargetId = r.GetStringOrNull(6), + Details = r.GetStringOrNull(7), + RemoteAddress = r.GetStringOrNull(8), + }; +} diff --git a/src/Titano.Data/Repositories/DbAccess.cs b/src/Titano.Data/Repositories/DbAccess.cs new file mode 100644 index 00000000..77a419cf --- /dev/null +++ b/src/Titano.Data/Repositories/DbAccess.cs @@ -0,0 +1,145 @@ +using System.Buffers.Text; +using System.Globalization; +using System.Text; + +namespace Titano.Data.Repositories; + +/// One page of a keyset-paginated listing; pass back to get the following page. +public sealed record Page(IReadOnlyList Items, string? NextCursor); + +/// +/// Where repository commands run: on a caller's session (so they join its transaction) or on a session +/// borrowed from the pool for the duration of one call. +/// +internal sealed class DbAccess +{ + private readonly IDatabase? _database; + private readonly IDbSession? _session; + + public DbAccess(IDatabase database) + { + _database = database; + Sql = SqlDialect.For(database.Dialect); + } + + public DbAccess(IDbSession session) + { + _session = session; + Sql = SqlDialect.For(session.Dialect); + } + + public SqlDialect Sql { get; } + + public async Task RunAsync(Func> work, CancellationToken cancellationToken) + { + if (_session is not null) return await work(_session).ConfigureAwait(false); + var session = await _database!.OpenAsync(cancellationToken).ConfigureAwait(false); + await using (session.ConfigureAwait(false)) return await work(session).ConfigureAwait(false); + } + + /// Runs atomically: inside the caller's transaction, or in a new one. + public Task InTransactionAsync(Func> work, CancellationToken cancellationToken) => + RunAsync(async session => + { + if (session.InTransaction) return await work(session).ConfigureAwait(false); + var transaction = await session.BeginAsync(cancellationToken).ConfigureAwait(false); + await using (transaction.ConfigureAwait(false)) + { + var result = await work(session).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + }, cancellationToken); + + public Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + RunAsync(s => s.ExecuteAsync(sql, parameters, cancellationToken), cancellationToken); + + public async Task> ListAsync(string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) => + await RunAsync(s => s.QueryListAsync(sql, parameters, map, cancellationToken), cancellationToken).ConfigureAwait(false); + + public Task SingleAsync(string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) => + RunAsync(s => s.QuerySingleOrDefaultAsync(sql, parameters, map, cancellationToken), cancellationToken); + + public Task ScalarAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + RunAsync(s => s.ScalarAsync(sql, parameters, cancellationToken), cancellationToken); +} + +/// +/// Opaque keyset cursors: the sort value and id of the last row of a page, tagged with the listing they belong +/// to so a cursor cannot be replayed against a different ordering. +/// +internal static class Cursor +{ + public static string Encode(string scope, object? value, Guid id) + { + var payload = value switch + { + null => "n", + DateTime d => "t" + d.Ticks.ToString(CultureInfo.InvariantCulture), + DateTimeOffset o => "o" + o.UtcTicks.ToString(CultureInfo.InvariantCulture), + long l => "i" + l.ToString(CultureInfo.InvariantCulture), + int i => "i" + i.ToString(CultureInfo.InvariantCulture), + string s => "s" + s, + _ => throw new NotSupportedException($"Cursor values of type {value.GetType().Name} are not supported."), + }; + return Base64Url.EncodeToString(Encoding.UTF8.GetBytes($"{scope}|{id:N}|{payload}")); + } + + /// Decodes a cursor of ; anything else is a . + public static (object? Value, Guid Id) Decode(string scope, string cursor) + { + string text; + try + { + text = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor)); + } + catch (FormatException ex) + { + throw new FormatException("Invalid paging cursor.", ex); + } + var parts = text.Split('|', 3); + if (parts.Length != 3 || parts[0] != scope || !Guid.TryParseExact(parts[1], "N", out var id) || parts[2].Length == 0) + throw new FormatException("The paging cursor does not belong to this listing."); + var payload = parts[2][1..]; + object? value = parts[2][0] switch + { + 'n' => null, + 't' => new DateTime(long.Parse(payload, CultureInfo.InvariantCulture), DateTimeKind.Unspecified), + 'o' => new DateTimeOffset(long.Parse(payload, CultureInfo.InvariantCulture), TimeSpan.Zero), + 'i' => long.Parse(payload, CultureInfo.InvariantCulture), + 's' => payload, + _ => throw new FormatException("Invalid paging cursor."), + }; + return (value, id); + } + + /// + /// Keyset condition "after (value, id)" for ORDER BY column dir NULLS LAST, id dir; adds its parameters + /// through , which returns the placeholder text. + /// + public static string After(string column, string idColumn, bool descending, object? value, Guid id, Func parameter) + { + var op = descending ? "<" : ">"; + var idParam = parameter(id); + if (value is null) return $"({column} IS NULL AND {idColumn} {op} {idParam})"; + var v = parameter(new DbParam(value)); + return $"({column} {op} {v} OR ({column} = {v} AND {idColumn} {op} {idParam}) OR {column} IS NULL)"; + } + + public static int ClampLimit(int limit) => Math.Clamp(limit, 1, 1000); +} + +/// Builds positional parameter lists alongside SQL text. +internal sealed class SqlParameters +{ + private readonly List _values = []; + + /// Adds a value and returns its placeholder ($n). + public string Add(DbParam value) + { + _values.Add(value); + return "$" + _values.Count.ToString(CultureInfo.InvariantCulture); + } + + public DbParam[] ToArray() => [.. _values]; +} diff --git a/src/Titano.Data/Repositories/FrameRepository.cs b/src/Titano.Data/Repositories/FrameRepository.cs new file mode 100644 index 00000000..30350e5e --- /dev/null +++ b/src/Titano.Data/Repositories/FrameRepository.cs @@ -0,0 +1,157 @@ +using System.Text; +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Light statistics of one frame, written by the analysis job. +public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh); + +/// Frames of sequences: bulk import, paged listing, duplicate lookup and bulk updates. +public sealed class FrameRepository +{ + private static readonly string[] ColumnNames = + [ + "id", "sequence_id", "idx", "relative_path", "file_name", "original_file_name", "size", "sha256", "captured_at", + "utc_offset_minutes", "timestamp_source", "exposure_time", "f_number", "iso", "focal_length", "exposure_bias", + "white_balance", "orientation", "width", "height", "format", "preview_offset", "preview_length", + "mean_log_luminance", "clip_low", "clip_high", "flags", + ]; + + private static readonly string Columns = string.Join(", ", ColumnNames); + private static readonly string InsertSql = + $"INSERT INTO frames ({Columns}) VALUES ({string.Join(", ", ColumnNames.Select((_, i) => "$" + (i + 1)))})"; + + /// Rows per statement of the batched PostgreSQL updates (4 or fewer parameters per row). + private const int Batch = 1000; + + private readonly DbAccess _db; + + internal FrameRepository(DbAccess db) => _db = db; + + public async Task InsertAsync(Frame frame, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(InsertSql, Array.ConvertAll(Values(frame), v => new DbParam(v)), cancellationToken).ConfigureAwait(false); + + /// Inserts many frames at once (COPY on PostgreSQL, batched INSERTs in one transaction on SQLite). + public Task BulkInsertAsync(IEnumerable frames, CancellationToken cancellationToken = default) => + _db.RunAsync(session => session.BulkInsertAsync("frames", ColumnNames, frames.Select(Values).ToAsyncEnumerable(), cancellationToken), cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM frames WHERE id = $1", [id], Map, cancellationToken); + + /// Frames of a sequence by index, starting after (keyset paging). + public Task> ListBySequenceAsync(Guid sequenceId, int afterIndex = -1, int limit = 1000, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM frames WHERE sequence_id = $1 AND idx > $2 ORDER BY idx LIMIT $3", + [sequenceId, afterIndex, Cursor.ClampLimit(limit)], Map, cancellationToken); + + /// Every frame with this content hash (duplicate detection, upload short-circuit). + public Task> FindBySha256Async(string sha256, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM frames WHERE sha256 = $1 ORDER BY sequence_id, idx", [sha256.ToLowerInvariant()], Map, cancellationToken); + + /// Writes analysis results for many frames in one transaction; returns the number of frames updated. + public Task UpdateLightStatsAsync(IReadOnlyList stats, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var updated = 0; + if (_db.Sql.IsPostgres) + { + // One UPDATE … FROM (VALUES …) per batch instead of a round trip per frame. + for (var start = 0; start < stats.Count; start += Batch) + { + var count = Math.Min(Batch, stats.Count - start); + var sql = new StringBuilder("UPDATE frames AS f SET mean_log_luminance = v.m, clip_low = v.lo, clip_high = v.hi FROM (VALUES "); + var args = new DbParam[count * 4]; + for (var i = 0; i < count; i++) + { + var s = stats[start + i]; + sql.Append(i > 0 ? ", (" : "(").Append('$').Append(4 * i + 1).Append(", $").Append(4 * i + 2) + .Append(", $").Append(4 * i + 3).Append(", $").Append(4 * i + 4).Append(')'); + args[4 * i] = s.FrameId; + args[4 * i + 1] = s.MeanLogLuminance; + args[4 * i + 2] = s.ClipLow; + args[4 * i + 3] = s.ClipHigh; + } + sql.Append(") AS v(id, m, lo, hi) WHERE f.id = v.id"); + updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false); + } + } + else + { + foreach (var s in stats) + { + updated += await session.ExecuteAsync( + "UPDATE frames SET mean_log_luminance = $2, clip_low = $3, clip_high = $4 WHERE id = $1", + [s.FrameId, s.MeanLogLuminance, s.ClipLow, s.ClipHigh], cancellationToken).ConfigureAwait(false); + } + } + return updated; + }, cancellationToken); + + /// Sets and clears flags on many frames in one transaction; returns the number of frames updated. + public Task UpdateFlagsAsync(IReadOnlyList frameIds, FrameFlags set, FrameFlags clear, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + // 500 ids per statement stays below SQLite's historical 999-variable limit. + const int idsPerStatement = 500; + var updated = 0; + for (var start = 0; start < frameIds.Count; start += idsPerStatement) + { + var count = Math.Min(idsPerStatement, frameIds.Count - start); + var args = new DbParam[count + 2]; + args[0] = (int)set; + args[1] = (int)clear; + var placeholders = new StringBuilder(); + for (var i = 0; i < count; i++) + { + args[i + 2] = frameIds[start + i]; + placeholders.Append(i > 0 ? ", $" : "$").Append(i + 3); + } + updated += await session.ExecuteAsync($"UPDATE frames SET flags = (flags | $1) & ~$2 WHERE id IN ({placeholders})", + args, cancellationToken).ConfigureAwait(false); + } + return updated; + }, cancellationToken); + + /// Removes every frame of a sequence; returns how many. + public Task DeleteBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("DELETE FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken); + + private static object?[] Values(Frame f) => + [ + f.Id, f.SequenceId, f.Index, f.RelativePath, f.FileName, f.OriginalFileName, f.Size, f.Sha256?.ToLowerInvariant(), + SequenceRepository.Wall(f.CapturedAt), f.UtcOffsetMinutes, (int)f.TimestampSource, f.ExposureTime, f.FNumber, f.Iso, + f.FocalLength, f.ExposureBias, f.WhiteBalance, f.Orientation, f.Width, f.Height, (int)f.Format, f.PreviewOffset, + f.PreviewLength, f.MeanLogLuminance, f.ClipLow, f.ClipHigh, (int)f.Flags, + ]; + + private static Frame Map(DbRow r) => new() + { + Id = r.GetGuid(0), + SequenceId = r.GetGuid(1), + Index = r.GetInt32(2), + RelativePath = r.GetString(3), + FileName = r.GetString(4), + OriginalFileName = r.GetStringOrNull(5), + Size = r.GetInt64(6), + Sha256 = r.GetStringOrNull(7), + CapturedAt = r.GetDateTimeOrNull(8), + UtcOffsetMinutes = r.GetInt32OrNull(9), + TimestampSource = (TimestampSource)r.GetInt32(10), + ExposureTime = r.GetDoubleOrNull(11), + FNumber = r.GetDoubleOrNull(12), + Iso = r.GetInt32OrNull(13), + FocalLength = r.GetDoubleOrNull(14), + ExposureBias = r.GetDoubleOrNull(15), + WhiteBalance = r.GetInt32OrNull(16), + Orientation = r.GetInt32(17), + Width = r.GetInt32(18), + Height = r.GetInt32(19), + Format = (ImageFileFormat)r.GetInt32(20), + PreviewOffset = r.GetInt64OrNull(21), + PreviewLength = r.GetInt64OrNull(22), + MeanLogLuminance = r.GetDoubleOrNull(23), + ClipLow = r.GetDoubleOrNull(24), + ClipHigh = r.GetDoubleOrNull(25), + Flags = (FrameFlags)r.GetInt32(26), + }; +} diff --git a/src/Titano.Data/Repositories/JobRepository.cs b/src/Titano.Data/Repositories/JobRepository.cs new file mode 100644 index 00000000..228a8159 --- /dev/null +++ b/src/Titano.Data/Repositories/JobRepository.cs @@ -0,0 +1,142 @@ +using System.Globalization; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// +/// The persistent job queue (BRIEF §14.6): workers claim the oldest job of the highest priority atomically, +/// write checkpoints while running, and on startup requeue what a crash left running. +/// +public sealed class JobRepository +{ + private const string Columns = + "id, kind, target_ids, target_label, parameters_json, state, priority, progress_done, progress_total, items_per_second, " + + "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished"; + + private readonly DbAccess _db; + + internal JobRepository(DbAccess db) => _db = db; + + public async Task EnqueueAsync(Job job, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + $"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)", + [ + job.Id, (int)job.Kind, string.Join(',', job.TargetIds), job.TargetLabel, DbParam.Json(job.ParametersJson), (int)job.State, + (int)job.Priority, job.ProgressDone, job.ProgressTotal, job.ItemsPerSecond, job.Eta?.TotalSeconds, job.Checkpoint, job.LogTail, + job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, + ], cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken); + + /// + /// Marks the next queued job (highest priority, then oldest) of the given kinds as running for + /// and returns it, or null when none waits. Concurrent claimers never get the same + /// job: PostgreSQL skips rows locked by other claimers, SQLite holds its write lock across select and update. + /// + public Task ClaimNextAsync(string workerId, IReadOnlyCollection? kinds = null, CancellationToken cancellationToken = default) + { + var kindFilter = kinds is { Count: > 0 } + ? " AND kind IN (" + string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))) + ")" + : string.Empty; + var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY priority DESC, created, id LIMIT 1"; + var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1"; + DbParam[] args = [workerId, DateTimeOffset.UtcNow]; + if (_db.Sql.IsPostgres) + return _db.SingleAsync($"{claim} WHERE id = ({pick} FOR UPDATE SKIP LOCKED) RETURNING {Columns}", args, Map, cancellationToken); + + return _db.InTransactionAsync(async session => + { + var id = await session.ScalarAsync(pick, [], cancellationToken).ConfigureAwait(false); + if (id is null) return null; + await session.ExecuteAsync($"{claim} WHERE id = $3", [.. args, id], cancellationToken).ConfigureAwait(false); + return await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + } + + /// + /// Checkpoint of a running job. Returns false when the job is no longer running (cancelled or paused meanwhile), + /// which tells the worker to stop. + /// + public async Task UpdateProgressAsync(Guid id, long done, long total, double? itemsPerSecond, TimeSpan? eta, + string? checkpoint, string? logTail, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE jobs SET progress_done = $2, progress_total = $3, items_per_second = $4, eta_seconds = $5, checkpoint = $6, log_tail = $7 " + + $"WHERE id = $1 AND state = {(int)JobState.Running}", + [id, done, total, itemsPerSecond, eta?.TotalSeconds, checkpoint, logTail], cancellationToken).ConfigureAwait(false) > 0; + + /// Moves a job to ; done/failed/cancelled stamp the finish time, queued clears it for a retry. + public async Task SetStateAsync(Guid id, JobState state, string? error = null, CancellationToken cancellationToken = default) + { + var terminal = state is JobState.Done or JobState.Failed or JobState.Cancelled; + return await _db.ExecuteAsync("UPDATE jobs SET state = $2, error = $3, finished = $4 WHERE id = $1", + [id, (int)state, error, terminal ? DateTimeOffset.UtcNow : (DateTimeOffset?)null], cancellationToken).ConfigureAwait(false) > 0; + } + + /// Jobs, newest first, optionally of one state. + public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = new List(); + if (state is { } s) where.Add($"state = {p.Add((int)s)}"); + if (cursor is not null) + { + var (value, id) = Cursor.Decode("jobs", cursor); + where.Add(Cursor.After("created", "id", descending: true, value, id, p.Add)); + } + var take = Cursor.ClampLimit(limit); + var sql = $"SELECT {Columns} FROM jobs{(where.Count > 0 ? " WHERE " + string.Join(" AND ", where) : string.Empty)} " + + $"ORDER BY created DESC, id DESC LIMIT {p.Add(take + 1)}"; + return _db.RunAsync(async session => + { + var jobs = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false); + string? next = null; + if (jobs.Count > take) + { + jobs.RemoveAt(take); + next = Cursor.Encode("jobs", jobs[^1].Created, jobs[^1].Id); + } + return new Page(jobs, next); + }, cancellationToken); + } + + /// Deletes finished jobs (done, failed, cancelled) that finished before . + public Task PurgeHistoryAsync(DateTimeOffset finishedBefore, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"DELETE FROM jobs WHERE state IN ({(int)JobState.Done}, {(int)JobState.Failed}, {(int)JobState.Cancelled}) AND finished < $1", + [finishedBefore], cancellationToken); + + /// + /// Crash recovery: puts running jobs back in the queue, keeping their checkpoints. With + /// only that worker's jobs are requeued (other server instances keep theirs). + /// + public Task RequeueRunningAsync(string? nodeId = null, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"UPDATE jobs SET state = {(int)JobState.Queued}, node_id = NULL, started = NULL WHERE state = {(int)JobState.Running}" + + (nodeId is null ? string.Empty : " AND node_id = $1"), + nodeId is null ? [] : [nodeId], cancellationToken); + + private static Job Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Kind = (JobKind)r.GetInt32(1), + TargetIds = r.GetString(2) is { Length: > 0 } ids ? Array.ConvertAll(ids.Split(','), Guid.Parse) : [], + TargetLabel = r.GetStringOrNull(3), + ParametersJson = r.GetStringOrNull(4), + State = (JobState)r.GetInt32(5), + Priority = (JobPriority)r.GetInt32(6), + ProgressDone = r.GetInt64(7), + ProgressTotal = r.GetInt64(8), + ItemsPerSecond = r.GetDoubleOrNull(9), + Eta = r.GetDoubleOrNull(10) is { } seconds ? TimeSpan.FromSeconds(seconds) : null, + Checkpoint = r.GetStringOrNull(11), + LogTail = r.GetStringOrNull(12), + CreatedBy = r.GetGuidOrNull(13), + NodeId = r.GetStringOrNull(14), + Attempts = r.GetInt32(15), + Error = r.GetStringOrNull(16), + Created = r.GetDateTimeOffset(17), + Started = r.GetDateTimeOffsetOrNull(18), + Finished = r.GetDateTimeOffsetOrNull(19), + }; +} diff --git a/src/Titano.Data/Repositories/MediaCardRepository.cs b/src/Titano.Data/Repositories/MediaCardRepository.cs new file mode 100644 index 00000000..ab95cc5f --- /dev/null +++ b/src/Titano.Data/Repositories/MediaCardRepository.cs @@ -0,0 +1,125 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// +/// Identity of a file on a card as seen at import: path on the card, size and modification time. Times are +/// truncated to whole microseconds, the precision the database keeps, so keys built from the file system match +/// stored ones. +/// +public readonly record struct ImportKey +{ + public ImportKey(string path, long size, DateTimeOffset modified) + { + Path = path; + Size = size; + Modified = new DateTimeOffset(modified.UtcTicks - modified.UtcTicks % 10, TimeSpan.Zero); + } + + public string Path { get; } + + public long Size { get; } + + public DateTimeOffset Modified { get; } +} + +/// One file imported from a card and where it went. +public sealed record ImportRecord(Guid CardId, ImportKey Key, string? Sha256, Guid? FrameId, Guid? JobId, DateTimeOffset ImportedAt); + +/// Known memory cards and their import history (BRIEF §13), used to skip files already imported. +public sealed class MediaCardRepository +{ + private const string Columns = + "id, identity, volume_serial, label, capacity, nickname, camera_make, camera_model, camera_serial, profile_json, auto_import, first_seen, last_seen"; + + private static readonly string UpsertSql = SqlDialect.Upsert("media_cards", + [ + "id", "identity", "volume_serial", "label", "capacity", "nickname", "camera_make", "camera_model", "camera_serial", + "profile_json", "auto_import", "first_seen", "last_seen", + ], 1); + + private static readonly string RecordSql = SqlDialect.Upsert("import_history", + ["card_id", "path", "size", "mtime", "sha256", "frame_id", "job_id", "imported_at"], 4); + + private readonly DbAccess _db; + + internal MediaCardRepository(DbAccess db) => _db = db; + + public async Task UpsertAsync(MediaCard card, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [ + card.Id, card.Identity, (long)card.VolumeSerial, card.Label, card.Capacity, card.Nickname, card.CameraMake, card.CameraModel, + card.CameraSerial, DbParam.Json(card.ProfileJson), card.AutoImport, card.FirstSeen, card.LastSeen, + ], cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM media_cards WHERE id = $1", [id], Map, cancellationToken); + + /// The card with this {volumeSerial}-{label}-{capacity} identity, if seen before. + public Task FindByIdentityAsync(string identity, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM media_cards WHERE identity = $1", [identity], Map, cancellationToken); + + /// Cards, most recently seen first. + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM media_cards ORDER BY last_seen DESC, id", [], Map, cancellationToken); + + public async Task TouchAsync(Guid id, DateTimeOffset seen, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE media_cards SET last_seen = $2 WHERE id = $1", [id, seen], cancellationToken).ConfigureAwait(false) > 0; + + /// Forgets a card and its import history. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM media_cards WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// Records imported files in one transaction; re-recording a key updates its hash, frame and job. + public Task RecordImportsAsync(IEnumerable records, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var count = 0; + foreach (var r in records) + { + count += await session.ExecuteAsync(RecordSql, + [r.CardId, r.Key.Path, r.Key.Size, r.Key.Modified, r.Sha256?.ToLowerInvariant(), r.FrameId, r.JobId, r.ImportedAt], + cancellationToken).ConfigureAwait(false); + } + return count; + }, cancellationToken); + + /// Keys of every file already imported from the card, for skipping them on re-insert. + public async Task> GetImportedKeysAsync(Guid cardId, CancellationToken cancellationToken = default) + { + var keys = await _db.ListAsync("SELECT path, size, mtime FROM import_history WHERE card_id = $1", [cardId], + r => new ImportKey(r.GetString(0), r.GetInt64(1), r.GetDateTimeOffset(2)), cancellationToken).ConfigureAwait(false); + return keys.ToHashSet(); + } + + public async Task IsImportedAsync(Guid cardId, ImportKey key, CancellationToken cancellationToken = default) => + await _db.ScalarAsync("SELECT 1 FROM import_history WHERE card_id = $1 AND path = $2 AND size = $3 AND mtime = $4", + [cardId, key.Path, key.Size, key.Modified], cancellationToken).ConfigureAwait(false) is not null; + + /// Most recent imports from a card. + public Task> ListImportsAsync(Guid cardId, int limit = 1000, CancellationToken cancellationToken = default) => + _db.ListAsync( + "SELECT card_id, path, size, mtime, sha256, frame_id, job_id, imported_at FROM import_history WHERE card_id = $1 " + + "ORDER BY imported_at DESC, path LIMIT $2", + [cardId, Cursor.ClampLimit(limit)], + r => new ImportRecord(r.GetGuid(0), new ImportKey(r.GetString(1), r.GetInt64(2), r.GetDateTimeOffset(3)), + r.GetStringOrNull(4), r.GetGuidOrNull(5), r.GetGuidOrNull(6), r.GetDateTimeOffset(7)), + cancellationToken); + + private static MediaCard Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Identity = r.GetString(1), + VolumeSerial = checked((uint)r.GetInt64(2)), + Label = r.GetStringOrNull(3), + Capacity = r.GetInt64(4), + Nickname = r.GetStringOrNull(5), + CameraMake = r.GetStringOrNull(6), + CameraModel = r.GetStringOrNull(7), + CameraSerial = r.GetStringOrNull(8), + ProfileJson = r.GetStringOrNull(9), + AutoImport = r.GetBool(10), + FirstSeen = r.GetDateTimeOffset(11), + LastSeen = r.GetDateTimeOffset(12), + }; +} diff --git a/src/Titano.Data/Repositories/RenderNodeRepository.cs b/src/Titano.Data/Repositories/RenderNodeRepository.cs new file mode 100644 index 00000000..898f1500 --- /dev/null +++ b/src/Titano.Data/Repositories/RenderNodeRepository.cs @@ -0,0 +1,49 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Clients offering their PC as render node (BRIEF §14.7). +public sealed class RenderNodeRepository +{ + private const string Columns = "id, user_id, client_name, capabilities_json, last_heartbeat, state"; + + private static readonly string UpsertSql = SqlDialect.Upsert("render_nodes", + ["id", "user_id", "client_name", "capabilities_json", "last_heartbeat", "state"], 1); + + private readonly DbAccess _db; + + internal RenderNodeRepository(DbAccess db) => _db = db; + + /// Registers a node or refreshes its client name, capabilities and state. + public async Task RegisterAsync(RenderNode node, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [node.Id, node.UserId, node.ClientName, DbParam.Json(node.CapabilitiesJson), node.LastHeartbeat, node.State], + cancellationToken).ConfigureAwait(false); + + public async Task HeartbeatAsync(Guid id, string state, DateTimeOffset at, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE render_nodes SET last_heartbeat = $2, state = $3 WHERE id = $1", [id, at, state], cancellationToken) + .ConfigureAwait(false) > 0; + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM render_nodes WHERE id = $1", [id], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM render_nodes ORDER BY client_name, id", [], Map, cancellationToken); + + /// Nodes whose last heartbeat is at or after , most recent first. + public Task> ListOnlineAsync(DateTimeOffset since, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM render_nodes WHERE last_heartbeat >= $1 ORDER BY last_heartbeat DESC, id", [since], Map, cancellationToken); + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM render_nodes WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static RenderNode Map(DbRow r) => new() + { + Id = r.GetGuid(0), + UserId = r.GetGuid(1), + ClientName = r.GetString(2), + CapabilitiesJson = r.GetStringOrNull(3), + LastHeartbeat = r.GetDateTimeOffset(4), + State = r.GetString(5), + }; +} diff --git a/src/Titano.Data/Repositories/RenderRepository.cs b/src/Titano.Data/Repositories/RenderRepository.cs new file mode 100644 index 00000000..98448d28 --- /dev/null +++ b/src/Titano.Data/Repositories/RenderRepository.cs @@ -0,0 +1,62 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Exports of sequences; keeps sequences.rendered_count in step. +public sealed class RenderRepository +{ + private const string Columns = + "id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by"; + + private const string RecountSql = + "UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1"; + + private readonly DbAccess _db; + + internal RenderRepository(DbAccess db) => _db = db; + + public Task InsertAsync(Render render, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", + [ + render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec, + render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy, + ], cancellationToken).ConfigureAwait(false); + return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM renders WHERE id = $1", [id], Map, cancellationToken); + + /// Renders of a sequence, newest first. + public Task> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM renders WHERE sequence_id = $1 ORDER BY created DESC, id DESC", [sequenceId], Map, cancellationToken); + + public Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var sequenceId = await session.ScalarAsync("SELECT sequence_id FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false); + if (sequenceId is null) return false; + await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync(RecountSql, [sequenceId], cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + + private static Render Map(DbRow r) => new() + { + Id = r.GetGuid(0), + SequenceId = r.GetGuid(1), + PresetName = r.GetString(2), + SettingsJson = r.GetStringOrNull(3), + OutputPath = r.GetString(4), + Codec = r.GetStringOrNull(5), + Width = r.GetInt32(6), + Height = r.GetInt32(7), + Fps = r.GetDouble(8), + DurationSeconds = r.GetDouble(9), + Bytes = r.GetInt64(10), + Created = r.GetDateTimeOffset(11), + ProducedBy = r.GetStringOrNull(12), + }; +} diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs new file mode 100644 index 00000000..422ad364 --- /dev/null +++ b/src/Titano.Data/Repositories/SequenceRepository.cs @@ -0,0 +1,369 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Orderings of the Library; every one is keyset-paginated with the sequence id as tie-breaker. +public enum SequenceSort +{ + /// Latest first capture first; sequences without captures last. + Newest, + Oldest, + + /// Display title, case-insensitive. + Title, + FrameCount, + Size, +} + +/// Library filters (all optional, combined with AND) plus sort and page. +public sealed record SequenceQuery +{ + public Guid? ArchiveId { get; init; } + + /// Calendar year of the first capture. + public int? Year { get; init; } + + /// Exact camera model. + public string? Camera { get; init; } + + /// Status flags that must all be set. + public SequenceStatus WithStatus { get; init; } + + /// Status flags that must all be clear. + public SequenceStatus WithoutStatus { get; init; } + + public string? Tag { get; init; } + + /// Case-insensitive substring of the title, camera make/model or a tag. + public string? Text { get; init; } + + public Guid? OwnerUserId { get; init; } + + public SequenceSort Sort { get; init; } = SequenceSort.Newest; + + /// Page size, 1–1000. + public int Limit { get; init; } = 100; + + /// of the previous page, or null for the first page. + public string? Cursor { get; init; } +} + +/// Figures of the Archive screen (BRIEF §12.5). +public sealed record ArchiveStats( + int Sequences, + long Photos, + long Bytes, + IReadOnlyList ByYear, + IReadOnlyList ByMonth, + IReadOnlyList ByCamera, + IReadOnlyList ByFormat, + ArchiveHealth Health); + +public sealed record YearBucket(int Year, int Sequences, long Photos, long Bytes); + +/// One heatmap cell: sequences and photos whose first capture falls in the month. +public sealed record MonthBucket(int Year, int Month, int Sequences, long Photos); + +public sealed record CameraBucket(string? Make, string? Model, int Sequences, long Photos, long Bytes); + +public sealed record FormatBucket(ImageFileFormat Format, long Photos, long Bytes); + +/// Health counters: sequences needing attention and flagged frames. +public sealed record ArchiveHealth( + int Unverified, + int WithWarnings, + int WithErrors, + int NotAnalyzed, + long MissingFrames, + long CorruptFrames, + long DuplicateFrames); + +/// Sequences (projects) with their tags; Library listing and Archive statistics. +public sealed class SequenceRepository +{ + private const string Columns = + "s.id, s.archive_id, s.title, s.folder, s.camera_make, s.camera_model, s.camera_serial, s.lens, s.first_capture, s.last_capture, " + + "s.frame_count, s.median_interval, s.total_bytes, s.status, s.rendered_count, s.verified_at, s.hero_frame_id, s.rating, s.notes, " + + "s.settings_json, s.analysis_json, s.origin, s.sync_state, s.settings_version, s.frames_version, s.owner_user_id, s.warning_count, s.updated_at"; + + private static readonly string UpsertSql = SqlDialect.Upsert("sequences", + [ + "id", "archive_id", "title", "title_key", "search_text", "folder", "camera_make", "camera_model", "camera_serial", "lens", + "first_capture", "last_capture", "frame_count", "median_interval", "total_bytes", "status", "rendered_count", "verified_at", + "hero_frame_id", "rating", "notes", "settings_json", "analysis_json", "origin", "sync_state", "settings_version", + "frames_version", "owner_user_id", "warning_count", "updated_at", + ], 1); + + /// Ordinal of the tag list after , and of the sort key a listing appends after it. + private const int TagsOrdinal = 28; + private const int SortKeyOrdinal = 29; + + private readonly DbAccess _db; + private readonly string _select; + + internal SequenceRepository(DbAccess db) + { + _db = db; + _select = SelectSql(string.Empty); + } + + private string SelectSql(string extraColumns) => + $"SELECT {Columns}, (SELECT {_db.Sql.StringAgg("t.name")} FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id) AS tags{extraColumns} FROM sequences s"; + + /// Inserts or replaces the sequence row and its tag set. + public Task UpsertAsync(Sequence sequence, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + await UpsertRowAsync(session, sequence, cancellationToken).ConfigureAwait(false); + await ReplaceTagsAsync(session, sequence.Id, sequence.Tags, cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken); + + /// Deletes the sequence with its frames, renders and tag links. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// Replaces the tags of a sequence (trimmed, de-duplicated case-insensitively). + public async Task SetTagsAsync(Guid id, IEnumerable tags, CancellationToken cancellationToken = default) => + await _db.InTransactionAsync(async session => + { + if (await session.ScalarAsync("SELECT id FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) is null) + return false; + await ReplaceTagsAsync(session, id, tags, cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync("UPDATE sequences SET settings_version = settings_version + 1, updated_at = $2 WHERE id = $1", + [id, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken).ConfigureAwait(false); + + /// Sets and clears status flags in one statement. + public async Task UpdateStatusAsync(Guid id, SequenceStatus set, SequenceStatus clear, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE sequences SET status = (status | $2) & ~$3, updated_at = $4 WHERE id = $1", + [id, (int)set, (int)clear, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0; + + /// Recomputes frame count, total bytes and first/last capture from the frames table. + public Task RefreshStatsAsync(Guid id, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken).ConfigureAwait(false); + if (current is null) return null; + var stats = await session.QuerySingleAsync( + "SELECT count(*), COALESCE(SUM(size), 0), MIN(captured_at), MAX(captured_at) FROM frames WHERE sequence_id = $1", + [id], cancellationToken).ConfigureAwait(false); + var updated = current with + { + FrameCount = (int)stats.GetInt64(0), + TotalBytes = stats.GetInt64(1), + FirstCapture = stats.GetDateTimeOrNull(2), + LastCapture = stats.GetDateTimeOrNull(3), + FramesVersion = current.FramesVersion + 1, + UpdatedAt = DateTimeOffset.UtcNow, + }; + await UpsertRowAsync(session, updated, cancellationToken).ConfigureAwait(false); + return updated; + }, cancellationToken); + + /// One page of sequences matching . + public Task> ListAsync(SequenceQuery query, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = Filter(query, p); + var (column, descending) = SortKey(query.Sort); + var scope = "seq:" + query.Sort; + if (query.Cursor is not null) + { + var (value, id) = Cursor.Decode(scope, query.Cursor); + where.Add(Cursor.After(column, "s.id", descending, value, id, p.Add)); + } + var limit = Cursor.ClampLimit(query.Limit); + var direction = descending ? "DESC" : "ASC"; + var sql = $"{SelectSql($", {column} AS sort_key")}{Where(where)} " + + $"ORDER BY {column} {direction} NULLS LAST, s.id {direction} LIMIT {p.Add(limit + 1)}"; + return _db.RunAsync(async session => + { + var rows = await session.QueryListAsync(sql, p.ToArray(), r => (Item: Map(r), Key: SortValue(query.Sort, r)), cancellationToken).ConfigureAwait(false); + string? next = null; + if (rows.Count > limit) + { + rows.RemoveAt(limit); + next = Cursor.Encode(scope, rows[^1].Key, rows[^1].Item.Id); + } + return new Page(rows.ConvertAll(r => r.Item), next); + }, cancellationToken); + } + + /// Number of sequences matching the filters of (sort and page ignored). + public async Task CountAsync(SequenceQuery query, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = Filter(query, p); + return (int)await _db.ScalarAsync($"SELECT count(*) FROM sequences s{Where(where)}", p.ToArray(), cancellationToken).ConfigureAwait(false); + } + + /// Totals, distributions and health counters of one archive, or of all archives. + public Task GetStatsAsync(Guid? archiveId = null, CancellationToken cancellationToken = default) + { + var sql = _db.Sql; + DbParam[] args = archiveId is { } a ? [a] : []; + var seqWhere = archiveId is null ? string.Empty : " WHERE s.archive_id = $1"; + var seqAnd = archiveId is null ? " WHERE" : " WHERE s.archive_id = $1 AND"; + var frameFrom = archiveId is null ? "frames f" : "frames f JOIN sequences s ON s.id = f.sequence_id WHERE s.archive_id = $1"; + var year = sql.Year("s.first_capture"); + return _db.RunAsync(async session => + { + var totals = await session.QuerySingleAsync( + $"SELECT count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) FROM sequences s{seqWhere}", + args, cancellationToken).ConfigureAwait(false); + var byYear = await session.QueryListAsync( + $"SELECT {year}, count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) FROM sequences s" + + $"{seqAnd} s.first_capture IS NOT NULL GROUP BY 1 ORDER BY 1", args, + r => new YearBucket(r.GetInt32(0), r.GetInt32(1), r.GetInt64(2), r.GetInt64(3)), cancellationToken).ConfigureAwait(false); + var byMonth = await session.QueryListAsync( + $"SELECT {year}, {sql.Month("s.first_capture")}, count(*), COALESCE(SUM(s.frame_count), 0) FROM sequences s" + + $"{seqAnd} s.first_capture IS NOT NULL GROUP BY 1, 2 ORDER BY 1, 2", args, + r => new MonthBucket(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt64(3)), cancellationToken).ConfigureAwait(false); + var byCamera = await session.QueryListAsync( + $"SELECT s.camera_make, s.camera_model, count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) " + + $"FROM sequences s{seqWhere} GROUP BY s.camera_make, s.camera_model ORDER BY 4 DESC, 2 NULLS LAST, 1 NULLS LAST", args, + r => new CameraBucket(r.GetStringOrNull(0), r.GetStringOrNull(1), r.GetInt32(2), r.GetInt64(3), r.GetInt64(4)), cancellationToken).ConfigureAwait(false); + var byFormat = await session.QueryListAsync( + $"SELECT f.format, count(*), COALESCE(SUM(f.size), 0) FROM {frameFrom} GROUP BY f.format ORDER BY 2 DESC, 1", args, + r => new FormatBucket((ImageFileFormat)r.GetInt32(0), r.GetInt64(1), r.GetInt64(2)), cancellationToken).ConfigureAwait(false); + var sequenceHealth = await session.QuerySingleAsync( + "SELECT " + + "COALESCE(SUM(CASE WHEN s.verified_at IS NULL THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.HasWarnings}) <> 0 OR s.warning_count > 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.HasErrors}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.AnalyzedLight}) = 0 THEN 1 ELSE 0 END), 0) " + + $"FROM sequences s{seqWhere}", args, cancellationToken).ConfigureAwait(false); + var frameHealth = await session.QuerySingleAsync( + "SELECT " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Missing}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Corrupt}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Duplicate}) <> 0 THEN 1 ELSE 0 END), 0) " + + $"FROM {frameFrom}", args, cancellationToken).ConfigureAwait(false); + return new ArchiveStats( + totals.GetInt32(0), totals.GetInt64(1), totals.GetInt64(2), byYear, byMonth, byCamera, byFormat, + new ArchiveHealth( + sequenceHealth.GetInt32(0), sequenceHealth.GetInt32(1), sequenceHealth.GetInt32(2), sequenceHealth.GetInt32(3), + frameHealth.GetInt64(0), frameHealth.GetInt64(1), frameHealth.GetInt64(2))); + }, cancellationToken); + } + + private static List Filter(SequenceQuery query, SqlParameters p) + { + var where = new List(); + if (query.ArchiveId is { } archive) where.Add($"s.archive_id = {p.Add(archive)}"); + if (query.Year is { } year) + where.Add($"s.first_capture >= {p.Add(new DateTime(year, 1, 1))} AND s.first_capture < {p.Add(new DateTime(year + 1, 1, 1))}"); + if (query.Camera is { } camera) where.Add($"s.camera_model = {p.Add(camera)}"); + if (query.WithStatus != SequenceStatus.None) + { + var mask = p.Add((int)query.WithStatus); + where.Add($"(s.status & {mask}) = {mask}"); + } + if (query.WithoutStatus != SequenceStatus.None) where.Add($"(s.status & {p.Add((int)query.WithoutStatus)}) = 0"); + if (query.Tag is { } tag) + where.Add("EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id AND t.name_key = {p.Add(TagRepository.Key(tag))})"); + if (!string.IsNullOrWhiteSpace(query.Text)) + { + var pattern = p.Add(SqlDialect.ContainsPattern(query.Text.Trim().ToLowerInvariant())); + where.Add($"(s.search_text LIKE {pattern} ESCAPE '\\' OR EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id AND t.name_key LIKE {pattern} ESCAPE '\\'))"); + } + if (query.OwnerUserId is { } owner) where.Add($"s.owner_user_id = {p.Add(owner)}"); + return where; + } + + private static string Where(List conditions) => + conditions.Count == 0 ? string.Empty : " WHERE " + string.Join(" AND ", conditions); + + private static (string Column, bool Descending) SortKey(SequenceSort sort) => sort switch + { + SequenceSort.Newest => ("s.first_capture", true), + SequenceSort.Oldest => ("s.first_capture", false), + SequenceSort.Title => ("s.title_key", false), + SequenceSort.FrameCount => ("s.frame_count", true), + SequenceSort.Size => ("s.total_bytes", true), + _ => throw new ArgumentOutOfRangeException(nameof(sort), sort, null), + }; + + private static object? SortValue(SequenceSort sort, DbRow row) => sort switch + { + SequenceSort.Newest or SequenceSort.Oldest => row.GetDateTimeOrNull(SortKeyOrdinal), + SequenceSort.Title => row.GetString(SortKeyOrdinal), + _ => row.GetInt64(SortKeyOrdinal), + }; + + private static Task UpsertRowAsync(IDbSession session, Sequence s, CancellationToken cancellationToken) + { + var search = string.Join(' ', new[] { s.Title, s.CameraMake, s.CameraModel }.Where(v => !string.IsNullOrWhiteSpace(v))).ToLowerInvariant(); + return session.ExecuteAsync(UpsertSql, + [ + s.Id, s.ArchiveId, s.Title, s.DisplayTitle.ToLowerInvariant(), search, s.Folder, s.CameraMake, s.CameraModel, s.CameraSerial, s.Lens, + Wall(s.FirstCapture), Wall(s.LastCapture), s.FrameCount, s.MedianInterval, s.TotalBytes, (int)s.Status, s.RenderedCount, s.VerifiedAt, + s.HeroFrameId, s.Rating, s.Notes, DbParam.Json(s.SettingsJson), DbParam.Json(s.AnalysisJson), (int)s.Origin, (int)s.SyncState, + s.SettingsVersion, s.FramesVersion, s.OwnerUserId, s.WarningCount, s.UpdatedAt, + ], cancellationToken); + } + + private static async Task ReplaceTagsAsync(IDbSession session, Guid sequenceId, IEnumerable tags, CancellationToken cancellationToken) + { + await session.ExecuteAsync("DELETE FROM sequence_tags WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false); + foreach (var tag in TagRepository.NormalizeSet(tags)) + { + var key = TagRepository.Key(tag); + await session.ExecuteAsync("INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO NOTHING", + [Guid.CreateVersion7(), tag, key], cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync("INSERT INTO sequence_tags (sequence_id, tag_id) SELECT $1, id FROM tags WHERE name_key = $2", + [sequenceId, key], cancellationToken).ConfigureAwait(false); + } + } + + /// Camera wall-clock times are stored without zone, whatever kind the caller's value has. + internal static DateTime? Wall(DateTime? value) => + value is { } v ? DateTime.SpecifyKind(v, DateTimeKind.Unspecified) : null; + + private static Sequence Map(DbRow r) + { + var tags = r.GetStringOrNull(TagsOrdinal) is { Length: > 0 } list ? list.Split(SqlDialect.ListSeparator) : []; + Array.Sort(tags, StringComparer.OrdinalIgnoreCase); + return new Sequence + { + Id = r.GetGuid(0), + ArchiveId = r.GetGuid(1), + Title = r.GetStringOrNull(2), + Folder = r.GetString(3), + CameraMake = r.GetStringOrNull(4), + CameraModel = r.GetStringOrNull(5), + CameraSerial = r.GetStringOrNull(6), + Lens = r.GetStringOrNull(7), + FirstCapture = r.GetDateTimeOrNull(8), + LastCapture = r.GetDateTimeOrNull(9), + FrameCount = r.GetInt32(10), + MedianInterval = r.GetDoubleOrNull(11), + TotalBytes = r.GetInt64(12), + Status = (SequenceStatus)r.GetInt32(13), + RenderedCount = r.GetInt32(14), + VerifiedAt = r.GetDateTimeOffsetOrNull(15), + HeroFrameId = r.GetGuidOrNull(16), + Rating = r.GetInt32(17), + Notes = r.GetStringOrNull(18), + SettingsJson = r.GetStringOrNull(19), + AnalysisJson = r.GetStringOrNull(20), + Origin = (SequenceOrigin)r.GetInt32(21), + SyncState = (SyncState)r.GetInt32(22), + SettingsVersion = r.GetInt32(23), + FramesVersion = r.GetInt32(24), + OwnerUserId = r.GetGuidOrNull(25), + WarningCount = r.GetInt32(26), + UpdatedAt = r.GetDateTimeOffset(27), + Tags = tags, + }; + } +} diff --git a/src/Titano.Data/Repositories/SettingsRepository.cs b/src/Titano.Data/Repositories/SettingsRepository.cs new file mode 100644 index 00000000..73c56ca3 --- /dev/null +++ b/src/Titano.Data/Repositories/SettingsRepository.cs @@ -0,0 +1,93 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace Titano.Data.Repositories; + +/// Who a setting belongs to. +public enum SettingScope +{ + /// The installation (client app or server); no scope id. + App, + + /// One archive; the scope id is the archive id. + Archive, + + /// One user; the scope id is the user id. + User, +} + +/// Typed key/value settings stored as JSON (BRIEF §5 Setting). +public sealed class SettingsRepository +{ + private static readonly string UpsertSql = SqlDialect.Upsert("settings", ["scope", "scope_id", "key", "value_json", "updated_at"], 3); + + private readonly DbAccess _db; + + internal SettingsRepository(DbAccess db) => _db = db; + + /// The raw JSON of a setting, or null when unset. + public Task GetJsonAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => + _db.ScalarAsync("SELECT value_json FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", + [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken); + + /// Stores a JSON value; malformed JSON is rejected on both dialects. + public async Task SetJsonAsync(SettingScope scope, Guid? scopeId, string key, string json, CancellationToken cancellationToken = default) + { + using (JsonDocument.Parse(json)) + { + } + await _db.ExecuteAsync(UpsertSql, [ScopeName(scope), ScopeId(scope, scopeId), key, DbParam.Json(json), DateTimeOffset.UtcNow], cancellationToken) + .ConfigureAwait(false); + } + + /// Reads a setting with source-generated metadata (trim/AOT safe); default when unset. + public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => + await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json + ? JsonSerializer.Deserialize(json, typeInfo) + : default; + + public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => + SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, typeInfo), cancellationToken); + + /// Reads a setting through reflection-based serialization; default when unset. + [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] + [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] + public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => + await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json + ? JsonSerializer.Deserialize(json, options) + : default; + + [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] + [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] + public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => + SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, options), cancellationToken); + + public async Task DeleteAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", + [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken).ConfigureAwait(false) > 0; + + /// Every setting of a scope as key → JSON. + public async Task> ListAsync(SettingScope scope, Guid? scopeId, CancellationToken cancellationToken = default) + { + var rows = await _db.ListAsync("SELECT key, value_json FROM settings WHERE scope = $1 AND scope_id = $2 ORDER BY key", + [ScopeName(scope), ScopeId(scope, scopeId)], r => KeyValuePair.Create(r.GetString(0), r.GetString(1)), cancellationToken).ConfigureAwait(false); + return new Dictionary(rows, StringComparer.Ordinal); + } + + private static string ScopeName(SettingScope scope) => scope switch + { + SettingScope.App => "app", + SettingScope.Archive => "archive", + SettingScope.User => "user", + _ => throw new ArgumentOutOfRangeException(nameof(scope), scope, null), + }; + + private static string ScopeId(SettingScope scope, Guid? scopeId) => (scope, scopeId) switch + { + (SettingScope.App, null) => string.Empty, + (SettingScope.App, _) => throw new ArgumentException("App settings have no scope id.", nameof(scopeId)), + (_, { } id) => TextValues.FormatGuid(id), + _ => throw new ArgumentException($"{scope} settings need a scope id.", nameof(scopeId)), + }; +} diff --git a/src/Titano.Data/Repositories/TagRepository.cs b/src/Titano.Data/Repositories/TagRepository.cs new file mode 100644 index 00000000..07de96ce --- /dev/null +++ b/src/Titano.Data/Repositories/TagRepository.cs @@ -0,0 +1,79 @@ +using System.Text; + +namespace Titano.Data.Repositories; + +/// A tag and how many sequences carry it. +public sealed record TagInfo(Guid Id, string Name, int SequenceCount); + +/// +/// Normalised tags (BRIEF §5 Tag/SequenceTag): one row per case-insensitive name, linked to sequences through +/// sequence_tags. The first spelling of a name is kept. +/// +public sealed class TagRepository +{ + /// Longest tag name accepted, in characters. + public const int MaxLength = 64; + + private readonly DbAccess _db; + + internal TagRepository(DbAccess db) => _db = db; + + /// All tags by name with their usage counts. + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync( + "SELECT t.id, t.name, (SELECT count(*) FROM sequence_tags st WHERE st.tag_id = t.id) FROM tags t ORDER BY t.name_key", + [], r => new TagInfo(r.GetGuid(0), r.GetString(1), r.GetInt32(2)), cancellationToken); + + /// Renames a tag; a name already used by another tag violates the unique key (). + public async Task RenameAsync(Guid id, string name, CancellationToken cancellationToken = default) + { + var normalized = Normalize(name); + return await _db.ExecuteAsync("UPDATE tags SET name = $2, name_key = $3 WHERE id = $1", + [id, normalized, Key(normalized)], cancellationToken).ConfigureAwait(false) > 0; + } + + /// Deletes a tag and removes it from every sequence. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM tags WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// Deletes tags no sequence uses any more; returns how many. + public Task DeleteUnusedAsync(CancellationToken cancellationToken = default) => + _db.ExecuteAsync("DELETE FROM tags WHERE NOT EXISTS (SELECT 1 FROM sequence_tags st WHERE st.tag_id = tags.id)", [], cancellationToken); + + /// Trims, collapses inner whitespace and validates a tag name. + public static string Normalize(string name) + { + var sb = new StringBuilder(name.Length); + foreach (var c in name.Trim()) + { + if (char.IsControl(c)) throw new ArgumentException("Tags cannot contain control characters.", nameof(name)); + if (char.IsWhiteSpace(c)) + { + if (sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); + } + else + { + sb.Append(c); + } + } + if (sb.Length == 0) throw new ArgumentException("A tag cannot be empty.", nameof(name)); + if (sb.Length > MaxLength) throw new ArgumentException($"A tag is at most {MaxLength} characters.", nameof(name)); + return sb.ToString(); + } + + /// The case-insensitive identity of a tag name. + public static string Key(string name) => Normalize(name).ToLowerInvariant(); + + /// Normalised tags without case-insensitive duplicates, first spelling kept. + internal static List NormalizeSet(IEnumerable tags) + { + var seen = new HashSet(StringComparer.Ordinal); + var result = new List(); + foreach (var tag in tags) + { + var normalized = Normalize(tag); + if (seen.Add(normalized.ToLowerInvariant())) result.Add(normalized); + } + return result; + } +} diff --git a/src/Titano.Data/Repositories/TokenRepository.cs b/src/Titano.Data/Repositories/TokenRepository.cs new file mode 100644 index 00000000..8b88c0fc --- /dev/null +++ b/src/Titano.Data/Repositories/TokenRepository.cs @@ -0,0 +1,57 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// API session tokens, stored by SHA-256 hash, with sliding expiry and revocation (BRIEF §14.2). +public sealed class TokenRepository +{ + private const string Columns = "token_hash, user_id, client_name, created, expires, last_used, revoked"; + + private readonly DbAccess _db; + + internal TokenRepository(DbAccess db) => _db = db; + + public async Task InsertAsync(SessionToken token, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync($"INSERT INTO tokens ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7)", + [token.TokenHash, token.UserId, token.ClientName, token.Created, token.Expires, token.LastUsed, token.Revoked], + cancellationToken).ConfigureAwait(false); + + /// The token with this hash, revoked or expired ones included (the caller decides). + public Task GetAsync(string tokenHash, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM tokens WHERE token_hash = $1", [tokenHash], Map, cancellationToken); + + /// + /// Sliding expiry: records use at and moves the expiry to . + /// Returns false for unknown, revoked or already expired tokens. + /// + public async Task TouchAsync(string tokenHash, DateTimeOffset now, DateTimeOffset expires, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE tokens SET last_used = $2, expires = $3 WHERE token_hash = $1 AND revoked = FALSE AND expires > $2", + [tokenHash, now, expires], cancellationToken).ConfigureAwait(false) > 0; + + public async Task RevokeAsync(string tokenHash, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE token_hash = $1 AND revoked = FALSE", [tokenHash], cancellationToken) + .ConfigureAwait(false) > 0; + + /// Revokes every live token of a user (password change, account disabled). + public Task RevokeAllAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE", [userId], cancellationToken); + + public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM tokens WHERE user_id = $1 ORDER BY last_used DESC", [userId], Map, cancellationToken); + + /// Deletes tokens that expired by or were revoked. + public Task PurgeAsync(DateTimeOffset now, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("DELETE FROM tokens WHERE expires <= $1 OR revoked = TRUE", [now], cancellationToken); + + private static SessionToken Map(DbRow r) => new() + { + TokenHash = r.GetString(0), + UserId = r.GetGuid(1), + ClientName = r.GetStringOrNull(2), + Created = r.GetDateTimeOffset(3), + Expires = r.GetDateTimeOffset(4), + LastUsed = r.GetDateTimeOffset(5), + Revoked = r.GetBool(6), + }; +} diff --git a/src/Titano.Data/Repositories/UploadRepository.cs b/src/Titano.Data/Repositories/UploadRepository.cs new file mode 100644 index 00000000..355511ec --- /dev/null +++ b/src/Titano.Data/Repositories/UploadRepository.cs @@ -0,0 +1,135 @@ +namespace Titano.Data.Repositories; + +/// Life cycle of a resumable upload (BRIEF §14.4). +public enum UploadState +{ + /// Chunks are arriving. + Receiving, + + /// All chunks are in; the server is verifying the hash and moving the file into the archive. + Committing, + + /// The file is a frame of the archive (). + Committed, + Failed, + Cancelled, +} + +/// A chunked upload and its received-chunk bitmap (bit n of byte n/8, least significant first). +public sealed record Upload +{ + public required Guid Id { get; init; } + public required Guid UserId { get; init; } + public Guid? SequenceId { get; init; } + public required string FileName { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 announced by the client. + public required string Sha256 { get; init; } + + public DateTime? CapturedAt { get; init; } + public required int ChunkSize { get; init; } + public byte[] Received { get; init; } = []; + public int ReceivedCount { get; init; } + public UploadState State { get; init; } + public Guid? FrameId { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset UpdatedAt { get; init; } + + public int ChunkCount => (int)((Size + ChunkSize - 1) / ChunkSize); + + public bool IsComplete => ReceivedCount >= ChunkCount; + + public bool HasChunk(int index) => + index >= 0 && index / 8 < Received.Length && (Received[index / 8] & (1 << (index % 8))) != 0; +} + +/// Resumable uploads: creation, per-chunk bookkeeping, state changes and cleanup. +public sealed class UploadRepository +{ + private const string Columns = + "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at"; + + private readonly DbAccess _db; + + internal UploadRepository(DbAccess db) => _db = db; + + /// Stores a new upload with an empty bitmap sized for its chunk count. + public async Task CreateAsync(Upload upload, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(upload.ChunkSize, 1); + ArgumentOutOfRangeException.ThrowIfNegative(upload.Size); + var stored = upload with { Received = new byte[(upload.ChunkCount + 7) / 8], ReceivedCount = 0, Sha256 = upload.Sha256.ToLowerInvariant() }; + await _db.ExecuteAsync( + $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)", + [ + stored.Id, stored.UserId, stored.SequenceId, stored.FileName, stored.Size, stored.Sha256, SequenceRepository.Wall(stored.CapturedAt), + stored.ChunkSize, stored.Received, 0, (int)stored.State, stored.FrameId, stored.Created, stored.UpdatedAt, + ], cancellationToken).ConfigureAwait(false); + return stored; + } + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM uploads WHERE id = $1", [id], Map, cancellationToken); + + /// An upload of the same content by the same user that is still receiving, so a client can resume it. + public Task FindReceivingAsync(Guid userId, string sha256, CancellationToken cancellationToken = default) => + _db.SingleAsync( + $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} ORDER BY created DESC LIMIT 1", + [userId, sha256.ToLowerInvariant()], Map, cancellationToken); + + /// + /// Marks chunk as received (idempotent; concurrent chunks of one upload serialise on + /// its row) and returns the updated upload, or null when it does not exist. + /// + public Task MarkChunkReceivedAsync(Guid id, int index, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var upload = await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM uploads WHERE id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken) + .ConfigureAwait(false); + if (upload is null) return null; + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, upload.ChunkCount); + if (upload.HasChunk(index)) return upload; + var bitmap = (byte[])upload.Received.Clone(); + bitmap[index / 8] |= (byte)(1 << (index % 8)); + var updated = upload with { Received = bitmap, ReceivedCount = upload.ReceivedCount + 1, UpdatedAt = DateTimeOffset.UtcNow }; + await session.ExecuteAsync("UPDATE uploads SET received = $2, received_count = $3, updated_at = $4 WHERE id = $1", + [id, bitmap, updated.ReceivedCount, updated.UpdatedAt], cancellationToken).ConfigureAwait(false); + return updated; + }, cancellationToken); + + /// Moves an upload to , recording the frame it became when committed. + public async Task SetStateAsync(Guid id, UploadState state, Guid? frameId = null, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE uploads SET state = $2, frame_id = COALESCE($3, frame_id), updated_at = $4 WHERE id = $1", + [id, (int)state, frameId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0; + + public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM uploads WHERE user_id = $1 ORDER BY created DESC", [userId], Map, cancellationToken); + + /// Uploads still receiving but untouched since (abandoned; their part files can go). + public Task> ListStaleAsync(DateTimeOffset updatedBefore, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM uploads WHERE state = {(int)UploadState.Receiving} AND updated_at < $1 ORDER BY updated_at", + [updatedBefore], Map, cancellationToken); + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM uploads WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static Upload Map(DbRow r) => new() + { + Id = r.GetGuid(0), + UserId = r.GetGuid(1), + SequenceId = r.GetGuidOrNull(2), + FileName = r.GetString(3), + Size = r.GetInt64(4), + Sha256 = r.GetString(5), + CapturedAt = r.GetDateTimeOrNull(6), + ChunkSize = r.GetInt32(7), + Received = r.GetBytes(8), + ReceivedCount = r.GetInt32(9), + State = (UploadState)r.GetInt32(10), + FrameId = r.GetGuidOrNull(11), + Created = r.GetDateTimeOffset(12), + UpdatedAt = r.GetDateTimeOffset(13), + }; +} diff --git a/src/Titano.Data/Repositories/UserRepository.cs b/src/Titano.Data/Repositories/UserRepository.cs new file mode 100644 index 00000000..4fe75107 --- /dev/null +++ b/src/Titano.Data/Repositories/UserRepository.cs @@ -0,0 +1,75 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Server accounts. User names are unique case-insensitively. +public sealed class UserRepository +{ + private const string Columns = + "id, username, display_name, password_hash, role, permissions, quota_bytes, used_bytes, disabled, must_change_password, created, last_login"; + + private readonly DbAccess _db; + + internal UserRepository(DbAccess db) => _db = db; + + /// Adds a user; a taken name raises a with . + public async Task CreateAsync(User user, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "INSERT INTO users (id, username, username_key, display_name, password_hash, role, permissions, quota_bytes, used_bytes, " + + "disabled, must_change_password, created, last_login) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", + [ + user.Id, user.Username, Key(user.Username), user.DisplayName, user.PasswordHash, (int)user.Role, (long)user.Permissions, + user.QuotaBytes, user.UsedBytes, user.Disabled, user.MustChangePassword, user.Created, user.LastLogin, + ], cancellationToken).ConfigureAwait(false); + + /// Saves every field except id and creation time. + public async Task UpdateAsync(User user, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE users SET username = $2, username_key = $3, display_name = $4, password_hash = $5, role = $6, permissions = $7, " + + "quota_bytes = $8, used_bytes = $9, disabled = $10, must_change_password = $11, last_login = $12 WHERE id = $1", + [ + user.Id, user.Username, Key(user.Username), user.DisplayName, user.PasswordHash, (int)user.Role, (long)user.Permissions, + user.QuotaBytes, user.UsedBytes, user.Disabled, user.MustChangePassword, user.LastLogin, + ], cancellationToken).ConfigureAwait(false) > 0; + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM users WHERE id = $1", [id], Map, cancellationToken); + + public Task GetByUsernameAsync(string username, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM users WHERE username_key = $1", [Key(username)], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM users ORDER BY username_key", [], Map, cancellationToken); + + public async Task CountAsync(CancellationToken cancellationToken = default) => + (int)await _db.ScalarAsync("SELECT count(*) FROM users", [], cancellationToken).ConfigureAwait(false); + + /// Deletes the user with their tokens, render nodes and uploads. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM users WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + public async Task RecordLoginAsync(Guid id, DateTimeOffset at, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE users SET last_login = $2 WHERE id = $1", [id, at], cancellationToken).ConfigureAwait(false) > 0; + + /// Adds (negative to release) to the user's quota usage atomically. + public async Task AddUsedBytesAsync(Guid id, long delta, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE users SET used_bytes = used_bytes + $2 WHERE id = $1", [id, delta], cancellationToken).ConfigureAwait(false) > 0; + + private static string Key(string username) => username.Trim().ToLowerInvariant(); + + private static User Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Username = r.GetString(1), + DisplayName = r.GetStringOrNull(2), + PasswordHash = r.GetString(3), + Role = (UserRole)r.GetInt32(4), + Permissions = (Permissions)r.GetInt64(5), + QuotaBytes = r.GetInt64(6), + UsedBytes = r.GetInt64(7), + Disabled = r.GetBool(8), + MustChangePassword = r.GetBool(9), + Created = r.GetDateTimeOffset(10), + LastLogin = r.GetDateTimeOffsetOrNull(11), + }; +} diff --git a/src/Titano.Data/TitanoDatabase.cs b/src/Titano.Data/TitanoDatabase.cs new file mode 100644 index 00000000..7913e13a --- /dev/null +++ b/src/Titano.Data/TitanoDatabase.cs @@ -0,0 +1,155 @@ +using Titano.Data.Migrations; +using Titano.Data.Repositories; +using Titano.Data.Sqlite; + +namespace Titano.Data; + +/// The repositories of the Titano schema, bound either to the database (one session per call) or to one transaction. +public abstract class TitanoRepositories +{ + private protected TitanoRepositories(DbAccess access) + { + Archives = new ArchiveRepository(access); + Sequences = new SequenceRepository(access); + Frames = new FrameRepository(access); + Renders = new RenderRepository(access); + Jobs = new JobRepository(access); + MediaCards = new MediaCardRepository(access); + Users = new UserRepository(access); + Tokens = new TokenRepository(access); + RenderNodes = new RenderNodeRepository(access); + Settings = new SettingsRepository(access); + Tags = new TagRepository(access); + Audit = new AuditRepository(access); + Uploads = new UploadRepository(access); + } + + public ArchiveRepository Archives { get; } + public SequenceRepository Sequences { get; } + public FrameRepository Frames { get; } + public RenderRepository Renders { get; } + public JobRepository Jobs { get; } + public MediaCardRepository MediaCards { get; } + public UserRepository Users { get; } + public TokenRepository Tokens { get; } + public RenderNodeRepository RenderNodes { get; } + public SettingsRepository Settings { get; } + public TagRepository Tags { get; } + public AuditRepository Audit { get; } + public UploadRepository Uploads { get; } +} + +/// +/// Entry point of the data layer: opens SQLite or PostgreSQL, migrates the schema and exposes the repositories. +/// Each repository call borrows a pooled session; use to group calls atomically. +/// +/// +/// +/// await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Parse(connectionString), ct); +/// var page = await db.Sequences.ListAsync(new SequenceQuery { Year = 2026 }, ct); +/// await using var tx = await db.BeginAsync(ct); +/// await tx.Frames.InsertAsync(frame, ct); +/// await tx.Sequences.RefreshStatsAsync(frame.SequenceId, ct); +/// await tx.CommitAsync(ct); +/// +/// +public sealed class TitanoDatabase : TitanoRepositories, IAsyncDisposable +{ + private TitanoDatabase(IDatabase database, int schemaVersion) + : base(new DbAccess(database)) + { + Database = database; + SchemaVersion = schemaVersion; + } + + /// The underlying engine, for raw sessions and engine-specific features (backups, LISTEN). + public IDatabase Database { get; } + + public Dialect Dialect => Database.Dialect; + + /// Schema version after migration. + public int SchemaVersion { get; private set; } + + /// + /// Opens the database and applies pending migrations. Throws when a newer + /// build already migrated it. + /// + public static async Task OpenAsync(DatabaseOptions options, CancellationToken cancellationToken = default) + { + var database = DatabaseFactory.Open(options); + try + { + var version = await MigrationRunner.MigrateAsync(database, cancellationToken).ConfigureAwait(false); + return new TitanoDatabase(database, version); + } + catch + { + await database.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// Starts a transaction whose repositories all run on it; dispose without committing to roll back. + public async Task BeginAsync(CancellationToken cancellationToken = default) + { + var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false); + try + { + return new TitanoTransaction(session, await session.BeginAsync(cancellationToken).ConfigureAwait(false)); + } + catch + { + await session.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// SQLite only: writes a VACUUM INTO copy into , keeping the newest . + public Task BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default) => + AsSqlite().BackupAsync(directory, keep, cancellationToken); + + /// SQLite only: replaces the database with a backup, then migrates it to this build's schema. + public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default) + { + await AsSqlite().RestoreAsync(backupPath, cancellationToken).ConfigureAwait(false); + SchemaVersion = await MigrationRunner.MigrateAsync(Database, cancellationToken).ConfigureAwait(false); + } + + public ValueTask DisposeAsync() => Database.DisposeAsync(); + + private SqliteDatabase AsSqlite() => + Database as SqliteDatabase ?? throw new NotSupportedException("Backups of a PostgreSQL database are made with the server's own tools."); +} + +/// Repositories bound to one open transaction. +public sealed class TitanoTransaction : TitanoRepositories, IAsyncDisposable +{ + private readonly IDbTransaction _transaction; + + internal TitanoTransaction(IDbSession session, IDbTransaction transaction) + : base(new DbAccess(session)) + { + Session = session; + _transaction = transaction; + } + + /// The session the transaction runs on, for statements of your own inside it. + public IDbSession Session { get; } + + public Task CommitAsync(CancellationToken cancellationToken = default) => _transaction.CommitAsync(cancellationToken); + + public Task RollbackAsync(CancellationToken cancellationToken = default) => _transaction.RollbackAsync(cancellationToken); + + /// Rolls back unless committed, and returns the session to the pool. + public async ValueTask DisposeAsync() + { + try + { + await _transaction.DisposeAsync().ConfigureAwait(false); + } + finally + { + await Session.DisposeAsync().ConfigureAwait(false); + } + } +} From 2fbb7bc17979c5f0a7dad7d8f218e34f4603c002 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:05:43 +0000 Subject: [PATCH 075/188] test(data): cover migrations and every repository on both dialects Shared abstract suites run against in-memory/temp-file SQLite and, with TITANO_TEST_PG, a private PostgreSQL schema per test: migration idempotency and version refusal, keyset paging with ties for every sort, statistics, exclusive job claiming under 8 concurrent claimers, and the 100k-frame bulk insert under 15 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Infrastructure/TestData.cs | 80 ++++ .../Migrations/MigrationTests.cs | 95 +++++ tests/Titano.Data.Tests/Program.cs | 8 +- .../Repositories/BulkInsertTests.cs | 42 ++ .../Repositories/CatalogRepositoryTests.cs | 387 ++++++++++++++++++ .../Repositories/JobRepositoryTests.cs | 168 ++++++++ .../Repositories/MediaCardRepositoryTests.cs | 100 +++++ .../Repositories/ServerRepositoryTests.cs | 246 +++++++++++ 8 files changed, 1125 insertions(+), 1 deletion(-) create mode 100644 tests/Titano.Data.Tests/Infrastructure/TestData.cs create mode 100644 tests/Titano.Data.Tests/Migrations/MigrationTests.cs create mode 100644 tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs create mode 100644 tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs create mode 100644 tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs create mode 100644 tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs create mode 100644 tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs diff --git a/tests/Titano.Data.Tests/Infrastructure/TestData.cs b/tests/Titano.Data.Tests/Infrastructure/TestData.cs new file mode 100644 index 00000000..b0bc9814 --- /dev/null +++ b/tests/Titano.Data.Tests/Infrastructure/TestData.cs @@ -0,0 +1,80 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.Data.Tests.Infrastructure; + +/// Base of repository tests: a migrated per test. +public abstract class RepositoryTest(TestContext context) : DatabaseTest(context) +{ + /// Opens a fresh migrated database; forces a SQLite file. + protected async Task OpenTitanoAsync(bool multiConnection = false) => + Own(await TitanoDatabase.OpenAsync(await NewOptionsAsync(multiConnection), Ct)); +} + +/// Builders of valid entities with distinct ids; override fields with with. +internal static class TestData +{ + /// A fixed reference instant (microsecond precision, like the databases). + public static readonly DateTimeOffset Now = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero); + + public static Archive Archive(string name = "Main") => new() + { + Id = Guid.CreateVersion7(), + Name = name, + RootPath = "/archive/" + name, + Created = Now, + }; + + public static Sequence Sequence(Guid archiveId, DateTime? firstCapture = null, string? title = null, string camera = "EOS R5") => new() + { + Id = Guid.CreateVersion7(), + ArchiveId = archiveId, + Title = title, + Folder = $"2026/{Guid.NewGuid():N}", + CameraMake = "Canon", + CameraModel = camera, + FirstCapture = firstCapture, + LastCapture = firstCapture?.AddHours(1), + UpdatedAt = Now, + }; + + public static Frame Frame(Guid sequenceId, int index, DateTime? capturedAt = null) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = sequenceId, + Index = index, + RelativePath = $"2026/seq/originals/IMG_{index:0000}.CR3", + FileName = $"IMG_{index:0000}.CR3", + Size = 25_000_000 + index, + Sha256 = Convert.ToHexStringLower(BitConverter.GetBytes((long)index)).PadLeft(64, '0'), + CapturedAt = capturedAt ?? new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(5 * index), + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = 1 / 250.0, + FNumber = 8, + Iso = 100, + FocalLength = 24, + Width = 8192, + Height = 5464, + Format = ImageFileFormat.Cr3, + }; + + public static Job Job(JobKind kind = JobKind.Scan, JobPriority priority = JobPriority.Normal, DateTimeOffset? created = null) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + Priority = priority, + State = JobState.Queued, + Created = created ?? Now, + }; + + public static User User(string username = "alice") => new() + { + Id = Guid.CreateVersion7(), + Username = username, + PasswordHash = "pbkdf2-sha512$210000$salt$hash", + Role = UserRole.Editor, + Permissions = RolePermissions.Default(UserRole.Editor), + Created = Now, + }; +} diff --git a/tests/Titano.Data.Tests/Migrations/MigrationTests.cs b/tests/Titano.Data.Tests/Migrations/MigrationTests.cs new file mode 100644 index 00000000..755f9c20 --- /dev/null +++ b/tests/Titano.Data.Tests/Migrations/MigrationTests.cs @@ -0,0 +1,95 @@ +using Titano.Data.Migrations; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Migrations; + +public abstract class MigrationTests(TestContext context) : RepositoryTest(context) +{ + private static readonly string[] Tables = + [ + "archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens", + "render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", + ]; + + [Test] + public void EmbeddedScriptsAreFoundForBothDialects() + { + foreach (var dialect in new[] { Dialect.Sqlite, Dialect.Postgres }) + { + var migrations = MigrationRunner.Load(dialect); + Assert.NotEmpty(migrations); + Assert.Equal(1, migrations[0].Version); + Assert.Equal("initial", migrations[0].Name); + Assert.Contains("CREATE TABLE frames", migrations[0].Sql); + } + } + + [Test] + public async Task CreatesEveryTableAndIsIdempotent() + { + var titano = await OpenTitanoAsync(); + var latest = MigrationRunner.Load(Dialect)[^1].Version; + Assert.Equal(latest, titano.SchemaVersion); + Assert.Equal(latest, await MigrationRunner.MigrateAsync(titano.Database, Ct)); + + await using var session = await titano.Database.OpenAsync(Ct); + foreach (var table in Tables) Assert.Equal(0L, await session.ScalarAsync($"SELECT count(*) FROM {table}", [], Ct)); + var recorded = await session.QueryListAsync("SELECT version, name, applied_at FROM schema_migrations ORDER BY version", [], r => r, Ct); + Assert.Equal(MigrationRunner.Load(Dialect).Count, recorded.Count); + Assert.Equal("initial", recorded[0].GetString(1)); + Assert.True(recorded[0].GetDateTimeOffset(2) > DateTimeOffset.UtcNow.AddMinutes(-5)); + } + + [Test] + public async Task AppliesOnlyPendingMigrations() + { + var titano = await OpenTitanoAsync(); + var next = MigrationRunner.Load(Dialect).Append(new Migration(9000, "extra", "CREATE TABLE extra (id integer PRIMARY KEY)")).ToList(); + Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct)); + Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct)); + await using var session = await titano.Database.OpenAsync(Ct); + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM schema_migrations WHERE version = $1", [9000], Ct)); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM extra", [], Ct)); + } + + [Test] + public async Task RefusesADatabaseFromANewerBuild() + { + var titano = await OpenTitanoAsync(); + await using (var session = await titano.Database.OpenAsync(Ct)) + await session.ExecuteAsync("INSERT INTO schema_migrations (version, name, applied_at) VALUES ($1, $2, $3)", [9999, "future", DateTimeOffset.UtcNow], Ct); + var error = await Assert.ThrowsAsync(() => MigrationRunner.MigrateAsync(titano.Database, Ct)); + Assert.Equal(9999, error.DatabaseVersion); + Assert.Equal(MigrationRunner.Load(Dialect)[^1].Version, error.SupportedVersion); + } + + [Test] + public async Task AFailingMigrationLeavesNothingBehind() + { + var database = await OpenDatabaseAsync(); + List broken = + [ + new(1, "good", "CREATE TABLE good_one (id integer PRIMARY KEY)"), + new(2, "bad", "CREATE TABLE good_two (id integer PRIMARY KEY); THIS IS NOT SQL"), + ]; + await Assert.ThrowsAsync(() => MigrationRunner.MigrateAsync(database, broken, Ct)); + await using var session = await database.OpenAsync(Ct); + var leftovers = await session.ScalarAsync(ForDialect( + "SELECT count(*) FROM sqlite_master WHERE name IN ('good_one', 'good_two', 'schema_migrations')", + "SELECT count(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name IN ('good_one', 'good_two', 'schema_migrations')"), + [], Ct); + Assert.Equal(0L, leftovers); + } +} + +public sealed class SqliteMigrationTests(TestContext context) : MigrationTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresMigrationTests(TestContext context) : MigrationTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Program.cs b/tests/Titano.Data.Tests/Program.cs index 92339124..ffd81b63 100644 --- a/tests/Titano.Data.Tests/Program.cs +++ b/tests/Titano.Data.Tests/Program.cs @@ -1,8 +1,14 @@ +using Titano.Core.Diagnostics; using Titano.Testing; namespace Titano.Data.Tests; internal static class TestMain { - public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); + public static Task Main(string[] args) + { + // Migrations and schema drops log at Info for every test database; keep the console for warnings. + Log.MinimumLevel = LogLevel.Warning; + return TestRunner.RunAsync(args, typeof(TestMain).Assembly); + } } diff --git a/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs b/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs new file mode 100644 index 00000000..879f4972 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// The 100k-frame import of the Phase 2 gate must stay well under 15 s. +public abstract class BulkInsertTests(TestContext context) : RepositoryTest(context) +{ + [Test] + [Timeout(60_000)] + public async Task HundredThousandFramesInsertQuickly() + { + var db = await OpenTitanoAsync(multiConnection: true); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 100_000).Select(i => TestData.Frame(sequence.Id, i)).ToList(); + + var watch = Stopwatch.StartNew(); + Assert.Equal(100_000L, await db.Frames.BulkInsertAsync(frames, Ct)); + watch.Stop(); + Context.Log($"{Dialect}: 100k frames in {watch.Elapsed.TotalSeconds:F2} s"); + Assert.Less(watch.Elapsed.TotalSeconds, 15.0, "bulk insert time"); + + var refreshed = await db.Sequences.RefreshStatsAsync(sequence.Id, Ct); + Assert.Equal(100_000, refreshed!.FrameCount); + Assert.Equal(frames[^1], (await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 99_998, cancellationToken: Ct)).Single()); + } +} + +public sealed class SqliteBulkInsertTests(TestContext context) : BulkInsertTests(context) +{ + protected override Backend Backend => Backend.SqliteFile; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresBulkInsertTests(TestContext context) : BulkInsertTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs new file mode 100644 index 00000000..340fe506 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs @@ -0,0 +1,387 @@ +using System.Text.Json.Nodes; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// Archives, sequences, frames, renders and tags on both dialects. +public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task ArchivesRoundTripAndDelete() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive() with { ProxyLongEdge = -1, FolderTemplate = "{year}/{title}" }; + await db.Archives.UpsertAsync(archive, Ct); + await db.Archives.UpsertAsync(archive with { Name = "Renamed" }, Ct); + Assert.Equal(archive with { Name = "Renamed" }, await db.Archives.GetAsync(archive.Id, Ct)); + Assert.Count(1, await db.Archives.ListAsync(Ct)); + Assert.True(await db.Archives.DeleteAsync(archive.Id, Ct)); + Assert.Null(await db.Archives.GetAsync(archive.Id, Ct)); + Assert.False(await db.Archives.DeleteAsync(archive.Id, Ct)); + } + + [Test] + public async Task SequencesRoundTripEveryField() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 30, 15, 250), "Harbour sunset") with + { + CameraSerial = "0123", Lens = "RF 24-70", FrameCount = 1200, MedianInterval = 5.0, TotalBytes = 30_000_000_000, + Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, RenderedCount = 0, VerifiedAt = TestData.Now, + HeroFrameId = Guid.CreateVersion7(), Rating = 4, Notes = "windy", SettingsJson = "{\"fps\": 25, \"deflicker\": true}", + AnalysisJson = "{\"ev\": [12.5, 13]}", Origin = SequenceOrigin.Server, SyncState = SyncState.LocalAhead, + SettingsVersion = 3, FramesVersion = 7, OwnerUserId = Guid.CreateVersion7(), WarningCount = 2, Tags = ["Sunset", "harbour", "SUNSET"], + }; + await db.Sequences.UpsertAsync(sequence, Ct); + + var read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct)); + Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.SettingsJson!), JsonNode.Parse(read.SettingsJson!))); + Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.AnalysisJson!), JsonNode.Parse(read.AnalysisJson!))); + Assert.SequenceEqual(["harbour", "Sunset"], read.Tags); + Assert.Equal(sequence with { Tags = read.Tags, SettingsJson = read.SettingsJson, AnalysisJson = read.AnalysisJson }, read); + + await db.Sequences.UpsertAsync(sequence with { Title = null, Tags = ["night"], Rating = 1 }, Ct); + read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct)); + Assert.Null(read.Title); + Assert.Equal("2026-09-28 EOS R5", read.DisplayTitle); + Assert.SequenceEqual(["night"], read.Tags); + Assert.Equal(1, read.Rating); + } + + [Test] + public async Task DeletingASequenceRemovesItsFramesRendersAndTagLinks() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id) with { Tags = ["a"] }; + await db.Sequences.UpsertAsync(sequence, Ct); + await db.Frames.BulkInsertAsync(Enumerable.Range(0, 10).Select(i => TestData.Frame(sequence.Id, i)), Ct); + await db.Renders.InsertAsync(Render(sequence.Id), Ct); + + Assert.True(await db.Sequences.DeleteAsync(sequence.Id, Ct)); + Assert.Empty(await db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: Ct)); + Assert.Empty(await db.Renders.ListBySequenceAsync(sequence.Id, Ct)); + Assert.Equal(0, (await db.Tags.ListAsync(Ct)).Single().SequenceCount); + Assert.Equal(1, await db.Tags.DeleteUnusedAsync(Ct)); + } + + [Test] + public async Task ListingFiltersCombine() + { + var db = await OpenTitanoAsync(); + var main = TestData.Archive(); + var other = TestData.Archive("Other"); + await db.Archives.UpsertAsync(main, Ct); + await db.Archives.UpsertAsync(other, Ct); + var owner = Guid.CreateVersion7(); + var harbour = TestData.Sequence(main.Id, new DateTime(2024, 6, 1), "Porto di CITTÀ vecchia") with { Status = SequenceStatus.AnalyzedLight, Tags = ["sea"] }; + var stars = TestData.Sequence(main.Id, new DateTime(2025, 1, 2), "Milky way", "Z8") with { CameraMake = "Nikon", Tags = ["Night Sky"], OwnerUserId = owner }; + var clouds = TestData.Sequence(main.Id, new DateTime(2024, 12, 31, 23, 59, 59), "50%_clouds") with { Status = SequenceStatus.AnalyzedLight | SequenceStatus.Verified }; + var elsewhere = TestData.Sequence(other.Id, new DateTime(2024, 3, 3), "Elsewhere"); + var undated = TestData.Sequence(main.Id, null, "Undated"); + foreach (var s in new[] { harbour, stars, clouds, elsewhere, undated }) await db.Sequences.UpsertAsync(s, Ct); + + async Task Titles(SequenceQuery q) => + [.. (await db.Sequences.ListAsync(q with { Sort = SequenceSort.Title }, Ct)).Items.Select(s => s.Title!)]; + + Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { ArchiveId = main.Id, Year = 2024 })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Camera = "Z8" })); + Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight })); + Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight, WithoutStatus = SequenceStatus.Verified })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Tag = " night SKY " })); + Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { Text = "città" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "NIKON" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "ght sk" })); + Assert.SequenceEqual(["50%_clouds"], await Titles(new() { Text = "50%_" })); + Assert.Empty(await Titles(new() { Text = "5_%" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { OwnerUserId = owner })); + Assert.Equal(4, await db.Sequences.CountAsync(new() { ArchiveId = main.Id }, Ct)); + Assert.Equal(2, await db.Sequences.CountAsync(new() { ArchiveId = main.Id, Year = 2024 }, Ct)); + Assert.Equal(5, await db.Sequences.CountAsync(new(), Ct)); + } + + [Theory] + [Case(SequenceSort.Newest)] + [Case(SequenceSort.Oldest)] + [Case(SequenceSort.Title)] + [Case(SequenceSort.FrameCount)] + [Case(SequenceSort.Size)] + public async Task KeysetPagesVisitEveryRowOnceInOrderDespiteTies(SequenceSort sort) + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var all = Enumerable.Range(0, 23).Select(i => TestData.Sequence(archive.Id, + i % 5 == 4 ? null : new DateTime(2024 + i % 3, 1, 1, 12, 0, 0), + i % 4 == 0 ? null : "T" + (i % 6)) with { FrameCount = i % 3, TotalBytes = i % 4 * 1000L }) + .ToList(); + foreach (var s in all) await db.Sequences.UpsertAsync(s, Ct); + + var expected = Expected(all, sort).Select(s => s.Id).ToList(); + var seen = new List(); + string? cursor = null; + var pages = 0; + do + { + var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, Sort = sort, Limit = 4, Cursor = cursor }, Ct); + Assert.True(page.Items.Count is > 0 and <= 4); + seen.AddRange(page.Items.Select(s => s.Id)); + cursor = page.NextCursor; + pages++; + } + while (cursor is not null); + + Assert.Equal(6, pages); + Assert.SequenceEqual(expected, seen); + } + + [Test] + public async Task CursorsOnlyWorkForTheirOwnSort() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + for (var i = 0; i < 3; i++) await db.Sequences.UpsertAsync(TestData.Sequence(archive.Id, new DateTime(2024, 1, 1 + i)), Ct); + var page = await db.Sequences.ListAsync(new SequenceQuery { Limit = 1 }, Ct); + Assert.NotNull(page.NextCursor); + await Assert.ThrowsAsync(() => db.Sequences.ListAsync(new SequenceQuery { Sort = SequenceSort.Size, Cursor = page.NextCursor }, Ct)); + await Assert.ThrowsAsync(() => db.Sequences.ListAsync(new SequenceQuery { Cursor = "not-a-cursor" }, Ct)); + } + + [Test] + public async Task StatisticsAggregateTheArchive() + { + var db = await OpenTitanoAsync(); + var main = TestData.Archive(); + var other = TestData.Archive("Other"); + await db.Archives.UpsertAsync(main, Ct); + await db.Archives.UpsertAsync(other, Ct); + Sequence Seq(Guid archive, DateTime? first, string model, int frames, long bytes, SequenceStatus status) => + TestData.Sequence(archive, first, camera: model) with { FrameCount = frames, TotalBytes = bytes, Status = status }; + var a = Seq(main.Id, new DateTime(2024, 3, 10), "EOS R5", 10, 1000, SequenceStatus.AnalyzedLight) with { VerifiedAt = TestData.Now }; + var b = Seq(main.Id, new DateTime(2024, 3, 20), "Z8", 20, 2000, SequenceStatus.HasWarnings) with { CameraMake = "Nikon" }; + var c = Seq(main.Id, new DateTime(2025, 7, 1), "EOS R5", 30, 3000, SequenceStatus.HasErrors | SequenceStatus.AnalyzedLight); + var d = Seq(main.Id, null, "EOS R5", 0, 0, SequenceStatus.None) with { WarningCount = 1 }; + var e = Seq(other.Id, new DateTime(2023, 1, 1), "X-T5", 5, 500, SequenceStatus.None); + foreach (var s in new[] { a, b, c, d, e }) await db.Sequences.UpsertAsync(s, Ct); + await db.Frames.BulkInsertAsync( + [ + TestData.Frame(a.Id, 0) with { Flags = FrameFlags.Missing, Size = 100 }, + TestData.Frame(a.Id, 1) with { Format = ImageFileFormat.Jpeg, Size = 10, Flags = FrameFlags.Duplicate | FrameFlags.Corrupt }, + TestData.Frame(b.Id, 0) with { Size = 200 }, + TestData.Frame(e.Id, 0) with { Format = ImageFileFormat.Raf, Flags = FrameFlags.Missing }, + ], Ct); + + var stats = await db.Sequences.GetStatsAsync(main.Id, Ct); + Assert.Equal(4, stats.Sequences); + Assert.Equal(60L, stats.Photos); + Assert.Equal(6000L, stats.Bytes); + Assert.SequenceEqual([new YearBucket(2024, 2, 30, 3000), new YearBucket(2025, 1, 30, 3000)], stats.ByYear); + Assert.SequenceEqual([new MonthBucket(2024, 3, 2, 30), new MonthBucket(2025, 7, 1, 30)], stats.ByMonth); + Assert.SequenceEqual( + [new CameraBucket("Canon", "EOS R5", 3, 40, 4000), new CameraBucket("Nikon", "Z8", 1, 20, 2000)], + stats.ByCamera); + Assert.SequenceEqual([new FormatBucket(ImageFileFormat.Cr3, 2, 300), new FormatBucket(ImageFileFormat.Jpeg, 1, 10)], stats.ByFormat); + Assert.Equal(new ArchiveHealth(Unverified: 3, WithWarnings: 2, WithErrors: 1, NotAnalyzed: 2, MissingFrames: 1, CorruptFrames: 1, DuplicateFrames: 1), stats.Health); + + var everything = await db.Sequences.GetStatsAsync(cancellationToken: Ct); + Assert.Equal(5, everything.Sequences); + Assert.Equal(2L, everything.Health.MissingFrames); + Assert.Equal(2023, everything.ByYear[0].Year); + } + + [Test] + public async Task FramesBulkInsertPageAndFindDuplicates() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 250).Select(i => TestData.Frame(sequence.Id, i)).ToList(); + frames[7] = frames[7] with + { + OriginalFileName = "DSC_7.NEF", CapturedAt = new DateTime(2026, 9, 28, 18, 0, 35, 123), UtcOffsetMinutes = 120, ExposureBias = -0.3, + WhiteBalance = 5600, Orientation = 6, PreviewOffset = 1024, PreviewLength = 65536, MeanLogLuminance = -2.5, ClipLow = 0.01, + ClipHigh = 0.02, Flags = FrameFlags.Excluded, Sha256 = "AB" + new string('c', 62), + }; + Assert.Equal(250L, await db.Frames.BulkInsertAsync(frames, Ct)); + var copy = TestData.Frame(sequence.Id, 1000) with { Sha256 = frames[7].Sha256 }; + await db.Frames.InsertAsync(copy, Ct); + + Assert.Equal(frames[7] with { Sha256 = frames[7].Sha256!.ToLowerInvariant() }, await db.Frames.GetAsync(frames[7].Id, Ct)); + var pageOne = await db.Frames.ListBySequenceAsync(sequence.Id, limit: 100, cancellationToken: Ct); + var pageThree = await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 199, limit: 100, cancellationToken: Ct); + Assert.SequenceEqual(Enumerable.Range(0, 100), pageOne.Select(f => f.Index)); + Assert.SequenceEqual(Enumerable.Range(200, 50).Append(1000), pageThree.Select(f => f.Index)); + var duplicates = await db.Frames.FindBySha256Async(frames[7].Sha256!.ToUpperInvariant(), Ct); + Assert.SequenceEqual([7, 1000], duplicates.Select(f => f.Index)); + + var stats = Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct)); + Assert.Equal(251, stats.FrameCount); + Assert.Equal(frames.Sum(f => f.Size) + copy.Size, stats.TotalBytes); + Assert.Equal(frames[0].CapturedAt, stats.FirstCapture); + Assert.Equal(copy.CapturedAt, stats.LastCapture); + Assert.Equal(1, stats.FramesVersion); + } + + [Test] + public async Task FrameAnalysisAndFlagsUpdateInBulk() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 1200).Select(i => TestData.Frame(sequence.Id, i) with { Flags = FrameFlags.Missing }).ToList(); + await db.Frames.BulkInsertAsync(frames, Ct); + + var stats = frames.Select((f, i) => new FrameLightStats(f.Id, -i / 100.0, i % 2 == 0 ? null : 0.5, 0.001 * i)).ToList(); + Assert.Equal(1200, await db.Frames.UpdateLightStatsAsync(stats, Ct)); + var ids = frames.Where(f => f.Index % 3 == 0).Select(f => f.Id).ToList(); + Assert.Equal(400, await db.Frames.UpdateFlagsAsync(ids, FrameFlags.Duplicate | FrameFlags.Excluded, FrameFlags.Missing, Ct)); + + var read = new List(); + for (var after = -1; ; after = read[^1].Index) + { + var page = await db.Frames.ListBySequenceAsync(sequence.Id, after, 500, Ct); + if (page.Count == 0) break; + read.AddRange(page); + } + Assert.Equal(1200, read.Count); + foreach (var f in read) + { + Assert.Equal(-f.Index / 100.0, f.MeanLogLuminance); + Assert.Equal(f.Index % 2 == 0 ? null : 0.5, f.ClipLow); + Assert.Equal(f.Index % 3 == 0 ? FrameFlags.Duplicate | FrameFlags.Excluded : FrameFlags.Missing, f.Flags); + } + Assert.Equal(1200, await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct)); + } + + [Test] + public async Task RendersKeepTheSequenceCountInStep() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var first = Render(sequence.Id) with { Created = TestData.Now }; + var second = Render(sequence.Id) with { Created = TestData.Now.AddMinutes(5), SettingsJson = null, Codec = null }; + await db.Renders.InsertAsync(first, Ct); + await db.Renders.InsertAsync(second, Ct); + Assert.Equal(2, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount); + var list = await db.Renders.ListBySequenceAsync(sequence.Id, Ct); + Assert.SequenceEqual([second.Id, first.Id], list.Select(r => r.Id)); + Assert.Equal(second, list[0]); + Assert.True(await db.Renders.DeleteAsync(second.Id, Ct)); + Assert.False(await db.Renders.DeleteAsync(second.Id, Ct)); + Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount); + } + + [Test] + public async Task TagsCanBeListedRenamedAndDeleted() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var one = TestData.Sequence(archive.Id) with { Tags = ["Alps", "snow"] }; + var two = TestData.Sequence(archive.Id) with { Tags = ["alps"] }; + await db.Sequences.UpsertAsync(one, Ct); + await db.Sequences.UpsertAsync(two, Ct); + Assert.False(await db.Sequences.SetTagsAsync(Guid.CreateVersion7(), ["x"], Ct)); + + var tags = await db.Tags.ListAsync(Ct); + Assert.SequenceEqual([("Alps", 2), ("snow", 1)], tags.Select(t => (t.Name, t.SequenceCount))); + var snow = tags.Single(t => t.Name == "snow"); + await Assert.ThrowsAsync(() => db.Tags.RenameAsync(snow.Id, "ALPS", Ct)); + Assert.True(await db.Tags.RenameAsync(snow.Id, "Snow fields", Ct)); + Assert.SequenceEqual(["Alps", "Snow fields"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags); + Assert.True(await db.Tags.DeleteAsync(snow.Id, Ct)); + Assert.SequenceEqual(["Alps"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags); + Assert.True(await db.Sequences.SetTagsAsync(two.Id, [], Ct)); + Assert.Equal(1, (await db.Tags.ListAsync(Ct)).Single().SequenceCount); + Assert.Throws(() => TagRepository.Normalize(" \t ")); + Assert.Throws(() => TagRepository.Normalize("bad\u0001tag")); + } + + [Test] + public async Task TransactionsGroupRepositoryCalls() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + + await using (var tx = await db.BeginAsync(Ct)) + { + await tx.Sequences.UpsertAsync(sequence, Ct); + await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct); + Assert.NotNull(await tx.Sequences.GetAsync(sequence.Id, Ct)); + } + Assert.Null(await db.Sequences.GetAsync(sequence.Id, Ct)); + + await using (var tx = await db.BeginAsync(Ct)) + { + await tx.Sequences.UpsertAsync(sequence, Ct); + await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct); + await tx.Sequences.RefreshStatsAsync(sequence.Id, Ct); + await tx.CommitAsync(Ct); + } + Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FrameCount); + } + + private static Render Render(Guid sequenceId) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = sequenceId, + PresetName = "4K HEVC", + SettingsJson = "{\"crf\": 18}", + OutputPath = "exports/out.mp4", + Codec = "hevc", + Width = 3840, + Height = 2160, + Fps = 29.97, + DurationSeconds = 41.5, + Bytes = 123_456_789, + Created = TestData.Now, + ProducedBy = "node-1", + }; + + /// The order the database must produce: sort key with NULLS LAST, then id (as text) in the same direction. + private static IEnumerable Expected(List all, SequenceSort sort) + { + int ById(Sequence a, Sequence b) => string.CompareOrdinal(a.Id.ToString("D"), b.Id.ToString("D")); + int NullsLast(T? a, T? b, Comparison compare) where T : struct => + a is null ? (b is null ? 0 : 1) : b is null ? -1 : compare(a.Value, b.Value); + Comparison comparison = sort switch + { + SequenceSort.Newest => (a, b) => NullsLast(a.FirstCapture, b.FirstCapture, (x, y) => y.CompareTo(x)) is var c and not 0 ? c : -ById(a, b), + SequenceSort.Oldest => (a, b) => NullsLast(a.FirstCapture, b.FirstCapture, (x, y) => x.CompareTo(y)) is var c and not 0 ? c : ById(a, b), + SequenceSort.Title => (a, b) => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()) is var c and not 0 ? c : ById(a, b), + SequenceSort.FrameCount => (a, b) => b.FrameCount.CompareTo(a.FrameCount) is var c and not 0 ? c : -ById(a, b), + _ => (a, b) => b.TotalBytes.CompareTo(a.TotalBytes) is var c and not 0 ? c : -ById(a, b), + }; + var sorted = all.ToList(); + sorted.Sort(comparison); + return sorted; + } +} + +public sealed class SqliteCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs new file mode 100644 index 00000000..b4c661ec --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs @@ -0,0 +1,168 @@ +using System.Collections.Concurrent; +using Titano.Core.Model; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task JobsRoundTripEveryField() + { + var db = await OpenTitanoAsync(); + var job = TestData.Job(JobKind.Render, JobPriority.User) with + { + TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()], TargetLabel = "Harbour sunset", ParametersJson = "{\"preset\": \"4K\"}", + ProgressDone = 5, ProgressTotal = 10, ItemsPerSecond = 2.5, Eta = TimeSpan.FromSeconds(2), Checkpoint = "frame:5", + LogTail = "line 1\nline 2", CreatedBy = Guid.CreateVersion7(), NodeId = "node-a", Attempts = 1, Error = "boom", + State = JobState.Failed, Started = TestData.Now.AddMinutes(1), Finished = TestData.Now.AddMinutes(2), + }; + await db.Jobs.EnqueueAsync(job, Ct); + var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct)); + Assert.SequenceEqual(job.TargetIds, read.TargetIds); + Assert.Equal(job with { TargetIds = read.TargetIds }, read); + } + + [Test] + public async Task ClaimsByPriorityThenAgeAndKind() + { + var db = await OpenTitanoAsync(); + var oldBackground = TestData.Job(JobKind.Thumbs, JobPriority.Background, TestData.Now.AddMinutes(-10)); + var newUser = TestData.Job(JobKind.Render, JobPriority.User, TestData.Now); + var oldUser = TestData.Job(JobKind.Import, JobPriority.User, TestData.Now.AddMinutes(-1)); + var normal = TestData.Job(JobKind.Scan, JobPriority.Normal, TestData.Now.AddMinutes(-5)); + foreach (var job in new[] { oldBackground, newUser, oldUser, normal }) await db.Jobs.EnqueueAsync(job, Ct); + + var renderOnly = await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct); + Assert.Equal(newUser.Id, renderOnly?.Id); + Assert.Equal(JobState.Running, renderOnly!.State); + Assert.Equal("node-gpu", renderOnly.NodeId); + Assert.Equal(1, renderOnly.Attempts); + Assert.NotNull(renderOnly.Started); + Assert.Null(await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct)); + + var order = new List(); + while (await db.Jobs.ClaimNextAsync("server", cancellationToken: Ct) is { } claimed) order.Add(claimed.Id); + Assert.SequenceEqual([oldUser.Id, normal.Id, oldBackground.Id], order); + } + + [Test] + public async Task ConcurrentClaimersNeverShareAJob() + { + var db = await OpenTitanoAsync(multiConnection: true); + var jobs = Enumerable.Range(0, 40).Select(i => TestData.Job(created: TestData.Now.AddSeconds(i))).ToList(); + foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct); + + var claims = new ConcurrentBag<(string Worker, Guid Job)>(); + await Task.WhenAll(Enumerable.Range(0, 8).Select(w => Task.Run(async () => + { + var worker = "worker-" + w; + while (await db.Jobs.ClaimNextAsync(worker, cancellationToken: Ct) is { } job) claims.Add((worker, job.Id)); + }))); + + Assert.Equal(40, claims.Count); + Assert.Equal(40, claims.Select(c => c.Job).Distinct().Count()); + foreach (var (worker, id) in claims) + { + var stored = await db.Jobs.GetAsync(id, Ct); + Assert.Equal(worker, stored!.NodeId); + Assert.Equal(1, stored.Attempts); + } + } + + [Test] + public async Task ProgressIsRefusedOnceTheJobStopsRunning() + { + var db = await OpenTitanoAsync(); + var job = TestData.Job(); + await db.Jobs.EnqueueAsync(job, Ct); + Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 1, 10, null, null, null, null, Ct)); + await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct); + Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, 2.0, TimeSpan.FromSeconds(3), "cursor:4", "tail", Ct)); + var running = await db.Jobs.GetAsync(job.Id, Ct); + Assert.Equal((4L, 10L, "cursor:4", "tail"), (running!.ProgressDone, running.ProgressTotal, running.Checkpoint, running.LogTail)); + Assert.Equal(TimeSpan.FromSeconds(3), running.Eta); + + Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Cancelled, cancellationToken: Ct)); + Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct)); + var cancelled = await db.Jobs.GetAsync(job.Id, Ct); + Assert.Equal(JobState.Cancelled, cancelled!.State); + Assert.NotNull(cancelled.Finished); + + Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Queued, cancellationToken: Ct)); + Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Finished); + Assert.Equal(2, (await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct))!.Attempts); + Assert.False(await db.Jobs.SetStateAsync(Guid.CreateVersion7(), JobState.Done, cancellationToken: Ct)); + } + + [Test] + public async Task ListingPagesByStateNewestFirst() + { + var db = await OpenTitanoAsync(); + var jobs = Enumerable.Range(0, 7).Select(i => TestData.Job(created: TestData.Now.AddMinutes(i % 3))).ToList(); + foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct); + await db.Jobs.SetStateAsync(jobs[0].Id, JobState.Done, cancellationToken: Ct); + + var seen = new List(); + string? cursor = null; + do + { + var page = await db.Jobs.ListAsync(JobState.Queued, limit: 2, cursor: cursor, cancellationToken: Ct); + seen.AddRange(page.Items.Select(j => j.Id)); + cursor = page.NextCursor; + } + while (cursor is not null); + + var expected = jobs.Skip(1) + .OrderByDescending(j => j.Created) + .ThenByDescending(j => j.Id.ToString("D"), StringComparer.Ordinal) + .Select(j => j.Id); + Assert.SequenceEqual(expected, seen); + Assert.SequenceEqual([jobs[0].Id], (await db.Jobs.ListAsync(JobState.Done, cancellationToken: Ct)).Items.Select(j => j.Id)); + Assert.Equal(7, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task HistoryPurgeKeepsRecentAndActiveJobs() + { + var db = await OpenTitanoAsync(); + var old = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-100) }; + var oldFailed = TestData.Job() with { State = JobState.Failed, Finished = TestData.Now.AddDays(-91) }; + var recent = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-10) }; + var queued = TestData.Job(created: TestData.Now.AddDays(-200)); + foreach (var job in new[] { old, oldFailed, recent, queued }) await db.Jobs.EnqueueAsync(job, Ct); + Assert.Equal(2, await db.Jobs.PurgeHistoryAsync(TestData.Now.AddDays(-90), Ct)); + Assert.Equal(2, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task RunningJobsAreRequeuedAfterACrash() + { + var db = await OpenTitanoAsync(); + for (var i = 0; i < 3; i++) await db.Jobs.EnqueueAsync(TestData.Job(created: TestData.Now.AddSeconds(i)), Ct); + var a = await db.Jobs.ClaimNextAsync("node-a", cancellationToken: Ct); + var b = await db.Jobs.ClaimNextAsync("node-b", cancellationToken: Ct); + await db.Jobs.UpdateProgressAsync(a!.Id, 3, 9, null, null, "resume-here", null, Ct); + + Assert.Equal(1, await db.Jobs.RequeueRunningAsync("node-a", Ct)); + var requeued = await db.Jobs.GetAsync(a.Id, Ct); + Assert.Equal(JobState.Queued, requeued!.State); + Assert.Equal("resume-here", requeued.Checkpoint); + Assert.Null(requeued.NodeId); + Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(b!.Id, Ct))!.State); + Assert.Equal(1, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct)); + Assert.Equal(0, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct)); + } +} + +public sealed class SqliteJobRepositoryTests(TestContext context) : JobRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresJobRepositoryTests(TestContext context) : JobRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs new file mode 100644 index 00000000..efc1352a --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs @@ -0,0 +1,100 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +public abstract class MediaCardRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task CardsRoundTripAndAreFoundByIdentity() + { + var db = await OpenTitanoAsync(); + var card = Card(); + await db.MediaCards.UpsertAsync(card, Ct); + Assert.Equal(card, await db.MediaCards.GetAsync(card.Id, Ct)); + Assert.Equal(card, await db.MediaCards.FindByIdentityAsync(card.Identity, Ct)); + Assert.Null(await db.MediaCards.FindByIdentityAsync("unknown", Ct)); + + var seen = TestData.Now.AddDays(2); + Assert.True(await db.MediaCards.TouchAsync(card.Id, seen, Ct)); + await db.MediaCards.UpsertAsync(card with { Nickname = "Card B", LastSeen = seen }, Ct); + var other = Card() with { Identity = "1-OTHER-64", LastSeen = TestData.Now.AddDays(5) }; + await db.MediaCards.UpsertAsync(other, Ct); + Assert.SequenceEqual([other.Id, card.Id], (await db.MediaCards.ListAsync(Ct)).Select(c => c.Id)); + Assert.Equal("Card B", (await db.MediaCards.GetAsync(card.Id, Ct))!.Nickname); + + var clash = await Assert.ThrowsAsync(() => db.MediaCards.UpsertAsync(Card() with { Identity = card.Identity }, Ct)); + Assert.True(clash.IsUniqueViolation); + } + + [Test] + public async Task ImportHistoryLetsReinsertsSkipKnownFiles() + { + var db = await OpenTitanoAsync(); + var card = Card(); + await db.MediaCards.UpsertAsync(card, Ct); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frame = TestData.Frame(sequence.Id, 0); + await db.Frames.InsertAsync(frame, Ct); + + // File-system times carry 100 ns ticks; keys compare at the database's microsecond precision. + var modified = new DateTimeOffset(2026, 9, 28, 18, 0, 0, TimeSpan.FromHours(2)).AddTicks(1234567); + var first = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified); + var reused = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 24_000_000, modified.AddDays(30)); + var job = Guid.CreateVersion7(); + await db.MediaCards.RecordImportsAsync( + [ + new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now), + new ImportRecord(card.Id, reused, null, null, job, TestData.Now.AddDays(30)), + ], Ct); + await db.MediaCards.RecordImportsAsync([new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now)], Ct); + + var keys = await db.MediaCards.GetImportedKeysAsync(card.Id, Ct); + Assert.Equal(2, keys.Count); + Assert.True(keys.Contains(new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified.AddTicks(2)))); + Assert.True(await db.MediaCards.IsImportedAsync(card.Id, first, Ct)); + Assert.False(await db.MediaCards.IsImportedAsync(card.Id, new ImportKey(first.Path, first.Size + 1, modified), Ct)); + + var history = await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct); + Assert.Equal(reused, history[0].Key); + Assert.Equal(new string('f', 64), history[1].Sha256); + Assert.Equal(frame.Id, history[1].FrameId); + + await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct); + Assert.Null((await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct))[1].FrameId); + Assert.True(await db.MediaCards.DeleteAsync(card.Id, Ct)); + Assert.Equal(0, (await db.MediaCards.GetImportedKeysAsync(card.Id, Ct)).Count); + } + + private static MediaCard Card() => new() + { + Id = Guid.CreateVersion7(), + Identity = "3735928559-EOS_DIGITAL-128043712512", + VolumeSerial = 3735928559, + Label = "EOS_DIGITAL", + Capacity = 128_043_712_512, + CameraMake = "Canon", + CameraModel = "EOS R5", + CameraSerial = "0123", + ProfileJson = "{\"auto\": false}", + AutoImport = true, + FirstSeen = TestData.Now, + LastSeen = TestData.Now, + }; +} + +public sealed class SqliteMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs new file mode 100644 index 00000000..61dd5c2c --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs @@ -0,0 +1,246 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// Users, tokens, render nodes, settings, audit log and uploads on both dialects. +public abstract class ServerRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task UsersAreUniqueIgnoringCase() + { + var db = await OpenTitanoAsync(); + var alice = TestData.User("Alice") with { DisplayName = "Alice A.", QuotaBytes = 1L << 40, MustChangePassword = true, Role = UserRole.Admin, Permissions = Permissions.All }; + await db.Users.CreateAsync(alice, Ct); + var duplicate = await Assert.ThrowsAsync(() => db.Users.CreateAsync(TestData.User("ALICE"), Ct)); + Assert.True(duplicate.IsUniqueViolation); + + Assert.Equal(alice, await db.Users.GetByUsernameAsync(" alice ", Ct)); + Assert.True(await db.Users.UpdateAsync(alice with { Username = "alice2", Disabled = true, MustChangePassword = false }, Ct)); + Assert.True(await db.Users.RecordLoginAsync(alice.Id, TestData.Now, Ct)); + Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, 5000, Ct)); + Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, -1000, Ct)); + var read = Assert.NotNull(await db.Users.GetAsync(alice.Id, Ct)); + Assert.Equal(alice with { Username = "alice2", Disabled = true, MustChangePassword = false, LastLogin = TestData.Now, UsedBytes = 4000 }, read); + Assert.Null(await db.Users.GetByUsernameAsync("alice", Ct)); + Assert.Equal(1, await db.Users.CountAsync(Ct)); + Assert.Count(1, await db.Users.ListAsync(Ct)); + } + + [Test] + public async Task DeletingAUserRemovesTheirTokensNodesAndUploads() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + await db.Tokens.InsertAsync(Token(user.Id, "h1"), Ct); + await db.RenderNodes.RegisterAsync(Node(user.Id), Ct); + await db.Uploads.CreateAsync(Upload(user.Id, 10), Ct); + Assert.True(await db.Users.DeleteAsync(user.Id, Ct)); + Assert.Null(await db.Tokens.GetAsync("h1", Ct)); + Assert.Empty(await db.RenderNodes.ListAsync(Ct)); + Assert.Empty(await db.Uploads.ListByUserAsync(user.Id, Ct)); + } + + [Test] + public async Task TokensSlideRevokeAndPurge() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var token = Token(user.Id, "hash-1"); + await db.Tokens.InsertAsync(token, Ct); + await db.Tokens.InsertAsync(Token(user.Id, "hash-2"), Ct); + await db.Tokens.InsertAsync(Token(user.Id, "expired") with { Expires = TestData.Now.AddDays(-1) }, Ct); + Assert.Equal(token, await db.Tokens.GetAsync("hash-1", Ct)); + + var later = TestData.Now.AddDays(3); + Assert.True(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct)); + var touched = await db.Tokens.GetAsync("hash-1", Ct); + Assert.Equal((later, later.AddDays(30)), (touched!.LastUsed, touched.Expires)); + Assert.False(await db.Tokens.TouchAsync("expired", TestData.Now, later, Ct)); + Assert.False(await db.Tokens.TouchAsync("missing", TestData.Now, later, Ct)); + + Assert.True(await db.Tokens.RevokeAsync("hash-1", Ct)); + Assert.False(await db.Tokens.RevokeAsync("hash-1", Ct)); + Assert.False(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct)); + Assert.True((await db.Tokens.GetAsync("hash-1", Ct))!.Revoked); + Assert.Equal(2, await db.Tokens.RevokeAllAsync(user.Id, Ct)); + Assert.Count(3, await db.Tokens.ListByUserAsync(user.Id, Ct)); + Assert.Equal(3, await db.Tokens.PurgeAsync(TestData.Now, Ct)); + } + + [Test] + public async Task RenderNodesReportHeartbeats() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var node = Node(user.Id); + await db.RenderNodes.RegisterAsync(node, Ct); + var stale = Node(user.Id) with { ClientName = "old-pc", LastHeartbeat = TestData.Now.AddHours(-1) }; + await db.RenderNodes.RegisterAsync(stale, Ct); + await db.RenderNodes.RegisterAsync(node with { CapabilitiesJson = "{\"encoders\": [\"nvenc\"]}" }, Ct); + Assert.Equal("{\"encoders\": [\"nvenc\"]}", (await db.RenderNodes.GetAsync(node.Id, Ct))!.CapabilitiesJson); + + Assert.SequenceEqual([node.Id], (await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct)).Select(n => n.Id)); + Assert.True(await db.RenderNodes.HeartbeatAsync(stale.Id, "rendering", TestData.Now.AddMinutes(1), Ct)); + var online = await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct); + Assert.SequenceEqual([stale.Id, node.Id], online.Select(n => n.Id)); + Assert.Equal("rendering", online[0].State); + Assert.True(await db.RenderNodes.DeleteAsync(stale.Id, Ct)); + Assert.False(await db.RenderNodes.HeartbeatAsync(stale.Id, "idle", TestData.Now, Ct)); + } + + [Test] + public async Task SettingsAreTypedAndScoped() + { + var db = await OpenTitanoAsync(); + var archive = Guid.CreateVersion7(); + var user = Guid.CreateVersion7(); + var preferences = new Preferences("it", 4, [1.5, 2]); + await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences, TestJson.Default.Preferences, Ct); + await db.Settings.SetAsync(SettingScope.User, user, "ui", preferences with { Language = "en" }, TestJson.Default.Preferences, Ct); + await db.Settings.SetJsonAsync(SettingScope.Archive, archive, "proxy", "{\"longEdge\": 1920}", Ct); + + Assert.Equal(preferences, await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct), "app scope"); + Assert.Equal("en", (await db.Settings.GetAsync(SettingScope.User, user, "ui", TestJson.Default.Preferences, Ct))!.Language); + Assert.Null(await db.Settings.GetAsync(SettingScope.User, Guid.CreateVersion7(), "ui", TestJson.Default.Preferences, Ct)); + Assert.Equal(1920, JsonDocument.Parse((await db.Settings.GetJsonAsync(SettingScope.Archive, archive, "proxy", Ct))!).RootElement.GetProperty("longEdge").GetInt32()); + + await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences with { Columns = 6 }, TestJson.Default.Preferences, Ct); + Assert.Equal(6, (await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct))!.Columns); + await db.Settings.SetAsync(SettingScope.App, null, "count", 42, TestJson.Default.Int32, Ct); + Assert.SequenceEqual(["count", "ui"], (await db.Settings.ListAsync(SettingScope.App, null, Ct)).Keys.Order(StringComparer.Ordinal)); + Assert.True(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct)); + Assert.False(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct)); + + await Assert.ThrowsAsync(() => db.Settings.GetJsonAsync(SettingScope.User, null, "ui", Ct)); + await Assert.ThrowsAsync(() => db.Settings.GetJsonAsync(SettingScope.App, user, "ui", Ct)); + await Assert.ThrowsAsync(() => db.Settings.SetJsonAsync(SettingScope.App, null, "bad", "{not json", Ct)); + } + + [Test] + public async Task AuditLogPagesNewestFirst() + { + var db = await OpenTitanoAsync(); + var user = Guid.CreateVersion7(); + var entries = Enumerable.Range(0, 9).Select(i => new AuditEntry + { + Id = Guid.CreateVersion7(), At = TestData.Now.AddSeconds(i / 2), Action = "sequence.delete", UserId = i % 3 == 0 ? user : null, + Username = "alice", TargetKind = "sequence", TargetId = Guid.CreateVersion7().ToString(), Details = "{\"frames\": 10}", RemoteAddress = "10.0.0.1", + }).ToList(); + foreach (var e in entries) await db.Audit.AppendAsync(e, Ct); + + var seen = new List(); + string? cursor = null; + do + { + var page = await db.Audit.ListAsync(limit: 4, cursor: cursor, cancellationToken: Ct); + seen.AddRange(page.Items); + cursor = page.NextCursor; + } + while (cursor is not null); + Assert.SequenceEqual( + entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id.ToString("D"), StringComparer.Ordinal), + seen); + Assert.Equal(3, (await db.Audit.ListAsync(user, cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task UploadsTrackChunksAndStates() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var created = await db.Uploads.CreateAsync(Upload(user.Id, 8 * 1024 * 1024 * 9 + 1), Ct); + Assert.Equal(10, created.ChunkCount); + Assert.Equal(2, created.Received.Length); + Assert.Equal(created.Id, (await db.Uploads.FindReceivingAsync(user.Id, created.Sha256.ToUpperInvariant(), Ct))!.Id); + + foreach (var chunk in new[] { 0, 9, 3, 9 }) + { + var updated = await db.Uploads.MarkChunkReceivedAsync(created.Id, chunk, Ct); + Assert.True(updated!.HasChunk(chunk)); + } + await Assert.ThrowsAsync(() => db.Uploads.MarkChunkReceivedAsync(created.Id, 10, Ct)); + Assert.Null(await db.Uploads.MarkChunkReceivedAsync(Guid.CreateVersion7(), 0, Ct)); + + var stored = Assert.NotNull(await db.Uploads.GetAsync(created.Id, Ct)); + Assert.Equal(3, stored.ReceivedCount); + Assert.SequenceEqual([0, 3, 9], Enumerable.Range(0, 10).Where(stored.HasChunk)); + Assert.False(stored.IsComplete); + + await Task.WhenAll(Enumerable.Range(0, 10).Select(i => db.Uploads.MarkChunkReceivedAsync(created.Id, i, Ct))); + Assert.True((await db.Uploads.GetAsync(created.Id, Ct))!.IsComplete); + + Assert.Count(1, await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct)); + var frameId = Guid.CreateVersion7(); + Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, frameId, Ct)); + Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, cancellationToken: Ct)); + var committed = await db.Uploads.GetAsync(created.Id, Ct); + Assert.Equal((UploadState.Committed, (Guid?)frameId), (committed!.State, committed.FrameId)); + Assert.Empty(await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct)); + Assert.Null(await db.Uploads.FindReceivingAsync(user.Id, created.Sha256, Ct)); + Assert.True(await db.Uploads.DeleteAsync(created.Id, Ct)); + } + + private static SessionToken Token(Guid userId, string hash) => new() + { + TokenHash = hash, + UserId = userId, + ClientName = "Titano desktop", + Created = TestData.Now, + Expires = TestData.Now.AddDays(30), + LastUsed = TestData.Now, + }; + + private static RenderNode Node(Guid userId) => new() + { + Id = Guid.CreateVersion7(), + UserId = userId, + ClientName = "studio-pc", + CapabilitiesJson = "{\"encoders\": []}", + LastHeartbeat = TestData.Now, + }; + + private static Upload Upload(Guid userId, long size) => new() + { + Id = Guid.CreateVersion7(), + UserId = userId, + FileName = "IMG_0001.CR3", + Size = size, + Sha256 = new string('A', 64), + CapturedAt = new DateTime(2026, 9, 28, 18, 0, 0), + ChunkSize = 8 * 1024 * 1024, + Created = TestData.Now, + UpdatedAt = TestData.Now, + }; +} + +public sealed record Preferences(string Language, int Columns, double[] Zoom) +{ + public bool Equals(Preferences? other) => + other is not null && Language == other.Language && Columns == other.Columns && Zoom.SequenceEqual(other.Zoom); + + public override int GetHashCode() => HashCode.Combine(Language, Columns); +} + +[JsonSerializable(typeof(Preferences))] +[JsonSerializable(typeof(int))] +internal sealed partial class TestJson : JsonSerializerContext; + +public sealed class SqliteServerRepositoryTests(TestContext context) : ServerRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresServerRepositoryTests(TestContext context) : ServerRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} From c6857983d9b700de24d2590bb49476054ca5b2d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:06:13 +0000 Subject: [PATCH 076/188] style: whitespace formatting after metadata merge; record metadata decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 5 ++ .../Metadata/Builders/IfdSpec.cs | 48 +++++++++---------- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index b98dc3e8..4414bbab 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -45,3 +45,8 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Virtual-camera zoom is interpolated geometrically; trail length L ↦ decay 0.01^(1/L). | Linear zoom / half-life | Even perceived speed; the trail is gone at its stated length. | | 2026-10-02 | Motion estimation, sharpness and noise use sRGB-encoded luminance. | Linear light | Shadows keep texture weight; less exposure dependence. | | 2026-10-02 | Archive presets use 0.30 bpp (≈60 Mb/s at 4K24 HEVC 10-bit); share presets use the brief's per-codec defaults (0.10/0.07/0.05). | 0.07 bpp everywhere | An archive must survive later re-encoding; star fields are the hardest content. | +| 2026-10-02 | All metadata fallback chains (time, ISO, serial, lens, rating, size) live in `MetadataBuilder.Build`; parsers only collect candidates. | Fallbacks inside each parser | One place for priority rules; parsers are order-independent. | +| 2026-10-02 | `MetadataReader.Read(path)` throws when the file cannot be opened; malformed content becomes warnings (with a parser-fault safety net the fuzz tests require to stay unused). | Swallow everything | An unopenable file is not malformed input. | +| 2026-10-02 | HEIF `irot`/`imir` override Exif orientation (imir axis 0 = top↔bottom). | Exif first | HEIF decoders apply the transforms themselves; both would rotate twice. | +| 2026-10-02 | Main image size comes from the container's own size field (SOF, IHDR, ispe, VP8X, RAF crop record, RW2 borders, CR3 CMP1) before raster IFDs. | Always the largest raster IFD | That is what each container defines and what decoders output. | +| 2026-10-02 | Only MPF large-thumbnail entries count as previews; XMP date-only values are never used as capture times. | Every secondary image / midnight | Gain maps are not previews; midnight would be invented. | diff --git a/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs index 393cbfc0..a1a6af42 100644 --- a/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs +++ b/tests/Titano.Core.Tests/Metadata/Builders/IfdSpec.cs @@ -225,37 +225,37 @@ internal static class TiffFile case byte[] raw: return (raw, (uint)raw.Length); case ushort[] shorts: - { - var b = new byte[2 * shorts.Length]; - for (var i = 0; i < shorts.Length; i++) Write16(b.AsSpan(2 * i), shorts[i]); - return (b, (uint)shorts.Length); - } + { + var b = new byte[2 * shorts.Length]; + for (var i = 0; i < shorts.Length; i++) Write16(b.AsSpan(2 * i), shorts[i]); + return (b, (uint)shorts.Length); + } case uint[] longs: - { - var b = new byte[4 * longs.Length]; - for (var i = 0; i < longs.Length; i++) Write32(b.AsSpan(4 * i), longs[i]); - return (b, (uint)longs.Length); - } + { + var b = new byte[4 * longs.Length]; + for (var i = 0; i < longs.Length; i++) Write32(b.AsSpan(4 * i), longs[i]); + return (b, (uint)longs.Length); + } case (uint, uint)[] rationals: - { - var b = new byte[8 * rationals.Length]; - for (var i = 0; i < rationals.Length; i++) { - Write32(b.AsSpan(8 * i), rationals[i].Item1); - Write32(b.AsSpan(8 * i + 4), rationals[i].Item2); + var b = new byte[8 * rationals.Length]; + for (var i = 0; i < rationals.Length; i++) + { + Write32(b.AsSpan(8 * i), rationals[i].Item1); + Write32(b.AsSpan(8 * i + 4), rationals[i].Item2); + } + return (b, (uint)rationals.Length); } - return (b, (uint)rationals.Length); - } case (int, int)[] signed: - { - var b = new byte[8 * signed.Length]; - for (var i = 0; i < signed.Length; i++) { - Write32(b.AsSpan(8 * i), (uint)signed[i].Item1); - Write32(b.AsSpan(8 * i + 4), (uint)signed[i].Item2); + var b = new byte[8 * signed.Length]; + for (var i = 0; i < signed.Length; i++) + { + Write32(b.AsSpan(8 * i), (uint)signed[i].Item1); + Write32(b.AsSpan(8 * i + 4), (uint)signed[i].Item2); + } + return (b, (uint)signed.Length); } - return (b, (uint)signed.Length); - } default: throw new InvalidOperationException("Unsupported test value " + v.Data.GetType()); } From 5861d6d640e564eb58467c7cf6273101b986b341 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:06:17 +0000 Subject: [PATCH 077/188] feat(imaging): add separable resampler and pixel conversion tests Two-pass Lanczos3 (downscale, support stretched by the reduction) and Catmull-Rom (upscale) with normalised, edge-folded weights; exact area-average box path for thumbnails; pass order chosen by cost, Vector inner loops, parallel rows. Tests cover constant images, energy preservation, step ringing against the kernel's exact discrete bound, Exif orientations and dithering. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Imaging/Resampler.cs | 201 ++++++++++++++++++ .../Imaging/PixelConvertTests.cs | 128 +++++++++++ .../Imaging/ResamplerTests.cs | 156 ++++++++++++++ 3 files changed, 485 insertions(+) create mode 100644 src/Titano.Core/Imaging/Resampler.cs create mode 100644 tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs create mode 100644 tests/Titano.Core.Tests/Imaging/ResamplerTests.cs diff --git a/src/Titano.Core/Imaging/Resampler.cs b/src/Titano.Core/Imaging/Resampler.cs new file mode 100644 index 00000000..225917d1 --- /dev/null +++ b/src/Titano.Core/Imaging/Resampler.cs @@ -0,0 +1,201 @@ +using System.Numerics; + +namespace Titano.Core.Imaging; + +/// Reconstruction filters for . +public enum ResampleFilter +{ + /// Lanczos3 on axes that shrink, Catmull-Rom on axes that grow. + Auto, + + /// Exact area average (no ringing; fastest for large reductions such as thumbnails). + Box, + + Lanczos3, + CatmullRom, +} + +/// +/// Separable two-pass resampling of linear-light s. When shrinking, the kernel is stretched +/// by the reduction factor (proper low-pass support); weights are normalised and folded at the edges (clamp), so +/// constant images stay constant and mean energy is preserved. Rows are processed in parallel. +/// +public static class Resampler +{ + /// Resizes into a new buffer with the same channel count. + public static ImageBuffer Resize(ImageBuffer source, int width, int height, ResampleFilter filter = ResampleFilter.Auto, int maxDegreeOfParallelism = -1) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + var parallel = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }; + if (width == source.Width && height == source.Height) return source.Clone(); + var wx = width == source.Width ? null : Weights.Build(source.Width, width, filter); + var wy = height == source.Height ? null : Weights.Build(source.Height, height, filter); + if (wx is null) return Vertical(source, wy!, parallel); + if (wy is null) return Horizontal(source, wx, parallel); + + // Run the pass that leaves the smaller intermediate work first. + var horizontalFirst = (long)source.Height * width * wx.Stride + (long)height * width * wy.Stride + <= (long)height * source.Width * wy.Stride + (long)height * width * wx.Stride; + using var intermediate = horizontalFirst ? Horizontal(source, wx, parallel) : Vertical(source, wy, parallel); + return horizontalFirst ? Vertical(intermediate, wy, parallel) : Horizontal(intermediate, wx, parallel); + } + + /// Area-average reduction so that the long edge is at most + /// (a copy when the image is already small enough). + public static ImageBuffer Thumbnail(ImageBuffer source, int maxLongEdge) + { + var (w, h) = FitWithin(source.Width, source.Height, maxLongEdge); + return w == source.Width && h == source.Height ? source.Clone() : Resize(source, w, h, ResampleFilter.Box); + } + + /// Largest size with the same aspect ratio whose long edge is ≤ (never upscales). + public static (int Width, int Height) FitWithin(int width, int height, int maxLongEdge) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLongEdge); + var longEdge = Math.Max(width, height); + if (longEdge <= maxLongEdge) return (width, height); + var scale = maxLongEdge / (double)longEdge; + return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale))); + } + + private static ImageBuffer Horizontal(ImageBuffer source, Weights w, ParallelOptions parallel) + { + var result = new ImageBuffer(w.Length, source.Height, source.Channels, clear: false); + Parallel.For(0, source.Height, parallel, y => + { + for (var c = 0; c < source.Channels; c++) + { + ReadOnlySpan src = source.Row(c, y); + var dst = result.Row(c, y); + for (var x = 0; x < dst.Length; x++) + { + dst[x] = Dot(src.Slice(w.Start[x], w.Count[x]), w.Values.AsSpan(x * w.Stride, w.Count[x])); + } + } + }); + return result; + } + + private static ImageBuffer Vertical(ImageBuffer source, Weights w, ParallelOptions parallel) + { + var result = new ImageBuffer(source.Width, w.Length, source.Channels, clear: false); + Parallel.For(0, w.Length, parallel, y => + { + var taps = w.Values.AsSpan(y * w.Stride, w.Count[y]); + for (var c = 0; c < source.Channels; c++) + { + var dst = result.Row(c, y); + dst.Clear(); + for (var k = 0; k < taps.Length; k++) MultiplyAdd(source.Row(c, w.Start[y] + k), taps[k], dst); + } + }); + return result; + } + + private static float Dot(ReadOnlySpan a, ReadOnlySpan b) + { + var i = 0; + var sum = 0f; + if (Vector.IsHardwareAccelerated && a.Length >= Vector.Count) + { + var acc = Vector.Zero; + for (; i <= a.Length - Vector.Count; i += Vector.Count) acc += new Vector(a[i..]) * new Vector(b[i..]); + sum = Vector.Sum(acc); + } + for (; i < a.Length; i++) sum += a[i] * b[i]; + return sum; + } + + private static void MultiplyAdd(ReadOnlySpan src, float weight, Span dst) + { + var i = 0; + if (Vector.IsHardwareAccelerated) + { + var w = new Vector(weight); + for (; i <= dst.Length - Vector.Count; i += Vector.Count) (new Vector(dst[i..]) + new Vector(src[i..]) * w).CopyTo(dst[i..]); + } + for (; i < dst.Length; i++) dst[i] += src[i] * weight; + } + + /// Per output sample: a contiguous source range and its normalised weights (stride-padded). + private sealed class Weights + { + public required int Length { get; init; } + public required int Stride { get; init; } + public required int[] Start { get; init; } + public required int[] Count { get; init; } + public required float[] Values { get; init; } + + public static Weights Build(int source, int target, ResampleFilter filter) + { + var scale = target / (double)source; + var kind = filter == ResampleFilter.Auto ? (scale < 1 ? ResampleFilter.Lanczos3 : ResampleFilter.CatmullRom) : filter; + var radius = kind switch { ResampleFilter.Lanczos3 => 3.0, ResampleFilter.CatmullRom => 2.0, _ => 0.5 }; + var stretch = Math.Max(1.0, 1 / scale); + var stride = (int)Math.Ceiling(2 * radius * stretch) + 2; + var start = new int[target]; + var count = new int[target]; + var values = new float[target * stride]; + var taps = new double[source]; + for (var i = 0; i < target; i++) + { + double lo, hi; + if (kind == ResampleFilter.Box) + { + lo = i / scale; + hi = (i + 1) / scale; + } + else + { + var center = (i + 0.5) / scale; + lo = center - radius * stretch; + hi = center + radius * stretch; + } + int first = Math.Max(0, (int)Math.Floor(lo) - 1), last = Math.Min(source - 1, (int)Math.Ceiling(hi)); + int left = (int)Math.Floor(lo) - 1, right = (int)Math.Ceiling(hi); + Array.Clear(taps, first, last - first + 1); + var sum = 0.0; + for (var j = left; j <= right; j++) + { + double weight; + if (kind == ResampleFilter.Box) + { + weight = Math.Max(0, Math.Min(hi, j + 1) - Math.Max(lo, j)); + } + else + { + var x = (j + 0.5 - (i + 0.5) / scale) / stretch; + weight = kind == ResampleFilter.Lanczos3 ? Lanczos3(x) : CatmullRom(x); + } + if (weight == 0) continue; + taps[Math.Clamp(j, 0, source - 1)] += weight; // clamp-to-edge folds outside taps inward + sum += weight; + } + while (first < last && taps[first] == 0) first++; + while (last > first && taps[last] == 0) last--; + start[i] = first; + count[i] = last - first + 1; + for (var j = first; j <= last; j++) values[i * stride + j - first] = (float)(taps[j] / sum); + } + return new Weights { Length = target, Stride = stride, Start = start, Count = count, Values = values }; + } + + private static double Lanczos3(double x) + { + x = Math.Abs(x); + if (x < 1e-9) return 1; + if (x >= 3) return 0; + var px = Math.PI * x; + return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px); + } + + private static double CatmullRom(double x) + { + x = Math.Abs(x); + return x < 1 ? (1.5 * x - 2.5) * x * x + 1 + : x < 2 ? ((-0.5 * x + 2.5) * x - 4) * x + 2 + : 0; + } + } +} diff --git a/tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs b/tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs new file mode 100644 index 00000000..17b2954e --- /dev/null +++ b/tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs @@ -0,0 +1,128 @@ +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Imaging; + +public sealed class PixelConvertTests +{ + [Theory] + [Case(1)] + [Case(2)] + [Case(3)] + [Case(4)] + public void EightBitRoundTripIsExact(int channels) + { + const int w = 19, h = 7; + var pixels = new byte[w * h * channels]; + new Random(channels).NextBytes(pixels); + var keepAlpha = channels is 2 or 4; + using var image = PixelConvert.FromInterleaved8(pixels, w, h, channels, outputChannels: keepAlpha ? 4 : 0); + Assert.Equal(keepAlpha ? 4 : channels == 1 ? 1 : 3, image.Channels); + var back = PixelConvert.ToInterleaved8(image, channels); + Assert.SequenceEqual(pixels, back); + } + + [Test] + public void SixteenBitRoundTripWithinOneCode() + { + var samples = Enumerable.Range(0, 3 * 4096).Select(i => (ushort)(i * 16 % 65536)).ToArray(); + using var image = PixelConvert.FromInterleaved16(samples, 64, 64, 3); + var back = PixelConvert.ToInterleaved16(image, 3); + for (var i = 0; i < samples.Length; i++) Assert.InRange(back[i], samples[i] - 1, samples[i] + 1); + using var linear = PixelConvert.FromInterleaved16(samples, 64, 64, 3, TransferFunction.Linear); + Assert.SequenceEqual(samples, PixelConvert.ToInterleaved16(linear, 3, TransferFunction.Linear)); + } + + [Test] + public void CustomMaximumScalesTwelveBitData() + { + ushort[] samples = [0, 2048, 4095]; + using var image = PixelConvert.FromInterleaved16(samples, 3, 1, 1, TransferFunction.Linear, maxValue: 4095); + Assert.Approximately(2048 / 4095.0, image[0, 1, 0], 1e-6); + Assert.Equal(1f, image[0, 2, 0]); + } + + [Test] + public void GrayRgbConversions() + { + using var gray = PixelConvert.FromInterleaved8([0, 128, 255], 3, 1, 1); + using var rgb = PixelConvert.GrayToRgb(gray); + Assert.Equal(3, rgb.Channels); + Assert.Equal(gray[0, 1, 0], rgb[2, 1, 0]); + using var back = PixelConvert.RgbToGray(rgb); + Assert.Approximately(gray[0, 1, 0], back[0, 1, 0], 1e-6); + using var colour = PixelConvert.FromInterleaved8([255, 0, 0], 1, 1, 3, TransferFunction.Linear); + Assert.Equal((byte)Math.Round(ColorSpace.LinearToSrgb(ColorSpace.LumaR) * 255), PixelConvert.ToInterleaved8(colour, 1)[0]); + } + + [Theory] + [Case(1)] + [Case(2)] + [Case(3)] + [Case(4)] + [Case(5)] + [Case(6)] + [Case(7)] + [Case(8)] + public void OrientationMatchesExifDefinition(int orientation) + { + // A 3×2 image with unique values; Exif row 0 / column 0 placement per orientation (CIPA DC-008 table). + using var source = new ImageBuffer(3, 2, 1); + for (var i = 0; i < 6; i++) source.Plane(0)[i] = i; + using var result = PixelConvert.ApplyOrientation(source, orientation); + float[] expected = orientation switch + { + 1 => [0, 1, 2, 3, 4, 5], + 2 => [2, 1, 0, 5, 4, 3], + 3 => [5, 4, 3, 2, 1, 0], + 4 => [3, 4, 5, 0, 1, 2], + 5 => [0, 3, 1, 4, 2, 5], + 6 => [3, 0, 4, 1, 5, 2], + 7 => [5, 2, 4, 1, 3, 0], + _ => [2, 5, 1, 4, 0, 3], + }; + Assert.Equal(orientation >= 5 ? 2 : 3, result.Width); + Assert.SequenceEqual(expected, result.Plane(0).ToArray()); + } + + [Test] + public void LargeOrientationUsesTilesCorrectly() + { + using var source = new ImageBuffer(301, 157, 3); + for (var i = 0; i < source.Data.Length; i++) source.Data[i] = i; + using var rotated = PixelConvert.ApplyOrientation(source, 6); + using var back = PixelConvert.ApplyOrientation(rotated, 8); + Assert.SequenceEqual(source.Data.ToArray(), back.Data.ToArray()); + } + + [Test] + public void ClampHandlesNaNAndRange() + { + var values = Enumerable.Range(0, 37).Select(i => i % 5 == 0 ? float.NaN : i / 10f - 1f).ToArray(); + PixelConvert.Clamp(values); + for (var i = 0; i < values.Length; i++) Assert.InRange(values[i], 0, 1); + Assert.Equal(0f, values[5]); + } + + [Test] + public void DitherBreaksBandingButKeepsTheMean() + { + using var ramp = new ImageBuffer(256, 64, 1); + for (var y = 0; y < 64; y++) + { + for (var x = 0; x < 256; x++) ramp[0, x, y] = (float)ColorSpace.SrgbToLinear((100 + x / 64.0) / 255); + } + var plain = PixelConvert.ToInterleaved8(ramp, 1); + var dithered = PixelConvert.ToInterleaved8(ramp, 1, dither: true); + Assert.True(plain.Distinct().Count() <= 5, "a 4-code ramp quantises to few levels"); + for (var x0 = 0; x0 < 256; x0 += 64) + { + var mean = 0.0; + for (var y = 0; y < 64; y++) + { + for (var x = x0; x < x0 + 64; x++) mean += dithered[y * 256 + x]; + } + Assert.Approximately(100 + (x0 + 31.5) / 64.0, mean / (64 * 64), 0.15); + } + } +} diff --git a/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs b/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs new file mode 100644 index 00000000..4497cebb --- /dev/null +++ b/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs @@ -0,0 +1,156 @@ +using System.Diagnostics; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Imaging; + +public sealed class ResamplerTests(TestContext context) +{ + private static ImageBuffer Filled(int w, int h, Func value, int channels = 3) + { + var image = new ImageBuffer(w, h, channels); + for (var c = 0; c < channels; c++) + { + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) image[c, x, y] = value(c, x, y); + } + } + return image; + } + + [Theory] + [Case(ResampleFilter.Lanczos3, 97, 31)] + [Case(ResampleFilter.Lanczos3, 400, 260)] + [Case(ResampleFilter.CatmullRom, 400, 260)] + [Case(ResampleFilter.CatmullRom, 20, 15)] + [Case(ResampleFilter.Box, 37, 23)] + [Case(ResampleFilter.Box, 333, 211)] + [Case(ResampleFilter.Auto, 300, 40)] + public void ConstantImageStaysConstant(ResampleFilter filter, int width, int height) + { + using var source = Filled(150, 100, (c, _, _) => 0.25f + 0.25f * c); + using var result = Resampler.Resize(source, width, height, filter); + Assert.Equal(width, result.Width); + Assert.Equal(height, result.Height); + for (var c = 0; c < 3; c++) + { + foreach (var v in result.Plane(c)) Assert.Approximately(0.25 + 0.25 * c, v, 1e-5); + } + } + + [Theory] + [Case(ResampleFilter.Lanczos3)] + [Case(ResampleFilter.Box)] + [Case(ResampleFilter.CatmullRom)] + public void DownscalePreservesEnergy(ResampleFilter filter) + { + var rng = new Random(4); + using var source = Filled(640, 480, (_, x, y) => (float)(rng.NextDouble() * 0.5 + 0.4 * Math.Sin(x * 0.05) * Math.Cos(y * 0.07) + 0.4), 1); + using var result = Resampler.Resize(source, 213, 157, filter); + double Mean(ImageBuffer b) => b.Plane(0).ToArray().Average(v => (double)v); + var ratio = Mean(result) / Mean(source); + context.Log($"{filter}: mean ratio {ratio:F5}"); + Assert.Approximately(1, ratio, 0.005); + } + + [Theory] + [Case(ResampleFilter.Lanczos3, 0.3)] + [Case(ResampleFilter.Lanczos3, 2.7)] + [Case(ResampleFilter.CatmullRom, 3.0)] + [Case(ResampleFilter.CatmullRom, 0.45)] + [Case(ResampleFilter.Box, 0.3)] + public void StepRingingStaysWithinKernelBounds(ResampleFilter filter, double scale) + { + const int w = 200; + using var step = Filled(w, 4, (_, x, _) => x < w / 2 + 0.3 ? 0f : 1f, 1); + using var result = Resampler.Resize(step, (int)(w * scale), 4, filter); + var values = result.Row(0, 1).ToArray(); + var bound = StepBound(filter, scale); + context.Log($"{filter} ×{scale}: range [{values.Min():F4}, {values.Max():F4}], bound {bound:F4}"); + Assert.GreaterOrEqual(values.Min(), -bound - 1e-4); + Assert.LessOrEqual(values.Max(), 1 + bound + 1e-4); + if (filter == ResampleFilter.Box) + { + Assert.GreaterOrEqual(values.Min(), 0); + Assert.LessOrEqual(values.Max(), 1 + 1e-6); + } + Assert.Approximately(0, values[0], 1e-5); + Assert.Approximately(1, values[^1], 1e-5); + } + + /// + /// The "Lanczos bound" for a step at this scale: every output sample is a normalised sum of kernel taps spaced + /// 1/stretch apart, so on a step it equals a partial sum of those taps. The bound is the largest excursion + /// outside [0, 1] of any partial sum, over all sub-pixel phases. + /// + private static double StepBound(ResampleFilter filter, double scale) + { + if (filter == ResampleFilter.Box) return 0; + var radius = filter == ResampleFilter.Lanczos3 ? 3.0 : 2.0; + var stretch = Math.Max(1, 1 / scale); + var reach = (int)Math.Ceiling(radius * stretch) + 1; + var worst = 0.0; + for (var phase = 0.0; phase < 1; phase += 1 / 512.0) + { + var taps = new List(); + for (var k = -reach; k <= reach; k++) taps.Add(Kernel(filter, (k + phase) / stretch)); + var total = taps.Sum(); + var running = 0.0; + foreach (var t in taps) + { + running += t / total; + worst = Math.Max(worst, Math.Max(running - 1, -running)); + } + } + return worst; + } + + private static double Kernel(ResampleFilter filter, double x) + { + var a = Math.Abs(x); + if (filter == ResampleFilter.Lanczos3) return a < 1e-12 ? 1 : a >= 3 ? 0 : 3 * Math.Sin(Math.PI * a) * Math.Sin(Math.PI * a / 3) / (Math.PI * Math.PI * a * a); + return a < 1 ? (1.5 * a - 2.5) * a * a + 1 : a < 2 ? ((-0.5 * a + 2.5) * a - 4) * a + 2 : 0; + } + + [Test] + public void ThumbnailFitsAndAveragesAreas() + { + using var source = Filled(1200, 800, (c, x, _) => x % 2 == 0 ? 1f : 0f); + using var thumb = Resampler.Thumbnail(source, 300); + Assert.Equal(300, thumb.Width); + Assert.Equal(200, thumb.Height); + foreach (var v in thumb.Plane(1)) Assert.Approximately(0.5, v, 1e-5); + Assert.Equal((300, 200), Resampler.FitWithin(1200, 800, 300)); + Assert.Equal((10, 20), Resampler.FitWithin(10, 20, 300)); + using var small = Resampler.Thumbnail(thumb, 1000); + Assert.Equal(300, small.Width); + } + + [Test] + public void UpscaleInterpolatesThroughSamples() + { + using var source = Filled(16, 16, (_, x, y) => x * 0.05f + y * 0.01f, 1); + using var up = Resampler.Resize(source, 64, 64, ResampleFilter.CatmullRom); + // Catmull-Rom reproduces linear ramps exactly away from the edges. + for (var x = 8; x < 56; x++) + { + var sx = (x + 0.5) / 4 - 0.5; + Assert.Approximately(sx * 0.05 + ((20 + 0.5) / 4 - 0.5) * 0.01, up[0, x, 20], 1e-4); + } + } + + [Test] + public void TwentyFourMegapixelThumbnailIsFast() + { + using var source = new ImageBuffer(6000, 4000, 3, clear: true); + var sw = Stopwatch.StartNew(); + using var thumb = Resampler.Thumbnail(source, 320); + var box = sw.Elapsed; + sw.Restart(); + using var lanczos = Resampler.Resize(source, 1920, 1280); + context.Log($"24 MP → 320 px box {box.TotalMilliseconds:F0} ms; → 1920 px Lanczos3 {sw.Elapsed.TotalMilliseconds:F0} ms"); + Assert.Equal(320, thumb.Width); + Assert.Less(box.TotalSeconds, 2.5); + } +} From aba6d629b90bfb3baa65cacbf8f922ce406202d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:07:59 +0000 Subject: [PATCH 078/188] fix(video): roll back rejected MP4 samples and keep inspector reports read-only Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/Mp4/Mp4Muxer.cs | 22 ++- src/Titano.Core/Video/Mp4Inspector.cs | 146 ++++++++++-------- .../Titano.Core.Tests/Video/Mp4MuxerTests.cs | 16 ++ 3 files changed, 109 insertions(+), 75 deletions(-) diff --git a/src/Titano.Core/Video/Mp4/Mp4Muxer.cs b/src/Titano.Core/Video/Mp4/Mp4Muxer.cs index 2e1f3e74..27bccd5d 100644 --- a/src/Titano.Core/Video/Mp4/Mp4Muxer.cs +++ b/src/Titano.Core/Video/Mp4/Mp4Muxer.cs @@ -113,6 +113,7 @@ public sealed class Mp4Muxer /// /// Appends one access unit (H.264/HEVC: Annex-B or 4-byte length-prefixed NAL units; AV1: a temporal unit of OBUs) /// in decode order. is presentation minus decode time and may be negative. + /// A unit holding only parameter sets is recorded like and adds no sample. /// public void WriteSample(ReadOnlySpan data, long duration90k, bool isSync, long compositionOffset90k = 0) { @@ -122,8 +123,14 @@ public sealed class Mp4Muxer var start = _position; if (_stream.Position != start) _stream.Position = start; - var size = _config.Codec == VideoCodec.Av1 ? WriteObus(data) : WriteNalUnits(data); - if (size == 0) throw new ArgumentException("The sample contains no picture data", nameof(data)); + var (size, picture) = _config.Codec == VideoCodec.Av1 ? WriteObus(data) : WriteNalUnits(data); + if (size == 0) return; // only parameter sets / delimiters: recorded for the sample entry, no sample + if (!picture) + { + _stream.Position = start; // the next sample overwrites what was written + throw new ArgumentException("The sample contains no picture data", nameof(data)); + } + _position += size; if (_sizes.Count == 0 && !isSync) Log.Warning(LogCategory, "First sample is not a sync sample; players may not start decoding"); if (_chunkSampleCounts.Count == 0 || _chunkTicks >= ChunkTicks || _chunkBytes >= ChunkBytes) @@ -161,11 +168,12 @@ public sealed class Mp4Muxer _stream.Write(moov); if (_config.FastStart) MoveMoovToFront(configuration, moov.Length); else _position += moov.Length; + if (_stream.Length > _position) _stream.SetLength(_position); // drop bytes of a rejected last sample _stream.Flush(); _completed = true; } - private long WriteNalUnits(ReadOnlySpan data) + private (long Size, bool Picture) WriteNalUnits(ReadOnlySpan data) { Span length = stackalloc byte[4]; long size = 0; @@ -180,11 +188,10 @@ public sealed class Mp4Muxer size += 4 + nal.Length; picture |= IsPicture(nal[0]); } - _position += size; - return picture ? size : 0; + return (size, picture); } - private long WriteObus(ReadOnlySpan data) + private (long Size, bool Picture) WriteObus(ReadOnlySpan data) { var obus = Av1ObuParser.Split(data); if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length) @@ -209,8 +216,7 @@ public sealed class Mp4Muxer _stream.Write(obu.Payload(data)); size += n + obu.PayloadLength; } - _position += size; - return picture ? size : 0; + return (size, picture); } private static int WriteSizedHeader(Span header, ReadOnlySpan data, Av1Obu obu) diff --git a/src/Titano.Core/Video/Mp4Inspector.cs b/src/Titano.Core/Video/Mp4Inspector.cs index 1edfa8c7..d4cb3bf6 100644 --- a/src/Titano.Core/Video/Mp4Inspector.cs +++ b/src/Titano.Core/Video/Mp4Inspector.cs @@ -28,9 +28,16 @@ public readonly record struct Mp4SampleInfo(long Offset, int Size, long DecodeTi /// Result of : structure, stream properties and problems found. public sealed class Mp4Report { - public List Errors { get; } = []; - public List Warnings { get; } = []; - public bool IsValid => Errors.Count == 0; + private readonly List _errors = []; + private readonly List _warnings = []; + + /// Problems that make the file invalid or unplayable. + public IReadOnlyList Errors => _errors; + + /// Oddities players usually tolerate. + public IReadOnlyList Warnings => _warnings; + + public bool IsValid => _errors.Count == 0; public IReadOnlyList Boxes { get; internal set; } = []; /// Sample entry four-character code ("avc1", "hvc1", "av01"…). @@ -68,6 +75,10 @@ public sealed class Mp4Report public bool HasEditList { get; internal set; } public IReadOnlyList Samples { get; internal set; } = []; + internal void Error(string message) => _errors.Add(message); + + internal void Warning(string message) => _warnings.Add(message); + public override string ToString() { var sb = new StringBuilder(); @@ -91,6 +102,7 @@ public static class Mp4Inspector private const int MaxBoxes = 100_000; private const long MaxMoovBytes = 256L << 20; private const int CheckedSamples = 4; + private const long MaxSamples = 20_000_000; public static Mp4Report Inspect(string path) { @@ -103,7 +115,7 @@ public static class Mp4Inspector var report = new Mp4Report(); if (!stream.CanSeek || !stream.CanRead) { - report.Errors.Add("stream is not readable and seekable"); + report.Error("stream is not readable and seekable"); return report; } try @@ -112,7 +124,7 @@ public static class Mp4Inspector } catch (IOException ex) { - report.Errors.Add("read failed: " + ex.Message); + report.Error("read failed: " + ex.Message); } return report; } @@ -138,7 +150,7 @@ public static class Mp4Inspector { if (read < 16) { - report.Errors.Add($"box '{type}' at {pos} is truncated"); + report.Error($"box '{type}' at {pos} is truncated"); break; } size = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(header[8..]), long.MaxValue); @@ -151,12 +163,12 @@ public static class Mp4Inspector } if (size < headerSize) { - report.Errors.Add($"box '{type}' at {pos} has invalid size {size}"); + report.Error($"box '{type}' at {pos} has invalid size {size}"); break; } if (size > length - pos) { - report.Errors.Add($"box '{type}' at {pos} extends past the end of the file ({size} > {length - pos} bytes)"); + report.Error($"box '{type}' at {pos} extends past the end of the file ({size} > {length - pos} bytes)"); size = length - pos; } @@ -165,11 +177,11 @@ public static class Mp4Inspector { if (moov is not null) { - report.Errors.Add("more than one moov box"); + report.Error("more than one moov box"); } else if (size - headerSize > MaxMoovBytes) { - report.Errors.Add($"moov is implausibly large ({size} bytes)"); + report.Error($"moov is implausibly large ({size} bytes)"); } else { @@ -182,22 +194,22 @@ public static class Mp4Inspector var box = new Mp4Box(type, pos, size, headerSize, children); if (type == "moov" && moov is null && children.Count > 0) moov = box; if (type == "mdat") mdats.Add((pos + headerSize, pos + size)); - if (type == "moof") report.Warnings.Add("fragmented MP4 (moof) is not inspected"); + if (type == "moof") report.Warning("fragmented MP4 (moof) is not inspected"); top.Add(box); pos += size; } - if (pos < length && budget > 0) report.Warnings.Add($"{length - pos} trailing bytes after the last box"); + if (pos < length && budget > 0) report.Warning($"{length - pos} trailing bytes after the last box"); report.Boxes = top; if (top.Count == 0 || top[0].Type != "ftyp") { - if (top.Exists(b => b.Type == "ftyp")) report.Warnings.Add("ftyp is not the first box"); - else report.Errors.Add("ftyp box missing"); + if (top.Exists(b => b.Type == "ftyp")) report.Warning("ftyp is not the first box"); + else report.Error("ftyp box missing"); } - if (mdats.Count == 0) report.Errors.Add("mdat box missing"); + if (mdats.Count == 0) report.Error("mdat box missing"); if (moov is null) { - report.Errors.Add("moov box missing or empty"); + report.Error("moov box missing or empty"); return; } report.FastStart = mdats.Count > 0 && moov.Offset < mdats[0].Start; @@ -225,7 +237,7 @@ public static class Mp4Inspector } if (size < headerSize || size > end - pos) { - report.Errors.Add($"box '{type}' at {baseOffset + pos} overruns its parent"); + report.Error($"box '{type}' at {baseOffset + pos} overruns its parent"); return list; } var payloadStart = pos + headerSize; @@ -254,7 +266,7 @@ public static class Mp4Inspector private static void InspectMovie(Stream stream, Mp4Box moov, List<(long Start, long End)> mdats, Mp4Report report) { var mvhd = moov.Child("mvhd"); - if (mvhd is null) report.Errors.Add("mvhd missing"); + if (mvhd is null) report.Error("mvhd missing"); var movieScale = mvhd is null ? 0u : ReadTimescale(mvhd.Payload.Span, out _); Mp4Box? trak = null; @@ -268,25 +280,25 @@ public static class Mp4Inspector } if (trak is null) { - report.Errors.Add("no video track (trak with hdlr 'vide')"); + report.Error("no video track (trak with hdlr 'vide')"); return; } - if (trak.Child("tkhd") is null) report.Errors.Add("tkhd missing"); + if (trak.Child("tkhd") is null) report.Error("tkhd missing"); var mdia = trak.Child("mdia"); var mdhd = mdia?.Child("mdhd"); var minf = mdia?.Child("minf"); var stbl = minf?.Child("stbl"); - if (mdhd is null) report.Errors.Add("mdhd missing"); - if (minf?.Child("vmhd") is null) report.Errors.Add("vmhd missing"); - if (minf?.Child("dinf")?.Child("dref") is null) report.Errors.Add("dinf/dref missing"); + if (mdhd is null) report.Error("mdhd missing"); + if (minf?.Child("vmhd") is null) report.Error("vmhd missing"); + if (minf?.Child("dinf")?.Child("dref") is null) report.Error("dinf/dref missing"); if (stbl is null) { - report.Errors.Add("stbl missing"); + report.Error("stbl missing"); return; } long mdhdDuration = 0; var mediaScale = mdhd is null ? 0u : ReadTimescale(mdhd.Payload.Span, out mdhdDuration); - if (mdhd is not null && mediaScale == 0) report.Errors.Add("mdhd timescale is zero"); + if (mdhd is not null && mediaScale == 0) report.Error("mdhd timescale is zero"); report.TimeScale = mediaScale; var config = InspectSampleDescription(stbl, report); @@ -298,20 +310,20 @@ public static class Mp4Inspector long stscTotal = 0; foreach (var n in samplesPerChunk) stscTotal += n; - if (durations.Length != sizes.Length) report.Errors.Add($"stts covers {durations.Length} samples, stsz has {sizes.Length}"); - if (stscTotal != sizes.Length) report.Errors.Add($"stsc/stco map {stscTotal} samples, stsz has {sizes.Length}"); + if (durations.Length != sizes.Length) report.Error($"stts covers {durations.Length} samples, stsz has {sizes.Length}"); + if (stscTotal != sizes.Length) report.Error($"stsc/stco map {stscTotal} samples, stsz has {sizes.Length}"); var count = sizes.Length; report.FrameCount = count; if (count == 0) { - report.Errors.Add("track has no samples"); + report.Error("track has no samples"); return; } var offsets = ReadCompositionOffsets(stbl, count, report); var sync = ReadSyncSamples(stbl, count, report); report.SyncSampleCount = sync?.Count ?? count; - if (sync is not null && (sync.Count == 0 || sync[0] != 1)) report.Errors.Add("first sample is not a sync sample"); + if (sync is not null && (sync.Count == 0 || sync[0] != 1)) report.Error("first sample is not a sync sample"); var samples = new Mp4SampleInfo[count]; var index = 0; @@ -331,7 +343,7 @@ public static class Mp4Inspector decode += duration; bytes += sizes[index]; } - if (!InsideMdat(chunkStart, offset, mdats)) report.Errors.Add($"chunk {c + 1} [{chunkStart}, {offset}) lies outside mdat"); + if (!InsideMdat(chunkStart, offset, mdats)) report.Error($"chunk {c + 1} [{chunkStart}, {offset}) lies outside mdat"); } report.Samples = samples; report.MediaBytes = bytes; @@ -339,17 +351,17 @@ public static class Mp4Inspector for (var i = 0; i < durations.Length; i++) { if (durations[i] != 0) continue; - if (i == durations.Length - 1) report.Warnings.Add("last sample has zero duration"); - else report.Errors.Add($"sample {i + 1} has zero duration"); + if (i == durations.Length - 1) report.Warning("last sample has zero duration"); + else report.Error($"sample {i + 1} has zero duration"); } - if (mdhd is not null && mdhdDuration != decode) report.Warnings.Add($"mdhd duration {mdhdDuration} differs from the sample durations sum {decode}"); + if (mdhd is not null && mdhdDuration != decode) report.Warning($"mdhd duration {mdhdDuration} differs from the sample durations sum {decode}"); report.DurationTicks = decode; var elst = trak.Child("edts")?.Child("elst"); if (elst is not null && ReadEditList(elst.Payload.Span, out var segment, out var mediaTime, report)) { report.HasEditList = true; - if (mediaTime < 0 || (mediaTime >= decode && decode > 0)) report.Errors.Add($"edit list media_time {mediaTime} outside the media"); + if (mediaTime < 0 || (mediaTime >= decode && decode > 0)) report.Error($"edit list media_time {mediaTime} outside the media"); if (movieScale > 0) report.DurationTicks = (long)Math.Round(segment * (double)mediaScale / movieScale); } var seconds = mediaScale == 0 ? 0 : report.DurationTicks / (double)mediaScale; @@ -363,7 +375,7 @@ public static class Mp4Inspector var stsd = stbl.Child("stsd"); if (stsd is null || stsd.Children.Count == 0) { - report.Errors.Add("stsd missing or empty"); + report.Error("stsd missing or empty"); return null; } var entry = stsd.Children[0]; @@ -371,7 +383,7 @@ public static class Mp4Inspector var payload = entry.Payload.Span; if (payload.Length < 78) { - report.Errors.Add($"sample entry '{entry.Type}' truncated"); + report.Error($"sample entry '{entry.Type}' truncated"); return null; } report.Width = BinaryPrimitives.ReadUInt16BigEndian(payload[24..]); @@ -385,26 +397,26 @@ public static class Mp4Inspector }; if (configBox is null) { - report.Warnings.Add($"sample entry '{entry.Type}' is not validated"); + report.Warning($"sample entry '{entry.Type}' is not validated"); return null; } var box = entry.Child(configBox); if (box is null) { - report.Errors.Add($"{configBox} missing in '{entry.Type}'"); + report.Error($"{configBox} missing in '{entry.Type}'"); return null; } if (!DecoderConfiguration.TryParse(configBox, box.Payload.Span, out var config, out var error) || config is null) { - report.Errors.Add($"{configBox} unparseable: {error}"); + report.Error($"{configBox} unparseable: {error}"); return null; } - if (error is not null) report.Errors.Add(error); + if (error is not null) report.Error(error); report.Codec = config.Codec; report.CodecString = config.CodecString; report.BitDepth = config.BitDepth; if (config.Width != report.Width || config.Height != report.Height) - report.Errors.Add($"{configBox} declares {config.Width}x{config.Height}, sample entry {report.Width}x{report.Height}"); + report.Error($"{configBox} declares {config.Width}x{config.Height}, sample entry {report.Width}x{report.Height}"); return config; } @@ -423,12 +435,12 @@ public static class Mp4Inspector { var obus = Av1ObuParser.Split(data); if (obus.Count == 0 || obus[^1].Offset + obus[^1].TotalLength != data.Length) - report.Errors.Add($"sample {i + 1}: OBU sizes do not cover the sample"); + report.Error($"sample {i + 1}: OBU sizes do not cover the sample"); continue; } if (!AnnexBParser.TrySplitLengthPrefixed(data, 4, out var units)) { - report.Errors.Add($"sample {i + 1}: NAL length prefixes do not cover the sample"); + report.Error($"sample {i + 1}: NAL length prefixes do not cover the sample"); continue; } if (i != 0) continue; @@ -440,7 +452,7 @@ public static class Mp4Inspector ? AnnexBParser.H264Type(h) == H264NalUnitType.IdrSlice : AnnexBParser.HevcType(h) is >= HevcNalUnitType.BlaWLp and <= HevcNalUnitType.Cra; } - if (!randomAccess) report.Warnings.Add("first sample contains no IDR/IRAP picture"); + if (!randomAccess) report.Warning("first sample contains no IDR/IRAP picture"); } } @@ -449,7 +461,7 @@ public static class Mp4Inspector var box = stbl.Child("stts"); if (box is null) { - report.Errors.Add("stts missing"); + report.Error("stts missing"); return null; } var p = box.Payload.Span; @@ -459,9 +471,9 @@ public static class Mp4Inspector { var n = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 8)..]); var delta = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 8)..]); - if (list.Count + (long)n > 50_000_000) + if (list.Count + (long)n > MaxSamples) { - report.Errors.Add("stts sample count implausible"); + report.Error("stts sample count implausible"); return null; } for (var k = 0; k < n; k++) list.Add(delta); @@ -487,7 +499,7 @@ public static class Mp4Inspector covered += n; } report.HasCompositionOffsets = true; - if (covered != count) report.Errors.Add($"ctts covers {covered} of {count} samples"); + if (covered != count) report.Error($"ctts covers {covered} of {count} samples"); return result; } @@ -503,7 +515,7 @@ public static class Mp4Inspector var s = BinaryPrimitives.ReadUInt32BigEndian(p[(8 + i * 4)..]); if (s == 0 || s > count || (list.Count > 0 && s <= list[^1])) { - report.Errors.Add($"stss entry {s} out of order or range"); + report.Error($"stss entry {s} out of order or range"); break; } list.Add(s); @@ -516,42 +528,42 @@ public static class Mp4Inspector var box = stbl.Child("stsz") ?? stbl.Child("stz2"); if (box is null) { - report.Errors.Add("stsz missing"); + report.Error("stsz missing"); return null; } var p = box.Payload.Span; if (p.Length < 12) { - report.Errors.Add($"{box.Type} truncated"); + report.Error($"{box.Type} truncated"); return null; } var count = BinaryPrimitives.ReadUInt32BigEndian(p[8..]); - if (count > 50_000_000) + if (count > MaxSamples) { - report.Errors.Add($"{box.Type} sample count implausible"); + report.Error($"{box.Type} sample count implausible"); + return null; + } + var constant = box.Type == "stsz" ? BinaryPrimitives.ReadUInt32BigEndian(p[4..]) : 0; + if (box.Type == "stsz" && constant == 0 && p.Length < 12 + count * 4L) + { + report.Error("stsz truncated"); return null; } var sizes = new uint[count]; if (box.Type == "stsz") { - var constant = BinaryPrimitives.ReadUInt32BigEndian(p[4..]); if (constant != 0) { Array.Fill(sizes, constant); return sizes; } - if (p.Length < 12 + count * 4L) - { - report.Errors.Add("stsz truncated"); - return null; - } for (var i = 0; i < count; i++) sizes[i] = BinaryPrimitives.ReadUInt32BigEndian(p[(12 + i * 4)..]); return sizes; } var field = p[7]; if (field is not (4 or 8 or 16) || p.Length < 12 + (count * field + 7) / 8) { - report.Errors.Add("stz2 invalid"); + report.Error("stz2 invalid"); return null; } for (var i = 0; i < count; i++) @@ -571,7 +583,7 @@ public static class Mp4Inspector var box = stbl.Child("stco") ?? stbl.Child("co64"); if (box is null) { - report.Errors.Add("stco/co64 missing"); + report.Error("stco/co64 missing"); return null; } var wide = box.Type == "co64"; @@ -593,7 +605,7 @@ public static class Mp4Inspector var box = stbl.Child("stsc"); if (box is null) { - report.Errors.Add("stsc missing"); + report.Error("stsc missing"); return null; } var p = box.Payload.Span; @@ -606,10 +618,10 @@ public static class Mp4Inspector var next = i + 1 < entries ? BinaryPrimitives.ReadUInt32BigEndian(p[(8 + (i + 1) * 12)..]) : (uint)chunks + 1; if (first == 0 || next <= first || (i == 0 && first != 1)) { - report.Errors.Add("stsc first_chunk values invalid"); + report.Error("stsc first_chunk values invalid"); return null; } - if (BinaryPrimitives.ReadUInt32BigEndian(p[(16 + i * 12)..]) != 1) report.Errors.Add("stsc references a sample description other than 1"); + if (BinaryPrimitives.ReadUInt32BigEndian(p[(16 + i * 12)..]) != 1) report.Error("stsc references a sample description other than 1"); for (var c = first; c < next && c <= chunks; c++) perChunk[c - 1] = samples; } return perChunk; @@ -620,7 +632,7 @@ public static class Mp4Inspector segment = mediaTime = 0; var wide = p.Length > 0 && p[0] == 1; if (!Entries(p, wide ? 20 : 12, report, "elst", out var entries) || entries == 0) return false; - if (entries > 1) report.Warnings.Add($"edit list has {entries} entries; only the first is evaluated"); + if (entries > 1) report.Warning($"edit list has {entries} entries; only the first is evaluated"); segment = wide ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(p[8..]), long.MaxValue) : BinaryPrimitives.ReadUInt32BigEndian(p[8..]); mediaTime = wide ? BinaryPrimitives.ReadInt64BigEndian(p[16..]) : BinaryPrimitives.ReadInt32BigEndian(p[12..]); return true; @@ -632,13 +644,13 @@ public static class Mp4Inspector entries = 0; if (p.Length < 8) { - report.Errors.Add($"{type} truncated"); + report.Error($"{type} truncated"); return false; } var n = BinaryPrimitives.ReadUInt32BigEndian(p[4..]); if (n > (p.Length - 8) / entrySize) { - report.Errors.Add($"{type} declares {n} entries but holds {(p.Length - 8) / entrySize}"); + report.Error($"{type} declares {n} entries but holds {(p.Length - 8) / entrySize}"); return false; } entries = (int)n; diff --git a/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs b/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs index d505885b..ea1fd44b 100644 --- a/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs +++ b/tests/Titano.Core.Tests/Video/Mp4MuxerTests.cs @@ -198,6 +198,22 @@ public sealed class Mp4MuxerTests(TestContext context) Assert.Throws(() => muxer.WriteSample([0, 0, 1, 0x65, 1], 0, true)); } + [Test] + public void ParameterSetOnlyUnitsAddNoSampleAndSeiOnlyUnitsAreRejected() + { + using var ms = new MemoryStream(); + var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }); + muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()]), 3000, true); + Assert.Equal(0, muxer.SampleCount); + Assert.Throws(() => muxer.WriteSample(AnnexBParser.ToAnnexB([[0x06, 0x05, 0x01, 0x00, 0x80]]), 3000, false)); + muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Slice(true, 64, 1)]), 3000, true); + muxer.Complete(); + var report = Mp4Inspector.Inspect(ms); + AssertClean(report); + Assert.Equal(1, report.FrameCount); + Assert.Equal(0, report.Warnings.Count); + } + [Test] public void InspectorSurvivesTruncationAndCorruption() { From 49fa8c5214cb8369ddf317ed704be3e8b2d621aa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:09:54 +0000 Subject: [PATCH 079/188] style(data): apply dotnet format whitespace rules Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Postgres/PgConnector.cs | 56 +++++++++---------- src/Titano.Data/Postgres/PgTypes.cs | 18 +++--- .../Repositories/CatalogRepositoryTests.cs | 44 ++++++++++++--- .../Repositories/JobRepositoryTests.cs | 20 +++++-- .../Repositories/ServerRepositoryTests.cs | 11 +++- 5 files changed, 97 insertions(+), 52 deletions(-) diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs index 59c5f38d..21c2bf52 100644 --- a/src/Titano.Data/Postgres/PgConnector.cs +++ b/src/Titano.Data/Postgres/PgConnector.cs @@ -427,21 +427,21 @@ internal sealed class PgConnector : IAsyncDisposable WritePassword(PgMd5.Response(_settings.Username, RequirePassword(), payload.Slice(4, 4))); return scram; case 10: - { - var mechanisms = new List(); - var pos = 4; - while (pos < payload.Length && payload[pos] != 0) mechanisms.Add(ReadCString(payload, ref pos)); - if (!mechanisms.Contains(ScramSha256.Mechanism)) - throw new NotSupportedException($"The server offers SASL mechanisms {string.Join(", ", mechanisms)}; only {ScramSha256.Mechanism} is supported."); - scram = new ScramSha256(RequirePassword()); - var first = scram.ClientFirstMessage(); - _write.StartMessage('p'); - _write.WriteCString(ScramSha256.Mechanism); - _write.WriteInt32(first.Length); - _write.Write(first); - _write.EndMessage(); - return scram; - } + { + var mechanisms = new List(); + var pos = 4; + while (pos < payload.Length && payload[pos] != 0) mechanisms.Add(ReadCString(payload, ref pos)); + if (!mechanisms.Contains(ScramSha256.Mechanism)) + throw new NotSupportedException($"The server offers SASL mechanisms {string.Join(", ", mechanisms)}; only {ScramSha256.Mechanism} is supported."); + scram = new ScramSha256(RequirePassword()); + var first = scram.ClientFirstMessage(); + _write.StartMessage('p'); + _write.WriteCString(ScramSha256.Mechanism); + _write.WriteInt32(first.Length); + _write.Write(first); + _write.EndMessage(); + return scram; + } case 11: var final = (scram ?? throw ProtocolViolation((byte)'R')).ClientFinalMessage(payload[4..]); _write.StartMessage('p'); @@ -846,20 +846,20 @@ internal sealed class PgConnector : IAsyncDisposable LogNotice(); continue; case (byte)'S': - { - var pos = 0; - var name = ReadCString(Payload, ref pos); - _serverParameters[name] = ReadCString(Payload, ref pos); - continue; - } + { + var pos = 0; + var name = ReadCString(Payload, ref pos); + _serverParameters[name] = ReadCString(Payload, ref pos); + continue; + } case (byte)'A': - { - var pos = 4; - var channel = ReadCString(Payload, ref pos); - var payload = ReadCString(Payload, ref pos); - NotificationReceived?.Invoke(new PgNotification(BinaryPrimitives.ReadInt32BigEndian(Payload), channel, payload)); - continue; - } + { + var pos = 4; + var channel = ReadCString(Payload, ref pos); + var payload = ReadCString(Payload, ref pos); + NotificationReceived?.Invoke(new PgNotification(BinaryPrimitives.ReadInt32BigEndian(Payload), channel, payload)); + continue; + } default: return type; } diff --git a/src/Titano.Data/Postgres/PgTypes.cs b/src/Titano.Data/Postgres/PgTypes.cs index 0f8d3302..1f06cd9b 100644 --- a/src/Titano.Data/Postgres/PgTypes.cs +++ b/src/Titano.Data/Postgres/PgTypes.cs @@ -105,17 +105,17 @@ internal static class PgTypes WriteCopyEscaped(s, writer); return; case byte[] bytes: - { - var span = writer.GetSpan(3 + bytes.Length * 2); - "\\\\x"u8.CopyTo(span); - for (var i = 0; i < bytes.Length; i++) { - span[3 + 2 * i] = HexDigits[bytes[i] >> 4]; - span[4 + 2 * i] = HexDigits[bytes[i] & 0xF]; + var span = writer.GetSpan(3 + bytes.Length * 2); + "\\\\x"u8.CopyTo(span); + for (var i = 0; i < bytes.Length; i++) + { + span[3 + 2 * i] = HexDigits[bytes[i] >> 4]; + span[4 + 2 * i] = HexDigits[bytes[i] & 0xF]; + } + writer.Advance(3 + bytes.Length * 2); + return; } - writer.Advance(3 + bytes.Length * 2); - return; - } case int or long or double or bool or Guid or DateTimeOffset: case DateTime { Kind: DateTimeKind.Unspecified }: writer.Advance(FormatText(value, writer.GetSpan(64))); diff --git a/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs index 340fe506..6c0e1277 100644 --- a/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs +++ b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs @@ -32,11 +32,26 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe await db.Archives.UpsertAsync(archive, Ct); var sequence = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 30, 15, 250), "Harbour sunset") with { - CameraSerial = "0123", Lens = "RF 24-70", FrameCount = 1200, MedianInterval = 5.0, TotalBytes = 30_000_000_000, - Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, RenderedCount = 0, VerifiedAt = TestData.Now, - HeroFrameId = Guid.CreateVersion7(), Rating = 4, Notes = "windy", SettingsJson = "{\"fps\": 25, \"deflicker\": true}", - AnalysisJson = "{\"ev\": [12.5, 13]}", Origin = SequenceOrigin.Server, SyncState = SyncState.LocalAhead, - SettingsVersion = 3, FramesVersion = 7, OwnerUserId = Guid.CreateVersion7(), WarningCount = 2, Tags = ["Sunset", "harbour", "SUNSET"], + CameraSerial = "0123", + Lens = "RF 24-70", + FrameCount = 1200, + MedianInterval = 5.0, + TotalBytes = 30_000_000_000, + Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, + RenderedCount = 0, + VerifiedAt = TestData.Now, + HeroFrameId = Guid.CreateVersion7(), + Rating = 4, + Notes = "windy", + SettingsJson = "{\"fps\": 25, \"deflicker\": true}", + AnalysisJson = "{\"ev\": [12.5, 13]}", + Origin = SequenceOrigin.Server, + SyncState = SyncState.LocalAhead, + SettingsVersion = 3, + FramesVersion = 7, + OwnerUserId = Guid.CreateVersion7(), + WarningCount = 2, + Tags = ["Sunset", "harbour", "SUNSET"], }; await db.Sequences.UpsertAsync(sequence, Ct); @@ -120,7 +135,8 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe await db.Archives.UpsertAsync(archive, Ct); var all = Enumerable.Range(0, 23).Select(i => TestData.Sequence(archive.Id, i % 5 == 4 ? null : new DateTime(2024 + i % 3, 1, 1, 12, 0, 0), - i % 4 == 0 ? null : "T" + (i % 6)) with { FrameCount = i % 3, TotalBytes = i % 4 * 1000L }) + i % 4 == 0 ? null : "T" + (i % 6)) with + { FrameCount = i % 3, TotalBytes = i % 4 * 1000L }) .ToList(); foreach (var s in all) await db.Sequences.UpsertAsync(s, Ct); @@ -208,9 +224,19 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe var frames = Enumerable.Range(0, 250).Select(i => TestData.Frame(sequence.Id, i)).ToList(); frames[7] = frames[7] with { - OriginalFileName = "DSC_7.NEF", CapturedAt = new DateTime(2026, 9, 28, 18, 0, 35, 123), UtcOffsetMinutes = 120, ExposureBias = -0.3, - WhiteBalance = 5600, Orientation = 6, PreviewOffset = 1024, PreviewLength = 65536, MeanLogLuminance = -2.5, ClipLow = 0.01, - ClipHigh = 0.02, Flags = FrameFlags.Excluded, Sha256 = "AB" + new string('c', 62), + OriginalFileName = "DSC_7.NEF", + CapturedAt = new DateTime(2026, 9, 28, 18, 0, 35, 123), + UtcOffsetMinutes = 120, + ExposureBias = -0.3, + WhiteBalance = 5600, + Orientation = 6, + PreviewOffset = 1024, + PreviewLength = 65536, + MeanLogLuminance = -2.5, + ClipLow = 0.01, + ClipHigh = 0.02, + Flags = FrameFlags.Excluded, + Sha256 = "AB" + new string('c', 62), }; Assert.Equal(250L, await db.Frames.BulkInsertAsync(frames, Ct)); var copy = TestData.Frame(sequence.Id, 1000) with { Sha256 = frames[7].Sha256 }; diff --git a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs index b4c661ec..cacf4de9 100644 --- a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs +++ b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs @@ -13,10 +13,22 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c var db = await OpenTitanoAsync(); var job = TestData.Job(JobKind.Render, JobPriority.User) with { - TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()], TargetLabel = "Harbour sunset", ParametersJson = "{\"preset\": \"4K\"}", - ProgressDone = 5, ProgressTotal = 10, ItemsPerSecond = 2.5, Eta = TimeSpan.FromSeconds(2), Checkpoint = "frame:5", - LogTail = "line 1\nline 2", CreatedBy = Guid.CreateVersion7(), NodeId = "node-a", Attempts = 1, Error = "boom", - State = JobState.Failed, Started = TestData.Now.AddMinutes(1), Finished = TestData.Now.AddMinutes(2), + TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()], + TargetLabel = "Harbour sunset", + ParametersJson = "{\"preset\": \"4K\"}", + ProgressDone = 5, + ProgressTotal = 10, + ItemsPerSecond = 2.5, + Eta = TimeSpan.FromSeconds(2), + Checkpoint = "frame:5", + LogTail = "line 1\nline 2", + CreatedBy = Guid.CreateVersion7(), + NodeId = "node-a", + Attempts = 1, + Error = "boom", + State = JobState.Failed, + Started = TestData.Now.AddMinutes(1), + Finished = TestData.Now.AddMinutes(2), }; await db.Jobs.EnqueueAsync(job, Ct); var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct)); diff --git a/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs index 61dd5c2c..6b3521f1 100644 --- a/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs +++ b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs @@ -131,8 +131,15 @@ public abstract class ServerRepositoryTests(TestContext context) : RepositoryTes var user = Guid.CreateVersion7(); var entries = Enumerable.Range(0, 9).Select(i => new AuditEntry { - Id = Guid.CreateVersion7(), At = TestData.Now.AddSeconds(i / 2), Action = "sequence.delete", UserId = i % 3 == 0 ? user : null, - Username = "alice", TargetKind = "sequence", TargetId = Guid.CreateVersion7().ToString(), Details = "{\"frames\": 10}", RemoteAddress = "10.0.0.1", + Id = Guid.CreateVersion7(), + At = TestData.Now.AddSeconds(i / 2), + Action = "sequence.delete", + UserId = i % 3 == 0 ? user : null, + Username = "alice", + TargetKind = "sequence", + TargetId = Guid.CreateVersion7().ToString(), + Details = "{\"frames\": 10}", + RemoteAddress = "10.0.0.1", }).ToList(); foreach (var e in entries) await db.Audit.AppendAsync(e, Ct); From a15cecd65831ec4aa3832aae858e134abbbfd4ce Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:11:17 +0000 Subject: [PATCH 080/188] fix(windows): initialise COM on threads entering Media Foundation; record video decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 5 +++++ .../MediaFoundation/MediaFoundationEncoderSession.cs | 2 ++ .../MediaFoundation/MediaFoundationRuntime.cs | 2 ++ 3 files changed, 9 insertions(+) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 4414bbab..eee9bb36 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -50,3 +50,8 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | HEIF `irot`/`imir` override Exif orientation (imir axis 0 = top↔bottom). | Exif first | HEIF decoders apply the transforms themselves; both would rotate twice. | | 2026-10-02 | Main image size comes from the container's own size field (SOF, IHDR, ispe, VP8X, RAF crop record, RW2 borders, CR3 CMP1) before raster IFDs. | Always the largest raster IFD | That is what each container defines and what decoders output. | | 2026-10-02 | Only MPF large-thumbnail entries count as previews; XMP date-only values are never used as capture times. | Every secondary image / midnight | Gain maps are not previews; midnight would be invented. | +| 2026-10-02 | Media Foundation interop uses `[GeneratedComInterface]` with explicit release; threads entering MF call `Win32Com.EnsureInitialized()` (MTA unless already STA). | `[ComImport]` like WIC | Hardware encoders stall when sample references wait for GC; source-generated COM does not initialise apartments, so it is done explicitly. | +| 2026-10-02 | MP4: 16-byte `free`+`mdat` placeholder rewritten to a 64-bit header past 4 GiB; negative composition offsets shifted to ctts v0 plus an edit list; parameter sets moved into avcC/hvcC; fast start on by default. | Always 64-bit mdat / ctts v1 | Small files stay maximally compatible; wider player support. | +| 2026-10-02 | GIF: Wu-criterion median cut, frame differencing against the source last drawn, identical frames merged by holding one back. | Plain median cut / diff against dithered output | Max palette error 37 → small; 945 KB → 52 KB at equal PSNR; exact delays. | +| 2026-10-02 | AVI always carries OpenDML indexes plus idx1 (1 GiB RIFF segments). | idx1 only | Files beyond 2 GB stay playable. | +| 2026-10-02 | MF encoder capabilities: software H.264 ≤ 4096×2304, hardware assumed 4096² (H.264) / 8192² (HEVC/AV1); an unsupported size fails at media-type negotiation and the next encoder is tried. | Querying limits | MF has no reliable capability query. | diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs index f82354aa..7014417a 100644 --- a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationEncoderSession.cs @@ -102,6 +102,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession public void WriteFrame(ImageBuffer frame, long duration90k) { + Interop.Win32Com.EnsureInitialized(); ObjectDisposedException.ThrowIf(_disposed, this); if (_completed) throw new InvalidOperationException("The session is complete"); if (frame.Width != _settings.Width || frame.Height != _settings.Height) throw new ArgumentException("Frame size differs from the encode size", nameof(frame)); @@ -136,6 +137,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession public void Complete() { + Interop.Win32Com.EnsureInitialized(); ObjectDisposedException.ThrowIf(_disposed, this); if (_completed) throw new InvalidOperationException("The session is already complete"); if (_framesIn == 0) throw new InvalidOperationException("No frames were written"); diff --git a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs index a8cfb3a1..bf029fea 100644 --- a/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs +++ b/src/Titano.Core.Windows/MediaFoundation/MediaFoundationRuntime.cs @@ -16,6 +16,8 @@ internal static class MediaFoundationRuntime public static IDisposable Acquire() { if (!IsAvailable) throw new PlatformNotSupportedException("Media Foundation is not available on this system"); + // Media Foundation requires COM on the calling thread; source-generated COM does not initialise it implicitly. + Interop.Win32Com.EnsureInitialized(); lock (Gate) { if (_references == 0) ComObjects.Check(MfNative.MFStartup(MfNative.Version, MfNative.StartupLite), "MFStartup"); From 78dad093abd60aa240945f98bf9c0cf87be3d943 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:12:49 +0000 Subject: [PATCH 081/188] fix(codecs): read TIFF strips larger than the 64 MB per-read cap Single-strip uncompressed files (Photoshop's default) exceed TiffReader's bounded read; such strips are now read in pieces, the uncompressed path skips a copy, and hostile strip/tile counts are rejected up front. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Codecs/Tiff/TiffImageReader.cs | 28 ++++++++++++++++--- tests/Titano.Core.Tests/Codecs/TiffTests.cs | 14 ++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs index 09e8f367..93cc5178 100644 --- a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs +++ b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs @@ -76,6 +76,8 @@ public static class TiffImageReader private const int CompressionAdobeDeflate = 32946, CompressionPackBits = 32773, CompressionLossyJpeg = 34892; private const int PhotometricMinIsWhite = 0, PhotometricRgb = 2, PhotometricPalette = 3, PhotometricYCbCr = 6; private const int PhotometricCfa = 32803, PhotometricLinearRaw = 34892; + private const int MaxChunks = 1 << 24; + private const long MaxChunkBytes = int.MaxValue / 2; /// Decodes the first full-resolution image of a TIFF (or a DNG whose main image is not CFA). public static ImageBuffer Decode(Stream stream, TiffDecodeOptions? options = null) @@ -138,6 +140,7 @@ public static class TiffImageReader var g = Geometry.Read(reader, ifd, o); var warnings = new List(); var count = g.ChunksPerPlane * g.Planes; + if (count > MaxChunks) throw new InvalidDataException($"TIFF: {count} strips/tiles"); var offsets = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets) ?? throw new InvalidDataException("TIFF: missing strip/tile offsets"); var counts = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts); if (counts is null && count == 1 && g.Compression == CompressionNone) counts = [(uint)Math.Min(int.MaxValue, g.RowBytes * (long)g.ChunkHeight)]; @@ -149,7 +152,7 @@ public static class TiffImageReader for (var i = 0; i < Math.Min(count, Math.Min(offsets.Length, counts.Length)); i++) { if (counts[i] == 0) continue; - chunks[i] = reader.ReadRelative(offsets[i], (int)Math.Min(counts[i], int.MaxValue)); + chunks[i] = ReadChunk(reader, offsets[i], counts[i]); if (chunks[i] is null) warnings.Add($"TIFF: strip/tile {i} lies outside the file"); } var tables = g.Compression is CompressionJpeg or CompressionLossyJpeg && ifd.Entries.TryGetValue(TiffTags.JpegTables, out var t) ? reader.ReadBytes(t) : null; @@ -253,7 +256,7 @@ public static class TiffImageReader g.ChunksPerPlane = (g.Height + g.ChunkHeight - 1) / g.ChunkHeight; } g.RowBytes = ((long)g.ChunkWidth * g.ChunkSpp * g.Bps + 7) / 8; - if (g.RowBytes * g.ChunkHeight > TiffReader.MaxValueBytes * 4) throw new InvalidDataException("TIFF: strip/tile too large"); + if (g.RowBytes * g.ChunkHeight > MaxChunkBytes) throw new InvalidDataException("TIFF: strip/tile too large"); return g; } } @@ -272,7 +275,7 @@ public static class TiffImageReader if (g.IsJpeg) return DecodeJpegChunk(g, data, tables, ints!, x0, y0, validW, validH, plane); var expected = (int)(g.RowBytes * rows); - var raw = new byte[expected]; + var raw = g.Compression == CompressionNone && data.Length >= expected ? data : new byte[expected]; var produced = g.Compression switch { CompressionNone => Copy(data, raw), @@ -309,10 +312,27 @@ public static class TiffImageReader private static int Copy(byte[] data, byte[] raw) { var n = Math.Min(data.Length, raw.Length); - data.AsSpan(0, n).CopyTo(raw); + if (!ReferenceEquals(data, raw)) data.AsSpan(0, n).CopyTo(raw); return n; } + /// Reads one strip/tile; large uncompressed strips (single-strip files) exceed TiffReader's per-read cap + /// and are read in pieces. + private static byte[]? ReadChunk(TiffReader reader, uint offset, uint length) + { + if (length <= TiffReader.MaxValueBytes) return reader.ReadRelative(offset, (int)length); + if (length > MaxChunkBytes || offset + (long)length > reader.StreamLength - reader.Base) return null; + var result = new byte[length]; + for (long done = 0; done < length;) + { + var piece = (int)Math.Min(TiffReader.MaxValueBytes, length - done); + if (reader.ReadRelative(offset + done, piece) is not { } part) return null; + part.CopyTo(result, done); + done += piece; + } + return result; + } + private static void Place(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane) { if (g.Planes == 1) diff --git a/tests/Titano.Core.Tests/Codecs/TiffTests.cs b/tests/Titano.Core.Tests/Codecs/TiffTests.cs index 92777536..c5414c95 100644 --- a/tests/Titano.Core.Tests/Codecs/TiffTests.cs +++ b/tests/Titano.Core.Tests/Codecs/TiffTests.cs @@ -127,6 +127,20 @@ public sealed class TiffTests(TestContext context) Assert.SequenceEqual(samples, Raster(tiff).Samples!); } + [Test] + public void SingleStripLargerThanTheReaderCapDecodes() + { + // Photoshop-style single uncompressed strip of 70 MB (TiffReader reads at most 64 MB per call). + const int w = 5000, h = 7000; + var strip = new byte[w * h * 2]; + for (var i = 0; i < strip.Length; i += 2) BinaryPrimitives.WriteUInt16LittleEndian(strip.AsSpan(i), (ushort)(i * 7)); + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 16, compression: 1), [strip], tiled: false); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.Equal(unchecked((ushort)((w * h - 1) * 2 * 7)), raster.Samples![^1]); + Assert.Equal(unchecked((ushort)(12345 * 2 * 7)), raster.Samples[12345]); + } + [Test] public void PackedTwelveBitSamplesUnpack() { From f2c0709ef291f600134207f67473ed31271335f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:12:49 +0000 Subject: [PATCH 082/188] refactor(codecs): pool luminance rows and gate timing on optimised builds EncodeRow8/16 reuse one pooled scratch row for RGB-to-gray output instead of allocating per row; drop unused JPEG marker constants; the 24 MP timing test skips itself when the JIT optimiser is disabled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegTables.cs | 4 +- src/Titano.Core/Imaging/PixelConvert.cs | 51 ++++++++----------- .../Codecs/JpegPerformanceTests.cs | 4 ++ 3 files changed, 28 insertions(+), 31 deletions(-) diff --git a/src/Titano.Core/Codecs/Jpeg/JpegTables.cs b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs index 6e3d6f0a..78224a03 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegTables.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs @@ -3,8 +3,8 @@ namespace Titano.Core.Codecs.Jpeg; /// Constants shared by the JPEG encoder and decoders (ITU T.81 Annex K). internal static class JpegTables { - public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dnl = 0xDC, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC; - public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE, Com = 0xFE; + public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC; + public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE; /// Natural (row-major) index of the coefficient at each zig-zag position. public static ReadOnlySpan NaturalOrder => diff --git a/src/Titano.Core/Imaging/PixelConvert.cs b/src/Titano.Core/Imaging/PixelConvert.cs index 4a416d6a..86505660 100644 --- a/src/Titano.Core/Imaging/PixelConvert.cs +++ b/src/Titano.Core/Imaging/PixelConvert.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; @@ -132,57 +133,48 @@ public static class PixelConvert /// Encodes row into interleaved 8-bit samples (codec edge helper). internal static void EncodeRow8(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer, bool dither) { - var w = image.Width; Span offsets = stackalloc float[8]; - if (dither) - { - for (var i = 0; i < 8; i++) offsets[i] = 0.5f + Bayer[(y & 7) * 8 + i]; - } - else - { - offsets.Fill(0.5f); - } + for (var i = 0; i < 8; i++) offsets[i] = dither ? 0.5f + Bayer[(y & 7) * 8 + i] : 0.5f; var srgb = transfer == TransferFunction.Srgb; - var colour = channels is 1 or 2 ? 1 : 3; + var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool.Shared.Rent(image.Width) : null; for (var c = 0; c < channels; c++) { - if (c == colour) + if (c == (channels <= 2 ? 1 : 3)) { var a = image.Channels == 4 ? image.Row(3, y) : default; - for (var x = 0; x < w; x++) row[x * channels + c] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[x], 0f, 1f) * 255f + 0.5f); + for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[x], 0f, 1f) * 255f + 0.5f); continue; } - var src = SourceRow(image, y, c, colour, out var luminance); - for (var x = 0; x < w; x++) + var src = ColourRow(image, y, c, channels, scratch); + for (var x = 0; x < src.Length; x++) { - var v = luminance is null ? src[x] : luminance[x]; - var e = srgb ? ColorSpace.EncodeFast(v) : Math.Clamp(v, 0f, 1f); + var e = srgb ? ColorSpace.EncodeFast(src[x]) : Math.Clamp(src[x], 0f, 1f); row[x * channels + c] = (byte)Math.Clamp(e * 255f + offsets[x & 7], 0f, 255f); } } + if (scratch is not null) ArrayPool.Shared.Return(scratch); } /// Encodes row into interleaved 16-bit samples (codec edge helper). internal static void EncodeRow16(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer) { - var w = image.Width; var srgb = transfer == TransferFunction.Srgb; - var colour = channels is 1 or 2 ? 1 : 3; + var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool.Shared.Rent(image.Width) : null; for (var c = 0; c < channels; c++) { - if (c == colour) + if (c == (channels <= 2 ? 1 : 3)) { var a = image.Channels == 4 ? image.Row(3, y) : default; - for (var x = 0; x < w; x++) row[x * channels + c] = a.IsEmpty ? (ushort)65535 : (ushort)(Math.Clamp(a[x], 0f, 1f) * 65535f + 0.5f); + for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (ushort)65535 : (ushort)(Math.Clamp(a[x], 0f, 1f) * 65535f + 0.5f); continue; } - var src = SourceRow(image, y, c, colour, out var luminance); - for (var x = 0; x < w; x++) + var src = ColourRow(image, y, c, channels, scratch); + for (var x = 0; x < src.Length; x++) { - var v = luminance is null ? src[x] : luminance[x]; - row[x * channels + c] = srgb ? ColorSpace.Encode16(v) : (ushort)(Math.Clamp(v, 0f, 1f) * 65535f + 0.5f); + row[x * channels + c] = srgb ? ColorSpace.Encode16(src[x]) : (ushort)(Math.Clamp(src[x], 0f, 1f) * 65535f + 0.5f); } } + if (scratch is not null) ArrayPool.Shared.Return(scratch); } /// Single-channel buffer replicated into three channels. @@ -302,17 +294,18 @@ public static class PixelConvert return result; } - private static ReadOnlySpan SourceRow(ImageBuffer image, int y, int c, int colourChannels, out float[]? luminance) + /// Linear row feeding output colour channel : gray is replicated, and a gray output + /// from RGB takes Rec.709 luminance computed into . + private static ReadOnlySpan ColourRow(ImageBuffer image, int y, int c, int channels, float[]? scratch) { - luminance = null; if (image.Channels == 1) return image.Row(0, y); - if (colourChannels == 3) return image.Row(c, y); + if (scratch is null) return image.Row(c, y); var r = image.Row(0, y); var g = image.Row(1, y); var b = image.Row(2, y); - luminance = new float[image.Width]; + var luminance = scratch.AsSpan(0, image.Width); for (var x = 0; x < luminance.Length; x++) luminance[x] = ColorSpace.Luminance(r[x], g[x], b[x]); - return default; + return luminance; } /// De-interleaves one row: colour through (indices clamped to its range), alpha scaled. diff --git a/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs index 105e6d29..39d5ad48 100644 --- a/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs +++ b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Reflection; using Titano.Core.Codecs.Jpeg; using Titano.Testing; @@ -15,6 +16,9 @@ public sealed class JpegPerformanceTests(TestContext context) [Timeout(60_000)] public void Decodes24MegapixelOnOneCoreUnderThreeSeconds() { + // A Debug build disables the JIT optimiser in Titano.Core: timings would measure the build, not the codec. + if (typeof(JpegDecoder).Assembly.GetCustomAttribute()?.IsJITOptimizerDisabled == true) + TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)"); var rgb = Photo(); var sw = Stopwatch.StartNew(); var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 }); From 8d9b04c713687f6151a9c03bb60e11c252764719 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:13:09 +0000 Subject: [PATCH 083/188] refactor(data): pin server output settings and guard busy connections Pin bytea_output=hex and standard_conforming_strings=on in the startup packet instead of tracking ParameterStatus values nobody read, so the legacy bytea escape decoder goes away. A PostgreSQL connection now refuses a new command while a row stream is still open, and the pool discards such a connection. Drop unused SQLite declarations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Postgres/PgConnector.cs | 21 ++++---- src/Titano.Data/Postgres/PgPool.cs | 4 +- src/Titano.Data/Postgres/PgTypes.cs | 51 +++++++------------ src/Titano.Data/Sqlite/SqliteNative.cs | 2 - src/Titano.Data/Sqlite/SqliteSession.cs | 4 +- .../Postgres/PgProtocolUnitTests.cs | 9 ++-- .../Titano.Data.Tests/Postgres/PgWireTests.cs | 11 ++++ 7 files changed, 51 insertions(+), 51 deletions(-) diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs index 21c2bf52..a06d5292 100644 --- a/src/Titano.Data/Postgres/PgConnector.cs +++ b/src/Titano.Data/Postgres/PgConnector.cs @@ -36,7 +36,6 @@ internal sealed class PgConnector : IAsyncDisposable private readonly Dictionary> _statements = new(StringComparer.Ordinal); private readonly LinkedList _statementLru = new(); private readonly List _statementsToClose = []; - private readonly Dictionary _serverParameters = new(StringComparer.Ordinal); private byte[] _read = new byte[16 * 1024]; private int _readPos; private int _readEnd; @@ -48,6 +47,7 @@ internal sealed class PgConnector : IAsyncDisposable private int _disposed; private CancellationTokenSource _ioAbort = new(); private Task _pendingCancel = Task.CompletedTask; + private Operation? _active; private PgConnector(PostgresSettings settings, Socket socket, Stream stream) { @@ -64,9 +64,10 @@ internal sealed class PgConnector : IAsyncDisposable /// Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction. public char TransactionStatus { get; private set; } = 'I'; - public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); + /// A command's response is still being read (an enumeration that was neither finished nor disposed). + public bool IsBusy => _active is not null; - public IReadOnlyDictionary ServerParameters => _serverParameters; + public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); /// Receives NotificationResponse messages (listener connections). public Action? NotificationReceived { get; set; } @@ -379,6 +380,9 @@ internal sealed class PgConnector : IAsyncDisposable Parameter("TimeZone", "UTC"); Parameter("DateStyle", "ISO, MDY"); Parameter("extra_float_digits", "3"); + Parameter("bytea_output", "hex"); + // LIKE … ESCAPE '\' in the repositories needs backslashes to be literal in string constants. + Parameter("standard_conforming_strings", "on"); if (_settings.SearchPath is { } searchPath) Parameter("search_path", searchPath); _write.WriteByte(0); _write.EndMessage(); @@ -469,8 +473,10 @@ internal sealed class PgConnector : IAsyncDisposable private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken) { if (IsBroken) throw new DatabaseConnectionException("The connection is broken."); + if (IsBusy) throw new InvalidOperationException("A command is still running on this session; finish or dispose its enumeration first."); cancellationToken.ThrowIfCancellationRequested(); var op = new Operation(this, sql, parameters, decodeRows, cancellationToken); + _active = op; if (cancellationToken.CanBeCanceled) op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op); return op; @@ -545,6 +551,7 @@ internal sealed class PgConnector : IAsyncDisposable _ioAbort.Dispose(); _ioAbort = new CancellationTokenSource(); } + _active = null; MarkIdle(); } } @@ -846,12 +853,8 @@ internal sealed class PgConnector : IAsyncDisposable LogNotice(); continue; case (byte)'S': - { - var pos = 0; - var name = ReadCString(Payload, ref pos); - _serverParameters[name] = ReadCString(Payload, ref pos); - continue; - } + // ParameterStatus: the settings the decoder relies on are pinned in the startup packet. + continue; case (byte)'A': { var pos = 4; diff --git a/src/Titano.Data/Postgres/PgPool.cs b/src/Titano.Data/Postgres/PgPool.cs index 2e2002b6..8f2beb39 100644 --- a/src/Titano.Data/Postgres/PgPool.cs +++ b/src/Titano.Data/Postgres/PgPool.cs @@ -52,11 +52,11 @@ internal sealed class PgPool : IAsyncDisposable } } - /// Takes a connection back; a broken one, or one not idle at transaction level, is closed instead. + /// Takes a connection back; a broken or busy one, or one inside a transaction, is closed instead. public void Return(PgConnector connector) { PgConnector? discard = connector; - if (!connector.IsBroken && connector.TransactionStatus == 'I') + if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I') { connector.MarkIdle(); lock (_gate) diff --git a/src/Titano.Data/Postgres/PgTypes.cs b/src/Titano.Data/Postgres/PgTypes.cs index 1f06cd9b..443a0ad5 100644 --- a/src/Titano.Data/Postgres/PgTypes.cs +++ b/src/Titano.Data/Postgres/PgTypes.cs @@ -10,22 +10,16 @@ internal static class PgTypes { public const uint Bool = 16; public const uint Bytea = 17; - public const uint Char = 18; - public const uint Name = 19; public const uint Int8 = 20; public const uint Int2 = 21; public const uint Int4 = 23; public const uint Text = 25; public const uint Oid = 26; - public const uint Json = 114; public const uint Float4 = 700; public const uint Float8 = 701; - public const uint Bpchar = 1042; - public const uint Varchar = 1043; public const uint Date = 1082; public const uint Timestamp = 1114; public const uint TimestampTz = 1184; - public const uint Numeric = 1700; public const uint Uuid = 2950; public const uint Jsonb = 3802; @@ -151,7 +145,10 @@ internal static class PgTypes } } - /// Decodes a text-format result value by its type OID; unknown types stay strings. + /// + /// Decodes a text-format result value by its type OID. Every other type (text, varchar, bpchar, name, json, + /// jsonb, numeric, …) stays a string, which is also how numeric is meant to be read. + /// public static object Decode(uint oid, ReadOnlySpan utf8) { var inv = CultureInfo.InvariantCulture; @@ -185,35 +182,23 @@ internal static class PgTypes } } - /// bytea output: hex (\x0a0b, the default since 9.0) or the legacy escape format. + /// bytea in hex output format (\x0a0b), which the startup packet pins with bytea_output=hex. private static byte[] DecodeBytea(ReadOnlySpan text) { - if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x') - return Convert.FromHexString(Encoding.ASCII.GetString(text[2..])); - var result = new List(text.Length); - for (var i = 0; i < text.Length; i++) - { - if (text[i] != '\\') - { - result.Add(text[i]); - } - else if (i + 1 < text.Length && text[i + 1] == '\\') - { - result.Add((byte)'\\'); - i++; - } - else if (i + 3 < text.Length) - { - result.Add((byte)(((text[i + 1] - '0') << 6) | ((text[i + 2] - '0') << 3) | (text[i + 3] - '0'))); - i += 3; - } - else - { - throw new FormatException("Malformed bytea escape sequence."); - } - } - return [.. result]; + if (text.Length < 2 || text[0] != '\\' || text[1] != 'x' || text.Length % 2 != 0) + throw new FormatException("A bytea value is not in hex output format."); + var result = new byte[(text.Length - 2) / 2]; + for (var i = 0; i < result.Length; i++) result[i] = (byte)((HexValue(text[2 + 2 * i]) << 4) | HexValue(text[3 + 2 * i])); + return result; } + private static int HexValue(byte c) => c switch + { + >= (byte)'0' and <= (byte)'9' => c - '0', + >= (byte)'a' and <= (byte)'f' => c - 'a' + 10, + >= (byte)'A' and <= (byte)'F' => c - 'A' + 10, + _ => throw new FormatException("Invalid hex digit in a bytea value."), + }; + private static ReadOnlySpan HexDigits => "0123456789abcdef"u8; } diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs index 95fe8590..97938b91 100644 --- a/src/Titano.Data/Sqlite/SqliteNative.cs +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -14,7 +14,6 @@ internal static unsafe class SqliteNative private static int _resolverInstalled; public const int SQLITE_OK = 0; - public const int SQLITE_ERROR = 1; public const int SQLITE_INTERRUPT = 9; public const int SQLITE_BUSY = 5; public const int SQLITE_LOCKED = 6; @@ -70,7 +69,6 @@ internal static unsafe class SqliteNative [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_exec(nint db, byte* sql, nint callback, nint arg, out byte* errmsg); [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_free(void* p); [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db); - [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_errcode(nint db); [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_interrupt(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_changes(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_total_changes(nint db); diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs index 472a3155..4954f572 100644 --- a/src/Titano.Data/Sqlite/SqliteSession.cs +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -6,8 +6,8 @@ namespace Titano.Data.Sqlite; /// /// A pooled SQLite connection. Statements that write take the database write lock for their duration when no -/// transaction holds it already; SQLITE_BUSY/LOCKED from other processes is retried a few times outside -/// transactions. Cancellation interrupts the running statement with sqlite3_interrupt. +/// transaction holds it already; lock conflicts are retried (see ). Cancellation +/// interrupts the running statement with sqlite3_interrupt. /// internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession { diff --git a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs index 5e1ac58d..51e76d87 100644 --- a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs +++ b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs @@ -61,10 +61,13 @@ public sealed class PgProtocolUnitTests } [Test] - public void DecodesByteaInHexAndEscapeFormats() + public void DecodesHexByteaAndRejectsOtherForms() { - Assert.BytesEqual(new byte[] { 0xDE, 0xAD }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdead"u8)); - Assert.BytesEqual(new byte[] { (byte)'a', 0, (byte)'\\', 0xFF }, (byte[])PgTypes.Decode(PgTypes.Bytea, "a\\000\\\\\\377"u8)); + Assert.BytesEqual(new byte[] { 0xDE, 0xAD, 0x01 }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdeAD01"u8)); + Assert.Equal(0, ((byte[])PgTypes.Decode(PgTypes.Bytea, "\\x"u8)).Length); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "a\\000"u8)); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "\\xabc"u8)); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "\\xzz"u8)); } [Theory] diff --git a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs index 4e7ebfba..b9f15d97 100644 --- a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs +++ b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs @@ -260,6 +260,17 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context) Assert.Equal("x", second.GetString("b")); } + [Test] + public async Task ACommandCannotStartWhileARowStreamIsOpen() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct); + Assert.True(await rows.MoveNextAsync()); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT 1", [], Ct)); + await rows.DisposeAsync(); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + [Test] public async Task NoticesAndScriptsDoNotDisturbTheSession() { From 6aacaff8827afe752a052ab2ff57d5a874c620f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:14:41 +0000 Subject: [PATCH 084/188] fix(codecs): size JPEG bit-writer buffers in 64-bit arithmetic Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs | 2 +- src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs index dfc85e28..e65fb43a 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs @@ -161,7 +161,7 @@ public static class JpegEncoder acC = new JpegHuffmanCode(JpegTables.AcChromaBits, JpegTables.AcChromaValues); } - var writer = new JpegBitWriter(width * height * components / 4); + var writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components / 4)); Entropy(plan, o.RestartInterval, writer, null, [dcY, acY, dcC, acC]); WriteHeaders(output, plan, o, dcY, acY, dcC, acC); output.Write(writer.Written); diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs index 8bd6eb31..6db474d6 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs @@ -31,7 +31,7 @@ public static class JpegLosslessEncoder var codes = new JpegHuffmanCode[components]; for (var c = 0; c < components; c++) codes[c] = JpegHuffmanCode.Optimal(counter.Frequencies[c]); - var emitter = new Emitter { Writer = new JpegBitWriter(width * height * components), Codes = codes }; + var emitter = new Emitter { Writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components)), Codes = codes }; Walk(samples, layout, ref emitter); emitter.Writer.Flush(); From 5b5f38c91d41a1984ec36a4a09c6fb3f763d3011 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:15:59 +0000 Subject: [PATCH 085/188] feat(i18n): add Setup strings and tooltips English and Italian labels, messages and Tooltips.Setup.* entries for the installer window; error sentences carry the long-text budget. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Setup.resx | 49 ++++++++++++++++++++++++++++++++++++++++ i18n/en/Tooltips.resx | 24 ++++++++++++++++++++ i18n/it/Setup.it.resx | 49 ++++++++++++++++++++++++++++++++++++++++ i18n/it/Tooltips.it.resx | 24 ++++++++++++++++++++ 4 files changed, 146 insertions(+) create mode 100644 i18n/en/Setup.resx create mode 100644 i18n/it/Setup.it.resx diff --git a/i18n/en/Setup.resx b/i18n/en/Setup.resx new file mode 100644 index 00000000..23dab393 --- /dev/null +++ b/i18n/en/Setup.resx @@ -0,0 +1,49 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cancel + Close + Close programs + Install + Launch + Retry + Uninstall + Update + Server for Windows + Titano + Uploader + {0} is installed. + {0} was removed. + Windows denied access to the folder.long + The command line is not valid.long + There is not enough free disk space.long + Administrator approval was declined.long + Setup could not finish.long + {0} is not installed.long + This installer is damaged; download it again.long + {0} did not close.long + Some files could not be removed.long + Components + Folder + Language + Options + Install for + Browse + Version {0} · installed {1} + Version {0} + Desktop shortcut + Start when done + Start menu + Installing {0} + Removing {0} + Close {0} to continue. + All users + Just me + {0} needed + Remove my data + {0} Setup + Remove {0} + diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index b6393fa1..1d5c8702 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -27,6 +27,30 @@ Dark interface (default) Light interface Follow the Windows app mode + Install in Program Files for every account · asks for administrator approval + Return to the options without changing anything + Choose the installation folder + Close setup + Ask the running programs to close · each one handles its unsaved work + Install this program + Runs Titano Server on this PC for other devices and render nodes + The desktop app to import, archive and render time-lapses + Sends photos from watched folders to a Titano Server + Add shortcuts to the desktop + Where the programs are installed · your data stays in its own folder + Enter a full folder path that is not a drive root or a system folder + Copy the selected programs and register them with Windows + Folder of the installed programs + Install in your user folder · no administrator rights needed + Language of this setup + Open the program when setup finishes + Open the installed program + Already installed here · uninstall it first to change folder or scope + Also delete database, settings and logs in %LOCALAPPDATA%\Titano · photos in archives are not touched + Run the same step again + Add the programs to the Start menu + Remove programs, shortcuts and file types · your data is kept unless selected + Replace the installed version in place · your data is kept Collapse navigation to icons Show navigation names Stop the current job · it can be resumed later diff --git a/i18n/it/Setup.it.resx b/i18n/it/Setup.it.resx new file mode 100644 index 00000000..b2588356 --- /dev/null +++ b/i18n/it/Setup.it.resx @@ -0,0 +1,49 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Annulla + Chiudi + Chiudi programmi + Installa + Avvia + Riprova + Disinstalla + Aggiorna + Server per Windows + Titano + Uploader + {0} è installato. + {0} è stato rimosso. + Windows ha negato l'accesso alla cartella.long + La riga di comando non è valida.long + Lo spazio libero su disco non è sufficiente.long + L'autorizzazione di amministratore è stata negata.long + L'installazione non è stata completata.long + {0} non è installato.long + Il programma di installazione è danneggiato; scaricalo di nuovo.long + {0} non si è chiuso.long + Alcuni file non sono stati rimossi.long + Componenti + Cartella + Lingua + Opzioni + Installa per + Sfoglia + Versione {0} · installata {1} + Versione {0} + Collegamento sul desktop + Avvia al termine + Menu Start + Installazione di {0} + Rimozione di {0} + Chiudi {0} per continuare. + Tutti gli utenti + Solo per me + {0} necessari + Rimuovi i miei dati + Installazione di {0} + Rimozione di {0} + diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 6892a5f4..ca09ebc5 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -27,6 +27,30 @@ Interfaccia scura (predefinita) Interfaccia chiara Segui la modalità app di Windows + Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore + Torna alle opzioni senza modificare nulla + Scegli la cartella di installazione + Chiudi l'installazione + Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato + Installa questo programma + Esegue Titano Server su questo PC per altri dispositivi e nodi di rendering + L'app desktop per importare, archiviare e renderizzare time-lapse + Invia le foto dalle cartelle monitorate a un Titano Server + Aggiungi collegamenti al desktop + Dove vengono installati i programmi · i tuoi dati restano nella loro cartella + Inserisci il percorso completo di una cartella che non sia la radice di un'unità o una cartella di sistema + Copia i programmi selezionati e registrali in Windows + Cartella dei programmi installati + Installa nella tua cartella utente · non servono diritti di amministratore + Lingua di questa installazione + Apri il programma al termine dell'installazione + Apri il programma installato + Già installato qui · disinstallalo prima per cambiare cartella o ambito + Elimina anche database, impostazioni e log in %LOCALAPPDATA%\Titano · le foto negli archivi non vengono toccate + Esegui di nuovo lo stesso passaggio + Aggiungi i programmi al menu Start + Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta + Sostituisci la versione installata · i tuoi dati restano Riduci la navigazione alle icone Mostra i nomi della navigazione Ferma l'attività in corso · potrai riprenderla From c97b4fb82c622f06ef8c51c0c0007bd079173354 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:16:20 +0000 Subject: [PATCH 086/188] feat(setup): add one-screen installer, uninstaller and silent mode Titano.Setup reads the TPK1 payload from its own executable and installs per user (%LOCALAPPDATA%\Programs) or for all users (Program Files, relaunched elevated through ShellExecuteEx "runas"). Extraction is hash-verified into a staging folder and committed with rollback; upgrades replace files in place, remove obsolete ones and never touch %LOCALAPPDATA%\Titano. - Components, scope, folder (IFileOpenDialog picker), desktop and Start menu shortcuts (IShellLinkW), start-after-install, language picker - Add/Remove Programs entry, .titano file type, install log - /uninstall [/S] removes only logged files, shortcuts and registry entries; user data only when "Remove my data" is ticked; the uninstaller deletes itself through a temporary helper copy - Silent switches /S /DIR= /COMPONENTS= /ALLUSERS /NODESKTOP /NOSTARTMENU /LAUNCH /LANG= with documented exit codes; running programs are asked to close, never killed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Setup/App.cs | 76 +++ src/Titano.Setup/App.xaml | 4 - src/Titano.Setup/App.xaml.cs | 7 - src/Titano.Setup/Cli/SetupArguments.cs | 105 +++++ src/Titano.Setup/Cli/SetupExitCode.cs | 41 ++ src/Titano.Setup/Engine/Elevation.cs | 79 ++++ src/Titano.Setup/Engine/InstallEngine.cs | 149 ++++++ src/Titano.Setup/Engine/InstallLog.cs | 60 +++ src/Titano.Setup/Engine/InstallPlan.cs | 37 ++ src/Titano.Setup/Engine/RunningPrograms.cs | 54 +++ src/Titano.Setup/Engine/SelfCleanup.cs | 83 ++++ src/Titano.Setup/Engine/SetupPaths.cs | 78 ++++ src/Titano.Setup/Engine/SetupRegistry.cs | 110 +++++ src/Titano.Setup/Engine/SilentSetup.cs | 99 ++++ src/Titano.Setup/Engine/UninstallEngine.cs | 106 +++++ src/Titano.Setup/Interop/FolderPicker.cs | 129 ++++++ src/Titano.Setup/Interop/NativeMethods.cs | 57 +++ src/Titano.Setup/Interop/ShellLink.cs | 61 +++ src/Titano.Setup/Interop/StaThread.cs | 33 ++ src/Titano.Setup/Program.cs | 60 +++ src/Titano.Setup/Titano.Setup.csproj | 6 + src/Titano.Setup/Views/ComponentOption.cs | 49 ++ src/Titano.Setup/Views/SetupViewModel.cs | 514 +++++++++++++++++++++ src/Titano.Setup/Views/SetupWindow.xaml | 152 ++++++ src/Titano.Setup/Views/SetupWindow.xaml.cs | 45 ++ 25 files changed, 2183 insertions(+), 11 deletions(-) create mode 100644 src/Titano.Setup/App.cs delete mode 100644 src/Titano.Setup/App.xaml delete mode 100644 src/Titano.Setup/App.xaml.cs create mode 100644 src/Titano.Setup/Cli/SetupArguments.cs create mode 100644 src/Titano.Setup/Cli/SetupExitCode.cs create mode 100644 src/Titano.Setup/Engine/Elevation.cs create mode 100644 src/Titano.Setup/Engine/InstallEngine.cs create mode 100644 src/Titano.Setup/Engine/InstallLog.cs create mode 100644 src/Titano.Setup/Engine/InstallPlan.cs create mode 100644 src/Titano.Setup/Engine/RunningPrograms.cs create mode 100644 src/Titano.Setup/Engine/SelfCleanup.cs create mode 100644 src/Titano.Setup/Engine/SetupPaths.cs create mode 100644 src/Titano.Setup/Engine/SetupRegistry.cs create mode 100644 src/Titano.Setup/Engine/SilentSetup.cs create mode 100644 src/Titano.Setup/Engine/UninstallEngine.cs create mode 100644 src/Titano.Setup/Interop/FolderPicker.cs create mode 100644 src/Titano.Setup/Interop/NativeMethods.cs create mode 100644 src/Titano.Setup/Interop/ShellLink.cs create mode 100644 src/Titano.Setup/Interop/StaThread.cs create mode 100644 src/Titano.Setup/Program.cs create mode 100644 src/Titano.Setup/Views/ComponentOption.cs create mode 100644 src/Titano.Setup/Views/SetupViewModel.cs create mode 100644 src/Titano.Setup/Views/SetupWindow.xaml create mode 100644 src/Titano.Setup/Views/SetupWindow.xaml.cs diff --git a/src/Titano.Setup/App.cs b/src/Titano.Setup/App.cs new file mode 100644 index 00000000..b6868594 --- /dev/null +++ b/src/Titano.Setup/App.cs @@ -0,0 +1,76 @@ +using System.Windows; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Engine; +using Titano.Setup.Views; +using Titano.Ui.Theming; + +namespace Titano.Setup; + +/// +/// Interactive setup: opens the payload (or, for /uninstall, the installation), elevates an all-users +/// uninstall up front, and shows the setup window. The exit code is the view model's outcome. +/// +internal sealed class App(SetupArguments arguments) : Application +{ + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + ShutdownMode = ShutdownMode.OnExplicitShutdown; + ThemeManager.Initialize(this, AppTheme.Dark); + _ = StartAsync(); + } + + private async Task StartAsync() + { + try + { + var model = arguments.Uninstall ? await ForUninstallAsync() : ForInstall(); + if (model is null) return; + var window = new SetupWindow(model); + MainWindow = window; + window.Closed += (_, _) => + { + model.Dispose(); + Shutdown((int)model.ExitCode); + }; + window.Show(); + } + catch (Exception ex) + { + Log.Error("setup", "Setup could not start", ex); + Shutdown((int)SetupExitCode.Failed); + } + } + + private SetupViewModel ForInstall() + { + PayloadReader? payload = null; + try + { + payload = PayloadReader.OpenCurrentProcess(); + return SetupViewModel.ForInstall(arguments, payload); + } + catch (Exception ex) when (ex is PayloadException or SetupException) + { + payload?.Dispose(); + Log.Error("setup", "Cannot install", ex); + return SetupViewModel.ForFailure(arguments, SilentSetup.CodeFor(ex)); + } + } + + /// The uninstall window, or null when this process handed over to an elevated copy and is shutting down. + private async Task ForUninstallAsync() + { + var product = UninstallEngine.Locate(arguments.Directory, SilentSetup.PayloadProduct()); + if (product is null) return SetupViewModel.ForFailure(arguments, SetupExitCode.NotInstalled); + if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + { + var code = arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null); + Shutdown((int)code); + return null; + } + return SetupViewModel.ForUninstall(arguments, product); + } +} diff --git a/src/Titano.Setup/App.xaml b/src/Titano.Setup/App.xaml deleted file mode 100644 index f0e5e815..00000000 --- a/src/Titano.Setup/App.xaml +++ /dev/null @@ -1,4 +0,0 @@ - - diff --git a/src/Titano.Setup/App.xaml.cs b/src/Titano.Setup/App.xaml.cs deleted file mode 100644 index 24976df3..00000000 --- a/src/Titano.Setup/App.xaml.cs +++ /dev/null @@ -1,7 +0,0 @@ -using System.Windows; - -namespace Titano.Setup; - -public partial class App : Application -{ -} diff --git a/src/Titano.Setup/Cli/SetupArguments.cs b/src/Titano.Setup/Cli/SetupArguments.cs new file mode 100644 index 00000000..e5f54e19 --- /dev/null +++ b/src/Titano.Setup/Cli/SetupArguments.cs @@ -0,0 +1,105 @@ +using System.Text; + +namespace Titano.Setup.Cli; + +/// +/// Command-line switches, case-insensitive, with / or -: +/// /S silent · /DIR=path · /COMPONENTS=Titano,Uploader · /ALLUSERS · /NODESKTOP · +/// /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall. +/// Internal: /ELEVATED (relaunched for administrator rights), /CLEANUP=path /WAITPID=n (removes the +/// uninstaller after the uninstall process exits). +/// +internal sealed record SetupArguments +{ + public bool Silent { get; init; } + public bool Uninstall { get; init; } + public string? Directory { get; init; } + public IReadOnlyList? Components { get; init; } + public bool AllUsers { get; init; } + public bool NoDesktopShortcut { get; init; } + public bool NoStartMenu { get; init; } + public bool Launch { get; init; } + public string? Language { get; init; } + public bool Elevated { get; init; } + public string? CleanupTarget { get; init; } + public int WaitProcessId { get; init; } + + /// Parses ; throws for unknown or malformed switches. + public static SetupArguments Parse(IEnumerable args) + { + var result = new SetupArguments(); + foreach (var arg in args) + { + if (arg.Length < 2 || arg[0] is not ('/' or '-')) throw new ArgumentException($"Unexpected argument '{arg}'."); + var eq = arg.IndexOf('=', StringComparison.Ordinal); + var name = (eq < 0 ? arg[1..] : arg[1..eq]).ToUpperInvariant(); + var value = eq < 0 ? null : arg[(eq + 1)..]; + result = (name, value) switch + { + ("S", null) => result with { Silent = true }, + ("UNINSTALL", null) => result with { Uninstall = true }, + ("ALLUSERS", null) => result with { AllUsers = true }, + ("NODESKTOP", null) => result with { NoDesktopShortcut = true }, + ("NOSTARTMENU", null) => result with { NoStartMenu = true }, + ("LAUNCH", null) => result with { Launch = true }, + ("ELEVATED", null) => result with { Elevated = true }, + ("DIR", { Length: > 0 }) => result with { Directory = value.Trim('"') }, + ("LANG", { Length: > 0 }) => result with { Language = value }, + ("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }, + ("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') }, + ("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid }, + _ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."), + }; + } + if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID."); + return result; + } + + /// The switches that reproduce these arguments, for relaunching with administrator rights. + public IEnumerable ToSwitches() + { + if (Uninstall) yield return "/uninstall"; + if (Silent) yield return "/S"; + if (Directory is not null) yield return "/DIR=" + Directory; + if (Components is not null) yield return "/COMPONENTS=" + string.Join(',', Components); + if (AllUsers) yield return "/ALLUSERS"; + if (NoDesktopShortcut) yield return "/NODESKTOP"; + if (NoStartMenu) yield return "/NOSTARTMENU"; + if (Launch) yield return "/LAUNCH"; + if (Language is not null) yield return "/LANG=" + Language; + if (Elevated) yield return "/ELEVATED"; + } + + /// + /// Joins arguments into one command line that CommandLineToArgvW splits back into the same strings + /// (quotes around spaces, backslashes doubled before a quote). + /// + public static string JoinCommandLine(IEnumerable arguments) + { + var sb = new StringBuilder(); + foreach (var argument in arguments) + { + if (sb.Length > 0) sb.Append(' '); + if (argument.Length > 0 && argument.IndexOfAny([' ', '\t', '"']) < 0) + { + sb.Append(argument); + continue; + } + sb.Append('"'); + var backslashes = 0; + foreach (var c in argument) + { + if (c == '\\') + { + backslashes++; + continue; + } + sb.Append('\\', c == '"' ? backslashes * 2 + 1 : backslashes); + backslashes = 0; + sb.Append(c); + } + sb.Append('\\', backslashes * 2).Append('"'); + } + return sb.ToString(); + } +} diff --git a/src/Titano.Setup/Cli/SetupExitCode.cs b/src/Titano.Setup/Cli/SetupExitCode.cs new file mode 100644 index 00000000..d044bd45 --- /dev/null +++ b/src/Titano.Setup/Cli/SetupExitCode.cs @@ -0,0 +1,41 @@ +namespace Titano.Setup.Cli; + +/// Process exit codes of Titano.Setup (stable contract for silent deployments). +internal enum SetupExitCode +{ + Success = 0, + + /// Installation or removal did not complete; the setup log in %TEMP%\Titano Setup has details. + Failed = 1, + + InvalidArguments = 2, + + /// The installer carries no payload or the payload is damaged. + PayloadInvalid = 3, + + /// All-users operation and the administrator prompt was declined. + ElevationDeclined = 4, + + /// An installed program did not close when asked to. + ProgramRunning = 5, + + /// /uninstall found no installation. + NotInstalled = 6, + + DiskFull = 7, + + /// The window was closed before anything changed. + Cancelled = 8, + + /// + /// Internal: an instance relaunched with administrator rights finished and asks its unelevated parent to start + /// the program, so the program does not run elevated. The parent turns it into . + /// + LaunchRequested = 100, +} + +/// A setup failure that maps to a specific exit code and message. +internal sealed class SetupException(SetupExitCode code, string message) : Exception(message) +{ + public SetupExitCode Code { get; } = code; +} diff --git a/src/Titano.Setup/Engine/Elevation.cs b/src/Titano.Setup/Engine/Elevation.cs new file mode 100644 index 00000000..91f7936a --- /dev/null +++ b/src/Titano.Setup/Engine/Elevation.cs @@ -0,0 +1,79 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Security.Principal; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Administrator rights for all-users operations. Setup runs asInvoker and, only when needed, starts itself +/// again through ShellExecuteEx with the runas verb (the UAC prompt) and the same switches plus /ELEVATED. +/// +internal static class Elevation +{ + public static bool IsElevated + { + get + { + using var identity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator); + } + } + + /// + /// Runs this program elevated with and waits for it; see . + /// Returns when the prompt was refused. + /// + public static async Task RunElevatedAsync(SetupArguments arguments, string? launchProgram) => + Start(arguments, IntPtr.Zero) is { } child ? await WaitAsync(child, launchProgram).ConfigureAwait(false) : SetupExitCode.ElevationDeclined; + + /// Starts this program elevated (UAC prompt owned by ); null when the user declines. + public static Process? Start(SetupArguments arguments, IntPtr owner) + { + var start = new ProcessStartInfo(Environment.ProcessPath ?? throw new InvalidOperationException("Unknown setup path.")) + { + UseShellExecute = true, + Verb = "runas", + Arguments = SetupArguments.JoinCommandLine((arguments with { Elevated = true }).ToSwitches()), + ErrorDialogParentHandle = owner, + }; + try + { + return Process.Start(start) ?? throw new InvalidOperationException("The elevated setup did not start."); + } + catch (Win32Exception ex) when (ex.NativeErrorCode == NativeMethods.ERROR_CANCELLED) + { + return null; + } + } + + /// + /// Waits for the elevated copy and returns its exit code; when it asks for it, starts + /// from this unelevated process so the program does not run as administrator. + /// + public static async Task WaitAsync(Process child, string? launchProgram) + { + using (child) + { + await child.WaitForExitAsync().ConfigureAwait(false); + var code = (SetupExitCode)child.ExitCode; + if (code != SetupExitCode.LaunchRequested) return code; + if (launchProgram is not null) Launcher.Start(launchProgram); + return SetupExitCode.Success; + } + } +} + +/// Starts an installed program the way Explorer does. +internal static class Launcher +{ + public static void Start(string program) + { + using var process = Process.Start(new ProcessStartInfo(program) + { + UseShellExecute = true, + WorkingDirectory = System.IO.Path.GetDirectoryName(program)!, + }); + } +} diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs new file mode 100644 index 00000000..dc216279 --- /dev/null +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -0,0 +1,149 @@ +using System.IO; +using System.Reflection; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// What to install, where and with which shortcuts. +internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts); + +/// Overall progress (0–1) and the file being written. +internal readonly record struct SetupProgress(double Fraction, string CurrentFile); + +/// +/// Installs or upgrades in place from the payload: verified extraction into staging, an all-or-nothing move into +/// the folder, removal of files the previous version shipped and this one does not, then shortcuts, file types and +/// the Add/Remove Programs entry. The user data folder is never touched. +/// +internal sealed class InstallEngine(PayloadReader payload) +{ + private const double ExtractShare = 0.9; + + public PayloadManifest Manifest => payload.Manifest; + + /// Bytes the selected components occupy once installed, uninstaller included. + public long RequiredBytes(IEnumerable components) => Manifest.FilesFor(components).Sum(f => f.Size) + payload.PayloadOffset; + + /// Payload path of the program to start after installing: the first shortcut target among the components. + public string? LaunchTarget(IEnumerable components) + { + var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase); + return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target; + } + + public InstallLog Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken) + { + var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.Directory)); + var product = Manifest.Product; + var uninstaller = SetupPaths.UninstallerName(product); + var files = Manifest.FilesFor(request.Components); + if (files.Any(f => PayloadPath.Comparer.Equals(f.Path, uninstaller) || PayloadPath.Comparer.Equals(f.Path, InstallLog.FileName))) + throw new PayloadException(PayloadError.Corrupt, "The payload overwrites setup's own files."); + EnsureFreeSpace(directory, RequiredBytes(request.Components)); + var previous = InstallLog.TryLoad(directory); + Log.Info("setup", $"Installing {product} {Manifest.Version} ({string.Join(",", request.Components)}) to '{directory}' for {request.Scope}"); + + using (var transaction = new InstallTransaction(directory)) + { + var extractProgress = progress is null ? null : new MappedProgress(progress, 0, ExtractShare); + payload.Extract(files, transaction.StagingDirectory, extractProgress, cancellationToken); + payload.WriteStub(Path.Combine(transaction.StagingDirectory, uninstaller)); + cancellationToken.ThrowIfCancellationRequested(); + transaction.Commit([.. files.Select(f => f.Path), uninstaller]); + } + progress?.Report(new SetupProgress(ExtractShare, string.Empty)); + + var shortcuts = PlanShortcuts(request, directory); + var fileTypes = PlanFileTypes(request); + var log = new InstallLog + { + Product = product, + Version = Manifest.Version, + Scope = request.Scope, + Components = [.. request.Components], + Files = [.. files.Select(f => f.Path)], + Shortcuts = [.. shortcuts.Select(s => s.Link)], + Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))], + }; + if (previous is not null) RemoveLeftovers(directory, previous, log); + // Saved before registration so that an uninstall can always undo whatever follows. + log.Save(directory); + + foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name); + foreach (var a in fileTypes) + SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target)); + if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged(); + + var uninstallerPath = Path.Combine(directory, uninstaller); + var icon = LaunchTarget(request.Components) is { } main ? PayloadPath.Resolve(directory, main) : uninstallerPath; + SetupRegistry.WriteUninstallEntry(request.Scope, SetupPaths.ProductKey(product), new UninstallEntry( + product, Manifest.Version, Publisher, directory, uninstallerPath, icon, RequiredBytes(request.Components), AboutUrl)); + progress?.Report(new SetupProgress(1, string.Empty)); + Log.Info("setup", $"Installed {files.Count} files"); + return log; + } + + private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano"; + + private static string? AboutUrl => + typeof(InstallEngine).Assembly.GetCustomAttributes().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo + ? "https://github.com/" + repo + : null; + + private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory) + { + var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); + var result = new List<(string, string, string)>(); + foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component))) + { + var target = PayloadPath.Resolve(directory, s.Target); + if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name)); + if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name)); + } + return result; + } + + private List PlanFileTypes(InstallRequest request) + { + var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); + return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList(); + } + + /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). + private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) + { + var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); + if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete); + foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase)) + UninstallEngine.DeleteShortcut(link, previous.Scope); + foreach (var a in previous.Associations.Except(current.Associations)) + { + if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId); + } + } + + private static void EnsureFreeSpace(string directory, long required) + { + long available; + try + { + available = new DriveInfo(Path.GetPathRoot(directory)!).AvailableFreeSpace; + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) + { + // Network shares have no DriveInfo; the copy itself reports a full disk. + return; + } + if (available < required) throw new SetupException(SetupExitCode.DiskFull, $"{required:N0} bytes needed, {available:N0} available."); + } + + /// Maps extraction progress onto a slice of the overall bar. + private sealed class MappedProgress(IProgress target, double from, double to) : IProgress + { + public void Report(PayloadProgress value) => + target.Report(new SetupProgress(from + (to - from) * (value.Total == 0 ? 1 : (double)value.Done / value.Total), value.CurrentPath)); + } +} diff --git a/src/Titano.Setup/Engine/InstallLog.cs b/src/Titano.Setup/Engine/InstallLog.cs new file mode 100644 index 00000000..4cdc6f5c --- /dev/null +++ b/src/Titano.Setup/Engine/InstallLog.cs @@ -0,0 +1,60 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.IO; + +namespace Titano.Setup.Engine; + +/// +/// Record of one installation, kept as install-log.json in the install folder. The uninstaller carries no +/// payload, so everything it removes comes from here: payload files, shortcuts and file types. User data is never +/// listed. +/// +internal sealed class InstallLog +{ + public const string FileName = "install-log.json"; + + public int FormatVersion { get; set; } = 1; + public required string Product { get; set; } + public required string Version { get; set; } + public InstallScope Scope { get; set; } + public List Components { get; set; } = []; + + /// Installed payload paths, relative to the install folder (the uninstaller and this log excluded). + public List Files { get; set; } = []; + + /// Full paths of the shortcuts setup created. + public List Shortcuts { get; set; } = []; + public List Associations { get; set; } = []; + + [JsonIgnore] + public string ProductKey => SetupPaths.ProductKey(Product); + + [JsonIgnore] + public string UninstallerName => SetupPaths.UninstallerName(Product); + + /// The log in , or null when there is none or it is unreadable. + public static InstallLog? TryLoad(string directory) + { + var path = Path.Combine(directory, FileName); + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), InstallLogJson.Default.InstallLog) : null; + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + Titano.Core.Diagnostics.Log.Warning("setup", $"Install log '{path}' is unreadable", ex); + return null; + } + } + + public void Save(string directory) => + AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog)); +} + +/// A file type registered by setup. +internal sealed record InstalledAssociation(string Extension, string ProgId); + +[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)] +[JsonSerializable(typeof(InstallLog))] +internal sealed partial class InstallLogJson : JsonSerializerContext; diff --git a/src/Titano.Setup/Engine/InstallPlan.cs b/src/Titano.Setup/Engine/InstallPlan.cs new file mode 100644 index 00000000..6b9f3cdc --- /dev/null +++ b/src/Titano.Setup/Engine/InstallPlan.cs @@ -0,0 +1,37 @@ +using Titano.Core.Packaging; +using Titano.Setup.Cli; + +namespace Titano.Setup.Engine; + +/// +/// Where and what to install before the user changes anything: an existing installation fixes folder and scope +/// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. +/// +internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing) +{ + public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments) + { + var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product)); + var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); + var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product); + + IReadOnlyList components; + if (arguments.Components is { } requested) + { + var unknown = requested.FirstOrDefault(id => manifest.FindComponent(id) is null); + if (unknown is not null) throw new SetupException(SetupExitCode.InvalidArguments, $"Unknown component '{unknown}'."); + components = [.. requested.Select(id => manifest.FindComponent(id)!.Id).Distinct()]; + } + else + { + var previous = existing is null ? null : InstallLog.TryLoad(existing.Directory)?.Components; + var kept = previous?.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList(); + components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; + } + return new InstallPlan(scope, directory, components, existing); + } + + /// Executables to look for among running processes: the new payload's and the previous install's. + public static IEnumerable Programs(PayloadManifest manifest, string directory) => + manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []); +} diff --git a/src/Titano.Setup/Engine/RunningPrograms.cs b/src/Titano.Setup/Engine/RunningPrograms.cs new file mode 100644 index 00000000..b060a50b --- /dev/null +++ b/src/Titano.Setup/Engine/RunningPrograms.cs @@ -0,0 +1,54 @@ +using System.Diagnostics; +using System.IO; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when +/// the user clicks ✕); it never terminates a process. +/// +internal static class RunningPrograms +{ + /// Processes of (payload paths) started from inside . + public static IReadOnlyList Find(string directory, IEnumerable executables) + { + var names = executables + .Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal)) + .Select(Path.GetFileNameWithoutExtension) + .Distinct(StringComparer.OrdinalIgnoreCase); + var found = new List(); + foreach (var name in names) + { + foreach (var process in Process.GetProcessesByName(name)) + { + var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id); + if (image is not null && SetupPaths.IsSameOrInside(image, directory)) found.Add(process); + else process.Dispose(); + } + } + return found; + } + + /// Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt. + public static string Describe(IReadOnlyList processes) => + string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase)); + + /// Asks each process to close and waits up to ; returns those still running. + public static async Task> CloseAsync(IReadOnlyList processes, TimeSpan timeout) + { + foreach (var process in processes) + { + if (!process.HasExited) process.CloseMainWindow(); + } + using var cts = new CancellationTokenSource(timeout); + try + { + await Task.WhenAll(processes.Select(p => p.WaitForExitAsync(cts.Token))).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + return processes.Where(p => !p.HasExited).ToList(); + } +} diff --git a/src/Titano.Setup/Engine/SelfCleanup.cs b/src/Titano.Setup/Engine/SelfCleanup.cs new file mode 100644 index 00000000..3f296f16 --- /dev/null +++ b/src/Titano.Setup/Engine/SelfCleanup.cs @@ -0,0 +1,83 @@ +using System.Diagnostics; +using System.IO; +using System.Threading; +using Titano.Core.Diagnostics; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Removes the uninstaller, which cannot delete its own running executable. It copies itself to a fresh folder in +/// %TEMP% and starts the copy with /CLEANUP=<uninstaller> /WAITPID=<its id>; the copy waits for the +/// uninstaller to exit, deletes it and the then-empty install folder, and exits. The copy itself is scheduled for +/// deletion at the next restart when setup has administrator rights; otherwise Windows' temporary-file cleanup +/// removes it. This works for per-user installs, where MoveFileEx(MOVEFILE_DELAY_UNTIL_REBOOT) is not allowed. +/// +internal static class SelfCleanup +{ + private const string Prefix = "Uninstall "; + + /// Starts the helper that deletes once this process has exited. + public static void Schedule(string uninstallerPath) + { + var folder = Path.Combine(Path.GetTempPath(), "Titano Setup", "cleanup-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + var copy = Path.Combine(folder, "Titano-Cleanup.exe"); + File.Copy(Environment.ProcessPath!, copy); + var start = new ProcessStartInfo(copy) { UseShellExecute = false, CreateNoWindow = true }; + start.ArgumentList.Add("/CLEANUP=" + uninstallerPath); + start.ArgumentList.Add("/WAITPID=" + Environment.ProcessId.ToString(System.Globalization.CultureInfo.InvariantCulture)); + using var helper = Process.Start(start); + Log.Info("setup", $"Cleanup helper started for '{uninstallerPath}'"); + } + + /// The helper side: waits for , then removes the uninstaller and its empty folder. + public static SetupExitCode Run(string uninstallerPath, int processId) + { + var name = Path.GetFileName(uninstallerPath); + if (!Path.IsPathFullyQualified(uninstallerPath) || !name.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) + || !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + return SetupExitCode.InvalidArguments; + + try + { + using var parent = Process.GetProcessById(processId); + parent.WaitForExit(TimeSpan.FromMinutes(2)); + } + catch (ArgumentException) + { + // Already exited. + } + + var removed = false; + for (var attempt = 0; attempt < 20 && !removed; attempt++) + { + try + { + if (File.Exists(uninstallerPath)) File.Delete(uninstallerPath); + removed = true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Thread.Sleep(500); + } + } + var folder = Path.GetDirectoryName(uninstallerPath)!; + try + { + if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Install folder '{folder}' not removed", ex); + } + + if (Elevation.IsElevated && Environment.ProcessPath is { } self) + { + NativeMethods.DeleteAtReboot(self); + NativeMethods.DeleteAtReboot(Path.GetDirectoryName(self)!); + } + return removed ? SetupExitCode.Success : SetupExitCode.Failed; + } +} diff --git a/src/Titano.Setup/Engine/SetupPaths.cs b/src/Titano.Setup/Engine/SetupPaths.cs new file mode 100644 index 00000000..4a1ac77d --- /dev/null +++ b/src/Titano.Setup/Engine/SetupPaths.cs @@ -0,0 +1,78 @@ +using System.IO; +using Titano.Core.Packaging; + +namespace Titano.Setup.Engine; + +/// Per-user (no administrator rights) or machine-wide installation. +internal enum InstallScope +{ + CurrentUser, + AllUsers, +} + +/// Folders and names that depend on the product and the install scope. +internal static class SetupPaths +{ + private static string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + + /// %LOCALAPPDATA%\Programs\<product> for the current user, Program Files\<product> for all users. + public static string DefaultDirectory(InstallScope scope, string product) => Path.Combine( + scope == InstallScope.AllUsers ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) : Path.Combine(LocalAppData, "Programs"), + product); + + public static string StartMenu(InstallScope scope) => + Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonPrograms : Environment.SpecialFolder.Programs); + + public static string Desktop(InstallScope scope) => + Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonDesktopDirectory : Environment.SpecialFolder.DesktopDirectory); + + /// + /// %LOCALAPPDATA%\Titano: database, settings, logs and caches of the desktop programs. Installing and + /// upgrading never touch it; uninstall removes it only when the user asks. + /// + public static string UserData => Path.Combine(LocalAppData, "Titano"); + + /// Setup's own log files (%TEMP%\Titano Setup), outside the user data folder. + public static string LogDirectory => Path.Combine(Path.GetTempPath(), "Titano Setup"); + + /// Registry key name under …\CurrentVersion\Uninstall: the product name without spaces or symbols. + public static string ProductKey(string product) => string.Concat(product.Where(char.IsAsciiLetterOrDigit)); + + public static string UninstallerName(string product) => $"Uninstall {product}.exe"; + + /// + /// True for an absolute local or UNC folder whose names Windows stores verbatim, that is not a drive root, not + /// inside the Windows folder and not the user data folder. + /// + public static bool IsUsableInstallDirectory(string? path) + { + if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path) || path.IndexOfAny(Path.GetInvalidPathChars()) >= 0) return false; + string full; + try + { + full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + var root = Path.TrimEndingDirectorySeparator(Path.GetPathRoot(full) ?? string.Empty); + if (full.Length <= root.Length) return false; + foreach (var segment in full[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + if (!PayloadPath.IsValidSegment(segment)) return false; + } + return !IsSameOrInside(full, Environment.GetFolderPath(Environment.SpecialFolder.Windows)) + && !IsSameOrInside(full, UserData) + && !IsSameOrInside(UserData, full); + } + + /// True when is or lies inside it (case-insensitive). + public static bool IsSameOrInside(string path, string folder) + { + if (folder.Length == 0) return false; + var a = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + var b = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + return a.Equals(b, StringComparison.OrdinalIgnoreCase) || a.StartsWith(b + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs new file mode 100644 index 00000000..006c7703 --- /dev/null +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -0,0 +1,110 @@ +using System.Globalization; +using System.IO; +using System.Text.RegularExpressions; +using Microsoft.Win32; + +namespace Titano.Setup.Engine; + +/// An installation found in Add/Remove Programs. +internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version); + +/// Values written to the Add/Remove Programs entry. +internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl); + +/// +/// Registry state owned by setup: the Add/Remove Programs entry under +/// Software\Microsoft\Windows\CurrentVersion\Uninstall\<key> and file types under Software\Classes, +/// in HKCU for per-user installs and HKLM for all-users installs. +/// +internal static partial class SetupRegistry +{ + private const string UninstallRoot = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\"; + private const string ClassesRoot = @"Software\Classes\"; + + private static RegistryKey Hive(InstallScope scope) => scope == InstallScope.AllUsers ? Registry.LocalMachine : Registry.CurrentUser; + + /// The installation registered under whose folder still exists, current user first. + public static ExistingInstall? FindInstall(string productKey) + { + foreach (var scope in (ReadOnlySpan)[InstallScope.CurrentUser, InstallScope.AllUsers]) + { + using var key = Hive(scope).OpenSubKey(UninstallRoot + productKey); + if (key?.GetValue("InstallLocation") is string directory && Directory.Exists(directory)) + return new ExistingInstall(scope, directory, key.GetValue("DisplayVersion") as string ?? string.Empty); + } + return null; + } + + public static void WriteUninstallEntry(InstallScope scope, string productKey, UninstallEntry entry) + { + using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true); + var quoted = "\"" + entry.UninstallerPath + "\""; + key.SetValue("DisplayName", entry.DisplayName); + key.SetValue("DisplayVersion", entry.Version); + key.SetValue("Publisher", entry.Publisher); + key.SetValue("DisplayIcon", entry.DisplayIcon + ",0"); + key.SetValue("InstallLocation", entry.Directory); + key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); + key.SetValue("UninstallString", quoted + " /uninstall"); + key.SetValue("QuietUninstallString", quoted + " /uninstall /S"); + key.SetValue("EstimatedSize", (int)Math.Min(int.MaxValue, (entry.EstimatedBytes + 1023) / 1024), RegistryValueKind.DWord); + key.SetValue("NoModify", 1, RegistryValueKind.DWord); + key.SetValue("NoRepair", 1, RegistryValueKind.DWord); + if (entry.AboutUrl is not null) key.SetValue("URLInfoAbout", entry.AboutUrl); + } + + public static void DeleteUninstallEntry(InstallScope scope, string productKey) => + Hive(scope).DeleteSubKeyTree(UninstallRoot + productKey, throwOnMissingSubKey: false); + + /// Registers to open with "program" "%1" under . + public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program) + { + EnsureValid(extension, progId); + var hive = Hive(scope); + using (var type = hive.CreateSubKey(ClassesRoot + progId, writable: true)) + { + type.SetValue(string.Empty, description); + using (var icon = type.CreateSubKey("DefaultIcon", writable: true)) icon.SetValue(string.Empty, "\"" + program + "\",0"); + using var command = type.CreateSubKey(@"shell\open\command", writable: true); + command.SetValue(string.Empty, "\"" + program + "\" \"%1\""); + } + using var ext = hive.CreateSubKey(ClassesRoot + extension, writable: true); + ext.SetValue(string.Empty, progId); + using var openWith = ext.CreateSubKey("OpenWithProgids", writable: true); + openWith.SetValue(progId, string.Empty); + } + + /// Removes the ProgID and detaches the extension, leaving other programs' registrations intact. + public static void UnregisterFileType(InstallScope scope, string extension, string progId) + { + EnsureValid(extension, progId); + var hive = Hive(scope); + hive.DeleteSubKeyTree(ClassesRoot + progId, throwOnMissingSubKey: false); + using (var ext = hive.OpenSubKey(ClassesRoot + extension, writable: true)) + { + if (ext is null) return; + if (ext.GetValue(string.Empty) is string current && current.Equals(progId, StringComparison.OrdinalIgnoreCase)) ext.DeleteValue(string.Empty, false); + using (var openWith = ext.OpenSubKey("OpenWithProgids", writable: true)) + { + openWith?.DeleteValue(progId, false); + if (openWith is { ValueCount: 0, SubKeyCount: 0 }) ext.DeleteSubKey("OpenWithProgids", false); + } + if (ext.ValueCount > 0 || ext.SubKeyCount > 0) return; + } + hive.DeleteSubKey(ClassesRoot + extension, throwOnMissingSubKey: false); + } + + /// Guards registry paths built from a log file: an extension and a dotted ProgID, nothing else. + public static bool IsValidFileType(string extension, string progId) => ExtensionRegex().IsMatch(extension) && ProgIdRegex().IsMatch(progId); + + private static void EnsureValid(string extension, string progId) + { + if (!IsValidFileType(extension, progId)) throw new ArgumentException($"Invalid file type '{extension}' / '{progId}'."); + } + + [GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")] + private static partial Regex ExtensionRegex(); + + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")] + private static partial Regex ProgIdRegex(); +} diff --git a/src/Titano.Setup/Engine/SilentSetup.cs b/src/Titano.Setup/Engine/SilentSetup.cs new file mode 100644 index 00000000..a0c7a398 --- /dev/null +++ b/src/Titano.Setup/Engine/SilentSetup.cs @@ -0,0 +1,99 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; + +namespace Titano.Setup.Engine; + +/// +/// /S: install or uninstall without a window, reporting only through the exit code and the setup log. +/// Running programs are asked to close; if they do not, setup stops with . +/// Silent uninstall never removes user data. +/// +internal static class SilentSetup +{ + public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20); + + public static async Task RunAsync(SetupArguments arguments) + { + try + { + return arguments.Uninstall ? await UninstallAsync(arguments).ConfigureAwait(false) : await InstallAsync(arguments).ConfigureAwait(false); + } + catch (Exception ex) + { + Log.Error("setup", "Silent setup failed", ex); + return CodeFor(ex); + } + } + + /// Exit code for a failure. + public static SetupExitCode CodeFor(Exception ex) => ex switch + { + SetupException s => s.Code, + PayloadException => SetupExitCode.PayloadInvalid, + // ERROR_DISK_FULL / ERROR_HANDLE_DISK_FULL + IOException { HResult: unchecked((int)0x80070070) or unchecked((int)0x80070027) } => SetupExitCode.DiskFull, + _ => SetupExitCode.Failed, + }; + + private static async Task InstallAsync(SetupArguments arguments) + { + using var payload = PayloadReader.OpenCurrentProcess(); + var engine = new InstallEngine(payload); + var plan = InstallPlan.Resolve(engine.Manifest, arguments); + if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory)) + Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'"); + if (!SetupPaths.IsUsableInstallDirectory(plan.Directory)) return SetupExitCode.InvalidArguments; + if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments; + + var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null; + if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); + + if (!await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory)).ConfigureAwait(false)) + return SetupExitCode.ProgramRunning; + var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu); + engine.Install(request, null, CancellationToken.None); + + if (launch is null) return SetupExitCode.Success; + if (arguments.Elevated) return SetupExitCode.LaunchRequested; + Launcher.Start(launch); + return SetupExitCode.Success; + } + + private static async Task UninstallAsync(SetupArguments arguments) + { + var product = UninstallEngine.Locate(arguments.Directory, PayloadProduct()); + if (product is null) return SetupExitCode.NotInstalled; + if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false); + if (!await CloseProgramsAsync(product.Directory, product.Log.Files).ConfigureAwait(false)) return SetupExitCode.ProgramRunning; + UninstallEngine.Uninstall(product, removeUserData: false, null); + return SetupExitCode.Success; + } + + /// The product named by this program's payload, when it has one (a full installer run with /uninstall). + public static string? PayloadProduct() + { + try + { + using var payload = PayloadReader.OpenCurrentProcess(); + return payload.Manifest.Product; + } + catch (PayloadException) + { + return null; + } + } + + private static async Task CloseProgramsAsync(string directory, IEnumerable programs) + { + var running = RunningPrograms.Find(directory, programs); + if (running.Count == 0) return true; + Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close"); + var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false); + foreach (var p in running) p.Dispose(); + return still.Count == 0; + } +} diff --git a/src/Titano.Setup/Engine/UninstallEngine.cs b/src/Titano.Setup/Engine/UninstallEngine.cs new file mode 100644 index 00000000..d793b225 --- /dev/null +++ b/src/Titano.Setup/Engine/UninstallEngine.cs @@ -0,0 +1,106 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// An installation found on disk: its folder and log. +internal sealed record InstalledProduct(string Directory, InstallLog Log); + +/// +/// Removes an installation using only its log: shortcuts, file types, logged files, the log and the Add/Remove +/// Programs entry, then the uninstaller itself. Files the log does not list are left alone; the user data folder +/// is deleted only when removeUserData is set by an explicit choice in the window. +/// +internal static class UninstallEngine +{ + /// The installation to remove: /DIR, the uninstaller's own folder, or the registered location. + public static InstalledProduct? Locate(string? directory, string? productFromPayload) + { + var candidates = new List { directory, Path.GetDirectoryName(Environment.ProcessPath) }; + if (productFromPayload is not null) candidates.Add(SetupRegistry.FindInstall(SetupPaths.ProductKey(productFromPayload))?.Directory); + foreach (var candidate in candidates) + { + if (string.IsNullOrEmpty(candidate)) continue; + if (InstallLog.TryLoad(candidate) is { } log) return new InstalledProduct(Path.GetFullPath(candidate), log); + } + return null; + } + + public static void Uninstall(InstalledProduct product, bool removeUserData, IProgress? progress) + { + var (directory, log) = product; + Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {removeUserData})"); + // First, so that a failure here leaves the program installed and the uninstaller able to retry. + if (removeUserData && Directory.Exists(SetupPaths.UserData)) + { + Log.Info("setup", $"Removing user data '{SetupPaths.UserData}' at the user's request"); + Directory.Delete(SetupPaths.UserData, recursive: true); + } + foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope); + progress?.Report(new SetupProgress(0.1, string.Empty)); + + var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList(); + foreach (var a in fileTypes) SetupRegistry.UnregisterFileType(log.Scope, a.Extension, a.ProgId); + if (fileTypes.Count > 0) NativeMethods.NotifyAssociationsChanged(); + progress?.Report(new SetupProgress(0.2, string.Empty)); + + var failed = InstalledFiles.Remove(directory, log.Files.Where(PayloadPath.IsValid)); + progress?.Report(new SetupProgress(0.8, string.Empty)); + if (failed.Count > 0) + { + // Keep the entry and a log of what is left, so the user can run the uninstaller again. + log.Files = [.. failed]; + log.Shortcuts = []; + log.Associations = []; + log.Save(directory); + throw new SetupException(SetupExitCode.Failed, $"{failed.Count} file(s) could not be removed."); + } + + SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey); + File.Delete(Path.Combine(directory, InstallLog.FileName)); + var uninstaller = Path.Combine(directory, log.UninstallerName); + try + { + if (Environment.ProcessPath is { } self && Path.GetFullPath(self).Equals(Path.GetFullPath(uninstaller), StringComparison.OrdinalIgnoreCase)) + { + SelfCleanup.Schedule(uninstaller); + } + else + { + if (File.Exists(uninstaller)) File.Delete(uninstaller); + InstalledFiles.Remove(directory, [], removeEmptyRoot: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) + { + // Everything else is gone; a leftover uninstaller is not worth failing the removal. + Log.Warning("setup", $"Uninstaller '{uninstaller}' not removed", ex); + } + progress?.Report(new SetupProgress(1, string.Empty)); + } + + /// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder. + public static void DeleteShortcut(string link, InstallScope scope) + { + var folder = Path.GetDirectoryName(link); + var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) + && (folder.Equals(SetupPaths.StartMenu(scope), StringComparison.OrdinalIgnoreCase) + || folder.Equals(SetupPaths.Desktop(scope), StringComparison.OrdinalIgnoreCase)); + if (!allowed) + { + Log.Warning("setup", $"Ignoring shortcut outside the shortcut folders: '{link}'"); + return; + } + try + { + File.Delete(link); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Shortcut '{link}' not removed", ex); + } + } +} diff --git a/src/Titano.Setup/Interop/FolderPicker.cs b/src/Titano.Setup/Interop/FolderPicker.cs new file mode 100644 index 00000000..cc77e7e5 --- /dev/null +++ b/src/Titano.Setup/Interop/FolderPicker.cs @@ -0,0 +1,129 @@ +using System.IO; +using System.Runtime.InteropServices; + +namespace Titano.Setup.Interop; + +/// The Windows folder picker: IFileOpenDialog with FOS_PICKFOLDERS (no WinForms). +internal static class FolderPicker +{ + private const uint FOS_PICKFOLDERS = 0x20; + private const uint FOS_FORCEFILESYSTEM = 0x40; + private const uint FOS_PATHMUSTEXIST = 0x800; + private const uint SIGDN_FILESYSPATH = 0x80058000; + + /// Shows the picker owned by ; returns the chosen folder or null when cancelled. + public static string? Pick(IntPtr owner, string title, string? initialFolder) + { + var dialog = (IFileOpenDialog)new FileOpenDialogObject(); + try + { + dialog.GetOptions(out var options); + dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); + dialog.SetTitle(title); + if (NearestExisting(initialFolder) is { } start && TryCreateItem(start) is { } item) + { + dialog.SetFolder(item); + Marshal.ReleaseComObject(item); + } + var hr = dialog.Show(owner); + if (hr == NativeMethods.HRESULT_ERROR_CANCELLED) return null; + Marshal.ThrowExceptionForHR(hr); + dialog.GetResult(out var result); + try + { + result.GetDisplayName(SIGDN_FILESYSPATH, out var path); + return path; + } + finally + { + Marshal.ReleaseComObject(result); + } + } + finally + { + Marshal.FinalReleaseComObject(dialog); + } + } + + private static string? NearestExisting(string? folder) + { + try + { + for (var dir = folder; !string.IsNullOrEmpty(dir); dir = Path.GetDirectoryName(dir)) + { + if (Directory.Exists(dir)) return dir; + } + } + catch (ArgumentException) + { + } + return null; + } + + private static IShellItem? TryCreateItem(string path) + { + try + { + return SHCreateItemFromParsingName(path, IntPtr.Zero, typeof(IShellItem).GUID); + } + catch (COMException) + { + return null; + } + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] + [return: MarshalAs(UnmanagedType.Interface)] + private static extern IShellItem SHCreateItemFromParsingName(string path, IntPtr bindContext, [MarshalAs(UnmanagedType.LPStruct)] Guid riid); + + [ComImport] + [Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] + private class FileOpenDialogObject; + + /// IModalWindow → IFileDialog → IFileOpenDialog, flattened in vtable order. + [ComImport] + [Guid("D57C7288-D4AD-4768-BE02-9D969532D960")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFileOpenDialog + { + [PreserveSig] + int Show(IntPtr parent); + void SetFileTypes(uint count, IntPtr filterSpec); + void SetFileTypeIndex(uint index); + void GetFileTypeIndex(out uint index); + void Advise(IntPtr events, out uint cookie); + void Unadvise(uint cookie); + void SetOptions(uint options); + void GetOptions(out uint options); + void SetDefaultFolder(IShellItem item); + void SetFolder(IShellItem item); + void GetFolder(out IShellItem item); + void GetCurrentSelection(out IShellItem item); + void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); + void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); + void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text); + void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); + void GetResult(out IShellItem item); + void AddPlace(IShellItem item, int place); + void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension); + void Close(int hr); + void SetClientGuid(in Guid guid); + void ClearClientData(); + void SetFilter(IntPtr filter); + void GetResults(out IntPtr items); + void GetSelectedItems(out IntPtr items); + } + + [ComImport] + [Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler(IntPtr bindContext, in Guid handler, in Guid riid, out IntPtr result); + void GetParent(out IShellItem parent); + void GetDisplayName(uint sigdn, [MarshalAs(UnmanagedType.LPWStr)] out string name); + void GetAttributes(uint mask, out uint attributes); + void Compare(IShellItem other, uint hint, out int order); + } +} diff --git a/src/Titano.Setup/Interop/NativeMethods.cs b/src/Titano.Setup/Interop/NativeMethods.cs new file mode 100644 index 00000000..e710bcfb --- /dev/null +++ b/src/Titano.Setup/Interop/NativeMethods.cs @@ -0,0 +1,57 @@ +using System.Runtime.InteropServices; + +namespace Titano.Setup.Interop; + +/// Win32 entry points used by setup (shell notification, delayed delete, process image path). +internal static partial class NativeMethods +{ + public const int ERROR_CANCELLED = 1223; + public const int HRESULT_ERROR_CANCELLED = unchecked((int)0x800704C7); + + private const int SHCNE_ASSOCCHANGED = 0x08000000; + private const int SHCNF_IDLIST = 0x0000; + private const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4; + private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + + /// Tells Explorer that file associations changed so icons and "open with" refresh. + public static void NotifyAssociationsChanged() => SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero); + + /// Asks Windows to delete a file or empty folder at the next restart (needs administrator rights). + public static bool DeleteAtReboot(string path) => MoveFileExW(path, null, MOVEFILE_DELAY_UNTIL_REBOOT); + + /// Full path of the executable of process , or null when it cannot be queried. + public static unsafe string? ProcessImagePath(int processId) + { + var handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + if (handle == IntPtr.Zero) return null; + try + { + const int capacity = 1024; + var buffer = stackalloc char[capacity]; + var length = capacity; + return QueryFullProcessImageNameW(handle, 0, buffer, ref length) ? new string(buffer, 0, length) : null; + } + finally + { + CloseHandle(handle); + } + } + + [LibraryImport("shell32.dll")] + private static partial void SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2); + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool MoveFileExW(string existingFileName, string? newFileName, int flags); + + [LibraryImport("kernel32.dll", SetLastError = true)] + private static partial IntPtr OpenProcess(int desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, int processId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool QueryFullProcessImageNameW(IntPtr process, int flags, char* exeName, ref int size); + + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CloseHandle(IntPtr handle); +} diff --git a/src/Titano.Setup/Interop/ShellLink.cs b/src/Titano.Setup/Interop/ShellLink.cs new file mode 100644 index 00000000..6f033480 --- /dev/null +++ b/src/Titano.Setup/Interop/ShellLink.cs @@ -0,0 +1,61 @@ +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +namespace Titano.Setup.Interop; + +/// Creates .lnk shortcuts through the shell's IShellLinkW and IPersistFile COM interfaces. +internal static class ShellLink +{ + /// Writes a shortcut at that starts in its own folder. + public static void Create(string linkPath, string target, string description) + { + StaThread.Run(() => + { + var link = (IShellLinkW)new ShellLinkObject(); + try + { + link.SetPath(target); + link.SetWorkingDirectory(Path.GetDirectoryName(target)!); + link.SetIconLocation(target, 0); + link.SetDescription(description); + Directory.CreateDirectory(Path.GetDirectoryName(linkPath)!); + ((IPersistFile)link).Save(linkPath, true); + } + finally + { + Marshal.FinalReleaseComObject(link); + } + }); + } + + [ComImport] + [Guid("00021401-0000-0000-C000-000000000046")] + private class ShellLinkObject; + + /// Vtable-ordered declaration; only the setters are called, so getters take raw pointers. + [ComImport] + [Guid("000214F9-0000-0000-C000-000000000046")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellLinkW + { + void GetPath(IntPtr file, int maxPath, IntPtr findData, uint flags); + void GetIDList(out IntPtr idList); + void SetIDList(IntPtr idList); + void GetDescription(IntPtr name, int maxName); + void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string name); + void GetWorkingDirectory(IntPtr dir, int maxPath); + void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string dir); + void GetArguments(IntPtr args, int maxPath); + void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string args); + void GetHotkey(out short hotkey); + void SetHotkey(short hotkey); + void GetShowCmd(out int showCmd); + void SetShowCmd(int showCmd); + void GetIconLocation(IntPtr iconPath, int maxIconPath, out int icon); + void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string iconPath, int icon); + void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string relativePath, int reserved); + void Resolve(IntPtr hwnd, int flags); + void SetPath([MarshalAs(UnmanagedType.LPWStr)] string file); + } +} diff --git a/src/Titano.Setup/Interop/StaThread.cs b/src/Titano.Setup/Interop/StaThread.cs new file mode 100644 index 00000000..a32a78f7 --- /dev/null +++ b/src/Titano.Setup/Interop/StaThread.cs @@ -0,0 +1,33 @@ +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace Titano.Setup.Interop; + +/// Runs work on a short-lived single-threaded apartment, as the apartment-threaded shell COM objects expect. +internal static class StaThread +{ + public static void Run(Action action) + { + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + action(); + return; + } + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + action(); + } + catch (Exception ex) + { + failure = ExceptionDispatchInfo.Capture(ex); + } + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + failure?.Throw(); + } +} diff --git a/src/Titano.Setup/Program.cs b/src/Titano.Setup/Program.cs new file mode 100644 index 00000000..0b8fb35c --- /dev/null +++ b/src/Titano.Setup/Program.cs @@ -0,0 +1,60 @@ +using System.Globalization; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Setup.Cli; +using Titano.Setup.Engine; + +namespace Titano.Setup; + +/// +/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the +/// . The return value is the process exit code (). +/// +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + using var log = new FileLogSink(SetupPaths.LogDirectory, "setup"); + Log.SetSink(log); + Log.Info("setup", $"Titano.Setup {typeof(Program).Assembly.GetName().Version} {string.Join(' ', args)}"); + + SetupArguments arguments; + try + { + arguments = SetupArguments.Parse(args); + } + catch (ArgumentException ex) + { + Log.Error("setup", ex.Message); + return (int)SetupExitCode.InvalidArguments; + } + ApplyLanguage(arguments.Language); + + if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId); + if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult(); + + return new App(arguments).Run(); + } + + /// Sets the UI language: the requested code, else the best match for the Windows display language. + public static void ApplyLanguage(string? code) + { + var requested = CultureInfo.CurrentUICulture; + if (code is not null) + { + try + { + requested = CultureInfo.GetCultureInfo(code); + } + catch (CultureNotFoundException) + { + Log.Warning("setup", $"Unknown language '{code}'"); + } + } + var culture = Languages.BestMatch(requested); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + } +} diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj index 4aa167fd..f18d0311 100644 --- a/src/Titano.Setup/Titano.Setup.csproj +++ b/src/Titano.Setup/Titano.Setup.csproj @@ -7,6 +7,12 @@ Titano.Setup app.manifest titano + + Titano.Setup.Program + + + + true diff --git a/src/Titano.Setup/Views/ComponentOption.cs b/src/Titano.Setup/Views/ComponentOption.cs new file mode 100644 index 00000000..062ba257 --- /dev/null +++ b/src/Titano.Setup/Views/ComponentOption.cs @@ -0,0 +1,49 @@ +using Titano.Core.Localization; +using Titano.Core.Packaging; +using Titano.Ui.Mvvm; + +namespace Titano.Setup.Views; + +/// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. +internal sealed class ComponentOption(PayloadComponent component, bool selected, Action changed) : LocalizedViewModel +{ + private bool _selected = selected; + + public string Id => component.Id; + + public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName; + + public string ToolTip => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); + + public string SizeText => ByteSize.Format(component.EstimatedSize); + + public bool IsSelected + { + get => _selected; + set + { + if (Set(ref _selected, value)) changed(); + } + } +} + +/// Language offered in the picker. +internal sealed record LanguageOption(string Code, string Name); + +/// Decimal byte sizes as Explorer shows them for drives ("1.5 MB"). +internal static class ByteSize +{ + private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"]; + + public static string Format(long bytes) + { + double value = bytes; + var unit = 0; + while (value >= 1000 && unit < Units.Length - 1) + { + value /= 1000; + unit++; + } + return value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture) + " " + Units[unit]; + } +} diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs new file mode 100644 index 00000000..1b6d4aee --- /dev/null +++ b/src/Titano.Setup/Views/SetupViewModel.cs @@ -0,0 +1,514 @@ +using System.Collections; +using System.ComponentModel; +using System.IO; +using System.Windows.Input; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Engine; +using Titano.Ui.Mvvm; + +namespace Titano.Setup.Views; + +/// What the setup screen currently shows. +internal enum SetupStage +{ + Options, + Confirm, + Working, + Done, + Failed, +} + +/// +/// The single setup screen for install and uninstall: options, a prompt when installed programs must close, +/// progress, success and failure. Work runs on the thread pool and reports through . +/// +internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo +{ + private const string FallbackProduct = "Titano"; + private readonly SetupArguments _arguments; + private readonly PayloadReader? _payload; + private readonly InstallEngine? _engine; + private readonly InstallPlan? _plan; + private readonly InstalledProduct? _installed; + private readonly string _product; + private readonly string? _version; + private SetupStage _stage; + private string _directory = string.Empty; + private bool _allUsers; + private bool _desktop; + private bool _startMenu; + private bool _launchAfter; + private bool _removeUserData; + private bool _closeConfirmed; + private double _progress; + private bool _indeterminate; + private string _progressFile = string.Empty; + private string _runningPrograms = string.Empty; + private SetupExitCode _failure; + private bool _accessDenied; + private string? _launchProgram; + private Func? _operation; + + private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed) + { + _arguments = arguments; + _product = product; + _version = version; + _payload = payload; + _installed = installed; + if (payload is not null) + { + _engine = new InstallEngine(payload); + _plan = InstallPlan.Resolve(_engine.Manifest, arguments); + _directory = _plan.Directory; + _allUsers = _plan.Scope == InstallScope.AllUsers; + } + _desktop = !arguments.NoDesktopShortcut; + _startMenu = !arguments.NoStartMenu; + _launchAfter = arguments.Launch; + Components = _engine is null + ? [] + : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), OnComponentsChanged))]; + Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; + + PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart); + BrowseCommand = new RelayCommand(Browse, () => IsOptions && CanChangeLocation); + CloseProgramsCommand = new RelayCommand(() => + { + _closeConfirmed = true; + Start(_operation!); + }, () => IsConfirm && _operation is not null); + BackCommand = new RelayCommand(() => Stage = SetupStage.Options, () => IsConfirm); + LaunchCommand = new RelayCommand(Launch, () => CanLaunch); + CloseCommand = new RelayCommand(() => Finish(ExitCode), () => !IsWorking); + RetryCommand = new RelayCommand(() => Start(_operation!), () => CanRetry && _operation is not null); + } + + public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) => + new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null); + + public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) => + new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory }; + + /// A screen that can only report why setup cannot run (no payload, nothing installed…). + public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code) + { + var model = new SetupViewModel(arguments, SilentSetup.PayloadProduct() ?? FallbackProduct, null, null, null); + model.Fail(new SetupException(code, code.ToString())); + return model; + } + + /// Raised when setup is finished and the window should close; holds the outcome. + public event EventHandler? Finished; + + /// Raised with false to hide the window while an elevated copy works, true to show it again. + public event EventHandler? VisibilityRequested; + + public event EventHandler? ErrorsChanged; + + /// Shows the folder picker; provided by the view, which owns the window handle. + public Func? PickFolder { get; set; } + + /// Window handle that owns the administrator prompt. + public IntPtr WindowHandle { get; set; } + + public SetupExitCode ExitCode { get; private set; } = SetupExitCode.Cancelled; + + public bool IsInstall => _engine is not null; + public bool IsUninstall => _installed is not null; + + public string WindowTitle => IsUninstall ? Loc.L("Setup.Window.Uninstall", _product) : Loc.L("Setup.Window.Title", _product); + public string Heading => _product; + + public string SubHeading => _version is null + ? string.Empty + : _plan?.Existing is { Version.Length: > 0 } existing + ? Loc.L("Setup.Header.Upgrade", _version, existing.Version) + : Loc.L("Setup.Header.Version", _version); + + public IReadOnlyList Languages { get; } + + public LanguageOption SelectedLanguage + { + get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0]; + set + { + if (value is not null) Program.ApplyLanguage(value.Code); + } + } + + public SetupStage Stage + { + get => _stage; + private set + { + _stage = value; + OnAllPropertiesChanged(); + CommandManager.InvalidateRequerySuggested(); + } + } + + public bool IsOptions => _stage == SetupStage.Options; + public bool IsInstallOptions => IsOptions && IsInstall; + public bool IsUninstallOptions => IsOptions && IsUninstall; + public bool IsConfirm => _stage == SetupStage.Confirm; + public bool IsWorking => _stage == SetupStage.Working; + public bool IsDone => _stage == SetupStage.Done; + public bool IsFailed => _stage == SetupStage.Failed; + + // ---- Install options ---- + + public IReadOnlyList Components { get; } + + private List SelectedComponents => [.. Components.Where(c => c.IsSelected).Select(c => c.Id)]; + + public string RequiredSpaceText => _engine is null ? string.Empty : Loc.L("Setup.Space.Required", ByteSize.Format(_engine.RequiredBytes(SelectedComponents))); + + /// False when upgrading: the existing folder and scope are kept. + public bool CanChangeLocation => _plan?.Existing is null; + + public bool IsAllUsers + { + get => _allUsers; + set + { + var before = DefaultDirectory(); + if (!Set(ref _allUsers, value)) return; + OnPropertyChanged(nameof(IsJustMe)); + // Follow the scope while the folder is still the suggested one. + if (string.Equals(Path.TrimEndingDirectorySeparator(_directory), before, StringComparison.OrdinalIgnoreCase)) Directory = DefaultDirectory(); + } + } + + public bool IsJustMe + { + get => !_allUsers; + set => IsAllUsers = !value; + } + + public string Directory + { + get => _directory; + set + { + if (!Set(ref _directory, value ?? string.Empty)) return; + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory))); + OnPropertyChanged(nameof(DirectoryToolTip)); + } + } + + private bool IsDirectoryValid => SetupPaths.IsUsableInstallDirectory(_directory); + + public string DirectoryToolTip => !CanChangeLocation + ? Loc.L("Tooltips.Setup.Locked") + : IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid"); + + public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked"); + public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked"); + + public bool DesktopShortcut + { + get => _desktop; + set => Set(ref _desktop, value); + } + + public bool StartMenuShortcuts + { + get => _startMenu; + set => Set(ref _startMenu, value); + } + + public bool LaunchAfter + { + get => _launchAfter; + set => Set(ref _launchAfter, value); + } + + public bool HasDesktopOption => SelectedShortcuts().Any(s => s.Desktop); + public bool HasStartMenuOption => SelectedShortcuts().Any(s => s.StartMenu); + public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null; + + public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update"); + public string InstallToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update"); + + private bool CanStart => IsOptions && (IsUninstall || (IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected))); + + // ---- Uninstall options ---- + + public bool RemoveUserData + { + get => _removeUserData; + set => Set(ref _removeUserData, value); + } + + // ---- Confirm, progress, outcome ---- + + public string ConfirmText => Loc.L("Setup.Running.Prompt", _runningPrograms); + + public string WorkingText => IsUninstall ? Loc.L("Setup.Progress.Removing", _product) : Loc.L("Setup.Progress.Installing", _product); + + public double Progress + { + get => _progress; + private set + { + if (Set(ref _progress, value)) OnPropertyChanged(nameof(ProgressText)); + } + } + + public string ProgressText => _indeterminate ? string.Empty : _progress.ToString("P0", Loc.Culture); + + public bool IsIndeterminate + { + get => _indeterminate; + private set + { + if (Set(ref _indeterminate, value)) OnPropertyChanged(nameof(ProgressText)); + } + } + + public string ProgressFile + { + get => _progressFile; + private set => Set(ref _progressFile, value); + } + + public string DoneText => IsUninstall ? Loc.L("Setup.Done.Removed", _product) : Loc.L("Setup.Done.Installed", _product); + + public bool CanLaunch => IsDone && _launchProgram is not null; + + public string ErrorText => _failure switch + { + SetupExitCode.PayloadInvalid => Loc.L("Setup.Error.Payload"), + SetupExitCode.ElevationDeclined => Loc.L("Setup.Error.Elevation"), + SetupExitCode.ProgramRunning => Loc.L("Setup.Error.Running", _runningPrograms), + SetupExitCode.DiskFull => Loc.L("Setup.Error.DiskFull"), + SetupExitCode.NotInstalled => Loc.L("Setup.Error.NotInstalled", _product), + SetupExitCode.InvalidArguments => Loc.L("Setup.Error.Arguments"), + _ when _accessDenied => Loc.L("Setup.Error.Access"), + _ => IsUninstall ? Loc.L("Setup.Error.Uninstall") : Loc.L("Setup.Error.Install"), + }; + + public bool CanRetry => IsFailed && _failure is not (SetupExitCode.PayloadInvalid or SetupExitCode.NotInstalled or SetupExitCode.InvalidArguments); + + public ICommand PrimaryCommand { get; } + public ICommand BrowseCommand { get; } + public ICommand CloseProgramsCommand { get; } + public ICommand BackCommand { get; } + public ICommand LaunchCommand { get; } + public ICommand CloseCommand { get; } + public ICommand RetryCommand { get; } + + public bool HasErrors => IsInstall && !IsDirectoryValid; + + public IEnumerable GetErrors(string? propertyName) => + propertyName == nameof(Directory) && HasErrors ? new[] { Loc.L("Tooltips.Setup.FolderInvalid") } : Array.Empty(); + + /// Called once the window is visible: an elevated copy continues the install the user already started. + public void OnShown() + { + if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync); + } + + public override void Dispose() + { + foreach (var c in Components) c.Dispose(); + _payload?.Dispose(); + base.Dispose(); + } + + private void Start(Func operation) + { + _operation = operation; + _ = operation(); + } + + private async Task InstallAsync() + { + var engine = _engine!; + try + { + var request = new InstallRequest( + Path.TrimEndingDirectorySeparator(Path.GetFullPath(_directory)), + _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, + SelectedComponents, + HasDesktopOption && _desktop, + HasStartMenuOption && _startMenu); + var target = engine.LaunchTarget(request.Components); + var program = target is null ? null : PayloadPath.Resolve(request.Directory, target); + var launch = _launchAfter ? program : null; + + if (request.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + { + await InstallElevatedAsync(request, launch); + return; + } + if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return; + + BeginWork(indeterminate: false); + var progress = new Progress(ReportProgress); + await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); + _launchProgram = program; + Complete(); + if (launch is not null) Launch(); + } + catch (Exception ex) + { + Fail(ex); + } + } + + /// All users without administrator rights: an elevated copy installs with the chosen options. + private async Task InstallElevatedAsync(InstallRequest request, string? launch) + { + if (_arguments.Elevated) throw new SetupException(SetupExitCode.ElevationDeclined, "Still not elevated after relaunch."); + var switches = new SetupArguments + { + Directory = request.Directory, + Components = request.Components, + AllUsers = true, + NoDesktopShortcut = !request.DesktopShortcuts, + NoStartMenu = !request.StartMenuShortcuts, + Launch = launch is not null, + Language = Loc.Culture.Name, + }; + var child = Elevation.Start(switches, WindowHandle) ?? throw new SetupException(SetupExitCode.ElevationDeclined, "Administrator approval declined."); + VisibilityRequested?.Invoke(this, false); + Finish(await Elevation.WaitAsync(child, launch)); + } + + private async Task UninstallAsync() + { + var installed = _installed!; + try + { + if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return; + BeginWork(indeterminate: false); + var progress = new Progress(ReportProgress); + var removeData = _removeUserData; + await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress)); + Complete(); + } + catch (Exception ex) + { + Fail(ex); + } + } + + /// + /// True when no installed program runs from . Otherwise the first call asks the user + /// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues. + /// + private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs) + { + var running = RunningPrograms.Find(directory, programs); + try + { + if (running.Count == 0) return true; + _runningPrograms = RunningPrograms.Describe(running); + if (!_closeConfirmed) + { + Stage = SetupStage.Confirm; + return false; + } + _closeConfirmed = false; + BeginWork(indeterminate: true); + var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout); + if (still.Count == 0) return true; + _runningPrograms = RunningPrograms.Describe(still); + throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}"); + } + finally + { + foreach (var p in running) p.Dispose(); + } + } + + private void Browse() + { + if (PickFolder?.Invoke(_directory) is not { } folder) return; + // Choosing a parent such as D:\Apps installs into D:\Apps\, never loose files in D:\Apps. + Directory = Path.GetFileName(Path.TrimEndingDirectorySeparator(folder)).Equals(_product, StringComparison.OrdinalIgnoreCase) + ? folder + : Path.Combine(folder, _product); + } + + private void Launch() + { + if (_launchProgram is null) return; + if (_arguments.Elevated) + { + // The unelevated parent starts the program, so it does not run as administrator. + Finish(SetupExitCode.LaunchRequested); + return; + } + try + { + Launcher.Start(_launchProgram); + } + catch (Win32Exception ex) + { + Log.Warning("setup", $"Could not start '{_launchProgram}'", ex); + } + Finish(SetupExitCode.Success); + } + + private void Finish(SetupExitCode code) + { + ExitCode = code; + Finished?.Invoke(this, EventArgs.Empty); + } + + private void BeginWork(bool indeterminate) + { + Progress = 0; + ProgressFile = string.Empty; + IsIndeterminate = indeterminate; + Stage = SetupStage.Working; + } + + private void ReportProgress(SetupProgress value) + { + IsIndeterminate = false; + Progress = value.Fraction; + if (value.CurrentFile.Length > 0) ProgressFile = value.CurrentFile; + } + + private void Complete() + { + ExitCode = SetupExitCode.Success; + Stage = SetupStage.Done; + } + + private void Fail(Exception ex) + { + Log.Error("setup", IsUninstall ? "Uninstall failed" : "Install failed", ex); + _failure = SilentSetup.CodeFor(ex); + _accessDenied = ex is UnauthorizedAccessException; + ExitCode = _failure; + VisibilityRequested?.Invoke(this, true); + Stage = SetupStage.Failed; + } + + private void OnComponentsChanged() + { + OnPropertyChanged(nameof(RequiredSpaceText)); + OnPropertyChanged(nameof(HasDesktopOption)); + OnPropertyChanged(nameof(HasStartMenuOption)); + OnPropertyChanged(nameof(HasLaunchOption)); + CommandManager.InvalidateRequerySuggested(); + } + + private IEnumerable SelectedShortcuts() + { + if (_engine is null) return []; + var selected = SelectedComponents; + return _engine.Manifest.Shortcuts.Where(s => selected.Contains(s.Component, StringComparer.OrdinalIgnoreCase)); + } + + private string DefaultDirectory() => + SetupPaths.DefaultDirectory(_allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _product); +} diff --git a/src/Titano.Setup/Views/SetupWindow.xaml b/src/Titano.Setup/Views/SetupWindow.xaml new file mode 100644 index 00000000..9b4495b6 --- /dev/null +++ b/src/Titano.Setup/Views/SetupWindow.xaml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -405,7 +409,7 @@ - From 65fdaaf6e4a4ec7936e2a19feffa22d6222709ee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:34:03 +0000 Subject: [PATCH 118/188] test(uploader): match transport calls by path in the engine test Two workers hash in parallel, so the first call is not always the first item. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.App.Tests/Uploader/UploadEngineTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs b/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs index 550f6b5f..f2d940bb 100644 --- a/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs +++ b/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs @@ -27,7 +27,8 @@ public sealed class UploadEngineTests(TestContext context) Assert.True(queue.Items.All(i => i.State == UploadItemState.Verified && i.FrameId is not null)); Assert.True(queue.Items.All(i => File.Exists(i.Path))); - Assert.Equal(Sha256(queue.Items[0].Path), transport.Calls[0].Sha256); + // Two workers hash in parallel, so calls arrive in either order. + foreach (var item in queue.Items) Assert.Equal(Sha256(item.Path), transport.Calls.Single(c => c.Path == item.Path).Sha256); Assert.Equal(2, confirmed.Count); }); From 33d7284c25319746fbac54ec6780f3caef230a53 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:37:43 +0000 Subject: [PATCH 119/188] feat(render): render plan for constant, adaptive, interpolated and remapped timing Output frames on the export frame grid with fractional source positions, exact 90 kHz durations, held/interpolated flags, motion cuts and plan statistics; FitToSeconds rescales the output axis. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Export/FrameRateText.cs | 36 ++ src/Titano.Core/Render/RenderPlan.cs | 442 ++++++++++++++++++ .../Render/RenderPlanTests.cs | 193 ++++++++ 3 files changed, 671 insertions(+) create mode 100644 src/Titano.Core/Export/FrameRateText.cs create mode 100644 src/Titano.Core/Render/RenderPlan.cs create mode 100644 tests/Titano.Core.Tests/Render/RenderPlanTests.cs diff --git a/src/Titano.Core/Export/FrameRateText.cs b/src/Titano.Core/Export/FrameRateText.cs new file mode 100644 index 00000000..c4a6013c --- /dev/null +++ b/src/Titano.Core/Export/FrameRateText.cs @@ -0,0 +1,36 @@ +using System.Globalization; +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// Frame rates as stored in project files: "num/den" ("24000/1001"), a decimal ("29.97") or an integer ("30"). +public static class FrameRateText +{ + /// Parses a frame rate; decimals near the NTSC rates map to their exact fractions. + public static bool TryParse(string? text, out Rational rate) + { + rate = default; + if (string.IsNullOrWhiteSpace(text)) return false; + var s = text.Trim(); + var slash = s.IndexOf('/', StringComparison.Ordinal); + if (slash >= 0) + { + if (!int.TryParse(s.AsSpan(0, slash), NumberStyles.None, CultureInfo.InvariantCulture, out var num) + || !int.TryParse(s.AsSpan(slash + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var den) + || num <= 0 || den <= 0) return false; + rate = new Rational(num, den); + return true; + } + if (!double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var fps) || !(fps > 0 && fps <= 1000)) return false; + rate = Rational.FromFps(fps); + return true; + } + + /// Canonical text: "num/den" for fractional rates, the integer otherwise. + public static string Format(Rational rate) => rate.Denominator == 1 + ? rate.Numerator.ToString(CultureInfo.InvariantCulture) + : string.Create(CultureInfo.InvariantCulture, $"{rate.Numerator}/{rate.Denominator}"); + + /// Exact rational equality (24000/1001 equals 48000/2002). + public static bool AreEqual(Rational a, Rational b) => (long)a.Numerator * b.Denominator == (long)b.Numerator * a.Denominator; +} diff --git a/src/Titano.Core/Render/RenderPlan.cs b/src/Titano.Core/Render/RenderPlan.cs new file mode 100644 index 00000000..b8e8cffb --- /dev/null +++ b/src/Titano.Core/Render/RenderPlan.cs @@ -0,0 +1,442 @@ +using Titano.Core.Export; +using Titano.Core.Mathematics; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Render; + +[Flags] +public enum PlannedFrameFlags +{ + None = 0, + + /// Synthesised between two included source frames from the motion field. + Interpolated = 1, + + /// Shown for more than one output frame period. + Held = 2, +} + +/// One output frame of a . +/// Source frame index; fractional for synthesised frames (it may fall on an excluded frame). +/// Included source frame at or before the position. +/// Included source frame after the position; equals for whole frames. +/// Blend position between (0) and (1); 0 for whole frames. +/// Presentation time on the 90 kHz clock. +/// Display duration on the 90 kHz clock. +/// First output frame period at . +/// Output frame periods covered (more than one = held). +/// Source frames advanced per output frame period towards the next planned frame (scales motion blur). +public readonly record struct PlannedFrame( + double SourcePosition, + int From, + int To, + double Fraction, + long Start90k, + long Duration90k, + int StartSlot, + int Slots, + double Speed, + PlannedFrameFlags Flags) +{ + public bool IsInterpolated => (Flags & PlannedFrameFlags.Interpolated) != 0; + + public bool IsHeld => (Flags & PlannedFrameFlags.Held) != 0; +} + +/// Rules of the timing modes (documented defaults; BRIEF §11.1). +public sealed record RenderPlanOptions +{ + public static RenderPlanOptions Default { get; } = new(); + + /// An interval longer than this multiple of the median capture interval is a gap: Adaptive compresses + /// it and motion (blur, synthesis) is treated as discontinuous across it. + public double GapFactor { get; init; } = 3; + + /// Adaptive: longest display of a compressed gap, in playback frames (gaps are shown as + /// GapFactor + log2(ratio / GapFactor) frames up to this cap). + public double MaxGapFrames { get; init; } = 5; + + /// Adaptive: an interval of at least this multiple of the median and is a + /// deliberate pause and becomes a fixed visual cut. + public double PauseFactor { get; init; } = 20; + + public double MinimumPauseSeconds { get; init; } = 120; + + /// Adaptive: video seconds the frame before a deliberate pause stays on screen. + public double PauseCutSeconds { get; init; } = 0.2; + + /// Interpolated: most consecutive missing (or excluded) frames synthesised in one gap; longer gaps are cuts. + public int MaxSynthesizedFrames { get; init; } = 3; +} + +/// Figures for the Time tab's plan chart. +/// Frames in the sequence. +/// Frames excluded by the user. +/// Included frames shown whole at least once. +/// Included frames never shown nor used for synthesis (dropped by speed-ups). +/// Planned frames (held frames count once). +/// Output frame periods at the plan frame rate. +/// Planned frames covering several periods. +/// Planned frames synthesised between two source frames. +/// Motion discontinuities (gaps, pauses, long exclusion runs). +/// Median capture interval, when capture times are known. +public sealed record RenderPlanStatistics( + int SourceFrames, + int ExcludedFrames, + int ShownFrames, + int SkippedFrames, + int OutputFrames, + int OutputSlots, + int HeldFrames, + int InterpolatedFrames, + int Cuts, + double DurationSeconds, + double MinimumSpeed, + double MaximumSpeed, + double? MedianIntervalSeconds); + +/// +/// The list of output frames of a render (BRIEF §11.1): every timing mode produces planned frames with a (possibly +/// fractional) source position and a duration on the output frame grid. +/// +/// The playback rate (, default the output rate) is how many source frames +/// one second of video shows; the output grid is the export frame rate. +/// Constant: every included frame lasts one playback frame (whole frames only). +/// Adaptive: a frame lasts its capture interval in median intervals; intervals up to +/// are kept proportional (bursts play faster, small gaps are held), longer gaps are compressed logarithmically and +/// capped, deliberate pauses become a fixed cut of ; unknown or +/// non-positive intervals count as one. +/// Interpolated: like Constant, but gaps of up to missing or +/// excluded frames get their periods back with synthesised in-betweens, and slower-than-real-time playback is +/// synthesised rather than held. +/// Remapped: a Fritsch–Carlson monotone spline through maps output time to +/// source time (both 0–1); fractional positions are synthesised. +/// +/// rescales the output time axis. Each output period shows one picture +/// (synthesised stretches sampled at the period start, whole frames at its centre); consecutive periods showing the +/// same picture merge into one held frame. Durations are differences of the rounded 90 kHz times of period boundaries, +/// so they add up exactly to the total. +/// +public sealed class RenderPlan +{ + private const double SnapEpsilon = 1e-6; + private readonly bool[] _cutBefore; + private readonly int[] _includedOrder; + + private RenderPlan(TimingMode mode, Rational frameRate, double playbackRate, PlannedFrame[] frames, int slots, int[] included, + bool[] cutBefore, RenderPlanStatistics statistics, IReadOnlyList warnings) + { + Mode = mode; + FrameRate = frameRate; + PlaybackRate = playbackRate; + Frames = frames; + SlotCount = slots; + Duration90k = TicksAt(frameRate, slots); + IncludedFrames = included; + _cutBefore = cutBefore; + _includedOrder = new int[cutBefore.Length]; + Array.Fill(_includedOrder, -1); + for (var k = 0; k < included.Length; k++) _includedOrder[included[k]] = k; + Statistics = statistics; + Warnings = warnings; + } + + public TimingMode Mode { get; } + + /// Output frame rate (the grid of every duration). + public Rational FrameRate { get; } + + /// Source frames per second of video before fitting. + public double PlaybackRate { get; } + + public IReadOnlyList Frames { get; } + + /// Output frame periods covered by the plan. + public int SlotCount { get; } + + /// Exact total duration on the 90 kHz clock. + public long Duration90k { get; } + + public double DurationSeconds => Duration90k / 90000.0; + + /// Source indices that are not excluded, ascending. + public IReadOnlyList IncludedFrames { get; } + + public RenderPlanStatistics Statistics { get; } + + /// Localisation keys of planning remarks (e.g. Adaptive without capture times). + public IReadOnlyList Warnings { get; } + + /// True when motion is discontinuous between and the included frame before it. + public bool IsCutBefore(int sourceIndex) => _cutBefore[sourceIndex]; + + /// The included frame after with continuous motion, or −1. + public int NextContinuous(int sourceIndex) + { + var k = _includedOrder[sourceIndex]; + if (k < 0 || k + 1 >= IncludedFrames.Count) return -1; + var next = IncludedFrames[k + 1]; + return _cutBefore[next] ? -1 : next; + } + + /// The included frame before with continuous motion, or −1. + public int PreviousContinuous(int sourceIndex) + { + var k = _includedOrder[sourceIndex]; + return k <= 0 || _cutBefore[sourceIndex] ? -1 : IncludedFrames[k - 1]; + } + + /// Start of output period on the 90 kHz clock, rounded half up. + public static long TicksAt(Rational frameRate, long slot) => + (slot * 90000L * frameRate.Denominator * 2 + frameRate.Numerator) / (2L * frameRate.Numerator); + + /// Builds the plan for a sequence. + /// Capture time per source frame (clock-corrected when available, e.g. + /// LightAnalysisReport.AdjustedTimes); null for unknown. + /// Timing settings and excluded frames. + /// Output (encoded) frame rate. + public static RenderPlan Build(IReadOnlyList captureTimes, ProjectSettings project, Rational frameRate, RenderPlanOptions? options = null) + { + ArgumentNullException.ThrowIfNull(captureTimes); + ArgumentNullException.ThrowIfNull(project); + if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate)); + options ??= RenderPlanOptions.Default; + var n = captureTimes.Count; + var timing = project.Timing; + var mode = timing.Mode.Resolve(TimingMode.Constant); + var playback = FrameRateText.TryParse(timing.FrameRate.Resolve(string.Empty), out var rate) ? rate.Value : frameRate.Value; + var warnings = new List(); + + var excluded = new bool[n]; + foreach (var i in project.ExcludedFrames) + { + if ((uint)i < (uint)n) excluded[i] = true; + } + var included = new List(n); + for (var i = 0; i < n; i++) + { + if (!excluded[i]) included.Add(i); + } + + var median = MedianInterval(captureTimes); + if (mode is TimingMode.Adaptive or TimingMode.Interpolated && median is null) warnings.Add("Render.Plan.NoCaptureTimes"); + var cutBefore = new bool[n]; + var entries = Timeline(captureTimes, included, mode, playback, median, options, cutBefore); + if (entries.Length == 0) + { + warnings.Add("Render.Plan.NoFrames"); + var empty = new RenderPlanStatistics(n, n - included.Count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, median); + return new RenderPlan(mode, frameRate, playback, [], 0, [.. included], cutBefore, empty, warnings); + } + + var total = entries[^1].Start + entries[^1].Length; + var seconds = timing.FitToSeconds is { } fit && fit > 0 ? fit : total / playback; + var slots = (int)long.Clamp((long)double.Round(seconds * frameRate.Value), 1, int.MaxValue / 2); + var remap = mode == TimingMode.Remapped ? RemapSpline(timing.RemapCurve, warnings) : null; + + var frames = new List(); + Sample? open = null; + var openStart = 0; + for (var k = 0; k <= slots; k++) + { + Sample? sample = null; + if (k < slots) + { + sample = Locate(entries, TimelinePosition(k, slots, total, remap), TimelinePosition(k + 0.5, slots, total, remap), total); + if (open is { } current && current.SameAs(sample.Value)) continue; + } + if (open is { } done) frames.Add(Planned(done, openStart, k - openStart, frameRate)); + open = sample; + openStart = k; + } + + var planned = frames.ToArray(); + AssignSpeeds(planned); + var statistics = Summarise(n, n - included.Count, included, planned, slots, cutBefore, frameRate, median); + return new RenderPlan(mode, frameRate, playback, planned, slots, [.. included], cutBefore, statistics, warnings); + } + + /// A stretch of the playback timeline shown by one included frame. + /// Start in playback frames. + /// Length in playback frames (> 0). + /// Source index shown at the start. + /// Next included source index, −1 for the last. + /// The position moves linearly towards across the stretch (synthesis). + private readonly record struct Entry(double Start, double Length, int Index, int Next, bool Continuous); + + private readonly record struct Sample(int From, int To, double Fraction, double Position) + { + public bool SameAs(Sample other) => From == other.From && To == other.To && Fraction == other.Fraction; + } + + private static Entry[] Timeline(IReadOnlyList times, List included, TimingMode mode, double playback, double? median, + RenderPlanOptions options, bool[] cutBefore) + { + var entries = new Entry[included.Count]; + double start = 0; + for (var k = 0; k < included.Count; k++) + { + var index = included[k]; + var next = k + 1 < included.Count ? included[k + 1] : -1; + double length = 1; + var continuous = false; + if (next >= 0) + { + var seconds = times[index] is { } a && times[next] is { } b ? (b - a).TotalSeconds : double.NaN; + var ratio = median is { } m && seconds > 0 ? seconds / m : double.NaN; + var steps = next - index; + var gap = double.Max(double.IsNaN(ratio) ? steps : ratio, steps) > options.GapFactor; + switch (mode) + { + case TimingMode.Adaptive: + length = AdaptiveLength(ratio, seconds, playback, options, ref gap); + break; + case TimingMode.Interpolated: + var periods = int.Max(steps, double.IsNaN(ratio) ? 1 : (int)double.Min(double.Round(ratio), int.MaxValue / 2)); + gap = periods - 1 > options.MaxSynthesizedFrames; + if (!gap) + { + length = periods; + continuous = true; + } + break; + case TimingMode.Remapped: + continuous = !gap; + break; + } + cutBefore[next] = gap; + } + entries[k] = new Entry(start, length, index, next, continuous); + start += length; + } + return entries; + } + + private static double AdaptiveLength(double ratio, double seconds, double playback, RenderPlanOptions options, ref bool gap) + { + if (double.IsNaN(ratio)) return 1; + if (ratio <= options.GapFactor) return ratio; + gap = true; + if (ratio >= options.PauseFactor && seconds >= options.MinimumPauseSeconds) return double.Max(options.PauseCutSeconds * playback, 1e-3); + return double.Min(options.MaxGapFrames, options.GapFactor + double.Log2(ratio / options.GapFactor)); + } + + /// Playback-timeline position of output period (fractional slots address its interior). + private static double TimelinePosition(double slot, int slots, double total, MonotoneSpline? remap) + { + var x = slot / slots; + return remap is null ? x * total : double.Clamp(remap.Evaluate(x), 0, 1) * total; + } + + /// + /// The picture of an output period. Synthesised stretches are sampled at the period start (so equal rates give whole + /// frames); whole-frame stretches at the period centre, which rounds every frame boundary to the nearest period + /// (ties keep the earlier frame, so a 2× speed-up shows frames 0, 2, 4…). + /// + private static Sample Locate(Entry[] entries, double start, double centre, double total) + { + var e = entries[Find(entries, double.Clamp(start, 0, total), atBoundary: true)]; + if (e.Continuous && e.Next >= 0) + { + var fraction = double.Clamp((start - e.Start) / e.Length, 0, 1); + if (fraction < SnapEpsilon) return new Sample(e.Index, e.Index, 0, e.Index); + if (fraction > 1 - SnapEpsilon) return new Sample(e.Next, e.Next, 0, e.Next); + return new Sample(e.Index, e.Next, fraction, e.Index + fraction * (e.Next - e.Index)); + } + var index = entries[Find(entries, double.Clamp(centre, 0, total), atBoundary: false)].Index; + return new Sample(index, index, 0, index); + } + + /// Entry containing ; a position within 1e-9 of a boundary belongs to the entry starting + /// there when , else to the one ending there. + private static int Find(Entry[] entries, double u, bool atBoundary) + { + var limit = atBoundary ? u + 1e-9 : u - 1e-9; + int lo = 0, hi = entries.Length - 1; + while (lo < hi) + { + var mid = (lo + hi + 1) >> 1; + if (atBoundary ? entries[mid].Start <= limit : entries[mid].Start < limit) lo = mid; + else hi = mid - 1; + } + return lo; + } + private static PlannedFrame Planned(Sample s, int startSlot, int slots, Rational rate) + { + var start = TicksAt(rate, startSlot); + var flags = (s.Fraction > 0 ? PlannedFrameFlags.Interpolated : PlannedFrameFlags.None) | (slots > 1 ? PlannedFrameFlags.Held : PlannedFrameFlags.None); + return new PlannedFrame(s.Position, s.From, s.To, s.Fraction, start, TicksAt(rate, startSlot + slots) - start, startSlot, slots, 0, flags); + } + + private static void AssignSpeeds(PlannedFrame[] frames) + { + for (var k = 0; k + 1 < frames.Length; k++) + frames[k] = frames[k] with { Speed = (frames[k + 1].SourcePosition - frames[k].SourcePosition) / frames[k].Slots }; + if (frames.Length > 1) frames[^1] = frames[^1] with { Speed = frames[^2].Speed }; + else if (frames.Length == 1) frames[0] = frames[0] with { Speed = 1 }; + } + + /// Sorted, clamped and made non-decreasing so the spline (and the remap) is monotone. + private static MonotoneSpline? RemapSpline(IReadOnlyList curve, List warnings) + { + var points = curve.Where(p => double.IsFinite(p.X) && double.IsFinite(p.Y)) + .Select(p => (X: double.Clamp(p.X, 0, 1), Y: double.Clamp(p.Y, 0, 1))) + .OrderBy(p => p.X) + .ToList(); + if (points.Count == 0) return null; + var xs = new List(points.Count); + var ys = new List(points.Count); + var adjusted = false; + foreach (var (x, y) in points) + { + var value = y; + if (ys.Count > 0 && value < ys[^1]) + { + value = ys[^1]; + adjusted = true; + } + if (xs.Count > 0 && x == xs[^1]) + { + ys[^1] = double.Max(ys[^1], value); + continue; + } + xs.Add(x); + ys.Add(value); + } + if (adjusted) warnings.Add("Render.Plan.RemapNotMonotonic"); + return new MonotoneSpline(xs.ToArray(), ys.ToArray()); + } + + private static double? MedianInterval(IReadOnlyList times) + { + var intervals = new List(times.Count); + for (var i = 1; i < times.Count; i++) + { + if (times[i - 1] is { } a && times[i] is { } b && b > a) intervals.Add((b - a).TotalSeconds); + } + return intervals.Count == 0 ? null : Mathematics.Statistics.Median(intervals.ToArray()); + } + + private static RenderPlanStatistics Summarise(int sourceFrames, int excludedFrames, List included, PlannedFrame[] frames, int slots, + bool[] cutBefore, Rational rate, double? median) + { + var shown = new HashSet(); + var used = new HashSet(); + int held = 0, interpolated = 0; + double minSpeed = double.PositiveInfinity, maxSpeed = double.NegativeInfinity; + foreach (var f in frames) + { + used.Add(f.From); + used.Add(f.To); + if (f.Fraction == 0) shown.Add(f.From); + if (f.IsHeld) held++; + if (f.IsInterpolated) interpolated++; + minSpeed = double.Min(minSpeed, f.Speed); + maxSpeed = double.Max(maxSpeed, f.Speed); + } + var cuts = cutBefore.Count(c => c); + return new RenderPlanStatistics(sourceFrames, excludedFrames, shown.Count, included.Count - used.Count, frames.Length, slots, held, interpolated, + cuts, TicksAt(rate, slots) / 90000.0, frames.Length > 0 ? minSpeed : 0, frames.Length > 0 ? maxSpeed : 0, median); + } +} diff --git a/tests/Titano.Core.Tests/Render/RenderPlanTests.cs b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs new file mode 100644 index 00000000..c269fa0f --- /dev/null +++ b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs @@ -0,0 +1,193 @@ +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Render; + +public sealed class RenderPlanTests +{ + private static readonly DateTime Start = new(2024, 6, 21, 19, 0, 0); + + private static DateTime?[] Regular(int count, double interval = 10) => + Enumerable.Range(0, count).Select(i => (DateTime?)Start.AddSeconds(i * interval)).ToArray(); + + private static ProjectSettings Timing(TimingMode mode, string? playback = null, double? fit = null, IReadOnlyList? curve = null, int[]? excluded = null) => new() + { + Timing = new TimingSettings + { + Mode = new Auto().WithManual(mode), + FrameRate = playback is null ? new Auto() : new Auto().WithManual(playback), + FitToSeconds = fit, + RemapCurve = curve ?? [new(0, 0), new(1, 1)], + }, + ExcludedFrames = excluded ?? [], + }; + + private static void AssertExactDurations(RenderPlan plan) + { + Assert.Equal(plan.Duration90k, plan.Frames.Sum(f => f.Duration90k)); + Assert.Equal(RenderPlan.TicksAt(plan.FrameRate, plan.SlotCount), plan.Duration90k); + long t = 0; + var slot = 0; + foreach (var f in plan.Frames) + { + Assert.Equal(t, f.Start90k); + Assert.Equal(slot, f.StartSlot); + Assert.Greater(f.Duration90k, 0); + t += f.Duration90k; + slot += f.Slots; + } + Assert.Equal(plan.SlotCount, slot); + Assert.Monotonic(plan.Frames.Select(f => f.SourcePosition)); + } + + [Test] + public void ConstantShowsEveryFrameOnceAtTheOutputRate() + { + var plan = RenderPlan.Build(Regular(100), Timing(TimingMode.Constant), new Rational(24, 1)); + Assert.Equal(100, plan.Frames.Count); + Assert.SequenceEqual(Enumerable.Range(0, 100).Select(i => (double)i), plan.Frames.Select(f => f.SourcePosition)); + Assert.True(plan.Frames.All(f => f.Duration90k == 3750 && f.Flags == PlannedFrameFlags.None && f.Speed == 1)); + Assert.Equal(375_000L, plan.Duration90k); + AssertExactDurations(plan); + } + + [Test] + public void ExcludedFramesAreSkipped() + { + var plan = RenderPlan.Build(Regular(20), Timing(TimingMode.Constant, excluded: [3, 7, 99]), new Rational(25, 1)); + Assert.Equal(18, plan.Frames.Count); + Assert.DoesNotContain(3, plan.Frames.Select(f => f.From)); + Assert.DoesNotContain(7, plan.Frames.Select(f => f.To)); + Assert.Equal(2, plan.Statistics.ExcludedFrames); + Assert.Equal(2.0, plan.Frames.Single(f => f.From == 2).Speed); + AssertExactDurations(plan); + } + + [Test] + public void NtscDurationsAccumulateWithoutDrift() + { + var plan = RenderPlan.Build(Regular(1001), Timing(TimingMode.Constant), Rational.Fps2997); + Assert.Equal(1001 * 3003L, plan.Duration90k); + Assert.True(plan.Frames.All(f => f.Duration90k == 3003)); + var fps23 = RenderPlan.Build(Regular(7), Timing(TimingMode.Constant), Rational.Fps23976); + Assert.SequenceEqual(new long[] { 3754, 3754, 3753, 3754, 3754, 3754, 3753 }, fps23.Frames.Select(f => f.Duration90k)); + Assert.Equal(26_276L, fps23.Duration90k); + AssertExactDurations(fps23); + } + + [Test] + public void SlowerPlaybackHoldsFramesInConstantAndSynthesisesInInterpolated() + { + var held = RenderPlan.Build(Regular(10), Timing(TimingMode.Constant, playback: "12"), new Rational(24, 1)); + Assert.Equal(10, held.Frames.Count); + Assert.True(held.Frames.All(f => f.Slots == 2 && f.IsHeld && f.Duration90k == 7500)); + AssertExactDurations(held); + + var smooth = RenderPlan.Build(Regular(10), Timing(TimingMode.Interpolated, playback: "12"), new Rational(24, 1)); + Assert.Equal(19, smooth.Frames.Count); + Assert.Equal(9, smooth.Statistics.InterpolatedFrames); + Assert.Equal(0.5, smooth.Frames[1].SourcePosition); + Assert.Equal(0.5, smooth.Frames[1].Fraction); + Assert.Equal(9.0, smooth.Frames[^1].SourcePosition); + Assert.True(smooth.Frames[^1].IsHeld, "the last frame has no successor to blend towards"); + AssertExactDurations(smooth); + } + + [Test] + public void FitToSecondsScalesThePlan() + { + var shorter = RenderPlan.Build(Regular(100), Timing(TimingMode.Constant, fit: 2), new Rational(25, 1)); + Assert.Equal(50, shorter.SlotCount); + Assert.Equal(180_000L, shorter.Duration90k); + Assert.True(shorter.Frames.All(f => f.Fraction == 0 && f.SourcePosition % 2 == 0)); + Assert.Equal(50, shorter.Statistics.SkippedFrames); + Assert.Approximately(2.0, shorter.Statistics.MaximumSpeed, 1e-9); + + var longer = RenderPlan.Build(Regular(100), Timing(TimingMode.Interpolated, fit: 7.96), new Rational(25, 1)); + Assert.Equal(199, longer.SlotCount); + Assert.Equal(716_400L, longer.Duration90k); + Assert.Greater(longer.Statistics.InterpolatedFrames, 90); + AssertExactDurations(longer); + } + + [Test] + public void AdaptiveFollowsCaptureTimeAndShortensPauses() + { + var times = Regular(40); + for (var i = 11; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(10); // 2× interval into frame 11 + for (var i = 21; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(60); // 7× gap into frame 21 + for (var i = 31; i < 40; i++) times[i] = times[i]!.Value.AddHours(1); // deliberate pause into frame 31 + var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1)); + Assert.Equal(40, plan.Frames.Count); + Assert.Equal(2, plan.Frames[10].Slots); + Assert.Equal(4, plan.Frames[20].Slots); // 3 + log2(7/3) = 4.22 periods, rounded on the grid + Assert.Equal(5, plan.Frames[30].Slots); // 0.2 s × 24 fps = 4.8 periods + Assert.True(plan.Frames.Where((_, i) => i is not (10 or 20 or 30)).All(f => f.Slots == 1)); + Assert.False(plan.IsCutBefore(11)); + Assert.True(plan.IsCutBefore(21)); + Assert.True(plan.IsCutBefore(31)); + Assert.Equal(-1, plan.NextContinuous(30)); + Assert.Equal(29, plan.PreviousContinuous(30)); + Assert.Equal(2, plan.Statistics.Cuts); + Assert.Approximately(10.0, plan.Statistics.MedianIntervalSeconds!.Value, 1e-9); + AssertExactDurations(plan); + } + + [Test] + public void InterpolatedFillsMissingAndExcludedFrames() + { + var times = Regular(40); + for (var i = 20; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(10); // one capture missing before frame 20 + for (var i = 35; i < 40; i++) times[i] = times[i]!.Value.AddSeconds(600); // too long to synthesise + var plan = RenderPlan.Build(times, Timing(TimingMode.Interpolated, excluded: [30]), new Rational(30, 1)); + var gap = plan.Frames.Single(f => f.From == 19 && f.IsInterpolated); + Assert.Equal(19.5, gap.SourcePosition); + Assert.Equal(20, gap.To); + var excluded = plan.Frames.Single(f => f.From == 29 && f.IsInterpolated); + Assert.Equal(30.0, excluded.SourcePosition); + Assert.Equal(31, excluded.To); + Assert.Equal(0.5, excluded.Fraction); + Assert.True(plan.IsCutBefore(35)); + Assert.False(plan.Frames.Any(f => f.From == 34 && f.IsInterpolated)); + Assert.Equal(41, plan.Frames.Count); + AssertExactDurations(plan); + } + + [Test] + public void RemapIsMonotoneEvenForBadCurves() + { + var ease = RenderPlan.Build(Regular(120), Timing(TimingMode.Remapped, curve: [new(0, 0), new(0.5, 0.2), new(1, 1)]), new Rational(24, 1)); + AssertExactDurations(ease); + Assert.Equal(120, ease.SlotCount); + Assert.Equal(0.0, ease.Frames[0].SourcePosition); + Assert.Greater(ease.Frames[^1].SourcePosition, 115); + Assert.Less(ease.Frames[^1].Speed * ease.Frames[^1].Slots, 3.5); + Assert.Less(ease.Frames[10].Speed, 0.5); + Assert.Empty(ease.Warnings); + + var bad = RenderPlan.Build(Regular(60), Timing(TimingMode.Remapped, curve: [new(1, 1), new(0, 0.1), new(0.4, 0.8), new(0.6, 0.3)]), new Rational(24, 1)); + Assert.Contains("Render.Plan.RemapNotMonotonic", bad.Warnings); + AssertExactDurations(bad); + Assert.Approximately(0.1 * 60, bad.Frames[0].SourcePosition, 1e-9); + } + + [Test] + public void EverythingExcludedGivesAnEmptyPlan() + { + var plan = RenderPlan.Build(Regular(3), Timing(TimingMode.Constant, excluded: [0, 1, 2]), new Rational(30, 1)); + Assert.Empty(plan.Frames); + Assert.Equal(0L, plan.Duration90k); + Assert.Contains("Render.Plan.NoFrames", plan.Warnings); + } + + [Test] + public void AdaptiveWithoutCaptureTimesFallsBackToConstantPacing() + { + var plan = RenderPlan.Build(new DateTime?[12], Timing(TimingMode.Adaptive), new Rational(30, 1)); + Assert.Equal(12, plan.Frames.Count); + Assert.Contains("Render.Plan.NoCaptureTimes", plan.Warnings); + AssertExactDurations(plan); + } +} From 11a38f745a73d415cdbb923a7d24edfd911d59d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:40:01 +0000 Subject: [PATCH 120/188] feat(data): persistent job engine with checkpoints, pause/resume and crash recovery JobEngine claims queued jobs atomically, persists progress at most every checkpoint interval, stops a handler when its job is cancelled or paused elsewhere and requeues jobs a crash left running. Also installs the SQLite import resolver under a lock so a concurrent first caller cannot reach a P/Invoke before the resolver is in place. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Jobs/JobEngine.cs | 246 ++++++++++++++++++ src/Titano.Data/Jobs/JobHandler.cs | 131 ++++++++++ src/Titano.Data/Sqlite/SqliteNative.cs | 11 +- .../Titano.Data.Tests/Jobs/JobEngineTests.cs | 135 ++++++++++ 4 files changed, 521 insertions(+), 2 deletions(-) create mode 100644 src/Titano.Data/Jobs/JobEngine.cs create mode 100644 src/Titano.Data/Jobs/JobHandler.cs create mode 100644 tests/Titano.Data.Tests/Jobs/JobEngineTests.cs diff --git a/src/Titano.Data/Jobs/JobEngine.cs b/src/Titano.Data/Jobs/JobEngine.cs new file mode 100644 index 00000000..b2b279f4 --- /dev/null +++ b/src/Titano.Data/Jobs/JobEngine.cs @@ -0,0 +1,246 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Titano.Core.Diagnostics; +using Titano.Core.Model; + +namespace Titano.Data.Jobs; + +public sealed record JobEngineOptions +{ + /// Concurrent workers (BRIEF §14.6: default cores / 2). + public int Workers { get; init; } = Math.Max(1, Environment.ProcessorCount / 2); + + /// Identity stamped on claimed jobs (node id); also used for crash recovery. + public string WorkerId { get; init; } = Environment.MachineName; + + /// Kinds this engine runs; null = every kind with a registered handler. + public IReadOnlyCollection? Kinds { get; init; } + + public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5); + + /// Fallback poll for jobs enqueued by other processes. + public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3); + + /// Finished jobs older than this are purged (BRIEF §14.6: 90 days). + public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90); +} + +/// +/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the +/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their +/// checkpoints). Used by the desktop client (local mode) and the server. +/// +public sealed class JobEngine : IAsyncDisposable +{ + private readonly TitanoDatabase _db; + private readonly Dictionary _handlers; + private readonly ConcurrentDictionary _running = new(); + private readonly Channel _wake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); + private readonly CancellationTokenSource _shutdown = new(); + private readonly List _workers = []; + + public JobEngine(TitanoDatabase db, IEnumerable handlers, JobEngineOptions? options = null) + { + _db = db; + Options = options ?? new JobEngineOptions(); + _handlers = handlers.ToDictionary(h => h.Kind); + } + + public JobEngineOptions Options { get; } + + /// A job changed state (queued, running, done, failed, cancelled, paused). + public event Action? JobChanged; + + /// Progress of a running job (high frequency; throttle in the UI). + public event Action? Progress; + + public IReadOnlyCollection RunningJobIds => [.. _running.Keys]; + + /// Requeues this worker's interrupted jobs, purges old history and starts the workers. + public async Task StartAsync(CancellationToken cancellationToken = default) + { + var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false); + if (requeued > 0) Log.Info("jobs", $"Requeued {requeued} interrupted job(s)"); + await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false); + for (var i = 0; i < Options.Workers; i++) + { + var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}"; + _workers.Add(Task.Run(() => WorkerLoopAsync(id, _shutdown.Token), CancellationToken.None)); + } + } + + /// Queues a job and wakes a worker. + public async Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel = null, string? parametersJson = null, + JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) + { + var job = new Job + { + Id = Guid.CreateVersion7(), + Kind = kind, + TargetIds = targets, + TargetLabel = targetLabel, + ParametersJson = parametersJson, + Priority = priority, + State = JobState.Queued, + CreatedBy = createdBy, + Created = DateTimeOffset.UtcNow, + }; + await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false); + JobChanged?.Invoke(job); + Wake(); + return job; + } + + /// Cancels a queued or running job; a running handler observes its token. + public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken); + + /// Pauses a job: a running one stops at its next check and keeps its checkpoint. + public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken); + + /// Resumes a paused job or retries a failed/cancelled one from its last checkpoint. + public async Task ResumeAsync(Guid id, CancellationToken cancellationToken = default) + { + await _db.Jobs.SetStateAsync(id, JobState.Queued, null, cancellationToken).ConfigureAwait(false); + await NotifyAsync(id, cancellationToken).ConfigureAwait(false); + Wake(); + } + + /// Signals workers that new work may be available (also call on PostgreSQL NOTIFY). + public void Wake() => _wake.Writer.TryWrite(true); + + public async ValueTask DisposeAsync() + { + await _shutdown.CancelAsync().ConfigureAwait(false); + try + { + await Task.WhenAll(_workers).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + _shutdown.Dispose(); + } + + internal void PublishProgress(JobContext context) + { + var (rate, eta) = context.Rate(); + Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message)); + } + + internal async Task PersistAsync(JobContext context) + { + var (rate, eta) = context.Rate(); + try + { + return await _db.Jobs.UpdateProgressAsync(context.Job.Id, context.Done, context.Total, rate, eta, context.Checkpoint, context.LogTail, CancellationToken.None) + .ConfigureAwait(false); + } + catch (DatabaseException ex) when (ex.IsTransient) + { + Log.Warning("jobs", "Progress not saved (transient database error)", ex); + return true; + } + } + + internal void StopJob(Guid id) + { + if (_running.TryGetValue(id, out var cts)) cts.Cancel(); + } + + private async Task TransitionAsync(Guid id, JobState state, CancellationToken cancellationToken) + { + await _db.Jobs.SetStateAsync(id, state, null, cancellationToken).ConfigureAwait(false); + StopJob(id); + await NotifyAsync(id, cancellationToken).ConfigureAwait(false); + } + + private async Task NotifyAsync(Guid id, CancellationToken cancellationToken) + { + if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job); + } + + private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown) + { + var kinds = Options.Kinds ?? [.. _handlers.Keys]; + while (!shutdown.IsCancellationRequested) + { + Job? job; + try + { + job = await _db.Jobs.ClaimNextAsync(workerId, kinds, shutdown).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + catch (DatabaseException ex) + { + Log.Warning("jobs", "Claiming a job failed", ex); + job = null; + } + + if (job is null) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown); + timeout.CancelAfter(Options.PollInterval); + try + { + await _wake.Reader.ReadAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Poll interval elapsed or shutdown. + } + continue; + } + + await RunAsync(job, shutdown).ConfigureAwait(false); + } + } + + private async Task RunAsync(Job job, CancellationToken shutdown) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown); + _running[job.Id] = cts; + JobChanged?.Invoke(job); + var context = new JobContext(this, job, cts.Token); + JobState final; + string? error = null; + try + { + if (!_handlers.TryGetValue(job.Kind, out var handler)) + throw new InvalidOperationException($"No handler for {job.Kind} jobs on this worker."); + await handler.RunAsync(context).ConfigureAwait(false); + await PersistAsync(context).ConfigureAwait(false); + final = JobState.Done; + } + catch (OperationCanceledException) when (cts.IsCancellationRequested) + { + await PersistAsync(context).ConfigureAwait(false); + if (shutdown.IsCancellationRequested) + { + // Engine stopping: leave the job running so the next start requeues it from its checkpoint. + _running.TryRemove(job.Id, out _); + return; + } + // Cancel or pause already wrote the state; keep it. + _running.TryRemove(job.Id, out _); + await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false); + return; + } + catch (Exception ex) + { + Log.Error("jobs", $"{job.Kind} job {job.Id} failed", ex); + context.Log(ex.Message); + await PersistAsync(context).ConfigureAwait(false); + final = JobState.Failed; + error = ex.Message; + } + finally + { + _running.TryRemove(job.Id, out _); + } + await _db.Jobs.SetStateAsync(job.Id, final, error, CancellationToken.None).ConfigureAwait(false); + await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Titano.Data/Jobs/JobHandler.cs b/src/Titano.Data/Jobs/JobHandler.cs new file mode 100644 index 00000000..a8c18705 --- /dev/null +++ b/src/Titano.Data/Jobs/JobHandler.cs @@ -0,0 +1,131 @@ +using System.Diagnostics; +using System.Text; +using Titano.Core.Model; + +namespace Titano.Data.Jobs; + +/// Runs one kind of job (scan, verify, render, …). Handlers must honour +/// and resume from when it is set. +public interface IJobHandler +{ + JobKind Kind { get; } + + Task RunAsync(JobContext context); +} + +/// Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients). +public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message); + +/// Everything a handler needs while it runs. Progress is cheap to report; the engine persists it at most every +/// checkpoint interval (BRIEF §14.6: checkpoints every 5 s). +public sealed class JobContext +{ + private const int LogTailLines = 40; + private readonly JobEngine _engine; + private readonly Stopwatch _clock = Stopwatch.StartNew(); + private readonly Queue _log = new(); + private readonly Lock _gate = new(); + private long _lastPersistTicks; + private long _rateDone; + private double _rateSeconds; + private double? _rate; + + internal JobContext(JobEngine engine, Job job, CancellationToken cancellation) + { + _engine = engine; + Job = job; + Cancellation = cancellation; + Checkpoint = job.Checkpoint; + Done = job.ProgressDone; + Total = job.ProgressTotal; + _rateDone = Done; + if (job.LogTail is { Length: > 0 } tail) + { + foreach (var line in tail.Split('\n')) _log.Enqueue(line); + } + } + + public Job Job { get; } + + /// Signalled on cancel, pause and engine shutdown. + public CancellationToken Cancellation { get; } + + /// Resume cursor saved by a previous attempt (null on the first run). + public string? Checkpoint { get; private set; } + + public long Done { get; private set; } + + public long Total { get; private set; } + + public string? Message { get; private set; } + + /// Reports progress; persisted and broadcast at most every checkpoint interval. + public ValueTask ReportAsync(long done, long total, string? message = null) => ReportCoreAsync(done, total, message, force: false); + + /// Saves a resume cursor together with the current progress (persisted immediately). + public ValueTask CheckpointAsync(string checkpoint, long done, long total) + { + Checkpoint = checkpoint; + return ReportCoreAsync(done, total, Message, force: true); + } + + /// Appends a line to the job log (the last lines are kept with the job). + public void Log(string line) + { + lock (_gate) + { + _log.Enqueue($"{DateTime.UtcNow:HH:mm:ss} {line}"); + while (_log.Count > LogTailLines) _log.Dequeue(); + } + } + + internal string LogTail + { + get + { + lock (_gate) + { + var sb = new StringBuilder(); + foreach (var l in _log) + { + if (sb.Length > 0) sb.Append('\n'); + sb.Append(l); + } + return sb.ToString(); + } + } + } + + /// Throughput as a moving average over windows of at least two seconds, and the time left at that rate. + internal (double? Rate, TimeSpan? Eta) Rate() + { + lock (_gate) + { + var seconds = _clock.Elapsed.TotalSeconds; + var span = seconds - _rateSeconds; + if (span >= 2 && Done >= _rateDone) + { + var sample = (Done - _rateDone) / span; + _rate = _rate is { } previous ? previous * 0.7 + sample * 0.3 : sample; + _rateDone = Done; + _rateSeconds = seconds; + } + TimeSpan? eta = _rate is > 0 && Total > Done ? TimeSpan.FromSeconds((Total - Done) / _rate.Value) : null; + return (_rate, eta); + } + } + + private async ValueTask ReportCoreAsync(long done, long total, string? message, bool force) + { + Done = done; + Total = total; + Message = message; + var now = _clock.ElapsedTicks; + var due = now - Interlocked.Read(ref _lastPersistTicks) >= _engine.Options.CheckpointInterval.TotalSeconds * Stopwatch.Frequency; + _engine.PublishProgress(this); + if (!force && !due) return; + Interlocked.Exchange(ref _lastPersistTicks, now); + if (!await _engine.PersistAsync(this).ConfigureAwait(false)) + _engine.StopJob(Job.Id); // cancelled or paused by someone else + } +} diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs index 97938b91..b86a4c77 100644 --- a/src/Titano.Data/Sqlite/SqliteNative.cs +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -11,7 +11,9 @@ namespace Titano.Data.Sqlite; internal static unsafe class SqliteNative { private const string Library = "titano-sqlite3"; - private static int _resolverInstalled; + // Set only after the resolver is in place: a concurrent first caller must not reach a P/Invoke before that. + private static readonly Lock ResolverGate = new(); + private static bool _resolverInstalled; public const int SQLITE_OK = 0; public const int SQLITE_INTERRUPT = 9; @@ -43,8 +45,13 @@ internal static unsafe class SqliteNative /// Routes the logical library name to the platform's system SQLite (once per process). public static void EnsureResolver() { - if (Interlocked.Exchange(ref _resolverInstalled, 1) == 0) + if (Volatile.Read(ref _resolverInstalled)) return; + lock (ResolverGate) + { + if (_resolverInstalled) return; NativeLibrary.SetDllImportResolver(typeof(SqliteNative).Assembly, Resolve); + Volatile.Write(ref _resolverInstalled, true); + } } private static nint Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) diff --git a/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs b/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs new file mode 100644 index 00000000..eec610a2 --- /dev/null +++ b/tests/Titano.Data.Tests/Jobs/JobEngineTests.cs @@ -0,0 +1,135 @@ +using Titano.Core.Model; +using Titano.Data.Jobs; +using Titano.Testing; + +namespace Titano.Data.Tests.Jobs; + +[Category("jobs")] +public sealed class JobEngineTests(TestContext context) +{ + private sealed class CountingHandler(JobKind kind, int steps, Func? onStep = null) : IJobHandler + { + public JobKind Kind => kind; + public List SeenCheckpoints { get; } = []; + public int Completed; + + public async Task RunAsync(JobContext c) + { + lock (SeenCheckpoints) SeenCheckpoints.Add(c.Checkpoint); + var start = c.Checkpoint is { } cp ? int.Parse(cp, System.Globalization.CultureInfo.InvariantCulture) : 0; + for (var i = start; i < steps; i++) + { + c.Cancellation.ThrowIfCancellationRequested(); + if (onStep is not null) await onStep(i, c.Cancellation); + await c.CheckpointAsync((i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), i + 1, steps); + } + Interlocked.Increment(ref Completed); + } + } + + private async Task OpenAsync() => + await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation); + + private static async Task WaitForStateAsync(TitanoDatabase db, Guid id, JobState state, TimeSpan timeout) + { + var until = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < until) + { + var job = await db.Jobs.GetAsync(id); + if (job?.State == state) return job; + await Task.Delay(20); + } + Assert.Fail($"Job {id} did not reach {state}"); + return null!; + } + + [Test] + public async Task RunsQueuedJobsToCompletion() + { + await using var db = await OpenAsync(); + var handler = new CountingHandler(JobKind.Verify, 5); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 2, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(100) }); + var progress = 0; + engine.Progress += _ => Interlocked.Increment(ref progress); + await engine.StartAsync(); + var a = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], "A"); + var b = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], "B"); + var doneA = await WaitForStateAsync(db, a.Id, JobState.Done, TimeSpan.FromSeconds(10)); + await WaitForStateAsync(db, b.Id, JobState.Done, TimeSpan.FromSeconds(10)); + Assert.Equal(2, handler.Completed); + Assert.Equal(5L, doneA.ProgressDone); + Assert.Greater(progress, 0); + } + + [Test] + public async Task CancelStopsARunningJob() + { + await using var db = await OpenAsync(); + var started = new TaskCompletionSource(); + var handler = new CountingHandler(JobKind.Scan, 1000, async (i, ct) => + { + if (i == 0) started.TrySetResult(); + await Task.Delay(10, ct); + }); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" }); + await engine.StartAsync(); + var job = await engine.EnqueueAsync(JobKind.Scan, []); + await started.Task.WaitAsync(TimeSpan.FromSeconds(10)); + await engine.CancelAsync(job.Id); + await WaitForStateAsync(db, job.Id, JobState.Cancelled, TimeSpan.FromSeconds(5)); + Assert.Equal(0, handler.Completed); + } + + [Test] + public async Task PauseAndResumeContinueFromCheckpoint() + { + await using var db = await OpenAsync(); + var gate = new SemaphoreSlim(0); + var handler = new CountingHandler(JobKind.Proxies, 20, async (i, ct) => + { + if (i == 10) await gate.WaitAsync(ct); + }); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(100) }); + await engine.StartAsync(); + var job = await engine.EnqueueAsync(JobKind.Proxies, []); + var until = DateTime.UtcNow.AddSeconds(10); + while ((await db.Jobs.GetAsync(job.Id))!.Checkpoint != "10" && DateTime.UtcNow < until) await Task.Delay(20); + await engine.PauseAsync(job.Id); + var paused = await WaitForStateAsync(db, job.Id, JobState.Paused, TimeSpan.FromSeconds(5)); + Assert.Equal("10", paused.Checkpoint); + gate.Release(10); + await engine.ResumeAsync(job.Id); + await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10)); + Assert.Equal("10", handler.SeenCheckpoints[^1]); + } + + [Test] + public async Task CrashedJobsResumeAfterRestart() + { + await using var db = await OpenAsync(); + var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Thumbs, State = JobState.Queued, Created = DateTimeOffset.UtcNow }; + await db.Jobs.EnqueueAsync(job); + var claimed = await db.Jobs.ClaimNextAsync("t"); + Assert.NotNull(claimed); + await db.Jobs.UpdateProgressAsync(job.Id, 7, 12, null, null, "7", null); + // Simulated crash: the job stays "running" for worker t. A new engine with the same id requeues it. + var handler = new CountingHandler(JobKind.Thumbs, 12); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" }); + await engine.StartAsync(); + await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10)); + Assert.Equal("7", handler.SeenCheckpoints.Single()); + } + + [Test] + public async Task HandlerFailureMarksJobFailedWithMessage() + { + await using var db = await OpenAsync(); + var handler = new CountingHandler(JobKind.Render, 3, (i, _) => i == 1 ? throw new InvalidOperationException("encoder lost") : Task.CompletedTask); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" }); + await engine.StartAsync(); + var job = await engine.EnqueueAsync(JobKind.Render, []); + var failed = await WaitForStateAsync(db, job.Id, JobState.Failed, TimeSpan.FromSeconds(10)); + Assert.Equal("encoder lost", failed.Error); + Assert.Contains("encoder lost", failed.LogTail); + } +} From 34b7c2736de95f90a7d906d5f607e33cb4fae48e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:40:19 +0000 Subject: [PATCH 121/188] feat(analysis): add streaming deep analysis with resumable checkpoints Per-frame statistics, nine-patch shift, Draft flow on sampled pairs, stars, clouds, sky/land luminance and exposure-aligned scene distance, then sequence-level flicker, received exposure steps, white balance, shake, day/night, hero frame and findings in a versioned analysis.json. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/Deep/CloudCoverage.cs | 84 ++++ .../Analysis/Deep/DeepAnalysisCheckpoint.cs | 108 +++++ .../Analysis/Deep/DeepAnalysisJson.cs | 25 + .../Analysis/Deep/DeepAnalysisOptions.cs | 69 +++ .../Analysis/Deep/DeepAnalysisReport.cs | 226 +++++++++ src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs | 210 ++++++++ src/Titano.Core/Analysis/Deep/DeepFrame.cs | 82 ++++ .../Analysis/Deep/DeepSequenceAnalysis.cs | 450 ++++++++++++++++++ src/Titano.Core/Analysis/Deep/FrameProbe.cs | 147 ++++++ .../Analysis/Deep/HistogramDistance.cs | 61 +++ src/Titano.Core/Analysis/Deep/IFrameSource.cs | 25 + .../Analysis/Deep/StarFieldDetector.cs | 57 +++ .../Analysis/Deep/DeepAnalyzerTests.cs | 311 ++++++++++++ .../Analysis/Deep/DeepFixtures.cs | 125 +++++ 14 files changed, 1980 insertions(+) create mode 100644 src/Titano.Core/Analysis/Deep/CloudCoverage.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepAnalysisCheckpoint.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepAnalysisJson.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepAnalysisOptions.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepFrame.cs create mode 100644 src/Titano.Core/Analysis/Deep/DeepSequenceAnalysis.cs create mode 100644 src/Titano.Core/Analysis/Deep/FrameProbe.cs create mode 100644 src/Titano.Core/Analysis/Deep/HistogramDistance.cs create mode 100644 src/Titano.Core/Analysis/Deep/IFrameSource.cs create mode 100644 src/Titano.Core/Analysis/Deep/StarFieldDetector.cs create mode 100644 tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs create mode 100644 tests/Titano.Core.Tests/Analysis/Deep/DeepFixtures.cs diff --git a/src/Titano.Core/Analysis/Deep/CloudCoverage.cs b/src/Titano.Core/Analysis/Deep/CloudCoverage.cs new file mode 100644 index 00000000..62138d12 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/CloudCoverage.cs @@ -0,0 +1,84 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis.Deep; + +/// +/// Cloud coverage estimate (BRIEF §10.2) from sky texture: the sky (weight ≥ 0.9 of a ) is +/// cut into square blocks and a block is cloudy when the 30th percentile of |Laplacian| of its sRGB-encoded luminance +/// exceeds max(·σ, ). σ is the 10th percentile of the blocks' +/// Immerkær (1996) noise estimates, so the clouds' own texture does not raise the noise floor. Cloud texture lifts nearly every pixel of a block while stars touch a few, so the low percentile ignores +/// star fields; the Laplacian ignores smooth sky gradients. A uniform overcast reads as clear sky. +/// +public static class CloudCoverage +{ + /// The 30th percentile of |Laplacian| of pure Gaussian noise is ≈ 1.7σ, so this is 3.5 × the noise level. + public const double NoiseFactor = 6; + + public const double MinimumTexture = 0.004; + + /// Fraction of sky blocks that are cloudy; NaN when no block is sky. + public static double Estimate(ImageBuffer image, ReadOnlySpan skyWeights, int block = 8) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentOutOfRangeException.ThrowIfLessThan(block, 3); + if (skyWeights.Length != image.PlaneLength) throw new ArgumentException("One sky weight per pixel is required.", nameof(skyWeights)); + int w = image.Width, h = image.Height; + if (w < 3 || h < 3) return double.NaN; + var e = new float[image.PlaneLength]; + ColorSpace.Luminance(image, e); + for (var i = 0; i < e.Length; i++) e[i] = ColorSpace.EncodeFast(e[i]); + var threshold = double.Max(NoiseFactor * Noise(e, w, h, block), MinimumTexture); + + var values = new double[block * block]; + int sky = 0, cloudy = 0; + for (var by = 0; by + block <= h; by += block) + { + for (var bx = 0; bx + block <= w; bx += block) + { + double weight = 0; + var count = 0; + for (var y = by; y < by + block; y++) + { + for (var x = bx; x < bx + block; x++) + { + var i = y * w + x; + weight += skyWeights[i]; + if (x == 0 || y == 0 || x == w - 1 || y == h - 1) continue; + values[count++] = double.Abs(e[i - 1] + e[i + 1] + e[i - w] + e[i + w] - 4.0 * e[i]); + } + } + if (weight < 0.9 * block * block || count == 0) continue; + sky++; + if (Statistics.Select(values.AsSpan(0, count), (int)(0.3 * (count - 1))) > threshold) cloudy++; + } + } + return sky > 0 ? (double)cloudy / sky : double.NaN; + } + + /// 10th percentile over whole blocks of the Immerkær fast noise σ (interior pixels only). + private static double Noise(float[] e, int w, int h, int block) + { + var estimates = new List(); + for (var by = 0; by + block <= h; by += block) + { + for (var bx = 0; bx + block <= w; bx += block) + { + double sum = 0; + var count = 0; + for (var y = int.Max(1, by); y < int.Min(h - 1, by + block); y++) + { + for (var x = int.Max(1, bx); x < int.Min(w - 1, bx + block); x++) + { + var i = y * w + x; + sum += double.Abs(e[i - w - 1] + e[i - w + 1] + e[i + w - 1] + e[i + w + 1] + - 2.0 * (e[i - w] + e[i + w] + e[i - 1] + e[i + 1]) + 4.0 * e[i]); + count++; + } + } + if (count > 0) estimates.Add(double.Sqrt(double.Pi / 2) / 6 * sum / count); + } + } + return estimates.Count > 0 ? Statistics.Percentile(estimates.ToArray(), 0.1) : 0; + } +} diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalysisCheckpoint.cs b/src/Titano.Core/Analysis/Deep/DeepAnalysisCheckpoint.cs new file mode 100644 index 00000000..4faad2e1 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepAnalysisCheckpoint.cs @@ -0,0 +1,108 @@ +using System.Text; +using System.Text.Json; + +namespace Titano.Core.Analysis.Deep; + +/// +/// Where persists per-frame results while it runs, so a crashed or cancelled analysis +/// resumes after the last persisted frame. +/// +public interface IDeepAnalysisCheckpoint +{ + /// + /// Frames persisted by an earlier run with the same , in index order from 0. A store + /// holding another fingerprint discards its content and starts over. + /// + ValueTask> LoadAsync(string fingerprint, CancellationToken cancellationToken); + + /// Persists the next frames (consecutive indices) durably before returning. + ValueTask AppendAsync(IReadOnlyList frames, CancellationToken cancellationToken); +} + +/// +/// Checkpoint as a JSON-lines file (e.g. .titano/analysis.partial): a header line with the fingerprint, then +/// one per line, flushed to disk after every batch. A torn last line from a crash is dropped +/// on load. Delete the file once the final report is saved. +/// +public sealed class DeepAnalysisCheckpointFile(string path) : IDeepAnalysisCheckpoint +{ + /// Conventional file name next to . + public const string FileName = "analysis.partial"; + + private static readonly UTF8Encoding Utf8 = new(false); + + public string Path { get; } = path; + + public async ValueTask> LoadAsync(string fingerprint, CancellationToken cancellationToken) + { + var frames = new List(); + if (File.Exists(Path)) + { + var bytes = await File.ReadAllBytesAsync(Path, cancellationToken).ConfigureAwait(false); + var valid = Parse(bytes, fingerprint, frames); + if (valid > 0) + { + // Cut a torn or foreign tail so later appends continue a well-formed file. + await using var stream = new FileStream(Path, FileMode.Open, FileAccess.Write, FileShare.None); + stream.SetLength(valid); + return frames; + } + } + var header = JsonSerializer.Serialize(new CheckpointHeader(fingerprint), DeepCheckpointJson.Default.CheckpointHeader) + "\n"; + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(Path))!); + await File.WriteAllBytesAsync(Path, Utf8.GetBytes(header), cancellationToken).ConfigureAwait(false); + return frames; + } + + public async ValueTask AppendAsync(IReadOnlyList frames, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(frames); + var text = new StringBuilder(); + foreach (var frame in frames) text.Append(JsonSerializer.Serialize(frame, DeepCheckpointJson.Default.DeepFrame)).Append('\n'); + await using var stream = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.None); + await stream.WriteAsync(Utf8.GetBytes(text.ToString()), cancellationToken).ConfigureAwait(false); + stream.Flush(flushToDisk: true); + } + + public void Delete() + { + if (File.Exists(Path)) File.Delete(Path); + } + + /// Reads the header and the contiguous frames after it; returns the byte length of the valid prefix + /// (0 when the header is missing or belongs to another fingerprint). + private static int Parse(byte[] bytes, string fingerprint, List frames) + { + var offset = 0; + var valid = 0; + var line = 0; + while (offset < bytes.Length) + { + var end = Array.IndexOf(bytes, (byte)'\n', offset); + if (end < 0) break; + var span = bytes.AsSpan(offset, end - offset); + try + { + if (line == 0) + { + if (JsonSerializer.Deserialize(span, DeepCheckpointJson.Default.CheckpointHeader)?.Fingerprint != fingerprint) return 0; + } + else + { + var frame = JsonSerializer.Deserialize(span, DeepCheckpointJson.Default.DeepFrame); + if (frame is null || frame.Index != frames.Count) break; + frames.Add(frame); + } + } + catch (JsonException) + { + if (line == 0) return 0; + break; + } + line++; + offset = end + 1; + valid = offset; + } + return valid; + } +} diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalysisJson.cs b/src/Titano.Core/Analysis/Deep/DeepAnalysisJson.cs new file mode 100644 index 00000000..7a61cc52 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepAnalysisJson.cs @@ -0,0 +1,25 @@ +using System.Text.Json.Serialization; + +namespace Titano.Core.Analysis.Deep; + +/// Source-generated JSON for analysis.json and the database summary: compact, camelCase, enums as names. +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + UseStringEnumConverter = true, + PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(DeepAnalysisReport))] +[JsonSerializable(typeof(AnalysisSummary))] +internal sealed partial class DeepAnalysisJson : JsonSerializerContext; + +/// Checkpoint lines: exact doubles, NaN written as a literal so unmeasured values survive a resume. +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, + UseStringEnumConverter = true)] +[JsonSerializable(typeof(DeepFrame))] +[JsonSerializable(typeof(CheckpointHeader))] +internal sealed partial class DeepCheckpointJson : JsonSerializerContext; + +/// First line of a checkpoint file. +internal sealed record CheckpointHeader(string Fingerprint); diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalysisOptions.cs b/src/Titano.Core/Analysis/Deep/DeepAnalysisOptions.cs new file mode 100644 index 00000000..79c5e537 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepAnalysisOptions.cs @@ -0,0 +1,69 @@ +using System.Globalization; + +namespace Titano.Core.Analysis.Deep; + +/// Parameters of ; every value enters the checkpoint fingerprint. +public sealed record DeepAnalysisOptions +{ + public static DeepAnalysisOptions Default { get; } = new(); + + /// Upper bound of the analysis long edge (BRIEF §10.2: half native, capped at 2048). + public int MaxAnalysisLongEdge { get; init; } = 2048; + + /// Sources smaller than twice this are analysed at this size (or native when smaller). + public int MinAnalysisLongEdge { get; init; } = 512; + + /// Long edge of the plane the per-frame shift is measured on (nine phase-correlation patches). + public int CorrelationLongEdge { get; init; } = 1024; + + /// Long edge of the optical-flow images (Draft quality). + public int FlowLongEdge { get; init; } = 512; + + /// Optical flow runs on the pair (k − 1, k) for every k divisible by this. + public int FlowEvery { get; init; } = 10; + + /// Long edge of the thumbnails used for regions and cloud coverage. + public int ThumbnailLongEdge { get; init; } = 256; + + /// Frames sampled evenly for the sky/land mask. + public int RegionSampleFrames { get; init; } = 15; + + /// Frames whose trimmed mean log2 luminance is at or below this are dark (night) frames. + public double DarkLogLuminance { get; init; } = -4; + + /// Point sources per megapixel from which a dark frame shows a star field. + public double StarFieldDensity { get; init; } = 30; + + /// Smallest exposure-aligned histogram distance that can be a scene change. + public double SceneChangeMinimum { get; init; } = 0.25; + + /// σ (frames) of the camera-path smoothing used for the shake measure (as StabilizerOptions). + public double ShakeSmoothingSigma { get; init; } = 12; + + /// Frames measured concurrently; also the batch size between checkpoints. + public int MaxDegreeOfParallelism { get; init; } = int.Clamp(Environment.ProcessorCount, 1, 4); + + /// Analysis long edge for a source whose oriented long edge is (0 = unknown). + public int AnalysisLongEdge(int sourceLongEdge) + { + if (sourceLongEdge <= 0) return MaxAnalysisLongEdge; + var half = (sourceLongEdge + 1) / 2; + return int.Min(sourceLongEdge, int.Min(MaxAnalysisLongEdge, int.Max(MinAnalysisLongEdge, half))); + } + + /// Stable text of every value that changes per-frame results (parallelism excluded). + public string Fingerprint() => string.Create(CultureInfo.InvariantCulture, + $"edge={MinAnalysisLongEdge}-{MaxAnalysisLongEdge};corr={CorrelationLongEdge};flow={FlowLongEdge}/{FlowEvery};thumb={ThumbnailLongEdge};regions={RegionSampleFrames};dark={DarkLogLuminance}"); + + internal void Validate() + { + ArgumentOutOfRangeException.ThrowIfLessThan(MinAnalysisLongEdge, 16); + ArgumentOutOfRangeException.ThrowIfLessThan(MaxAnalysisLongEdge, MinAnalysisLongEdge); + ArgumentOutOfRangeException.ThrowIfLessThan(CorrelationLongEdge, 16); + ArgumentOutOfRangeException.ThrowIfLessThan(FlowLongEdge, 16); + ArgumentOutOfRangeException.ThrowIfLessThan(FlowEvery, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(ThumbnailLongEdge, 16); + ArgumentOutOfRangeException.ThrowIfLessThan(RegionSampleFrames, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(MaxDegreeOfParallelism, 1); + } +} diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs b/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs new file mode 100644 index 00000000..78c9810f --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs @@ -0,0 +1,226 @@ +using System.Text.Json; +using Titano.Core.IO; + +namespace Titano.Core.Analysis.Deep; + +/// Light condition of a whole sequence. +public enum DayNight +{ + Unknown, + Day, + Night, + DayToNight, + NightToDay, +} + +/// +/// Per-frame series of the report as compact parallel arrays (one entry per frame, null = not measured), rounded to +/// what charts and render rules need (~100 bytes per frame in JSON). Shifts and motion are in source pixels. +/// +public sealed record DeepFrameColumns +{ + /// Trimmed mean log2 luminance, 0.001 EV. + public double?[] LogLuminance { get; init; } = []; + + public double?[] ClipLow { get; init; } = []; + public double?[] ClipHigh { get; init; } = []; + + /// log2(R/G) and log2(B/G) of the mean colour, 0.001. + public double?[] RedRatio { get; init; } = []; + + public double?[] BlueRatio { get; init; } = []; + + /// Correlated colour temperature in kelvin, null when not near-Planckian. + public double?[] Kelvin { get; init; } = []; + + /// Laplacian variance and noise σ of sRGB-encoded luminance, two significant digits. + public double?[] Sharpness { get; init; } = []; + + public double?[] Noise { get; init; } = []; + + /// Content motion from the previous usable frame, 0.01 px. + public double?[] ShiftX { get; init; } = []; + + public double?[] ShiftY { get; init; } = []; + + /// Stars per megapixel of the analysis image (dark frames only). + public double?[] StarDensity { get; init; } = []; + + public double?[] CloudCoverage { get; init; } = []; + public double?[] SkyLogLuminance { get; init; } = []; + public double?[] LandLogLuminance { get; init; } = []; + public double?[] SceneDistance { get; init; } = []; + + /// per frame. + public int[] Flags { get; init; } = []; + + /// Frames k whose optical flow from k − 1 was sampled, with median and 95th-percentile magnitude (px per frame). + public int[] MotionFrames { get; init; } = []; + + public double[] MotionMedian { get; init; } = []; + public double[] MotionP95 { get; init; } = []; + + public DeepFrameFlags FlagsOf(int index) => (DeepFrameFlags)Flags[index]; +} + +/// RMS deviation of the step-free luminance from its smooth curve. +/// RMS frame-to-frame flicker relative to the curve (). +/// Period of periodic flicker (). +/// Deflicker window: 4 × period or correlation length, odd, bounded. +public sealed record FlickerSummary(double AmplitudeEv, double FrameToFrameEv, double? PeriodFrames, double PeakCorrelation, double CorrelationLength, int RecommendedWindow); + +/// Horizon row / mask height at up to 64 evenly spaced columns (horizon method only). +/// RMS of the difference between the sky and land residuals: how independently they flicker. +public sealed record RegionSummary(RegionMethod Method, double Confidence, double SkyFraction, int MaskWidth, int MaskHeight, double[]? Horizon, double DivergenceEv); + +/// One metadata exposure step as the pixels received it (). +public sealed record ExposureStepSummary(int Index, double ExpectedEv, double? MeasuredEv, bool Received, double Length); + +/// Median frames between received steps (two or more received). +/// Half the typical spacing, 12 for a single step, null without received steps. +/// 5–95 % range of the step-free luminance: how much the light itself changed. +public sealed record ExposureSummary(int MetadataSteps, int ReceivedSteps, double? TypicalSpacing, int? TransitionLength, double SceneRangeEv, IReadOnlyList Steps); + +/// RMS frame-to-frame colour-ratio deviation from the smoothed ratios (log2 units). +/// Largest range of the smoothed colour ratios (slow, deliberate change). +public sealed record WhiteBalanceSummary(double JitterLog2, double DriftLog2, double? KelvinLow, double? KelvinHigh); + +/// RMS distance of the camera path from its smoothed path, source pixels. +/// Area fraction a centred crop must give up to hide every correction. +/// Average drift of the smoothed path. +/// Share of frame pairs whose shift could be measured (textured patches). +public sealed record ShakeSummary(double RmsPx, double MaxPx, double CropCost, double PanPxPerFrame, bool PanDetected, double MeasuredFraction); + +/// Median of the sampled pairs' median flow magnitude, source px per frame. +/// Median of the sampled pairs' 95th-percentile magnitude: the typical speed of moving content. +public sealed record MotionSummary(int Pairs, double? MedianPx, double? P95Px, double? MaxP95Px); + +/// Median stars per megapixel over dark frames. +/// Mean cloudy fraction of the sky. +public sealed record SkySummary(DayNight Light, double DarkFraction, int DarkFrames, int StarFrames, double? StarDensity, bool StarField, double? CloudCoverage); + +public sealed record FrameIssues(int[] Undecodable, int[] Black, int[] White, int[] Duplicate, int[] SceneChanges) +{ + /// Every frame that would flash or stutter in a render, ascending. + public int[] Excludable() => [.. Undecodable.Concat(Black).Concat(White).Concat(Duplicate).Distinct().Order()]; +} + +/// A with numeric arguments, so the report round-trips through JSON. +public sealed record DeepFinding(string Key, FindingSeverity Severity, double[] Arguments, int[] Frames) +{ + public Finding ToFinding() => new(Key, Severity, [.. Arguments.Cast()], Frames); +} + +/// Resource keys of the findings produced by the deep analysis; arguments are numbers. +public static class DeepFindingKeys +{ + public const string UnreadableFrames = "Advisor.Finding.UnreadableFrames"; + public const string BlackFrames = "Advisor.Finding.BlackFrames"; + public const string WhiteFrames = "Advisor.Finding.WhiteFrames"; + public const string DuplicateFrames = "Advisor.Finding.DuplicateFrames"; + public const string SceneChanges = "Advisor.Finding.SceneChanges"; + public const string Flicker = "Advisor.Finding.Flicker"; + public const string Shake = "Advisor.Finding.Shake"; + public const string Panning = "Advisor.Finding.Panning"; + public const string StarField = "Advisor.Finding.StarField"; + public const string Clouds = "Advisor.Finding.Clouds"; + public const string WhiteBalanceJitter = "Advisor.Finding.WhiteBalanceJitter"; + public const string StepsNotReceived = "Advisor.Finding.StepsNotReceived"; +} + +/// +/// Result of the deep analysis (BRIEF §10.2), stored as .titano/analysis.json. Versioned; per-frame data is +/// columnar (), sequence-level results are small records. +/// +public sealed record DeepAnalysisReport +{ + public const int CurrentVersion = 1; + + /// File name inside a sequence's .titano folder. + public const string FileName = "analysis.json"; + + public int Version { get; init; } = CurrentVersion; + public int FrameCount { get; init; } + + /// Dominant oriented source size from metadata (0 when unknown): the pixel unit of shifts and motion. + public int SourceWidth { get; init; } + + public int SourceHeight { get; init; } + public int AnalysisLongEdge { get; init; } + public DeepFrameColumns Frames { get; init; } = new(); + public required FlickerSummary Flicker { get; init; } + public RegionSummary? Regions { get; init; } + public required ExposureSummary Exposure { get; init; } + public required WhiteBalanceSummary WhiteBalance { get; init; } + public required ShakeSummary Shake { get; init; } + public required MotionSummary Motion { get; init; } + public required SkySummary Sky { get; init; } + public required FrameIssues Issues { get; init; } + + /// Suggested hero frame: sharp, well exposed, near golden hour or mid-sequence, not excluded. + public int? HeroIndex { get; init; } + + public IReadOnlyList Findings { get; init; } = []; + + public string ToJson() => JsonSerializer.Serialize(this, DeepAnalysisJson.Default.DeepAnalysisReport); + + public static DeepAnalysisReport FromJson(string json) + { + var report = JsonSerializer.Deserialize(json, DeepAnalysisJson.Default.DeepAnalysisReport) + ?? throw new InvalidDataException("analysis.json is empty."); + if (report.Version > CurrentVersion) + throw new InvalidDataException($"analysis.json version {report.Version} is newer than this Titano ({CurrentVersion})."); + return report; + } + + /// Writes the report atomically (temp file, flush, rename). + public void Save(string path) => AtomicFile.WriteAllText(path, ToJson()); + + public static DeepAnalysisReport Load(string path) => FromJson(File.ReadAllText(path)); +} + +/// Compact digest of a for the sequence row of the database (BRIEF §5). +public sealed record AnalysisSummary +{ + public int Version { get; init; } = DeepAnalysisReport.CurrentVersion; + public int FrameCount { get; init; } + public DayNight Light { get; init; } + public double FlickerEv { get; init; } + public double? FlickerPeriod { get; init; } + + /// Shake RMS in source pixels. + public double ShakePx { get; init; } + + /// Typical speed of moving content (). + public double? MotionPx { get; init; } + + public bool StarField { get; init; } + public double? StarDensity { get; init; } + public double? CloudCoverage { get; init; } + public int WarningCount { get; init; } + public int? HeroIndex { get; init; } + + public static AnalysisSummary From(DeepAnalysisReport report) + { + ArgumentNullException.ThrowIfNull(report); + return new AnalysisSummary + { + FrameCount = report.FrameCount, + Light = report.Sky.Light, + FlickerEv = report.Flicker.AmplitudeEv, + FlickerPeriod = report.Flicker.PeriodFrames, + ShakePx = report.Shake.RmsPx, + MotionPx = report.Motion.P95Px, + StarField = report.Sky.StarField, + StarDensity = report.Sky.StarDensity, + CloudCoverage = report.Sky.CloudCoverage, + WarningCount = report.Findings.Count(f => f.Severity >= FindingSeverity.Warning), + HeroIndex = report.HeroIndex, + }; + } + + public string ToJson() => JsonSerializer.Serialize(this, DeepAnalysisJson.Default.AnalysisSummary); + + public static AnalysisSummary FromJson(string json) => + JsonSerializer.Deserialize(json, DeepAnalysisJson.Default.AnalysisSummary) ?? throw new InvalidDataException("Analysis summary is empty."); +} diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs new file mode 100644 index 00000000..e0e55593 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs @@ -0,0 +1,210 @@ +using System.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Motion; + +namespace Titano.Core.Analysis.Deep; + +/// +/// Deep analysis (BRIEF §10.2): one streaming pass over every frame. A pre-pass segments sky and land on a sample of +/// thumbnails; then frames are probed in parallel batches (: statistics, stars, region +/// luminance, clouds) and compared in order with the previous usable frame (nine-patch phase-correlation shift, duplicate +/// test, exposure-aligned histogram distance, Draft optical flow on every -th +/// pair). Memory is one batch of analysis images plus the previous frame's reduced planes. After every batch the new +/// s go to the checkpoint, so an interrupted run resumes after the last persisted frame with +/// identical results. Sequence-level results are computed by . +/// +public static class DeepAnalyzer +{ + public static async Task AnalyzeAsync( + IFrameSource source, + DeepAnalysisOptions? options = null, + IDeepAnalysisCheckpoint? checkpoint = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(source); + options ??= DeepAnalysisOptions.Default; + options.Validate(); + var n = source.Count; + var metadata = new LightFrame[n]; + for (var i = 0; i < n; i++) metadata[i] = source.Metadata(i); + + var frames = new DeepFrame[n]; + var start = 0; + if (checkpoint is not null) + { + var saved = await checkpoint.LoadAsync(Fingerprint(n, options), cancellationToken).ConfigureAwait(false); + while (start < saved.Count && start < n && saved[start].Index == start) frames[start] = saved[start++]; + } + + var mask = n > 0 ? await FrameProbe.SegmentRegionsAsync(source, options, cancellationToken).ConfigureAwait(false) : null; + using var state = new SequentialState(options); + await PrimeAsync(source, frames, start, options, mask, state, cancellationToken).ConfigureAwait(false); + + var clock = Stopwatch.StartNew(); + var batch = options.MaxDegreeOfParallelism; + for (var first = start; first < n; first += batch) + { + cancellationToken.ThrowIfCancellationRequested(); + var count = int.Min(batch, n - first); + var tasks = new Task[count]; + for (var k = 0; k < count; k++) + { + var index = first + k; + tasks[k] = Task.Run(() => FrameProbe.RunAsync(source, index, options, mask, cancellationToken), cancellationToken); + } + var produced = new DeepFrame[count]; + try + { + await Task.WhenAll(tasks).ConfigureAwait(false); + for (var k = 0; k < count; k++) produced[k] = frames[first + k] = state.Next(tasks[k].Result, cancellationToken); + } + finally + { + foreach (var task in tasks) + { + if (task.IsCompletedSuccessfully) task.Result.Dispose(); + } + } + if (checkpoint is not null) await checkpoint.AppendAsync(produced, cancellationToken).ConfigureAwait(false); + if (progress is not null) + { + var done = first + count; + var rate = (done - start) / double.Max(clock.Elapsed.TotalSeconds, 1e-3); + progress.Report(new AnalysisProgress(done, n, rate, TimeSpan.FromSeconds((n - done) / rate))); + } + } + + return DeepSequenceAnalysis.Build(frames, metadata, mask, options); + } + + /// Identifies checkpoints written by this version for this frame count and these options. + public static string Fingerprint(int frameCount, DeepAnalysisOptions options) + { + ArgumentNullException.ThrowIfNull(options); + return $"titano-deep/{DeepAnalysisReport.CurrentVersion};frames={frameCount};{options.Fingerprint()}"; + } + + /// Restores the comparison state of a resumed run from the last usable frame before . + private static async Task PrimeAsync(IFrameSource source, DeepFrame[] frames, int start, DeepAnalysisOptions options, RegionMask? mask, SequentialState state, CancellationToken cancellationToken) + { + var last = start - 1; + while (last >= 0 && !frames[last].IsUsable) last--; + if (last < 0) return; + using var probe = await FrameProbe.RunAsync(source, last, options, mask, cancellationToken).ConfigureAwait(false); + state.Next(probe, cancellationToken); + } + + /// + /// The order-dependent comparisons: each usable frame is compared with the previous usable frame and becomes the + /// new reference; undecodable, black and white frames leave the state untouched. + /// + private sealed class SequentialState(DeepAnalysisOptions options) : IDisposable + { + private const int MinimumStabilizerSize = 16; + private readonly OpticalFlowEngine _flow = new(FlowQuality.Draft); + private Stabilizer? _stabilizer; + private FrameStatistics? _previous; + private ImageBuffer? _previousFlow; + private int _previousIndex = -1; + + public DeepFrame Next(FrameProbe probe, CancellationToken cancellationToken) + { + if (probe.Statistics is not { } stats) return new DeepFrame { Index = probe.Index, Flags = DeepFrameFlags.Undecodable }; + var frame = Measured(probe.Index, stats); + if (!probe.IsUsable) return frame; + + var (shiftX, shiftY) = Shift(probe); + var duplicate = _previous is not null && FrameStatistics.AreLikelyDuplicates(_previous, stats); + var scene = _previous is null ? double.NaN : HistogramDistance.ExposureAligned(_previous, stats); + var (motionMedian, motionP95) = Motion(probe, stats, cancellationToken); + frame = frame with + { + Flags = frame.Flags | (duplicate ? DeepFrameFlags.Duplicate : DeepFrameFlags.None), + ShiftX = shiftX, + ShiftY = shiftY, + MotionMedian = motionMedian, + MotionP95 = motionP95, + StarDensity = probe.StarDensity, + CloudCoverage = probe.CloudCoverage, + SkyLogLuminance = probe.SkyLogLuminance, + LandLogLuminance = probe.LandLogLuminance, + SceneDistance = scene, + }; + + _previous = stats; + _previousIndex = probe.Index; + _previousFlow?.Dispose(); + _previousFlow = null; + _previousFlow = probe.TakeFlow(); + return frame; + } + + public void Dispose() + { + _flow.Dispose(); + _stabilizer?.Dispose(); + _previousFlow?.Dispose(); + } + + private DeepFrame Measured(int index, FrameStatistics stats) + { + var flags = DeepFrameFlags.None; + if (stats.IsBlack()) flags |= DeepFrameFlags.Black; + if (stats.IsWhite()) flags |= DeepFrameFlags.White; + if (stats.MeanLogLuminance <= options.DarkLogLuminance) flags |= DeepFrameFlags.Dark; + var green = stats.MeanGreen; + return new DeepFrame + { + Index = index, + Flags = flags, + LogLuminance = stats.MeanLogLuminance, + ClipLow = stats.ClipLowFraction, + ClipHigh = stats.ClipHighFraction, + RedRatio = stats.MeanRed > 0 && green > 0 ? double.Log2(stats.MeanRed / green) : double.NaN, + BlueRatio = stats.MeanBlue > 0 && green > 0 ? double.Log2(stats.MeanBlue / green) : double.NaN, + Kelvin = stats.ColorTemperature?.Kelvin ?? double.NaN, + Sharpness = stats.Sharpness, + Noise = stats.Noise, + }; + } + + /// Content motion at the centre of the correlation plane, in source pixels; NaN for the first frame of a + /// size, too small planes and frames without textured patches. + private (double X, double Y) Shift(FrameProbe probe) + { + int w = probe.CorrelationWidth, h = probe.CorrelationHeight; + if (w < MinimumStabilizerSize || h < MinimumStabilizerSize || probe.Correlation is null) return (double.NaN, double.NaN); + if (_stabilizer is null || _stabilizer.Width != w || _stabilizer.Height != h) + { + _stabilizer?.Dispose(); + _stabilizer = new Stabilizer(w, h); + _stabilizer.AddFrame(probe.Correlation); + return (double.NaN, double.NaN); + } + var motion = _stabilizer.AddFrame(probe.Correlation); + if (!motion.Estimated) return (double.NaN, double.NaN); + double cx = (w - 1) / 2.0, cy = (h - 1) / 2.0; + var (x, y) = motion.Transform.Apply(cx, cy); + return ((x - cx) * probe.CorrelationScale, (y - cy) * probe.CorrelationScale); + } + + /// Draft flow from the previous frame with the current frame brought to the previous mean level, so + /// flicker and exposure steps do not read as motion; magnitudes in source pixels per frame. + private (double Median, double P95) Motion(FrameProbe probe, FrameStatistics stats, CancellationToken cancellationToken) + { + if (probe.Index % options.FlowEvery != 0 || _previousIndex != probe.Index - 1) return (double.NaN, double.NaN); + if (probe.Flow is not { } current || _previousFlow is not { } previous || previous.Width != current.Width || previous.Height != current.Height) + return (double.NaN, double.NaN); + using var levelled = current.Clone(); + var gain = (float)double.Exp2(_previous!.MeanLogLuminance - stats.MeanLogLuminance); + if (float.IsFinite(gain)) + { + foreach (ref var v in levelled.Data) v *= gain; + } + using var field = _flow.Compute(previous, levelled, cancellationToken); + var statistics = field.Statistics(); + return (statistics.MedianMagnitude * probe.FlowScale, statistics.P95Magnitude * probe.FlowScale); + } + } +} diff --git a/src/Titano.Core/Analysis/Deep/DeepFrame.cs b/src/Titano.Core/Analysis/Deep/DeepFrame.cs new file mode 100644 index 00000000..f2884ef4 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepFrame.cs @@ -0,0 +1,82 @@ +namespace Titano.Core.Analysis.Deep; + +/// Per-frame conditions found by the deep analysis. +[Flags] +public enum DeepFrameFlags +{ + None = 0, + + /// The source could not decode the frame; every measurement is NaN. + Undecodable = 1, + + Black = 2, + White = 4, + + /// Statistically identical to the previous decoded frame. + Duplicate = 8, + + /// Exposure-aligned histogram jump from the previous frame (camera moved or bumped); set at sequence level. + SceneChange = 16, + + /// Trimmed mean log2 luminance at or below . + Dark = 32, + + /// Dark frame with at least stars per megapixel; set at sequence level. + StarField = 64, +} + +/// +/// Exact per-frame measurements of : what a checkpoint persists and what the +/// sequence-level results are computed from. NaN marks a value that was not measured. Shifts and motion are in +/// source pixels (oriented full resolution). +/// +public sealed record DeepFrame +{ + public int Index { get; init; } + public DeepFrameFlags Flags { get; init; } + + /// Trimmed mean log2 luminance (). + public double LogLuminance { get; init; } = double.NaN; + + public double ClipLow { get; init; } = double.NaN; + public double ClipHigh { get; init; } = double.NaN; + + /// log2(R/G) of the mean colour (white-balance drift signal). + public double RedRatio { get; init; } = double.NaN; + + /// log2(B/G) of the mean colour. + public double BlueRatio { get; init; } = double.NaN; + + /// Correlated colour temperature of the mean colour; NaN when not near-Planckian. + public double Kelvin { get; init; } = double.NaN; + + public double Sharpness { get; init; } = double.NaN; + public double Noise { get; init; } = double.NaN; + + /// Content motion from the previous decoded frame at the image centre (nine-patch similarity fit). + public double ShiftX { get; init; } = double.NaN; + + public double ShiftY { get; init; } = double.NaN; + + /// Median optical-flow magnitude from the previous frame, px per frame (sampled pairs only). + public double MotionMedian { get; init; } = double.NaN; + + /// 95th-percentile optical-flow magnitude from the previous frame (sampled pairs only). + public double MotionP95 { get; init; } = double.NaN; + + /// Point sources per megapixel of the analysis image (dark frames only). + public double StarDensity { get; init; } = double.NaN; + + /// Fraction of sky blocks with cloud texture (frames with a sky region only). + public double CloudCoverage { get; init; } = double.NaN; + + /// Trimmed mean log2 luminance of the sky region (region deflicker signal). + public double SkyLogLuminance { get; init; } = double.NaN; + + public double LandLogLuminance { get; init; } = double.NaN; + + /// Exposure-aligned chi-square histogram distance from the previous decoded frame. + public double SceneDistance { get; init; } = double.NaN; + + public bool IsUsable => (Flags & (DeepFrameFlags.Undecodable | DeepFrameFlags.Black | DeepFrameFlags.White)) == 0; +} diff --git a/src/Titano.Core/Analysis/Deep/DeepSequenceAnalysis.cs b/src/Titano.Core/Analysis/Deep/DeepSequenceAnalysis.cs new file mode 100644 index 00000000..bb1a4d77 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/DeepSequenceAnalysis.cs @@ -0,0 +1,450 @@ +using Titano.Core.Mathematics; +using Titano.Core.Motion; + +namespace Titano.Core.Analysis.Deep; + +/// +/// Sequence-level results of the deep analysis, computed from the exact s and the frame +/// metadata: exposure steps as received (), flicker spectrum and amplitude on the +/// step-free luminance (, ), region divergence, white-balance +/// jitter (), shake from the integrated shifts (camera path minus its +/// smoothing, as ), motion, stars, clouds, day/night, +/// scene changes, the hero frame and the findings. +/// +public static class DeepSequenceAnalysis +{ + /// Flicker below this RMS is not visible (≈ 1.4 % brightness). + public const double VisibleFlickerEv = 0.02; + + /// Colour-ratio jitter (log2 RMS) above which white-balance smoothing helps (≈ 0.7 %). + public const double VisibleWhiteBalanceJitter = 0.01; + + /// Mid-grey (18 %) in log2 luminance, the hero frame's exposure target. + private const double MidGreyEv = -2.47; + + private const int HorizonSamples = 64; + + public static DeepAnalysisReport Build(IReadOnlyList frames, IReadOnlyList metadata, RegionMask? mask, DeepAnalysisOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + ArgumentNullException.ThrowIfNull(metadata); + options ??= DeepAnalysisOptions.Default; + var n = frames.Count; + if (metadata.Count != n) throw new ArgumentException("One metadata entry per frame is required.", nameof(metadata)); + var light = LightAnalyzer.Analyze(metadata); + var (sourceWidth, sourceHeight) = light.DominantSize ?? (0, 0); + var luminance = new double[n]; + for (var i = 0; i < n; i++) luminance[i] = frames[i].IsUsable ? frames[i].LogLuminance : double.NaN; + + var (exposure, offsets) = Exposure(luminance, light); + var flat = new double[n]; + for (var i = 0; i < n; i++) flat[i] = luminance[i] - offsets[i]; + exposure = exposure with { SceneRangeEv = Range(flat, 0.05, 0.95) }; + var flicker = Flicker(flat); + var sceneChanges = SceneChanges(frames, options); + var starFrames = new HashSet(); + var sky = Sky(frames, flat, light, options, starFrames); + var shake = Shake(frames, sourceWidth, sourceHeight, options); + var issues = new FrameIssues( + Where(frames, f => (f.Flags & DeepFrameFlags.Undecodable) != 0), + Where(frames, f => (f.Flags & DeepFrameFlags.Black) != 0), + Where(frames, f => (f.Flags & DeepFrameFlags.White) != 0), + Where(frames, f => (f.Flags & DeepFrameFlags.Duplicate) != 0), + [.. sceneChanges.Order()]); + var report = new DeepAnalysisReport + { + FrameCount = n, + SourceWidth = sourceWidth, + SourceHeight = sourceHeight, + AnalysisLongEdge = options.AnalysisLongEdge(int.Max(sourceWidth, sourceHeight)), + Frames = Columns(frames, sceneChanges, starFrames), + Flicker = flicker, + Regions = Regions(frames, mask, flicker.RecommendedWindow), + Exposure = exposure, + WhiteBalance = WhiteBalance(frames), + Shake = shake, + Motion = Motion(frames), + Sky = sky, + Issues = issues, + HeroIndex = Hero(frames, sceneChanges, light.DayPhases), + }; + return report with { Findings = Findings(report) }; + } + + private static (ExposureSummary Summary, double[] Offsets) Exposure(double[] luminance, LightAnalysisReport light) + { + var n = luminance.Length; + if (light.ExposureSteps.Count == 0 || n == 0) return (new ExposureSummary(0, 0, null, null, 0, []), new double[n]); + var result = HolyGrailEngine.Compute(luminance, light.ExposureValues); + var received = result.Transitions.Where(t => t.Received).Select(t => t.Index).ToArray(); + double? spacing = null; + int? length = null; + if (received.Length >= 2) + { + var gaps = new double[received.Length - 1]; + for (var i = 1; i < received.Length; i++) gaps[i - 1] = received[i] - received[i - 1]; + spacing = Statistics.Median(gaps); + length = int.Max(2, (int)double.Round(spacing.Value / 2)); + } + else if (received.Length == 1) + { + length = HolyGrailOptions.Default.SingleStepTransitionFrames; + } + var steps = result.Transitions + .Select(t => new ExposureStepSummary(t.Index, Round(t.ExpectedEv, 3), double.IsFinite(t.MeasuredEv) ? Round(t.MeasuredEv, 3) : null, t.Received, Round(t.Length, 2))) + .ToList(); + return (new ExposureSummary(result.Transitions.Count, received.Length, spacing, length, 0, steps), result.StepOffsets); + } + + private static FlickerSummary Flicker(double[] flat) + { + if (Count(flat) < 3) return new FlickerSummary(0, 0, null, 0, 0, FlickerSpectrumOptions.Default.MinimumWindow); + var spectrum = FlickerSpectrum.Analyze(flat); + var diagnostics = DeflickerEngine.Compute(flat, new DeflickerOptions { Window = spectrum.RecommendedWindow }).Diagnostics; + return new FlickerSummary( + Round(diagnostics.ResidualRms, 4), + Round(diagnostics.FlickerBefore, 4), + spectrum.DominantPeriod is { } p ? Round(p, 2) : null, + Round(spectrum.PeakCorrelation, 3), + Round(spectrum.CorrelationLength, 2), + spectrum.RecommendedWindow); + } + + private static RegionSummary? Regions(IReadOnlyList frames, RegionMask? mask, int window) + { + if (mask is null) return null; + double[]? horizon = null; + if (mask.Horizon is { } h) + { + var count = int.Min(HorizonSamples, mask.Width); + horizon = new double[count]; + for (var k = 0; k < count; k++) + { + var x = count > 1 ? (int)((long)k * (mask.Width - 1) / (count - 1)) : 0; + horizon[k] = Round(h[x] / mask.Height, 4); + } + } + double skyFraction = 0; + foreach (var w in mask.Sky) skyFraction += w; + skyFraction /= mask.Sky.Length; + + var n = frames.Count; + var sky = new double[n]; + var land = new double[n]; + for (var i = 0; i < n; i++) + { + sky[i] = frames[i].IsUsable ? frames[i].SkyLogLuminance : double.NaN; + land[i] = frames[i].IsUsable ? frames[i].LandLogLuminance : double.NaN; + } + var divergence = 0.0; + if (Count(sky) >= 3 && Count(land) >= 3) + { + var skyFit = LocalRegression.Smooth(sky, window, 1, 3).Fitted; + var landFit = LocalRegression.Smooth(land, window, 1, 3).Fitted; + var difference = new double[n]; + for (var i = 0; i < n; i++) difference[i] = sky[i] - skyFit[i] - (land[i] - landFit[i]); + divergence = Statistics.Rms(difference); + } + return new RegionSummary(mask.Method, Round(mask.Confidence, 3), Round(skyFraction, 3), mask.Width, mask.Height, horizon, + Round(double.IsFinite(divergence) ? divergence : 0, 4)); + } + + private static WhiteBalanceSummary WhiteBalance(IReadOnlyList frames) + { + var n = frames.Count; + var red = new double[n]; + var green = new double[n]; + var blue = new double[n]; + var kelvin = new double[n]; + for (var i = 0; i < n; i++) + { + var f = frames[i]; + var valid = f.IsUsable && double.IsFinite(f.RedRatio) && double.IsFinite(f.BlueRatio); + red[i] = valid ? double.Exp2(f.RedRatio) : double.NaN; + green[i] = valid ? 1 : double.NaN; + blue[i] = valid ? double.Exp2(f.BlueRatio) : double.NaN; + kelvin[i] = f.IsUsable ? f.Kelvin : double.NaN; + } + if (Count(red) < 3) return new WhiteBalanceSummary(0, 0, null, null); + var result = WhiteBalanceSmoother.Smooth(red, green, blue); + var deviation = new double[n]; + for (var i = 0; i < n; i++) + { + var dr = result.RedRatio[i] - result.SmoothedRedRatio[i]; + var db = result.BlueRatio[i] - result.SmoothedBlueRatio[i]; + deviation[i] = double.Sqrt(dr * dr + db * db); + } + var drift = double.Max(Range(result.SmoothedRedRatio, 0, 1), Range(result.SmoothedBlueRatio, 0, 1)); + var hasKelvin = Count(kelvin) > 0; + return new WhiteBalanceSummary( + Round(Statistics.Rms(deviation), 4), + Round(drift, 4), + hasKelvin ? double.Round(Statistics.Percentile(kelvin, 0.05)) : null, + hasKelvin ? double.Round(Statistics.Percentile(kelvin, 0.95)) : null); + } + + private static ShakeSummary Shake(IReadOnlyList frames, int sourceWidth, int sourceHeight, DeepAnalysisOptions options) + { + var n = frames.Count; + if (n < 2) return new ShakeSummary(0, 0, 0, 0, false, 0); + var x = new double[n]; + var y = new double[n]; + int measured = 0, pairs = 0; + for (var i = 1; i < n; i++) + { + var f = frames[i]; + var known = double.IsFinite(f.ShiftX) && double.IsFinite(f.ShiftY); + if (f.IsUsable) pairs++; + if (known) measured++; + x[i] = x[i - 1] + (known ? f.ShiftX : 0); + y[i] = y[i - 1] + (known ? f.ShiftY : 0); + } + var sx = PathSmoother.LocalLinear(x, options.ShakeSmoothingSigma); + var sy = PathSmoother.LocalLinear(y, options.ShakeSmoothingSigma); + double sum = 0, max = 0, maxX = 0, maxY = 0; + for (var i = 0; i < n; i++) + { + double rx = x[i] - sx[i], ry = y[i] - sy[i]; + var r2 = rx * rx + ry * ry; + sum += r2; + max = double.Max(max, double.Sqrt(r2)); + maxX = double.Max(maxX, double.Abs(rx)); + maxY = double.Max(maxY, double.Abs(ry)); + } + var width = sourceWidth > 0 ? sourceWidth : options.AnalysisLongEdge(0); + var height = sourceHeight > 0 ? sourceHeight : width; + var scale = double.Clamp(double.Min(1 - 2 * maxX / width, 1 - 2 * maxY / height), 0, 1); + var drift = double.Hypot(sx[n - 1] - sx[0], sy[n - 1] - sy[0]); + return new ShakeSummary( + Round(double.Sqrt(sum / n), 3), + Round(max, 3), + Round(1 - scale * scale, 4), + Round(drift / (n - 1), 3), + drift >= 0.02 * width, + Round(pairs > 1 ? double.Min(1, measured / (double)(pairs - 1)) : 0, 3)); + } + + private static MotionSummary Motion(IReadOnlyList frames) + { + var medians = frames.Where(f => double.IsFinite(f.MotionP95)).Select(f => f.MotionMedian).ToArray(); + var p95 = frames.Where(f => double.IsFinite(f.MotionP95)).Select(f => f.MotionP95).ToArray(); + if (p95.Length == 0) return new MotionSummary(0, null, null, null); + return new MotionSummary(p95.Length, Round(Statistics.Median(medians), 3), Round(Statistics.Median(p95), 3), Round(p95.Max(), 3)); + } + + private static SkySummary Sky(IReadOnlyList frames, double[] flat, LightAnalysisReport light, DeepAnalysisOptions options, HashSet starFrames) + { + int usable = 0, dark = 0; + var densities = new List(); + var clouds = new List(); + foreach (var f in frames) + { + if (!f.IsUsable) continue; + usable++; + if (double.IsFinite(f.CloudCoverage)) clouds.Add(f.CloudCoverage); + if ((f.Flags & DeepFrameFlags.Dark) == 0) continue; + dark++; + if (!double.IsFinite(f.StarDensity)) continue; + densities.Add(f.StarDensity); + if (f.StarDensity >= options.StarFieldDensity) starFrames.Add(f.Index); + } + var darkFraction = usable > 0 ? (double)dark / usable : 0; + return new SkySummary( + DayNightOf(flat, darkFraction, usable, light.DayPhases), + Round(darkFraction, 3), + dark, + starFrames.Count, + densities.Count > 0 ? double.Round(Statistics.Median(densities.ToArray())) : null, + starFrames.Count > 0 && starFrames.Count >= 0.25 * usable, + clouds.Count > 0 ? Round(clouds.Average(), 3) : null); + } + + /// + /// Solar phases when GPS gave them for most frames; otherwise the step-free luminance: a 10–90 % range of at + /// least 3 EV is a transition (direction from the first and last tenth), else the dark-frame share decides. + /// + private static DayNight DayNightOf(double[] flat, double darkFraction, int usable, DayPhase?[] phases) + { + int day = 0, night = 0, known = 0; + DayPhase? first = null, last = null; + foreach (var phase in phases) + { + if (phase is not { } p) continue; + known++; + first ??= p; + last = p; + if (p is DayPhase.Day or DayPhase.GoldenHour) day++; + else if (p is DayPhase.Night or DayPhase.AstronomicalTwilight or DayPhase.NauticalTwilight) night++; + } + if (known * 2 >= phases.Length && known > 0) + { + if (day > 0 && night > 0) return first >= DayPhase.CivilTwilight && last < DayPhase.CivilTwilight ? DayNight.DayToNight : DayNight.NightToDay; + return night > day ? DayNight.Night : DayNight.Day; + } + if (usable == 0) return DayNight.Unknown; + if (Range(flat, 0.1, 0.9) >= 3) + { + var tenth = int.Max(1, flat.Length / 10); + var start = Statistics.Mean(flat.AsSpan(0, tenth)); + var end = Statistics.Mean(flat.AsSpan(flat.Length - tenth)); + if (double.IsFinite(start) && double.IsFinite(end)) return start > end ? DayNight.DayToNight : DayNight.NightToDay; + } + return darkFraction >= 0.5 ? DayNight.Night : DayNight.Day; + } + + /// Spikes of the exposure-aligned histogram distance: above max(minimum, median + 10 robust σ). + private static HashSet SceneChanges(IReadOnlyList frames, DeepAnalysisOptions options) + { + var candidates = frames.Where(f => f.IsUsable && (f.Flags & DeepFrameFlags.Duplicate) == 0 && double.IsFinite(f.SceneDistance)).ToList(); + var result = new HashSet(); + if (candidates.Count == 0) return result; + var distances = candidates.Select(f => f.SceneDistance).ToArray(); + var median = Statistics.Median(distances); + var sigma = Statistics.MadToSigma * Statistics.MedianAbsoluteDeviation(distances, median); + var threshold = double.Max(options.SceneChangeMinimum, median + 10 * sigma); + foreach (var f in candidates) + { + if (f.SceneDistance > threshold) result.Add(f.Index); + } + return result; + } + + /// + /// Highest √(relative sharpness) × exposure × time score over usable, unique, non-scene-change frames. Exposure + /// favours mid-grey and penalises clipping; time favours golden hour (when GPS gave phases) or the middle of the + /// sequence. Ties go to the earliest frame. + /// + private static int? Hero(IReadOnlyList frames, HashSet sceneChanges, DayPhase?[] phases) + { + var candidates = frames.Where(f => f.IsUsable && (f.Flags & DeepFrameFlags.Duplicate) == 0 && !sceneChanges.Contains(f.Index) + && double.IsFinite(f.Sharpness) && double.IsFinite(f.LogLuminance)).ToList(); + if (candidates.Count == 0) return null; + var medianSharpness = Statistics.Median(candidates.Select(f => f.Sharpness).ToArray()); + var n = frames.Count; + int? best = null; + var bestScore = double.NegativeInfinity; + foreach (var f in candidates) + { + var sharp = medianSharpness > 0 ? double.Min(2, f.Sharpness / medianSharpness) : 1; + var level = (f.LogLuminance - MidGreyEv) / 1.5; + var exposure = double.Exp(-level * level) * double.Max(0, 1 - 5 * f.ClipHigh - 2 * f.ClipLow); + var phase = f.Index < phases.Length ? phases[f.Index] : null; + var time = phase switch + { + DayPhase.GoldenHour => 1.0, + DayPhase.CivilTwilight => 0.8, + DayPhase.Day => 0.6, + null => n > 1 ? 1 - 2 * double.Abs((double)f.Index / (n - 1) - 0.5) : 1, + _ => 0.4, + }; + var score = double.Sqrt(sharp) * exposure * (0.5 + 0.5 * time); + if (score > bestScore) + { + bestScore = score; + best = f.Index; + } + } + return best; + } + + private static List Findings(DeepAnalysisReport report) + { + var findings = new List(); + void Add(string key, FindingSeverity severity, int[] frames, params double[] args) => + findings.Add(new DeepFinding(key, severity, args, frames.Length > Finding.MaxFrames ? frames[..Finding.MaxFrames] : frames)); + + var issues = report.Issues; + if (issues.Undecodable.Length > 0) Add(DeepFindingKeys.UnreadableFrames, FindingSeverity.Warning, issues.Undecodable, issues.Undecodable.Length); + if (issues.Black.Length > 0) Add(DeepFindingKeys.BlackFrames, FindingSeverity.Warning, issues.Black, issues.Black.Length); + if (issues.White.Length > 0) Add(DeepFindingKeys.WhiteFrames, FindingSeverity.Warning, issues.White, issues.White.Length); + if (issues.Duplicate.Length > 0) Add(DeepFindingKeys.DuplicateFrames, FindingSeverity.Warning, issues.Duplicate, issues.Duplicate.Length); + if (issues.SceneChanges.Length > 0) Add(DeepFindingKeys.SceneChanges, FindingSeverity.Warning, issues.SceneChanges, issues.SceneChanges.Length); + var ignored = report.Exposure.Steps.Where(s => !s.Received).Select(s => s.Index).ToArray(); + if (ignored.Length > 0) Add(DeepFindingKeys.StepsNotReceived, FindingSeverity.Warning, ignored, ignored.Length); + if (report.Flicker.AmplitudeEv >= VisibleFlickerEv) Add(DeepFindingKeys.Flicker, FindingSeverity.Info, [], Round(report.Flicker.AmplitudeEv, 3)); + if (report.Shake.RmsPx >= 0.3) Add(DeepFindingKeys.Shake, FindingSeverity.Info, [], Round(report.Shake.RmsPx, 2), Round(100 * report.Shake.CropCost, 1)); + if (report.Shake.PanDetected) Add(DeepFindingKeys.Panning, FindingSeverity.Info, [], Round(report.Shake.PanPxPerFrame, 2)); + if (report.Sky.StarField) Add(DeepFindingKeys.StarField, FindingSeverity.Info, [], report.Sky.StarFrames); + if (report.Sky.CloudCoverage is { } cover && cover >= 0.1) Add(DeepFindingKeys.Clouds, FindingSeverity.Info, [], double.Round(100 * cover)); + if (report.WhiteBalance.JitterLog2 >= VisibleWhiteBalanceJitter) + Add(DeepFindingKeys.WhiteBalanceJitter, FindingSeverity.Info, [], Round(100 * (double.Exp2(report.WhiteBalance.JitterLog2) - 1), 1)); + return findings; + } + + private static DeepFrameColumns Columns(IReadOnlyList frames, HashSet sceneChanges, HashSet starFrames) + { + var n = frames.Count; + double?[] Column(Func value, Func quantise) + { + var column = new double?[n]; + for (var i = 0; i < n; i++) + { + var v = value(frames[i]); + column[i] = double.IsFinite(v) ? quantise(v) : null; + } + return column; + } + + var flags = new int[n]; + for (var i = 0; i < n; i++) + { + var f = frames[i].Flags; + if (sceneChanges.Contains(i)) f |= DeepFrameFlags.SceneChange; + if (starFrames.Contains(i)) f |= DeepFrameFlags.StarField; + flags[i] = (int)f; + } + var sampled = frames.Where(f => double.IsFinite(f.MotionP95)).ToArray(); + return new DeepFrameColumns + { + LogLuminance = Column(f => f.LogLuminance, v => Round(v, 3)), + ClipLow = Column(f => f.ClipLow, v => Round(v, 3)), + ClipHigh = Column(f => f.ClipHigh, v => Round(v, 3)), + RedRatio = Column(f => f.RedRatio, v => Round(v, 3)), + BlueRatio = Column(f => f.BlueRatio, v => Round(v, 3)), + Kelvin = Column(f => f.Kelvin, double.Round), + Sharpness = Column(f => f.Sharpness, v => Significant(v, 2)), + Noise = Column(f => f.Noise, v => Significant(v, 2)), + ShiftX = Column(f => f.ShiftX, v => Round(v, 2)), + ShiftY = Column(f => f.ShiftY, v => Round(v, 2)), + StarDensity = Column(f => f.StarDensity, double.Round), + CloudCoverage = Column(f => f.CloudCoverage, v => Round(v, 2)), + SkyLogLuminance = Column(f => f.SkyLogLuminance, v => Round(v, 3)), + LandLogLuminance = Column(f => f.LandLogLuminance, v => Round(v, 3)), + SceneDistance = Column(f => f.SceneDistance, v => Round(v, 3)), + Flags = flags, + MotionFrames = [.. sampled.Select(f => f.Index)], + MotionMedian = [.. sampled.Select(f => Round(f.MotionMedian, 2))], + MotionP95 = [.. sampled.Select(f => Round(f.MotionP95, 2))], + }; + } + + private static int[] Where(IReadOnlyList frames, Func predicate) => [.. frames.Where(predicate).Select(f => f.Index)]; + + private static int Count(double[] values) + { + var count = 0; + foreach (var v in values) + { + if (double.IsFinite(v)) count++; + } + return count; + } + + /// Spread between two percentiles of the finite values (0 when fewer than two). + private static double Range(double[] values, double low, double high) + { + if (Count(values) < 2) return 0; + return Statistics.Percentile(values, high) - Statistics.Percentile(values, low); + } + + /// Rounds half away from zero; adding +0 turns −0 into 0 so JSON never spends a byte on the sign. + private static double Round(double value, int decimals) => double.Round(value, decimals, MidpointRounding.AwayFromZero) + 0.0; + + private static double Significant(double value, int digits) + { + if (value == 0) return 0; + var magnitude = (int)double.Floor(double.Log10(double.Abs(value))); + var decimals = digits - 1 - magnitude; + return decimals is >= 0 and <= 15 ? Round(value, decimals) : value; + } +} diff --git a/src/Titano.Core/Analysis/Deep/FrameProbe.cs b/src/Titano.Core/Analysis/Deep/FrameProbe.cs new file mode 100644 index 00000000..b74fb9f9 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/FrameProbe.cs @@ -0,0 +1,147 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; + +namespace Titano.Core.Analysis.Deep; + +/// +/// The measurements of one frame that need no other frame (statistics, stars, sky/land luminance, clouds) plus the +/// reduced planes the sequential stage of compares with the previous frame. Frames are +/// probed in parallel; the full analysis image is released before the probe is returned. +/// +internal sealed class FrameProbe : IDisposable +{ + private FrameProbe(int index) => Index = index; + + public int Index { get; } + + /// Null when the frame could not be decoded. + public FrameStatistics? Statistics { get; private set; } + + /// Perceptual luminance at the correlation size, row-major. + public float[]? Correlation { get; private set; } + + public int CorrelationWidth { get; private set; } + public int CorrelationHeight { get; private set; } + + /// Source pixels per correlation-plane pixel. + public double CorrelationScale { get; private set; } = 1; + + /// Flow-sized image; only for frames that take part in a sampled flow pair. + public ImageBuffer? Flow { get; private set; } + + /// Source pixels per flow-image pixel. + public double FlowScale { get; private set; } = 1; + + public double StarDensity { get; private set; } = double.NaN; + public double CloudCoverage { get; private set; } = double.NaN; + public double SkyLogLuminance { get; private set; } = double.NaN; + public double LandLogLuminance { get; private set; } = double.NaN; + + /// True when the frame is decoded and neither black nor white (it may update the sequential state). + public bool IsUsable => Statistics is { } s && !s.IsBlack() && !s.IsWhite(); + + /// Whether frame takes part in a sampled optical-flow pair (k − 1, k), k divisible by . + public static bool NeedsFlow(int index, int every) => index % every == 0 || (index + 1) % every == 0; + + public static async Task RunAsync(IFrameSource source, int index, DeepAnalysisOptions options, RegionMask? mask, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + var (sourceWidth, sourceHeight) = source.Metadata(index).OrientedSize; + var edge = options.AnalysisLongEdge(int.Max(sourceWidth, sourceHeight)); + var loaded = await source.LoadAsync(index, edge, cancellationToken).ConfigureAwait(false); + var probe = new FrameProbe(index); + if (loaded is null) return probe; + cancellationToken.ThrowIfCancellationRequested(); + using var analysis = int.Max(loaded.Width, loaded.Height) > edge ? Reduce(loaded, edge) : loaded; + var sourceLong = sourceWidth > 0 && sourceHeight > 0 ? int.Max(sourceWidth, sourceHeight) : int.Max(analysis.Width, analysis.Height); + probe.Measure(analysis, sourceLong, options, mask); + return probe; + } + + /// Hands the flow image over to the caller, who then disposes it. + public ImageBuffer? TakeFlow() + { + var flow = Flow; + Flow = null; + return flow; + } + + public void Dispose() + { + Flow?.Dispose(); + Flow = null; + } + + private static ImageBuffer Reduce(ImageBuffer image, int edge) + { + using (image) return AnalysisImage.Downscale(image, edge); + } + + private void Measure(ImageBuffer analysis, int sourceLong, DeepAnalysisOptions options, RegionMask? mask) + { + var stats = FrameStatistics.Measure(analysis); + Statistics = stats; + if (!IsUsable) return; + + if (stats.MeanLogLuminance <= options.DarkLogLuminance) StarDensity = StarFieldDetector.Density(analysis, stats.Noise); + + if (mask is not null) + { + using var thumbnail = AnalysisImage.Downscale(analysis, options.ThumbnailLongEdge); + var fitted = mask.Resample(thumbnail.Width, thumbnail.Height); + (SkyLogLuminance, LandLogLuminance) = RegionDeflicker.Measure(thumbnail, fitted); + CloudCoverage = Deep.CloudCoverage.Estimate(thumbnail, fitted.Sky); + } + + using (var correlation = AnalysisImage.Downscale(analysis, options.CorrelationLongEdge)) + { + CorrelationWidth = correlation.Width; + CorrelationHeight = correlation.Height; + CorrelationScale = (double)sourceLong / int.Max(correlation.Width, correlation.Height); + var plane = new float[correlation.PlaneLength]; + PlaneOps.PerceptualLuminance(correlation, plane); + Correlation = plane; + } + + if (NeedsFlow(Index, options.FlowEvery)) + { + Flow = AnalysisImage.Downscale(analysis, options.FlowLongEdge); + FlowScale = (double)sourceLong / int.Max(Flow.Width, Flow.Height); + } + } + + /// Loads and measures the region-mask sample (thumbnails of usable frames that share the first one's size). + public static async Task SegmentRegionsAsync(IFrameSource source, DeepAnalysisOptions options, CancellationToken cancellationToken) + { + var n = source.Count; + var count = int.Min(options.RegionSampleFrames, n); + var thumbnails = new List(count); + try + { + for (var k = 0; k < count; k++) + { + var index = count > 1 ? (int)((long)k * (n - 1) / (count - 1)) : 0; + var (w, h) = source.Metadata(index).OrientedSize; + var edge = options.AnalysisLongEdge(int.Max(w, h)); + using var loaded = await source.LoadAsync(index, edge, cancellationToken).ConfigureAwait(false); + if (loaded is null) continue; + using var analysis = AnalysisImage.Downscale(loaded, edge); + var stats = FrameStatistics.Measure(analysis); + if (stats.IsBlack() || stats.IsWhite()) continue; + var thumbnail = AnalysisImage.Downscale(analysis, options.ThumbnailLongEdge); + if (thumbnails.Count > 0 && (thumbnail.Width != thumbnails[0].Width || thumbnail.Height != thumbnails[0].Height) || thumbnail.Height < 8) + { + thumbnail.Dispose(); + continue; + } + thumbnails.Add(thumbnail); + } + cancellationToken.ThrowIfCancellationRequested(); + return thumbnails.Count > 0 ? RegionSegmenter.Segment(thumbnails) : null; + } + finally + { + foreach (var t in thumbnails) t.Dispose(); + } + } +} diff --git a/src/Titano.Core/Analysis/Deep/HistogramDistance.cs b/src/Titano.Core/Analysis/Deep/HistogramDistance.cs new file mode 100644 index 00000000..257fb941 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/HistogramDistance.cs @@ -0,0 +1,61 @@ +namespace Titano.Core.Analysis.Deep; + +/// Scene-change measure between two s. +internal static class HistogramDistance +{ + private const double SmoothingBins = 2; + private const double BinsPerEv = FrameStatistics.HistogramBins / (FrameStatistics.HistogramMaxEv - FrameStatistics.HistogramMinEv); + + /// + /// Symmetric chi-square distance (0 = same, 1 = disjoint) after both histograms are smoothed with a Gaussian of + /// σ = 2 bins (⅛ EV) and the current one is shifted by the change of mean log-luminance (linear interpolation), + /// so flicker, exposure steps and brightness ramps score near zero while a new view scores high. Mass shifted out + /// of range counts as disjoint. + /// + public static double ExposureAligned(FrameStatistics previous, FrameStatistics current) + { + var a = Smooth(previous.Histogram); + var b = Smooth(current.Histogram); + var delta = current.MeanLogLuminance - previous.MeanLogLuminance; + var shift = double.IsFinite(delta) ? delta * BinsPerEv : 0; + double sum = 0, matched = 0, total = 0; + foreach (var v in b) total += v; + for (var i = 0; i < a.Length; i++) + { + var x = i + shift; + var j = (int)double.Floor(x); + var t = x - j; + var q = (1 - t) * At(b, j) + t * At(b, j + 1); + matched += q; + var both = a[i] + q; + if (both > 0) sum += (a[i] - q) * (a[i] - q) / both; + } + sum += double.Max(0, total - matched); + return 0.5 * sum; + } + + private static double At(double[] values, int index) => index >= 0 && index < values.Length ? values[index] : 0; + + /// Gaussian smoothing that keeps the total mass (kernel renormalised at the edges). + private static double[] Smooth(double[] histogram) + { + var radius = (int)double.Ceiling(3 * SmoothingBins); + Span kernel = stackalloc double[2 * radius + 1]; + for (var d = -radius; d <= radius; d++) kernel[d + radius] = double.Exp(-0.5 * d * d / (SmoothingBins * SmoothingBins)); + var result = new double[histogram.Length]; + for (var i = 0; i < histogram.Length; i++) + { + if (histogram[i] == 0) continue; + double weight = 0; + for (var d = -radius; d <= radius; d++) + { + if (i + d >= 0 && i + d < histogram.Length) weight += kernel[d + radius]; + } + for (var d = -radius; d <= radius; d++) + { + if (i + d >= 0 && i + d < histogram.Length) result[i + d] += histogram[i] * kernel[d + radius] / weight; + } + } + return result; + } +} diff --git a/src/Titano.Core/Analysis/Deep/IFrameSource.cs b/src/Titano.Core/Analysis/Deep/IFrameSource.cs new file mode 100644 index 00000000..8a5492ba --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/IFrameSource.cs @@ -0,0 +1,25 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis.Deep; + +/// +/// The frames of one sequence as reads them. Decoding is the implementer's job (archive +/// decoder on the client, proxies on the server, SyntheticSequence in tests). +/// +public interface IFrameSource +{ + int Count { get; } + + /// Metadata of frame (capture time, exposure, size, GPS); cheap, no decoding. + LightFrame Metadata(int index); + + /// + /// Decodes frame in linear light, oriented, with its long edge at most + /// (a larger result is downscaled by the caller). The caller owns and disposes the + /// buffer. Null when the frame cannot be decoded. + /// + ValueTask LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken); +} + +/// Progress of a deep analysis: frames done (including resumed ones), throughput of this run and its ETA. +public readonly record struct AnalysisProgress(int Done, int Total, double FramesPerSecond, TimeSpan? Eta); diff --git a/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs b/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs new file mode 100644 index 00000000..00cbe6f8 --- /dev/null +++ b/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs @@ -0,0 +1,57 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis.Deep; + +/// +/// Star-field detection (BRIEF §10.2): counts small bright points on sRGB-encoded luminance. A point is a strict +/// 3×3 local maximum that rises above the mean of the 5×5 ring around it by at least +/// max(·σ, ), whose 8 neighbours average less than half that +/// rise and whose ring stays below half of it everywhere (point-like: lit windows, the moon and textured land fail; +/// stars up to 2×2 pixels pass). +/// +public static class StarFieldDetector +{ + public const double NoiseFactor = 6; + public const double MinimumContrast = 0.05; + + /// Point sources per megapixel of ; is the encoded-luminance + /// noise σ (e.g. ). + public static double Density(ImageBuffer image, double noiseSigma) + { + ArgumentNullException.ThrowIfNull(image); + int w = image.Width, h = image.Height; + if (w < 5 || h < 5) return 0; + var e = new float[image.PlaneLength]; + ColorSpace.Luminance(image, e); + for (var i = 0; i < e.Length; i++) e[i] = ColorSpace.EncodeFast(e[i]); + var threshold = double.Max(NoiseFactor * (double.IsFinite(noiseSigma) ? noiseSigma : 0), MinimumContrast); + + var count = 0; + for (var y = 2; y < h - 2; y++) + { + for (var x = 2; x < w - 2; x++) + { + var i = y * w + x; + var c = e[i]; + // Ties go to the later pixel in raster order so a plateau counts once. + if (!(c >= e[i - w - 1] && c >= e[i - w] && c >= e[i - w + 1] && c >= e[i - 1] + && c > e[i + 1] && c > e[i + w - 1] && c > e[i + w] && c > e[i + w + 1])) continue; + double ring = 0, ringMax = 0; + for (var d = -2; d <= 2; d++) + { + ring += e[i - 2 * w + d] + e[i + 2 * w + d]; + ringMax = double.Max(ringMax, double.Max(e[i - 2 * w + d], e[i + 2 * w + d])); + if (d is <= -2 or >= 2) continue; + ring += e[i + d * w - 2] + e[i + d * w + 2]; + ringMax = double.Max(ringMax, double.Max(e[i + d * w - 2], e[i + d * w + 2])); + } + var background = ring / 16; + var rise = c - background; + if (rise < threshold || ringMax - background >= 0.5 * rise) continue; + double inner = e[i - w - 1] + e[i - w] + e[i - w + 1] + e[i - 1] + e[i + 1] + e[i + w - 1] + e[i + w] + e[i + w + 1]; + if (inner / 8 - background <= 0.5 * rise) count++; + } + } + return count * 1e6 / ((double)w * h); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs new file mode 100644 index 00000000..b198d41c --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs @@ -0,0 +1,311 @@ +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis.Deep; + +public sealed class DeepAnalyzerTests(TestContext context) +{ + [Test] + public async Task NightSkyShowsStarsDarknessFlickerAndNoShake() + { + var report = await DeepReports.Night; + context.Log($"{report.Sky} {report.Flicker} {report.Shake}"); + Assert.True(report.Sky.StarField); + Assert.Equal(DayNight.Night, report.Sky.Light); + Assert.Equal(report.FrameCount, report.Sky.StarFrames); + // Uniform ±0.12 EV flicker has an RMS of 0.069 EV. + Assert.Approximately(0.069, report.Flicker.AmplitudeEv, 0.01); + Assert.Equal(15, report.Flicker.RecommendedWindow); + Assert.Less(report.Shake.RmsPx, 0.05); + Assert.Equal(1.0, report.Shake.MeasuredFraction); + Assert.Empty(report.Issues.SceneChanges); + Assert.Equal(0.0, report.Motion.P95Px!.Value); + Assert.Equal(RegionMethod.Horizon, report.Regions!.Method); + Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.StarField); + Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Flicker); + Assert.True(report.Frames.FlagsOf(0).HasFlag(DeepFrameFlags.StarField | DeepFrameFlags.Dark)); + } + + [Test] + public async Task InjectedCameraJitterIsMeasuredAsShake() + { + var report = await DeepReports.NightJitter; + context.Log($"{report.Shake} {report.Motion}"); + // Integer offsets uniform in −2..2 per axis: 2 px RMS in 2D. + Assert.InRange(report.Shake.RmsPx, 1.6, 2.4); + Assert.InRange(report.Shake.CropCost, 0.02, 0.2); + Assert.False(report.Shake.PanDetected); + Assert.Greater(report.Motion.P95Px!.Value, 1); + Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Shake); + } + + [Test] + public async Task HolyGrailStepsAreReceivedAndSpacedByHalfTheirDistance() + { + var report = await DeepReports.HolyGrail; + Assert.Equal(5, report.Exposure.MetadataSteps); + Assert.Equal(5, report.Exposure.ReceivedSteps); + Assert.Equal(40.0, report.Exposure.TypicalSpacing); + Assert.Equal(20, report.Exposure.TransitionLength); + Assert.True(report.Exposure.Steps.All(s => s.MeasuredEv is > 0.9 and < 1.1)); + Assert.InRange(report.Exposure.SceneRangeEv, 5, 6); + Assert.Equal(DayNight.DayToNight, report.Sky.Light); + // Brightness ramps and steps are levelled before the flow, so the static scene shows no motion. + Assert.Equal(0.0, report.Motion.P95Px!.Value); + Assert.Empty(report.Issues.SceneChanges); + } + + [Theory] + [Case(8.0, 33)] + [Case(12.5, 51)] + [Case(40.0, 151)] + public async Task PeriodicFlickerGivesAWindowOfFourPeriods(double period, int window) + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = period, + }); + var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options); + Assert.Approximately(period, report.Flicker.PeriodFrames!.Value, 0.05 * period); + Assert.Equal(window, report.Flicker.RecommendedWindow); + Assert.Equal(1, window % 2); + } + + [Test] + public async Task BlackWhiteDuplicateAndUnreadableFramesAreFlagged() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 60, FlickerEv = 0.02, BlackFrames = [10], WhiteFrames = [20], DuplicateFrames = [30], + }); + var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence) { Undecodable = [40] }, DeepScenes.Options); + Assert.SequenceEqual([10], report.Issues.Black); + Assert.SequenceEqual([20], report.Issues.White); + Assert.SequenceEqual([30], report.Issues.Duplicate); + Assert.SequenceEqual([40], report.Issues.Undecodable); + Assert.SequenceEqual([10, 20, 30, 40], report.Issues.Excludable()); + Assert.Empty(report.Issues.SceneChanges); + Assert.Null(report.Frames.LogLuminance[40]); + Assert.True(report.Frames.FlagsOf(40).HasFlag(DeepFrameFlags.Undecodable)); + Assert.False(report.Issues.Excludable().Contains(report.HeroIndex!.Value)); + foreach (var key in new[] { DeepFindingKeys.BlackFrames, DeepFindingKeys.WhiteFrames, DeepFindingKeys.DuplicateFrames, DeepFindingKeys.UnreadableFrames }) + Assert.Equal(FindingSeverity.Warning, report.Findings.Single(f => f.Key == key).Severity); + Assert.Equal(4, AnalysisSummary.From(report).WarningCount); + } + + [Test] + public async Task ACutToAnotherViewIsASceneChange() + { + var first = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05 })); + var second = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05, Seed = 5, HorizonFraction = 0.75, SkyLevel = 0.6, LandLevel = 0.01, + })); + var report = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(first, second, 30), DeepScenes.Options); + Assert.SequenceEqual([30], report.Issues.SceneChanges); + Assert.True(report.Frames.FlagsOf(30).HasFlag(DeepFrameFlags.SceneChange)); + } + + [Test] + public async Task ResumingFromACheckpointGivesTheSameReport() + { + var expected = (await DeepReports.HolyGrail).ToJson(); + var checkpoint = new MemoryCheckpoint(); + var crashing = new SyntheticFrameSource(DeepScenes.HolyGrail()) + { + OnLoad = i => + { + if (i == 101) throw new IOException("simulated crash"); + }, + }; + await Assert.ThrowsAsync(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, checkpoint)); + var persisted = checkpoint.Frames.Count; + Assert.InRange(persisted, 90, 101); + + var resumed = new SyntheticFrameSource(DeepScenes.HolyGrail()); + var report = await DeepAnalyzer.AnalyzeAsync(resumed, DeepScenes.Options, checkpoint); + Assert.Equal(expected, report.ToJson()); + // Region sample + one priming frame + the frames not yet persisted. + Assert.Equal(DeepScenes.Options.RegionSampleFrames + 1 + (240 - persisted), resumed.Loads); + Assert.Equal(240, checkpoint.Frames.Count); + } + + [Test] + public async Task FileCheckpointDropsATornLineAndResumes() + { + var path = Path.Combine(context.CreateTempDirectory(), ".titano", DeepAnalysisCheckpointFile.FileName); + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, DuplicateFrames = [7] }); + var expected = (await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options)).ToJson(); + var file = new DeepAnalysisCheckpointFile(path); + var crashing = new SyntheticFrameSource(sequence) { OnLoad = i => { if (i == 21) throw new IOException("crash"); } }; + await Assert.ThrowsAsync(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, file)); + await File.AppendAllTextAsync(path, "{\"index\":20,\"flags\":\"No", context.Cancellation); + + var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, file); + Assert.Equal(expected, report.ToJson()); + Assert.Equal(41, File.ReadAllLines(path).Length); + + // Other options: the stale checkpoint is discarded instead of mixed in. + var other = DeepScenes.Options with { FlowEvery = 3 }; + var fresh = await new DeepAnalysisCheckpointFile(path).LoadAsync(DeepAnalyzer.Fingerprint(40, other), context.Cancellation); + Assert.Empty(fresh); + file.Delete(); + Assert.FileMissing(path); + } + + [Test] + public async Task ReportRoundTripsThroughJsonWithinTheSizeBudget() + { + var report = await DeepReports.NightJitter; + var json = report.ToJson(); + var copy = DeepAnalysisReport.FromJson(json); + Assert.Equal(json, copy.ToJson()); + var perFrame = (double)System.Text.Encoding.UTF8.GetByteCount(json) / report.FrameCount; + context.Log($"{perFrame:0.0} bytes per frame"); + Assert.LessOrEqual(perFrame, 120); + + var path = Path.Combine(context.CreateTempDirectory(), DeepAnalysisReport.FileName); + report.Save(path); + Assert.Equal(json, DeepAnalysisReport.Load(path).ToJson()); + + var summary = AnalysisSummary.From(report); + Assert.Equal(summary, AnalysisSummary.FromJson(summary.ToJson())); + Assert.True(summary.StarField); + Assert.Equal(DayNight.Night, summary.Light); + Assert.Equal(report.HeroIndex, summary.HeroIndex); + Assert.Less(summary.ToJson().Length, 400); + Assert.Throws(() => DeepAnalysisReport.FromJson(json.Replace("\"version\":1", "\"version\":99", StringComparison.Ordinal))); + } + + [Test] + public async Task ResultsDoNotDependOnParallelism() + { + var sequence = DeepScenes.NightSky(frames: 40, jitter: 2); + var serial = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 1 }); + var parallel = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 3 }); + Assert.Equal(serial.ToJson(), parallel.ToJson()); + } + + [Test] + public async Task CancellationStopsWithinOneBatch() + { + using var cancellation = new CancellationTokenSource(); + var checkpoint = new MemoryCheckpoint(); + var source = new SyntheticFrameSource(DeepScenes.HolyGrail()) + { + OnLoad = i => + { + if (i == 50) cancellation.Cancel(); + }, + }; + await Assert.ThrowsAsync(() => DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options, checkpoint, null, cancellation.Token)); + Assert.LessOrEqual(source.Loads, DeepScenes.Options.RegionSampleFrames + 52); + Assert.Equal(50, checkpoint.Frames.Count); + } + + [Test] + public async Task ProgressCountsEveryFrameUpToTheTotal() + { + var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 21 }); + var reports = new List(); + await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, progress: new SyncProgress(reports.Add)); + Assert.Equal(11, reports.Count); + Assert.Monotonic(reports.Select(r => (double)r.Done), strict: true); + Assert.Equal(21, reports[^1].Done); + Assert.True(reports.All(r => r.Total == 21 && r.FramesPerSecond > 0)); + Assert.Equal(TimeSpan.Zero, reports[^1].Eta); + } + + [Test] + public void StarDetectorCountsPointsButNotBlobs() + { + using var image = new ImageBuffer(128, 96, 3); + image.Data.Fill(1f / 2048); + var random = new Random(3); + var stars = 0; + for (var y = 6; y < 90; y += 12) + { + for (var x = 6; x < 122; x += 12) + { + var v = (float)(0.2 + 0.8 * random.NextDouble()); + for (var c = 0; c < 3; c++) image[c, x, y] = v; + stars++; + } + } + // A lit window: 4×4 bright block (extended, not a star). + for (var y = 40; y < 44; y++) + { + for (var x = 60; x < 64; x++) + { + for (var c = 0; c < 3; c++) image[c, x, y] = 0.8f; + } + } + var density = StarFieldDetector.Density(image, noiseSigma: 0); + Assert.Approximately(stars * 1e6 / (128 * 96), density, 1e-6); + } + + [Test] + public void CloudCoverageCountsTexturedSkyBlocks() + { + using var image = new ImageBuffer(128, 64, 3); + var sky = new float[image.PlaneLength]; + var random = new Random(9); + for (var y = 0; y < 64; y++) + { + for (var x = 0; x < 128; x++) + { + var i = y * 128 + x; + sky[i] = y < 32 ? 1 : 0; + // Smooth gradient everywhere; cloud texture on the left half of the sky. + var v = 0.2 + 0.002 * y + (y < 32 && x < 64 ? 0.15 * random.NextDouble() : 0); + for (var c = 0; c < 3; c++) image[c, x, y] = (float)v; + } + } + Assert.Approximately(0.5, CloudCoverage.Estimate(image, sky), 1e-9); + Assert.True(double.IsNaN(CloudCoverage.Estimate(image, new float[image.PlaneLength]))); + } + + [Test] + public void HistogramDistanceIgnoresExposureButNotContent() + { + using var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64 }).Render(0); + using var brighter = scene.Clone(); + foreach (ref var v in brighter.Data) v *= 1.7f; + using var other = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, HorizonFraction = 0.8, SkyLevel = 0.6 }).Render(0); + var a = FrameStatistics.Measure(scene); + Assert.Less(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(brighter)), 0.02); + Assert.Greater(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(other)), 0.3); + } + + /// Frames of before , then frames of . + private sealed class SplicedSource(IFrameSource first, IFrameSource second, int cut) : IFrameSource + { + public int Count => first.Count; + + public LightFrame Metadata(int index) => first.Metadata(index); + + public ValueTask LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) => + (index < cut ? first : second).LoadAsync(index, maxLongEdge, cancellationToken); + } + + /// Reports synchronously (Progress<T> posts to the thread pool and may reorder). + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(AnalysisProgress value) => report(value); + } +} + +/// Deep reports of the shared scenes, computed once per test run. +internal static class DeepReports +{ + private static readonly Lazy> NightReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky()), DeepScenes.Options)); + private static readonly Lazy> NightJitterReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), DeepScenes.Options)); + private static readonly Lazy> HolyGrailReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.HolyGrail()), DeepScenes.Options)); + + public static Task Night => NightReport.Value; + public static Task NightJitter => NightJitterReport.Value; + public static Task HolyGrail => HolyGrailReport.Value; +} diff --git a/tests/Titano.Core.Tests/Analysis/Deep/DeepFixtures.cs b/tests/Titano.Core.Tests/Analysis/Deep/DeepFixtures.cs new file mode 100644 index 00000000..c7890215 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/Deep/DeepFixtures.cs @@ -0,0 +1,125 @@ +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; + +namespace Titano.Core.Tests.Analysis.Deep; + +/// +/// over a . With > 0 the sequence is +/// rendered pixels larger on every side and each frame is cropped at a seeded integer offset +/// in ±jitter, which shakes the camera by a known amount. +/// +internal sealed class SyntheticFrameSource(SyntheticSequence sequence, int jitter = 0, int seed = 11) : IFrameSource +{ + private readonly (int X, int Y)[] _offsets = Offsets(sequence.Count, jitter, seed); + private int _loads; + + public SyntheticSequence Sequence { get; } = sequence; + + public int Width => Sequence.Options.Width - 2 * jitter; + public int Height => Sequence.Options.Height - 2 * jitter; + public int Count => Sequence.Count; + + /// Total calls of . + public int Loads => Volatile.Read(ref _loads); + + /// Frames that "fail to decode". + public HashSet Undecodable { get; init; } = []; + + /// Called on every load before decoding (may throw to simulate a crash, or cancel a token). + public Action? OnLoad { get; set; } + + /// Metadata without shutter time and aperture when true. + public bool StripExposure { get; init; } + + public LightFrame Metadata(int index) + { + var frame = LightFrame.From(Sequence.Metadata[index], index) with { Width = Width, Height = Height }; + return StripExposure ? frame with { ExposureTime = null, FNumber = null } : frame; + } + + public ValueTask LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Interlocked.Increment(ref _loads); + OnLoad?.Invoke(index); + if (Undecodable.Contains(index)) return ValueTask.FromResult(null); + using var full = Sequence.Render(index); + var (dx, dy) = _offsets[index]; + var image = new ImageBuffer(Width, Height, 3, clear: false); + for (var c = 0; c < 3; c++) + { + for (var y = 0; y < Height; y++) + full.Row(c, y + jitter + dy).Slice(jitter + dx, Width).CopyTo(image.Row(c, y)); + } + if (int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult(image); + using (image) return ValueTask.FromResult(AnalysisImage.Downscale(image, maxLongEdge)); + } + + private static (int, int)[] Offsets(int count, int jitter, int seed) + { + var random = new Random(seed); + var offsets = new (int, int)[count]; + for (var i = 0; i < count; i++) offsets[i] = jitter > 0 ? (random.Next(-jitter, jitter + 1), random.Next(-jitter, jitter + 1)) : (0, 0); + return offsets; + } +} + +/// In-memory checkpoint that records what was persisted. +internal sealed class MemoryCheckpoint : IDeepAnalysisCheckpoint +{ + private string? _fingerprint; + + public List Frames { get; } = []; + + public ValueTask> LoadAsync(string fingerprint, CancellationToken cancellationToken) + { + if (_fingerprint != fingerprint) Frames.Clear(); + _fingerprint = fingerprint; + return ValueTask.FromResult>([.. Frames]); + } + + public ValueTask AppendAsync(IReadOnlyList frames, CancellationToken cancellationToken) + { + Frames.AddRange(frames); + return ValueTask.CompletedTask; + } +} + +/// The synthetic scenes the deep-analysis and advisor tests share (small frames, fast). +internal static class DeepScenes +{ + /// Options for the tests: small sources are analysed at native size, flow on every 5th pair, two workers. + public static DeepAnalysisOptions Options { get; } = new() { MinAnalysisLongEdge = 64, FlowEvery = 5, MaxDegreeOfParallelism = 2, RegionSampleFrames = 9 }; + + /// Night sky with stars over dark land and random flicker. + public static SyntheticSequence NightSky(int frames = 90, int jitter = 0) => SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 160 + 2 * jitter, + Height = 112 + 2 * jitter, + FrameCount = frames, + IntervalSeconds = 20, + BaseExposureTime = 15, + BaseFNumber = 2.8, + BaseIso = 3200, + StarField = true, + StarCount = 160, + FlickerEv = 0.12, + Start = new DateTime(2024, 8, 12, 23, 0, 0), + }); + + /// Sunset: the scene darkens 6 EV while the camera opens up 1 EV every 40 frames. + public static SyntheticSequence HolyGrail(int frames = 240) => SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 160, + Height = 112, + FrameCount = frames, + IntervalSeconds = 15, + BaseExposureTime = 1.0 / 250, + StartEv = 0.5, + EndEv = -5.5, + FlickerEv = 0.03, + ExposureSteps = [new(40, -1), new(80, -1), new(120, -1), new(160, -1), new(200, -1)], + }); +} From 95dbf53569d4d2a1dbd930589a8d2ea2426f5da1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:41:41 +0000 Subject: [PATCH 122/188] ci: capture uploader screenshots; docs: record job engine, visuals and uploader decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/workflows/ci.yml | 18 +++++++++++------- docs/DECISIONS.md | 10 ++++++++++ src/Titano.Ui/Visuals/WrapLayout.cs | 16 ++++++++-------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e95bd97..951c33dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,13 +90,17 @@ jobs: if: runner.os == 'Windows' run: | set +e - src/Titano.App/bin/Release/net10.0-windows/Titano.exe --capture out/screenshots 2> out/capture.log & - wait $! - code=$? - cat out/capture.log - count=$(ls out/screenshots/*.png 2>/dev/null | wc -l) - echo "capture exit code $code, $count screenshot(s)" - if [ "$count" -eq 0 ]; then echo "::warning title=Screenshots::Titano --capture produced no images (exit $code)"; fi + for exe in src/Titano.App/bin/Release/net10.0-windows/Titano.exe src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe; do + name=$(basename "$exe" .exe) + before=$(ls out/screenshots/*.png 2>/dev/null | wc -l) + "$exe" --capture out/screenshots 2> "out/capture-$name.log" & + wait $! + code=$? + cat "out/capture-$name.log" + count=$(( $(ls out/screenshots/*.png 2>/dev/null | wc -l) - before )) + echo "$name capture exit code $code, $count screenshot(s)" + if [ "$count" -eq 0 ]; then echo "::warning title=Screenshots::$name --capture produced no images (exit $code)"; fi + done - name: Publish desktop programs (win-x64, self-contained single file) if: runner.os == 'Windows' diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 07168acd..7f814c0d 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -69,3 +69,13 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Migrations: all pending ones in one transaction under `pg_advisory_xact_lock`. | One transaction per migration | Atomic and safe when several servers start together. | | 2026-10-02 | Case-insensitive search/sort via lower-cased `search_text`/`title_key` columns (and `COLLATE "C"` on PG). | ILIKE / NOCASE | Identical results on both dialects. | | 2026-10-02 | Job claim: `UPDATE … WHERE id = (SELECT … FOR UPDATE SKIP LOCKED) RETURNING` on PG; immediate transaction on SQLite. | Advisory locks | Exclusive under concurrency, as specified. | +| 2026-10-02 | One `JobEngine` in Titano.Data runs every long operation for both the client and the server: handlers per `JobKind`, progress persisted at most every 5 s, a failed persist (job no longer running) stops the handler, a shutdown leaves jobs running so the next start requeues them from their checkpoint. | Per-feature background loops | One queue, one cancel/pause/resume path and one crash-recovery rule everywhere. | +| 2026-10-02 | Job throughput is a moving average over windows of at least 2 s. | Average since start | ETA follows speed changes (cache warm-up, network) without jitter. | +| 2026-10-02 | Visual controls (card grid, filmstrip, charts, preview, curve editor) keep their layout and math in WPF-free classes; colours are theme brush keys re-resolved on theme switch; charts, filmstrip and preview never mirror in RTL. | Math inside controls / brush properties | Testable on Linux; view models hold no brushes; time axes and images must not flip. | +| 2026-10-02 | `VirtualizingWrapPanel` does its own keyboard navigation and recycling; the focused container is kept alive. | ListBox navigation | Direct targets, wrapping across rows; focus survives scrolling. | +| 2026-10-02 | Library card slot 236 × 208 with a 16:9 thumbnail. | Mockup's 150 px thumbnail | DESIGN §4 specifies 16:9. | +| 2026-10-02 | Uploader sessions: key = 8 hex chars of the source folder's SHA-256 + first-frame time; leading test shots (first group < 8 frames) join the next session; watch-folder files always use automatic sessions. | Group by time only | Simultaneous cameras stay apart; unattended files never land in a sequence chosen for a manual drop. | +| 2026-10-02 | Uploader: a watch file counts as processed only after the server confirms it; offline, rejected-token and changed-certificate failures do not use up the three retries; a changed certificate signs the user out. | Mark at enqueue / count every failure | Clearing the queue loses nothing; an outage does not exhaust a large batch; never upload to an unverified server. | +| 2026-10-02 | Delete-after-upload also requires size and write time unchanged since hashing. | Server confirmation alone | BRIEF rule 8. | +| 2026-10-02 | Uploader settings are an in-window panel; single instance via a per-session mutex and a current-user named pipe; native tray menu (`TrackPopupMenuEx`). | Dialog / WM_COPYDATA / WPF ContextMenu | §12.1 allows modals only for login and destructive confirmations; works while hidden in the tray; dismisses reliably. | +| 2026-10-02 | Network watch folders are polled (default 5 min); local folders every 60 s plus `FileSystemWatcher` hints. | Watcher everywhere | SMB change notifications are unreliable. | diff --git a/src/Titano.Ui/Visuals/WrapLayout.cs b/src/Titano.Ui/Visuals/WrapLayout.cs index 52a26cab..f1a01fd4 100644 --- a/src/Titano.Ui/Visuals/WrapLayout.cs +++ b/src/Titano.Ui/Visuals/WrapLayout.cs @@ -158,15 +158,15 @@ public readonly struct WrapLayout if (index + Columns <= last) return index + Columns; return RowOf(index) < Rows - 1 ? last : index; case WrapStep.PageUp: - { - var row = Math.Max(0, RowOf(index) - page); - return row * Columns + ColumnOf(index); - } + { + var row = Math.Max(0, RowOf(index) - page); + return row * Columns + ColumnOf(index); + } case WrapStep.PageDown: - { - var row = Math.Min(Rows - 1, RowOf(index) + page); - return Math.Min(last, row * Columns + ColumnOf(index)); - } + { + var row = Math.Min(Rows - 1, RowOf(index) + page); + return Math.Min(last, row * Columns + ColumnOf(index)); + } case WrapStep.First: return 0; case WrapStep.Last: From b3801961aaca0ac990502b7134f139d836b78984 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:42:05 +0000 Subject: [PATCH 123/188] feat(video): managed encoder provider for MJPEG-AVI, image sequences, GIF and APNG Sessions write to a temporary file or folder that Complete renames into place and Dispose deletes; constant-rate outputs repeat held frames. Adds AVI/GIF/APNG readers used to verify rendered outputs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Render/Diagnostics/OutputReaders.cs | 410 ++++++++++++++++++ .../Video/Managed/ManagedEncoderProvider.cs | 64 +++ .../Video/Managed/ManagedSessions.cs | 270 ++++++++++++ .../Export/ManagedEncoderTests.cs | 190 ++++++++ 4 files changed, 934 insertions(+) create mode 100644 src/Titano.Core/Render/Diagnostics/OutputReaders.cs create mode 100644 src/Titano.Core/Video/Managed/ManagedEncoderProvider.cs create mode 100644 src/Titano.Core/Video/Managed/ManagedSessions.cs create mode 100644 tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs diff --git a/src/Titano.Core/Render/Diagnostics/OutputReaders.cs b/src/Titano.Core/Render/Diagnostics/OutputReaders.cs new file mode 100644 index 00000000..ddc7f5d3 --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/OutputReaders.cs @@ -0,0 +1,410 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Codecs.Png; +using Titano.Core.Hashing; +using Titano.Core.Imaging; +using Titano.Core.Video; + +namespace Titano.Core.Render.Diagnostics; + +/// A composed animation frame (8-bit sRGB RGBA canvas) and how long it is shown. +internal sealed record AnimationFrame(byte[] Rgba, long Duration90k); + +/// A decoded GIF or APNG used to verify rendered outputs. +internal sealed record AnimationInfo(int Width, int Height, IReadOnlyList Frames, int? LoopCount) +{ + public long Duration90k => Frames.Sum(f => f.Duration90k); + + /// Frame as a linear-light RGB buffer (alpha dropped). + public ImageBuffer ToLinear(int index) => PixelConvert.FromInterleaved8(Frames[index].Rgba, Width, Height, 4, TransferFunction.Srgb, 3); +} + +/// The structure of an MJPEG AVI: headers, the JPEG of every frame and the legacy index size. +internal sealed record AviInfo(int Width, int Height, Rational FrameRate, int HeaderFrames, int StreamFrames, IReadOnlyList Frames, int IndexEntries); + +/// Bounds-checked big/little-endian reads; every violation is an . +internal ref struct ByteCursor(ReadOnlySpan data) +{ + private readonly ReadOnlySpan _data = data; + + public int Position { get; set; } + + public readonly int Remaining => _data.Length - Position; + + public ReadOnlySpan Take(int count) + { + if (count < 0 || count > Remaining) throw new InvalidDataException($"Truncated data at offset {Position}"); + var span = _data.Slice(Position, count); + Position += count; + return span; + } + + public byte U8() => Take(1)[0]; + + public ushort U16Le() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2)); + + public uint U32Le() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4)); + + public uint U32Be() => BinaryPrimitives.ReadUInt32BigEndian(Take(4)); + + public string FourCc() => Encoding.ASCII.GetString(Take(4)); +} + +/// Reads AVI files written by (RIFF 'AVI ' plus 'AVIX' continuations). +internal static class AviReader +{ + public static AviInfo Read(ReadOnlySpan data) + { + var cursor = new ByteCursor(data); + var frames = new List(); + int width = 0, height = 0, headerFrames = 0, streamFrames = 0, index = 0; + var rate = default(Rational); + var first = true; + while (cursor.Remaining >= 12) + { + if (cursor.FourCc() != "RIFF") throw new InvalidDataException("RIFF expected"); + var size = (int)cursor.U32Le(); + var end = cursor.Position + size; + var type = cursor.FourCc(); + if (type != (first ? "AVI " : "AVIX")) throw new InvalidDataException($"Unexpected RIFF type '{type}'"); + Walk(ref cursor, end, frames, ref width, ref height, ref headerFrames, ref streamFrames, ref rate, ref index); + cursor.Position = end + (size & 1); + first = false; + } + if (first) throw new InvalidDataException("No RIFF list"); + if (width == 0 || rate.Numerator == 0) throw new InvalidDataException("Missing avih/strh headers"); + return new AviInfo(width, height, rate, headerFrames, streamFrames, frames, index); + } + + private static void Walk(ref ByteCursor cursor, int end, List frames, ref int width, ref int height, ref int headerFrames, + ref int streamFrames, ref Rational rate, ref int index) + { + while (cursor.Position + 8 <= end) + { + var id = cursor.FourCc(); + var size = (int)cursor.U32Le(); + if (size < 0 || cursor.Position + size > end) throw new InvalidDataException($"Chunk '{id}' overruns its list"); + if (id == "LIST") + { + var listEnd = cursor.Position + size; + cursor.FourCc(); + Walk(ref cursor, listEnd, frames, ref width, ref height, ref headerFrames, ref streamFrames, ref rate, ref index); + cursor.Position = listEnd + (size & 1); + continue; + } + var body = cursor.Take(size); + switch (id) + { + case "avih": + headerFrames = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[16..]); + width = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[32..]); + height = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[36..]); + break; + case "strh": + var scale = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[20..]); + var rateValue = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[24..]); + if (scale <= 0 || rateValue <= 0) throw new InvalidDataException("Invalid stream rate"); + rate = new Rational(rateValue, scale); + streamFrames = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[32..]); + break; + case "00dc": + if (size < 4 || body[0] != 0xFF || body[1] != 0xD8) throw new InvalidDataException("Video chunk is not a JPEG"); + frames.Add(body.ToArray()); + break; + case "idx1": + index = size / 16; + break; + } + cursor.Position += size & 1; + } + } +} + +/// GIF89a decoder with frame composition (disposal 0–3, transparency) for output verification. +internal static class GifReader +{ + public static AnimationInfo Decode(ReadOnlySpan data) + { + var cursor = new ByteCursor(data); + var signature = Encoding.ASCII.GetString(cursor.Take(6)); + if (signature is not ("GIF89a" or "GIF87a")) throw new InvalidDataException("Not a GIF"); + int width = cursor.U16Le(), height = cursor.U16Le(); + var packed = cursor.U8(); + cursor.Take(2); + if (width == 0 || height == 0) throw new InvalidDataException("Empty logical screen"); + var global = (packed & 0x80) != 0 ? cursor.Take(3 << ((packed & 7) + 1)).ToArray() : null; + var canvas = new byte[width * height * 4]; + var frames = new List(); + int? loop = null; + int delay = 0, disposal = 0, transparent = -1; + while (true) + { + var block = cursor.U8(); + if (block == 0x3B) break; + if (block == 0x21) + { + var label = cursor.U8(); + if (label == 0xF9) + { + if (cursor.U8() != 4) throw new InvalidDataException("Bad graphic control extension"); + var flags = cursor.U8(); + delay = cursor.U16Le(); + var index = cursor.U8(); + disposal = (flags >> 2) & 7; + transparent = (flags & 1) != 0 ? index : -1; + if (cursor.U8() != 0) throw new InvalidDataException("Unterminated graphic control extension"); + continue; + } + var payload = SubBlocks(ref cursor); + if (label == 0xFF && payload.Length >= 14 && Encoding.ASCII.GetString(payload, 0, 11) == "NETSCAPE2.0") loop = payload[12] | payload[13] << 8; + continue; + } + if (block != 0x2C) throw new InvalidDataException($"Unexpected block 0x{block:X2}"); + int left = cursor.U16Le(), top = cursor.U16Le(), w = cursor.U16Le(), h = cursor.U16Le(); + var imagePacked = cursor.U8(); + if (left + w > width || top + h > height || w == 0 || h == 0) throw new InvalidDataException("Frame outside the logical screen"); + if ((imagePacked & 0x40) != 0) throw new InvalidDataException("Interlaced frames are not verified"); + var table = (imagePacked & 0x80) != 0 ? cursor.Take(3 << ((imagePacked & 7) + 1)).ToArray() : global + ?? throw new InvalidDataException("No colour table"); + var minCode = cursor.U8(); + if (minCode is < 2 or > 8) throw new InvalidDataException("Bad LZW code size"); + var indices = Lzw(SubBlocks(ref cursor), minCode, w * h); + var saved = disposal == 3 ? (byte[])canvas.Clone() : null; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var i = indices[y * w + x]; + if (i == transparent) continue; + if (i * 3 + 2 >= table.Length) throw new InvalidDataException("Index outside the colour table"); + var o = ((top + y) * width + left + x) * 4; + canvas[o] = table[i * 3]; + canvas[o + 1] = table[i * 3 + 1]; + canvas[o + 2] = table[i * 3 + 2]; + canvas[o + 3] = 255; + } + } + frames.Add(new AnimationFrame((byte[])canvas.Clone(), delay * 900L)); + if (disposal == 2) + { + for (var y = 0; y < h; y++) canvas.AsSpan(((top + y) * width + left) * 4, w * 4).Clear(); + } + else if (saved is not null) + { + canvas = saved; + } + delay = 0; + disposal = 0; + transparent = -1; + } + return new AnimationInfo(width, height, frames, loop); + } + + private static byte[] SubBlocks(ref ByteCursor cursor) + { + using var buffer = new MemoryStream(); + while (true) + { + var length = cursor.U8(); + if (length == 0) return buffer.ToArray(); + buffer.Write(cursor.Take(length)); + } + } + + /// Variable-length LZW (GIF flavour: clear/end codes, codes up to 12 bits, deferred clear allowed). + private static byte[] Lzw(byte[] data, int minCode, int count) + { + var output = new byte[count]; + var prefix = new short[4096]; + var suffix = new byte[4096]; + var stack = new byte[4097]; + int clear = 1 << minCode, end = clear + 1; + int size = minCode + 1, next = end + 1, previous = -1, written = 0; + byte first = 0; + long bits = 0; + var bitCount = 0; + var pos = 0; + while (written < count) + { + while (bitCount < size && pos < data.Length) + { + bits |= (long)data[pos++] << bitCount; + bitCount += 8; + } + if (bitCount < size) throw new InvalidDataException("Image data ends early"); + var code = (int)(bits & ((1 << size) - 1)); + bits >>= size; + bitCount -= size; + if (code == clear) + { + size = minCode + 1; + next = end + 1; + previous = -1; + continue; + } + if (code == end) break; + int top = 0, current = code; + if (previous < 0) + { + if (code >= clear) throw new InvalidDataException("First code is not a literal"); + first = (byte)code; + output[written++] = first; + previous = code; + continue; + } + if (code > next || (code == next && next >= 4096)) throw new InvalidDataException("Invalid LZW code"); + if (code == next) + { + stack[top++] = first; + current = previous; + } + while (current >= clear) + { + stack[top++] = suffix[current]; + current = prefix[current]; + } + first = (byte)current; + stack[top++] = first; + while (top > 0 && written < count) output[written++] = stack[--top]; + if (next < 4096) + { + prefix[next] = (short)previous; + suffix[next] = first; + next++; + if (next == 1 << size && size < 12) size++; + } + previous = code; + } + if (written < count) throw new InvalidDataException("Image data ends early"); + return output; + } +} + +/// APNG decoder for output verification: chunk CRCs, the shared sequence counter, fcTL/fdAT layout, and +/// composition with every dispose and blend operation (each frame is decoded through ). +internal static class ApngReader +{ + private static readonly byte[] Signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + private sealed record Control(int Width, int Height, int X, int Y, long Duration90k, byte Dispose, byte Blend) + { + public List Data { get; } = []; + } + + public static AnimationInfo Decode(ReadOnlySpan data) + { + var cursor = new ByteCursor(data); + if (!cursor.Take(8).SequenceEqual(Signature)) throw new InvalidDataException("Not a PNG"); + byte[]? ihdr = null; + int? declaredFrames = null, plays = null; + var controls = new List(); + var sequence = 0u; + while (true) + { + var length = (int)cursor.U32Be(); + if (length < 0) throw new InvalidDataException("Chunk too long"); + var typeAndBody = cursor.Take(4 + length); + if (Crc32.Compute(typeAndBody) != cursor.U32Be()) throw new InvalidDataException("Chunk CRC mismatch"); + var type = Encoding.ASCII.GetString(typeAndBody[..4]); + var body = typeAndBody[4..]; + switch (type) + { + case "IHDR": + ihdr = body.ToArray(); + break; + case "acTL": + declaredFrames = (int)BinaryPrimitives.ReadUInt32BigEndian(body); + plays = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + break; + case "fcTL": + Expect(ref sequence, body); + var num = BinaryPrimitives.ReadUInt16BigEndian(body[20..]); + var den = BinaryPrimitives.ReadUInt16BigEndian(body[22..]); + controls.Add(new Control( + (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]), (int)BinaryPrimitives.ReadUInt32BigEndian(body[8..]), + (int)BinaryPrimitives.ReadUInt32BigEndian(body[12..]), (int)BinaryPrimitives.ReadUInt32BigEndian(body[16..]), + num * 90000L / (den == 0 ? 100 : den), body[24], body[25])); + break; + case "IDAT": + if (controls.Count != 1) throw new InvalidDataException("The default image must be the first frame"); + controls[0].Data.Add(body.ToArray()); + break; + case "fdAT": + Expect(ref sequence, body); + if (controls.Count == 0) throw new InvalidDataException("fdAT before fcTL"); + controls[^1].Data.Add(body[4..].ToArray()); + break; + } + if (type == "IEND") break; + } + if (ihdr is null || declaredFrames is null) throw new InvalidDataException("Missing IHDR or acTL"); + if (declaredFrames != controls.Count) throw new InvalidDataException($"acTL declares {declaredFrames} frames, {controls.Count} found"); + var width = (int)BinaryPrimitives.ReadUInt32BigEndian(ihdr); + var height = (int)BinaryPrimitives.ReadUInt32BigEndian(ihdr.AsSpan(4)); + var canvas = new byte[width * height * 4]; + var frames = new List(controls.Count); + foreach (var c in controls) + { + if (c.X + c.Width > width || c.Y + c.Height > height || c.Data.Count == 0) throw new InvalidDataException("Frame outside the canvas or without data"); + var saved = c.Dispose == 2 ? (byte[])canvas.Clone() : null; + Compose(canvas, width, Region(ihdr, c), c); + frames.Add(new AnimationFrame((byte[])canvas.Clone(), c.Duration90k)); + if (c.Dispose == 1) + { + for (var y = 0; y < c.Height; y++) canvas.AsSpan(((c.Y + y) * width + c.X) * 4, c.Width * 4).Clear(); + } + else if (saved is not null) + { + canvas = saved; + } + } + return new AnimationInfo(width, height, frames, plays); + } + + private static void Expect(ref uint sequence, ReadOnlySpan body) + { + if (BinaryPrimitives.ReadUInt32BigEndian(body) != sequence) throw new InvalidDataException($"Sequence number {sequence} expected"); + sequence++; + } + + /// Decodes one frame's data as a stand-alone PNG with the frame's size. + private static PngImage Region(byte[] ihdr, Control c) + { + using var png = new MemoryStream(); + png.Write(Signature); + var header = (byte[])ihdr.Clone(); + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)c.Width); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(4), (uint)c.Height); + PngEncoder.WriteChunk(png, "IHDR", header); + foreach (var part in c.Data) PngEncoder.WriteChunk(png, "IDAT", part); + PngEncoder.WriteChunk(png, "IEND", []); + var image = PngDecoder.Decode(png.ToArray()); + if (image.Warnings.Count > 0) throw new InvalidDataException("Frame data: " + image.Warnings[0]); + if (image.Pixels8 is null || image.Channels is not (3 or 4)) throw new InvalidDataException("Only 8-bit RGB/RGBA frames are verified"); + return image; + } + + private static void Compose(byte[] canvas, int width, PngImage frame, Control c) + { + var pixels = frame.Pixels8!; + var channels = frame.Channels; + for (var y = 0; y < c.Height; y++) + { + for (var x = 0; x < c.Width; x++) + { + var s = (y * c.Width + x) * channels; + var o = ((c.Y + y) * width + c.X + x) * 4; + var alpha = channels == 4 ? pixels[s + 3] : 255; + if (c.Blend == 1) + { + if (alpha == 0) continue; + if (alpha < 255) throw new InvalidDataException("Partial alpha blending is not verified"); + } + canvas[o] = pixels[s]; + canvas[o + 1] = pixels[s + 1]; + canvas[o + 2] = pixels[s + 2]; + canvas[o + 3] = (byte)alpha; + } + } + } +} diff --git a/src/Titano.Core/Video/Managed/ManagedEncoderProvider.cs b/src/Titano.Core/Video/Managed/ManagedEncoderProvider.cs new file mode 100644 index 00000000..f2b604bb --- /dev/null +++ b/src/Titano.Core/Video/Managed/ManagedEncoderProvider.cs @@ -0,0 +1,64 @@ +namespace Titano.Core.Video.Managed; + +/// +/// The encoders every platform has (BRIEF §11.3): MJPEG in AVI, JPEG / PNG (8 or 16-bit) / TIFF-16 / linear DNG image +/// sequences, animated GIF and APNG, all written by the in-house codecs. Frames are linear-light buffers at the output +/// size. Single files are written to a temporary sibling and renamed on ; +/// sequences go to a temporary folder renamed the same way, so a cancelled or failed encode leaves nothing behind. +/// AVI and image sequences are constant frame rate: a frame lasting several periods is repeated. +/// +public sealed class ManagedEncoderProvider : IVideoEncoderProvider +{ + public const string ProviderName = "managed"; + + /// Largest width or height of any managed output (JPEG, GIF and AVI headers use 16-bit sizes). + public const int MaxDimension = 65535; + + public string Name => ProviderName; + + public IReadOnlyList Capabilities { get; } = + [ + new(VideoCodec.Mjpeg, "Managed MJPEG", false, MaxDimension, MaxDimension, false), + new(VideoCodec.JpegSequence, "Managed JPEG sequence", false, MaxDimension, MaxDimension, false), + new(VideoCodec.PngSequence, "Managed PNG sequence", false, MaxDimension, MaxDimension, true), + new(VideoCodec.Tiff16Sequence, "Managed TIFF sequence", false, MaxDimension, MaxDimension, true), + new(VideoCodec.LinearDngSequence, "Managed linear DNG sequence", false, MaxDimension, MaxDimension, true), + new(VideoCodec.Gif, "Managed GIF", false, MaxDimension, MaxDimension, false), + new(VideoCodec.Apng, "Managed APNG", false, MaxDimension, MaxDimension, false), + ]; + + /// Bit depths each managed codec writes. + public static IReadOnlyList BitDepths(VideoCodec codec) => codec switch + { + VideoCodec.PngSequence => [8, 16], + VideoCodec.Tiff16Sequence => [16, 8], + VideoCodec.LinearDngSequence => [16], + VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif or VideoCodec.Apng => [8], + _ => [], + }; + + public bool CanEncode(EncodeSettings settings) => Problem(settings) is null; + + public IVideoEncoderSession Open(EncodeSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (Problem(settings) is { } problem) throw new NotSupportedException(problem); + var name = Capabilities.First(c => c.Codec == settings.Codec).Name; + return settings.Codec switch + { + VideoCodec.Mjpeg => new AviMjpegSession(settings, name), + VideoCodec.Gif => new GifSession(settings, name), + VideoCodec.Apng => new ApngSession(settings, name), + _ => new ImageSequenceSession(settings, name), + }; + } + + private static string? Problem(EncodeSettings s) + { + if (!VideoCodecInfo.IsManaged(s.Codec)) return $"{s.Codec} needs a platform encoder"; + if (s.Width is <= 0 or > MaxDimension || s.Height is <= 0 or > MaxDimension) return $"{s.Width}×{s.Height} is outside 1–{MaxDimension}"; + if (s.FrameRate.Numerator <= 0 || s.FrameRate.Denominator <= 0) return "The frame rate must be positive"; + if (!BitDepths(s.Codec).Contains(s.BitDepth)) return $"{s.Codec} cannot be written with {s.BitDepth}-bit samples"; + return string.IsNullOrWhiteSpace(s.OutputPath) ? "No output path" : null; + } +} diff --git a/src/Titano.Core/Video/Managed/ManagedSessions.cs b/src/Titano.Core/Video/Managed/ManagedSessions.cs new file mode 100644 index 00000000..da797ac2 --- /dev/null +++ b/src/Titano.Core/Video/Managed/ManagedSessions.cs @@ -0,0 +1,270 @@ +using System.IO.Compression; +using Titano.Core.Codecs.Apng; +using Titano.Core.Codecs.Dng; +using Titano.Core.Codecs.Gif; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.IO; +using Titano.Core.Video.Avi; + +namespace Titano.Core.Video.Managed; + +/// Lifecycle shared by the managed sessions: validation, completion, and deletion of partial output on dispose. +internal abstract class ManagedSession(EncodeSettings settings, string encoderName) : IVideoEncoderSession +{ + protected const string LogCategory = "ManagedEncoder"; + + private bool _completed; + private bool _disposed; + private int _frames; + + public string EncoderName { get; } = encoderName; + + public bool IsHardware => false; + + protected EncodeSettings Settings { get; } = settings; + + public void WriteFrame(ImageBuffer frame, long duration90k) + { + ArgumentNullException.ThrowIfNull(frame); + ObjectDisposedException.ThrowIf(_disposed, this); + if (_completed) throw new InvalidOperationException("The session is complete"); + if (frame.Width != Settings.Width || frame.Height != Settings.Height) throw new ArgumentException("Frame size differs from the encode size", nameof(frame)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration90k); + Write(frame, duration90k); + _frames++; + } + + public void Complete() + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_completed) throw new InvalidOperationException("The session is already complete"); + if (_frames == 0) throw new InvalidOperationException("No frames were written"); + Commit(); + _completed = true; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + if (!_completed) Discard(); + } + + protected abstract void Write(ImageBuffer frame, long duration90k); + + /// Finishes the container and moves it to . + protected abstract void Commit(); + + /// Closes and deletes everything written so far. + protected abstract void Discard(); + + protected static JpegEncodeOptions JpegOptions(int quality) => new() + { + Quality = int.Clamp(quality, 1, 100), + Subsampling = quality >= 90 ? JpegSubsampling.Yuv444 : JpegSubsampling.Yuv420, + OptimizeHuffman = true, + }; +} + +/// Maps variable frame durations onto a constant-rate grid: a frame is repeated for every period it covers +/// (rounded on the cumulative timeline, so the total stays exact). +internal sealed class ConstantRateClock(Rational frameRate) +{ + private long _ticks; + private long _periods; + + /// Periods the next frame of ticks occupies (0 when it is shorter than the grid allows). + public int Advance(long duration90k) + { + _ticks += duration90k; + var end = (_ticks * frameRate.Numerator * 2 + 90000L * frameRate.Denominator) / (2 * 90000L * frameRate.Denominator); + var periods = (int)(end - _periods); + _periods = end; + return periods; + } +} + +/// A single output file written to a temporary sibling and renamed into place. +internal abstract class SingleFileSession : ManagedSession +{ + private readonly string _tempPath; + + protected SingleFileSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) + { + _tempPath = AtomicFile.TempPathFor(settings.OutputPath); + File = new FileStream(_tempPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 1 << 20); + } + + protected FileStream File { get; } + + protected abstract void Finish(); + + protected override void Commit() + { + Finish(); + File.Flush(flushToDisk: true); + File.Dispose(); + AtomicFile.Commit(_tempPath, Settings.OutputPath); + } + + protected override void Discard() + { + File.Dispose(); + try + { + System.IO.File.Delete(_tempPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning(LogCategory, "Could not delete the partial output " + _tempPath, ex); + } + } +} + +internal sealed class AviMjpegSession : SingleFileSession +{ + private readonly AviMjpegWriter _writer; + private readonly ConstantRateClock _clock; + private readonly JpegEncodeOptions _jpeg; + + public AviMjpegSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) + { + try + { + _writer = new AviMjpegWriter(File, settings.Width, settings.Height, settings.FrameRate); + } + catch + { + Discard(); + throw; + } + _clock = new ConstantRateClock(settings.FrameRate); + _jpeg = JpegOptions(settings.Quality); + } + + protected override void Write(ImageBuffer frame, long duration90k) + { + var repeats = _clock.Advance(duration90k); + if (repeats == 0) return; + var jpeg = JpegEncoder.Encode(frame, _jpeg); + for (var i = 0; i < repeats; i++) _writer.WriteFrame(jpeg); + } + + protected override void Finish() => _writer.Complete(); +} + +internal sealed class GifSession : SingleFileSession +{ + private readonly GifEncoder _encoder; + + public GifSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) + { + try + { + _encoder = new GifEncoder(File, settings.Width, settings.Height); + } + catch + { + Discard(); + throw; + } + } + + protected override void Write(ImageBuffer frame, long duration90k) => _encoder.AddFrame(frame, duration90k); + + protected override void Finish() => _encoder.Complete(); +} + +internal sealed class ApngSession : SingleFileSession +{ + private readonly ApngEncoder _encoder; + + public ApngSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) + { + try + { + _encoder = new ApngEncoder(File, settings.Width, settings.Height, new ApngEncoderOptions { CompressionLevel = CompressionLevel.Optimal }); + } + catch + { + Discard(); + throw; + } + } + + protected override void Write(ImageBuffer frame, long duration90k) => _encoder.AddFrame(frame, duration90k); + + protected override void Finish() => _encoder.Complete(); +} + +/// +/// Numbered image files (<folder name>_000001.ext, 1-based, six digits) in the output folder. Files are written +/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion. +/// +internal sealed class ImageSequenceSession : ManagedSession +{ + private readonly string _folder; + private readonly string _temp; + private readonly string _stem; + private readonly string _extension; + private readonly ConstantRateClock _clock; + private int _index; + + public ImageSequenceSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) + { + _folder = Path.GetFullPath(settings.OutputPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (Directory.Exists(_folder) || System.IO.File.Exists(_folder)) throw new IOException($"The output \"{_folder}\" already exists"); + var parent = Path.GetDirectoryName(_folder) ?? throw new ArgumentException("The output folder needs a parent", nameof(settings)); + _stem = Path.GetFileName(_folder); + _extension = VideoCodecInfo.FileExtension(settings.Codec); + Directory.CreateDirectory(parent); + _temp = Path.Combine(parent, "." + _stem + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp"); + Directory.CreateDirectory(_temp); + _clock = new ConstantRateClock(settings.FrameRate); + } + + /// File name of the 1-based frame inside a sequence folder named . + public static string FrameName(string stem, int number, string extension) => + string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem}_{number:D6}{extension}"); + + protected override void Write(ImageBuffer frame, long duration90k) + { + var repeats = _clock.Advance(duration90k); + if (repeats == 0) return; + var bytes = Encode(frame); + for (var i = 0; i < repeats; i++) + { + _index++; + using var file = new FileStream(Path.Combine(_temp, FrameName(_stem, _index, _extension)), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16); + file.Write(bytes); + file.Flush(flushToDisk: true); + } + } + + protected override void Commit() => Directory.Move(_temp, _folder); + + protected override void Discard() + { + try + { + Directory.Delete(_temp, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning(LogCategory, "Could not delete the partial sequence " + _temp, ex); + } + } + + private byte[] Encode(ImageBuffer frame) => Settings.Codec switch + { + VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)), + VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal), + VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }), + VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame), + _ => throw new NotSupportedException($"{Settings.Codec} is not an image sequence"), + }; +} diff --git a/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs b/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs new file mode 100644 index 00000000..5e901acc --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs @@ -0,0 +1,190 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Render.Diagnostics; +using Titano.Core.Video; +using Titano.Core.Video.Managed; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ManagedEncoderTests +{ + private const int Width = 48; + private const int Height = 32; + private static readonly Rational Fps = new(30, 1); + + private readonly TestContext _context; + + public ManagedEncoderTests(TestContext context) => _context = context; + + private static ImageBuffer Frame(int seed) + { + var image = new ImageBuffer(Width, Height); + for (var y = 0; y < Height; y++) + { + for (var x = 0; x < Width; x++) + { + image[0, x, y] = (x + seed * 7) % Width / (float)Width; + image[1, x, y] = y / (float)Height * 0.8f; + image[2, x, y] = (x * y + seed * 13) % 23 / 22f * 0.5f; + } + } + return image; + } + + private static EncodeSettings Settings(string path, VideoCodec codec, int bitDepth = 8) => + new() { OutputPath = path, Codec = codec, Width = Width, Height = Height, FrameRate = Fps, BitDepth = bitDepth, Quality = 95 }; + + /// Three distinct frames lasting one, two and one periods. + private static void Encode(IVideoEncoderSession session) + { + long[] durations = [3000, 6000, 3000]; + for (var i = 0; i < 3; i++) + { + using var frame = Frame(i); + session.WriteFrame(frame, durations[i]); + } + session.Complete(); + } + + private static double Psnr(ImageBuffer expected, ImageBuffer actual) + { + var a = PixelConvert.ToInterleaved8(expected, 3); + var b = PixelConvert.ToInterleaved8(actual, 3); + double sum = 0; + for (var i = 0; i < a.Length; i++) sum += (a[i] - b[i]) * (a[i] - b[i]); + return sum == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255 / (sum / a.Length)); + } + + [Test] + public void MjpegAviRepeatsHeldFramesOnTheConstantRateGrid() + { + var dir = _context.CreateTempDirectory(); + var path = Path.Combine(dir, "out.avi"); + using (var session = new ManagedEncoderProvider().Open(Settings(path, VideoCodec.Mjpeg))) Encode(session); + var avi = AviReader.Read(File.ReadAllBytes(path)); + Assert.Equal(4, avi.Frames.Count); + Assert.Equal(4, avi.HeaderFrames); + Assert.Equal(4, avi.IndexEntries); + Assert.Equal(Fps, avi.FrameRate); + Assert.BytesEqual(avi.Frames[1], avi.Frames[2]); + using var decoded = JpegDecoder.DecodeToLinear(avi.Frames[3]); + using var expected = Frame(2); + Assert.Greater(Psnr(expected, decoded), 35); + Assert.SequenceEqual(new[] { "out.avi" }, Directory.GetFiles(dir).Select(Path.GetFileName)); + } + + [Theory] + [Case(VideoCodec.JpegSequence, 8)] + [Case(VideoCodec.PngSequence, 8)] + [Case(VideoCodec.PngSequence, 16)] + [Case(VideoCodec.Tiff16Sequence, 16)] + [Case(VideoCodec.LinearDngSequence, 16)] + public void SequencesWriteNumberedFilesIntoTheOutputFolder(VideoCodec codec, int bitDepth) + { + var dir = _context.CreateTempDirectory(); + var folder = Path.Combine(dir, "Harbour - sequence"); + using (var session = new ManagedEncoderProvider().Open(Settings(folder, codec, bitDepth))) Encode(session); + Assert.SequenceEqual(new[] { "Harbour - sequence" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName)); + var ext = VideoCodecInfo.FileExtension(codec); + var files = Directory.GetFiles(folder).Order(StringComparer.Ordinal).ToArray(); + Assert.SequenceEqual(Enumerable.Range(1, 4).Select(i => $"Harbour - sequence_{i:D6}{ext}"), files.Select(Path.GetFileName)); + Assert.BytesEqual(File.ReadAllBytes(files[1]), File.ReadAllBytes(files[2])); + using var expected = Frame(2); + var bytes = File.ReadAllBytes(files[3]); + switch (codec) + { + case VideoCodec.JpegSequence: + using (var jpeg = JpegDecoder.DecodeToLinear(bytes)) Assert.Greater(Psnr(expected, jpeg), 35); + break; + case VideoCodec.PngSequence when bitDepth == 8: + Assert.BytesEqual(PixelConvert.ToInterleaved8(expected, 3), PngDecoder.Decode(bytes).Pixels8); + break; + case VideoCodec.PngSequence: + Assert.SequenceEqual(PixelConvert.ToInterleaved16(expected, 3), PngDecoder.Decode(bytes).Pixels16!); + break; + case VideoCodec.Tiff16Sequence: + using (var tiff = TiffImageReader.Decode(bytes)) + { + for (var i = 0; i < tiff.Data.Length; i += 7) Assert.Approximately(expected.Data[i], tiff.Data[i], 2e-4); + } + break; + default: + using (var dng = TiffImageReader.Decode(bytes)) + { + for (var i = 0; i < dng.Data.Length; i += 7) Assert.Approximately(expected.Data[i], dng.Data[i], 1.0 / 65535); + } + break; + } + } + + [Theory] + [Case(VideoCodec.Gif)] + [Case(VideoCodec.Apng)] + public void AnimationsKeepVariableDurations(VideoCodec codec) + { + var dir = _context.CreateTempDirectory(); + var path = Path.Combine(dir, "out" + VideoCodecInfo.FileExtension(codec)); + using (var session = new ManagedEncoderProvider().Open(Settings(path, codec))) Encode(session); + var bytes = File.ReadAllBytes(path); + var animation = codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes); + Assert.Equal(3, animation.Frames.Count); + if (codec == VideoCodec.Apng) + { + Assert.SequenceEqual(new long[] { 3000, 6000, 3000 }, animation.Frames.Select(f => f.Duration90k)); + using var decoded = animation.ToLinear(1); + using var expected = Frame(1); + Assert.True(Psnr(expected, decoded) > 60); + } + else + { + Assert.Approximately(12000, animation.Duration90k, 900); + using var decoded = animation.ToLinear(1); + using var expected = Frame(1); + Assert.Greater(Psnr(expected, decoded), 22); + } + } + + [Theory] + [Case(VideoCodec.Mjpeg)] + [Case(VideoCodec.PngSequence)] + [Case(VideoCodec.Gif)] + [Case(VideoCodec.Apng)] + public void DisposingWithoutCompleteLeavesNothing(VideoCodec codec) + { + var dir = _context.CreateTempDirectory(); + var path = Path.Combine(dir, "partial" + (VideoCodecInfo.DefaultContainer(codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(codec))); + using (var session = new ManagedEncoderProvider().Open(Settings(path, codec))) + { + using var frame = Frame(0); + session.WriteFrame(frame, 3000); + session.WriteFrame(frame, 3000); + } + Assert.Empty(Directory.GetFileSystemEntries(dir)); + } + + [Test] + public void SessionsValidateTheirInput() + { + var dir = _context.CreateTempDirectory(); + var provider = new ManagedEncoderProvider(); + using (var session = provider.Open(Settings(Path.Combine(dir, "a.avi"), VideoCodec.Mjpeg))) + { + using var wrong = new ImageBuffer(Width + 2, Height); + Assert.Throws(() => session.WriteFrame(wrong, 3000)); + Assert.Throws(session.Complete); + } + Assert.Empty(Directory.GetFileSystemEntries(dir)); + + var existing = Directory.CreateDirectory(Path.Combine(dir, "taken")).FullName; + Assert.Throws(() => provider.Open(Settings(existing, VideoCodec.PngSequence))); + Assert.False(provider.CanEncode(Settings(Path.Combine(dir, "x.mp4"), VideoCodec.H264))); + Assert.False(provider.CanEncode(Settings(Path.Combine(dir, "x"), VideoCodec.PngSequence, bitDepth: 10))); + Assert.True(provider.CanEncode(Settings(Path.Combine(dir, "x"), VideoCodec.PngSequence, bitDepth: 16))); + Assert.Throws(() => provider.Open(Settings(Path.Combine(dir, "x.mp4"), VideoCodec.Hevc))); + Assert.Equal(7, provider.Capabilities.Count); + Assert.True(provider.Capabilities.All(c => !c.Hardware && VideoCodecInfo.IsManaged(c.Codec))); + } +} From 3223c8af394a01ace1c3430c5afb1236e0dca3cf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:43:36 +0000 Subject: [PATCH 124/188] fix(testing): escape XML-invalid characters in JUnit reports A theory case containing a control character crashed the JUnit writer after every test had passed, failing the Data test step on all runners. Also clears a stale rejected certificate fingerprint once a later handshake is accepted or the fingerprint is trusted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Client/CertificatePinning.cs | 32 +++++++++++++------ tests/Titano.Testing/TestRunner.cs | 28 ++++++++++++++-- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/src/Titano.Protocol/Client/CertificatePinning.cs b/src/Titano.Protocol/Client/CertificatePinning.cs index f905b429..6c24e37a 100644 --- a/src/Titano.Protocol/Client/CertificatePinning.cs +++ b/src/Titano.Protocol/Client/CertificatePinning.cs @@ -6,25 +6,39 @@ namespace Titano.Protocol.Client; /// /// Trust-on-first-use certificate validation: a certificate is accepted when it chains to a trusted root or when -/// its SHA-256 fingerprint is in the caller's trusted set. The last unknown fingerprint is remembered so the UI can -/// ask the user once and add it. +/// its SHA-256 fingerprint is in the caller's trusted set. The fingerprint rejected by the latest handshake is +/// remembered (and cleared by the next accepted one) so the UI can ask the user once and add it. /// public sealed class CertificatePinning(IEnumerable trustedFingerprints) { private readonly HashSet _trusted = new(trustedFingerprints.Select(Normalize), StringComparer.Ordinal); + private readonly Lock _gate = new(); + private string? _lastRejected; - public string? LastRejectedFingerprint { get; private set; } + public string? LastRejectedFingerprint + { + get { lock (_gate) return _lastRejected; } + } - public void Trust(string fingerprint) => _trusted.Add(Normalize(fingerprint)); + public void Trust(string fingerprint) + { + lock (_gate) + { + _trusted.Add(Normalize(fingerprint)); + _lastRejected = null; + } + } public bool Validate(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors) { if (certificate is null) return false; - if (errors == SslPolicyErrors.None) return true; - var fingerprint = Fingerprint(certificate); - if (_trusted.Contains(fingerprint)) return true; - LastRejectedFingerprint = fingerprint; - return false; + var fingerprint = errors == SslPolicyErrors.None ? null : Fingerprint(certificate); + lock (_gate) + { + var accepted = fingerprint is null || _trusted.Contains(fingerprint); + _lastRejected = accepted ? null : fingerprint; + return accepted; + } } public static string Fingerprint(X509Certificate certificate) => diff --git a/tests/Titano.Testing/TestRunner.cs b/tests/Titano.Testing/TestRunner.cs index 813b5f9e..3b0576f6 100644 --- a/tests/Titano.Testing/TestRunner.cs +++ b/tests/Titano.Testing/TestRunner.cs @@ -253,8 +253,8 @@ public static class TestRunner foreach (var r in results.OrderBy(r => r.Test.FullName, StringComparer.Ordinal)) { w.WriteStartElement("testcase"); - w.WriteAttributeString("classname", r.Test.Type.FullName); - w.WriteAttributeString("name", r.Test.FullName[(r.Test.Type.FullName!.Length + 1)..]); + w.WriteAttributeString("classname", Clean(r.Test.Type.FullName!)); + w.WriteAttributeString("name", Clean(r.Test.FullName[(r.Test.Type.FullName!.Length + 1)..])); w.WriteAttributeString("time", r.Duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); if (r.Outcome == TestOutcome.Failed) { @@ -276,7 +276,29 @@ public static class TestRunner w.WriteEndDocument(); } - private static string Clean(string s) => new(s.Where(XmlConvert.IsXmlChar).ToArray()); + /// Escapes characters XML cannot carry (theory cases may contain control characters) as \uXXXX. + private static string Clean(string s) + { + StringBuilder? sb = null; + for (var i = 0; i < s.Length; i++) + { + var c = s[i]; + if (XmlConvert.IsXmlChar(c)) + { + sb?.Append(c); + continue; + } + if (char.IsHighSurrogate(c) && i + 1 < s.Length && XmlConvert.IsXmlSurrogatePair(s[i + 1], c)) + { + sb?.Append(c).Append(s[i + 1]); + i++; + continue; + } + sb ??= new StringBuilder(s, 0, i, s.Length + 8); + sb.Append(CultureInfo.InvariantCulture, $"\\u{(int)c:X4}"); + } + return sb?.ToString() ?? s; + } private sealed class Options { From ece7f1add0f8531ef66fee27d7e4651628d9704c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:44:34 +0000 Subject: [PATCH 125/188] feat(data): archive ingest contract shared by server uploads and card import Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Archive/IArchiveIngest.cs | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/Titano.Data/Archive/IArchiveIngest.cs diff --git a/src/Titano.Data/Archive/IArchiveIngest.cs b/src/Titano.Data/Archive/IArchiveIngest.cs new file mode 100644 index 00000000..63c53889 --- /dev/null +++ b/src/Titano.Data/Archive/IArchiveIngest.cs @@ -0,0 +1,30 @@ +namespace Titano.Data.Archive; + +/// +/// A verified file waiting in a staging folder on the archive volume, ready to become a frame (BRIEF §4.3, §14.4). +/// Exactly one of , or selects the target: +/// an existing sequence, a new one with that title, or the sequence grouped automatically by session. +/// +public sealed record IngestRequest( + Guid ArchiveId, + Guid? SequenceId, + string? NewSequenceTitle, + string? SessionKey, + string StagedPath, + string OriginalFileName, + long Size, + string Sha256, + DateTime? ClientCapturedAt, + Guid? UserId); + +/// The committed frame; when the sequence already held a frame with that SHA-256. +public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate); + +/// +/// Commits staged files into the archive layout (originals folder, naming templates, sequence.json written +/// atomically) and the index. Used by the server's upload completion and by the client's card import. +/// +public interface IArchiveIngest +{ + Task CommitAsync(IngestRequest request, CancellationToken cancellationToken = default); +} From 446daeae2bdc419c502a562657697f20acf6ae8c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:45:12 +0000 Subject: [PATCH 126/188] fix(data): name the archive namespace Archiving to avoid the Archive entity Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/{Archive => Archiving}/IArchiveIngest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/Titano.Data/{Archive => Archiving}/IArchiveIngest.cs (97%) diff --git a/src/Titano.Data/Archive/IArchiveIngest.cs b/src/Titano.Data/Archiving/IArchiveIngest.cs similarity index 97% rename from src/Titano.Data/Archive/IArchiveIngest.cs rename to src/Titano.Data/Archiving/IArchiveIngest.cs index 63c53889..c8c1cb76 100644 --- a/src/Titano.Data/Archive/IArchiveIngest.cs +++ b/src/Titano.Data/Archiving/IArchiveIngest.cs @@ -1,4 +1,4 @@ -namespace Titano.Data.Archive; +namespace Titano.Data.Archiving; /// /// A verified file waiting in a staging folder on the archive volume, ready to become a frame (BRIEF §4.3, §14.4). From 9bd1161edbaf55890c89fc3ea378c1541422cb43 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:48:24 +0000 Subject: [PATCH 127/188] docs: update status per phase Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/STATUS.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/STATUS.md b/docs/STATUS.md index 32885bdd..8ae31a7c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,17 +1,26 @@ # Status -Current phase: **Phase 0 — Bootstrap** complete on Linux; Windows verification runs in CI. -Engine workstreams for Phases 1–2 and 5–6 (metadata, codecs, data, video, analysis, motion, Windows interop) are in progress. +Phase plan: docs/BRIEF.md §22. Windows behaviour is verified on CI (`windows-latest`); everything else also on Linux. + +| Phase | State | +|---|---| +| 0 Bootstrap | Done: solution, rules, Titano.Testing, zero-package guard, i18n (en, it; 36 cultures scaffolded), WPF shell, server skeleton, Docker, icons, CI. | +| 1 Metadata and imaging | Done: metadata parsers, managed codecs (JPEG, PNG, TIFF, GIF, APNG, ICO, linear DNG writer), WIC provider, colour/resampling. RAW/DNG decode pipeline in progress. | +| 2 Data layer and archive | Data layer done (SQLite binding, PostgreSQL wire client, migrations, repositories, job engine). Archive layout, sidecars, scan, rebuild, verify, duplicates, orphans, adopt: in progress. | +| 3 Library and Archive manager | Visual controls done (virtualised card grid, charts, filmstrip, preview, curve editor). Library, Jobs, Settings, Welcome, Server and About screens: in progress. Archive manager screen: next. | +| 4 Card import | Engine in progress with the archive workstream; screen next. | +| 5 Analysis advisor | In progress. | +| 6 Engine, encoding, editor | Video containers and encoders done (MP4, AVI, GIF/APNG, Media Foundation H.264/HEVC/AV1); render pipeline in progress; editor screen next. | +| 7 Server, sync, uploader | Uploader done. Full server (API, auth, uploads, sync, jobs, render nodes, events, admin panel, Windows service) in progress. | +| 8 Release readiness | Installer, release/docker workflows and Unraid template in place; translations, accessibility and performance passes pending. | +| 9 Monetization | Not started: requires explicit approval (§22). | ## How to try it ``` dotnet build Titano.slnx -c Release -dotnet run --project src/Titano.Server # http://localhost:8080/admin (set TITANO_DATA_PATH/TITANO_ARCHIVE_PATH) -src/Titano.App/bin/Release/net10.0-windows/Titano.exe # Windows -docker compose -f deploy/docker/docker-compose.yml up -d # server + PostgreSQL 17 +dotnet run --project src/Titano.Server # https://localhost:8443/admin (set TITANO_DATA_PATH/TITANO_ARCHIVE_PATH) +src/Titano.App/bin/Release/net10.0-windows/Titano.exe # Windows +src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe # Windows +docker compose -f deploy/docker/docker-compose.yml up -d # server + PostgreSQL 17 ``` - -## Next steps - -See docs/BRIEF.md §22 for the phase plan. From 262a0455dbb268f716652c033ddb23d2d548b542 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:48:34 +0000 Subject: [PATCH 128/188] feat(export): preset resolution with the Custom rule, output naming and estimates ExportResolver applies overrides and names the result after the preset it equals (or custom); ExportNaming expands the name template with collision suffixes; ExportEstimator predicts size and time from a calibratable throughput model. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Export/ExportEstimate.cs | 145 +++++++++++ src/Titano.Core/Export/ExportNaming.cs | 142 +++++++++++ src/Titano.Core/Export/ExportResolver.cs | 229 ++++++++++++++++++ .../Export/ExportEstimateTests.cs | 61 +++++ .../Export/ExportNamingTests.cs | 71 ++++++ .../Export/ExportResolverTests.cs | 131 ++++++++++ 6 files changed, 779 insertions(+) create mode 100644 src/Titano.Core/Export/ExportEstimate.cs create mode 100644 src/Titano.Core/Export/ExportNaming.cs create mode 100644 src/Titano.Core/Export/ExportResolver.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportEstimateTests.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportNamingTests.cs create mode 100644 tests/Titano.Core.Tests/Export/ExportResolverTests.cs diff --git a/src/Titano.Core/Export/ExportEstimate.cs b/src/Titano.Core/Export/ExportEstimate.cs new file mode 100644 index 00000000..bcd09ba0 --- /dev/null +++ b/src/Titano.Core/Export/ExportEstimate.cs @@ -0,0 +1,145 @@ +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// What a render will do, in the units the estimates need. +/// Distinct output pictures (planned frames). +/// Output frame periods (pictures repeated on constant-rate outputs). +/// Video duration. +/// Output width. +/// Output height. +/// Pixels of each decoded source frame. +/// Output frames that need optical flow (synthesised or motion-blurred). +/// Frames read by the preparation pass (0 when cached analysis covers everything). +/// True when a hardware encoder is expected. +public sealed record ExportWorkload( + int OutputFrames, + int OutputPeriods, + double DurationSeconds, + int Width, + int Height, + long WorkingPixels, + int FlowFrames, + int AnalysisFrames, + bool HardwareEncoder); + +/// Estimated output size and render time. +public sealed record ExportEstimate(long Bytes, TimeSpan Time); + +/// +/// Throughput of the stages on this machine, in megapixels (or frames) per second. Defaults are conservative figures +/// for a 4-core desktop; folds the measured time of a finished render into . +/// +public sealed record ThroughputModel +{ + public static ThroughputModel Default { get; } = new(); + + public double DecodeMegapixelsPerSecond { get; init; } = 80; + + /// Exposure, geometry and stacking per working-size pixel. + public double ProcessMegapixelsPerSecond { get; init; } = 60; + + /// Optical flow plus synthesis or blur per output pixel. + public double FlowMegapixelsPerSecond { get; init; } = 5; + + public double AnalysisFramesPerSecond { get; init; } = 40; + + public double HardwareEncodeMegapixelsPerSecond { get; init; } = 400; + + public double SoftwareVideoEncodeMegapixelsPerSecond { get; init; } = 50; + + public double JpegEncodeMegapixelsPerSecond { get; init; } = 60; + + public double PngEncodeMegapixelsPerSecond { get; init; } = 12; + + public double TiffEncodeMegapixelsPerSecond { get; init; } = 25; + + public double GifEncodeMegapixelsPerSecond { get; init; } = 20; + + /// Machine factor learnt from finished renders (2 = twice as fast as the defaults). + public double Scale { get; init; } = 1; + + /// Moves towards the ratio of a predicted to an actual render time. + /// 0 keeps the old scale, 1 adopts the new measurement entirely. + public ThroughputModel Calibrate(TimeSpan predicted, TimeSpan actual, double weight = 0.5) + { + if (predicted <= TimeSpan.Zero || actual <= TimeSpan.Zero) return this; + var ratio = predicted.TotalSeconds / actual.TotalSeconds; + return this with { Scale = double.Clamp(Scale * double.Pow(ratio, double.Clamp(weight, 0, 1)), 0.02, 50) }; + } + + internal double EncodeMegapixelsPerSecond(VideoCodec codec, bool hardware) => codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => hardware ? HardwareEncodeMegapixelsPerSecond : SoftwareVideoEncodeMegapixelsPerSecond, + VideoCodec.Mjpeg or VideoCodec.JpegSequence => JpegEncodeMegapixelsPerSecond, + VideoCodec.PngSequence or VideoCodec.Apng => PngEncodeMegapixelsPerSecond, + VideoCodec.Gif => GifEncodeMegapixelsPerSecond, + _ => TiffEncodeMegapixelsPerSecond, + }; +} + +/// +/// Output size and render time estimates for the Export tab. Video codecs: bit rate × duration plus 1 % container +/// overhead. Frame-based outputs: bits per pixel typical of photographic time-lapse content — JPEG by quality +/// (≈1 bpp at 50 to ≈9 bpp at 100), PNG 12/30 bpp (8/16-bit), TIFF-16 30 bpp, DNG 26 bpp, GIF 2.5 bpp for the first +/// frame and 1.2 bpp per difference frame, APNG 10 and 6 bpp — times the pictures written (constant-rate outputs repeat +/// held pictures). +/// +public static class ExportEstimator +{ + private static readonly (int Quality, double Bpp)[] JpegBits = [(1, 0.3), (50, 1.0), (75, 1.6), (85, 2.2), (90, 2.8), (95, 4.0), (100, 9.0)]; + + public static ExportEstimate Estimate(ResolvedExport export, ExportWorkload workload, ThroughputModel? model = null) + { + ArgumentNullException.ThrowIfNull(export); + ArgumentNullException.ThrowIfNull(workload); + return new ExportEstimate(EstimateBytes(export, workload), EstimateTime(export.Codec, workload, model ?? ThroughputModel.Default)); + } + + public static long EstimateBytes(ResolvedExport export, ExportWorkload w) + { + ArgumentNullException.ThrowIfNull(export); + ArgumentNullException.ThrowIfNull(w); + double pixels = (double)w.Width * w.Height; + var bits = export.Codec switch + { + VideoCodec.H264 or VideoCodec.Hevc or VideoCodec.Av1 => export.EffectiveBitRate(w.Width, w.Height) * w.DurationSeconds * 1.01, + VideoCodec.Mjpeg => (JpegBitsPerPixel(export.Quality) * pixels + 24 * 8) * w.OutputPeriods, + VideoCodec.JpegSequence => JpegBitsPerPixel(export.Quality) * pixels * w.OutputPeriods, + VideoCodec.PngSequence => (export.BitDepth > 8 ? 30 : 12) * pixels * w.OutputPeriods, + VideoCodec.Tiff16Sequence => (export.BitDepth > 8 ? 30 : 12) * pixels * w.OutputPeriods, + VideoCodec.LinearDngSequence => 26 * pixels * w.OutputPeriods, + VideoCodec.Gif => w.OutputFrames > 0 ? (2.5 + 1.2 * (w.OutputFrames - 1)) * pixels : 0, + VideoCodec.Apng => w.OutputFrames > 0 ? (10 + 6.0 * (w.OutputFrames - 1)) * pixels : 0, + _ => 0, + }; + return (long)double.Ceiling(bits / 8); + } + + public static TimeSpan EstimateTime(VideoCodec codec, ExportWorkload w, ThroughputModel model) + { + ArgumentNullException.ThrowIfNull(w); + ArgumentNullException.ThrowIfNull(model); + var outputMp = (double)w.Width * w.Height / 1e6; + var workingMp = w.WorkingPixels / 1e6; + var seconds = w.AnalysisFrames / model.AnalysisFramesPerSecond + + w.OutputFrames * (workingMp / model.DecodeMegapixelsPerSecond + workingMp / model.ProcessMegapixelsPerSecond + + outputMp / model.EncodeMegapixelsPerSecond(codec, w.HardwareEncoder)) + + w.FlowFrames * outputMp / model.FlowMegapixelsPerSecond; + return TimeSpan.FromSeconds(seconds / model.Scale); + } + + /// Typical JPEG bits per pixel at an IJG quality, piecewise linear between measured points. + public static double JpegBitsPerPixel(int quality) + { + quality = int.Clamp(quality, 1, 100); + for (var i = 1; i < JpegBits.Length; i++) + { + var (q1, b1) = JpegBits[i]; + if (quality > q1) continue; + var (q0, b0) = JpegBits[i - 1]; + return b0 + (b1 - b0) * (quality - q0) / (q1 - q0); + } + return JpegBits[^1].Bpp; + } +} diff --git a/src/Titano.Core/Export/ExportNaming.cs b/src/Titano.Core/Export/ExportNaming.cs new file mode 100644 index 00000000..29fdb9f1 --- /dev/null +++ b/src/Titano.Core/Export/ExportNaming.cs @@ -0,0 +1,142 @@ +using System.Globalization; +using System.Text; +using Titano.Core.Naming; +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// Values of the export name tokens. +public sealed record ExportNameContext +{ + /// Shoot date of the sequence (first capture), or the render date when unknown. + public required DateTime Date { get; init; } + + public string? Title { get; init; } + + /// Display name of the preset in the user's language ("Custom" for custom values). + public required string PresetName { get; init; } + + public int Width { get; init; } + public int Height { get; init; } + public Rational FrameRate { get; init; } = new(30, 1); + public required VideoCodec Codec { get; init; } +} + +/// An expanded export name and any template problems. +public sealed record ExportName(string Name, IReadOnlyList Errors) +{ + public bool IsValid => Errors.Count == 0; +} + +/// +/// Output names from (BRIEF §11.5). Tokens: {date} (optionally +/// {date:yyyyMMdd}), {title}, {preset}, {width}, {height}, {fps}, {codec}; +/// {{/}} are literal braces. The result is sanitised like ; an existing file or +/// folder gets a " (2)", " (3)"… suffix. +/// +public static class ExportNaming +{ + public static IReadOnlyList Tokens { get; } = ["date", "title", "preset", "width", "height", "fps", "codec"]; + + /// Name used when a template expands to nothing. + public const string FallbackName = "Render"; + + /// Short, file-name safe codec label ("H.264", "HEVC", "PNG"…). + public static string CodecLabel(VideoCodec codec) => codec switch + { + VideoCodec.H264 => "H.264", + VideoCodec.Hevc => "HEVC", + VideoCodec.Av1 => "AV1", + VideoCodec.Mjpeg => "MJPEG", + VideoCodec.JpegSequence => "JPEG", + VideoCodec.PngSequence => "PNG", + VideoCodec.Tiff16Sequence => "TIFF", + VideoCodec.LinearDngSequence => "DNG", + VideoCodec.Gif => "GIF", + VideoCodec.Apng => "APNG", + _ => codec.ToString(), + }; + + /// Expands into a sanitised name without extension. + public static ExportName Expand(string template, ExportNameContext context) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(context); + var errors = new List(); + var sb = new StringBuilder(); + for (var i = 0; i < template.Length; i++) + { + var c = template[i]; + if ((c == '{' || c == '}') && i + 1 < template.Length && template[i + 1] == c) + { + sb.Append(c); + i++; + continue; + } + if (c == '}') + { + errors.Add(new TemplateError(i, "UnopenedBrace", null)); + continue; + } + if (c != '{') + { + sb.Append(c); + continue; + } + var close = template.IndexOf('}', i + 1); + if (close < 0) + { + errors.Add(new TemplateError(i, "UnclosedBrace", null)); + sb.Append(template, i, template.Length - i); + break; + } + var body = template[(i + 1)..close]; + var colon = body.IndexOf(':', StringComparison.Ordinal); + var name = (colon < 0 ? body : body[..colon]).Trim().ToLowerInvariant(); + var format = colon < 0 ? null : body[(colon + 1)..]; + if (Value(name, format, context) is { } value) sb.Append(value.Replace('/', '-').Replace('\\', '-')); + else errors.Add(new TemplateError(i, name.Length == 0 ? "EmptyToken" : "UnknownToken", name)); + i = close; + } + var result = PathTemplate.SanitizeSegment(sb.ToString()); + return new ExportName(result.Length == 0 ? FallbackName : result, errors); + } + + /// + /// Full output path inside : the expanded name plus the codec's extension, or the bare name + /// for image sequences (a folder), made unique against existing files and folders. + /// + public static string OutputPath(string folder, string template, ExportNameContext context) + { + ArgumentException.ThrowIfNullOrWhiteSpace(folder); + var name = Expand(template, context).Name; + var extension = VideoCodecInfo.DefaultContainer(context.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(context.Codec); + return Unique(folder, name, extension); + } + + /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists. + public static string Unique(string folder, string name, string extension) + { + for (var n = 1; ; n++) + { + var candidate = Path.Combine(folder, (n == 1 ? name : string.Create(CultureInfo.InvariantCulture, $"{name} ({n})")) + extension); + if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate; + } + } + + private static string? Value(string token, string? format, ExportNameContext c) + { + var inv = CultureInfo.InvariantCulture; + return token switch + { + "date" => c.Date.ToString(format ?? "yyyy-MM-dd", inv), + "title" => c.Title ?? string.Empty, + "preset" => c.PresetName, + "width" => c.Width.ToString(format, inv), + "height" => c.Height.ToString(format, inv), + "fps" => c.FrameRate.ToString(), + "codec" => CodecLabel(c.Codec), + _ => null, + }; + } +} diff --git a/src/Titano.Core/Export/ExportResolver.cs b/src/Titano.Core/Export/ExportResolver.cs new file mode 100644 index 00000000..36be3b54 --- /dev/null +++ b/src/Titano.Core/Export/ExportResolver.cs @@ -0,0 +1,229 @@ +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Export; + +/// Export values after applying a project's overrides to its preset (BRIEF §11.4). +public sealed record ResolvedExport +{ + /// Id of the preset whose values these are, or . + public required string PresetId { get; init; } + + /// Id of the preset the overrides were applied to. + public required string BasePresetId { get; init; } + + /// Localisation key of the effective preset's name; null when custom. + public string? NameKey { get; init; } + + public bool IsCustom => PresetId == ExportResolver.CustomId; + + public required VideoCodec Codec { get; init; } + + public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec); + + public CodecProfile Profile { get; init; } + + public int BitDepth { get; init; } = 8; + + /// Output width; 0 derives it from the height and the aspect, or from the source. + public int Width { get; init; } + + /// Output height; 0 derives it from the width and the aspect, or from the source. + public int Height { get; init; } + + public Rational FrameRate { get; init; } = new(30, 1); + + /// Fixed bit rate in bit/s; 0 = at the render size. + public long BitRate { get; init; } + + public double BitsPerPixel { get; init; } + + /// Key-frame distance in frames. + public int GopFrames { get; init; } + + public int BFrames { get; init; } + + public int Quality { get; init; } = 92; + + public RateControl RateControl { get; init; } = RateControl.Vbr; + + /// Specific encoder name requested by the user, or null. + public string? Encoder { get; init; } + + /// Localisation keys of ignored or invalid override values. + public IReadOnlyList Warnings { get; init; } = []; + + /// Average bit rate for a render of ×. + public long EffectiveBitRate(int width, int height) + { + if (BitRate > 0) return BitRate; + var bpp = BitsPerPixel > 0 ? BitsPerPixel : ExportPreset.DefaultBitsPerPixel(Codec); + return (long)double.Round(bpp * width * height * FrameRate.Value); + } + + public EncodeSettings ToEncodeSettings(string outputPath, int width, int height) => new() + { + OutputPath = outputPath, + Codec = Codec, + Width = width, + Height = height, + FrameRate = FrameRate, + Profile = Profile, + BitDepth = BitDepth, + RateControl = RateControl, + BitRate = EffectiveBitRate(width, height), + Quality = Quality, + GopLength = GopFrames, + BFrames = BFrames, + EncoderName = Encoder, + }; +} + +/// +/// Applies to the selected preset and names the result: the preset's id when the values +/// equal it (or equal another preset), otherwise. Editing any value therefore flips the name to +/// "Custom" and editing it back restores the preset name. Unknown or contradictory override values are ignored with a +/// warning key. +/// +public static class ExportResolver +{ + public const string CustomId = "custom"; + + /// Preset used when none is selected, the stored id is unknown or the selection is "custom". + public const string DefaultPresetId = "1080p-h264"; + + public static ResolvedExport Resolve(ExportSettings settings, IReadOnlyList? presets = null) + { + ArgumentNullException.ThrowIfNull(settings); + presets ??= ExportPresets.BuiltIn; + var warnings = new List(); + var id = settings.Preset.Resolve(DefaultPresetId); + var basePreset = Find(presets, id) ?? Find(presets, DefaultPresetId) ?? presets.FirstOrDefault() + ?? throw new ArgumentException("No presets", nameof(presets)); + if (!basePreset.Id.Equals(id, StringComparison.OrdinalIgnoreCase) && !id.Equals(CustomId, StringComparison.OrdinalIgnoreCase)) + warnings.Add("Export.Warning.UnknownPreset"); + + var values = Apply(FromPreset(basePreset), settings.Overrides, warnings); + var match = Matches(values, FromPreset(basePreset)) ? basePreset : presets.FirstOrDefault(p => Matches(values, FromPreset(p))); + return values with + { + PresetId = match?.Id ?? CustomId, + BasePresetId = basePreset.Id, + NameKey = match?.NameKey, + Warnings = warnings, + }; + } + + /// The preset's own values (no overrides). + public static ResolvedExport FromPreset(ExportPreset preset) + { + ArgumentNullException.ThrowIfNull(preset); + return new ResolvedExport + { + PresetId = preset.Id, + BasePresetId = preset.Id, + NameKey = preset.NameKey, + Codec = preset.Codec, + Profile = preset.Profile, + BitDepth = preset.BitDepth, + Width = preset.Width, + Height = preset.Height, + FrameRate = preset.FrameRate, + BitRate = preset.BitRate, + BitsPerPixel = preset.BitsPerPixel, + GopFrames = int.Max(1, (int)double.Round(preset.GopSeconds * preset.FrameRate.Value)), + BFrames = preset.BFrames, + Quality = preset.Quality, + }; + } + + /// Parses a codec name or alias ("h264", "H.265", "hevc", "png", "tiff16", "dng"…). + public static bool TryParseCodec(string? text, out VideoCodec codec) + { + codec = default; + if (string.IsNullOrWhiteSpace(text)) return false; + var key = text.Trim().ToLowerInvariant().Replace(".", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal); + VideoCodec? parsed = key switch + { + "h264" or "avc" => VideoCodec.H264, + "h265" or "hevc" => VideoCodec.Hevc, + "av1" => VideoCodec.Av1, + "mjpeg" or "mjpg" => VideoCodec.Mjpeg, + "jpeg" or "jpg" or "jpegsequence" => VideoCodec.JpegSequence, + "png" or "pngsequence" => VideoCodec.PngSequence, + "tiff" or "tif" or "tiff16" or "tiff16sequence" => VideoCodec.Tiff16Sequence, + "dng" or "lineardng" or "lineardngsequence" => VideoCodec.LinearDngSequence, + "gif" => VideoCodec.Gif, + "apng" => VideoCodec.Apng, + _ => null, + }; + if (parsed is null) return false; + codec = parsed.Value; + return true; + } + + private static ExportPreset? Find(IReadOnlyList presets, string id) => + presets.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + private static ResolvedExport Apply(ResolvedExport v, ExportOverrides o, List warnings) + { + if (o.Codec is not null) + { + if (TryParseCodec(o.Codec, out var codec)) + { + if (codec != v.Codec) v = v with { Codec = codec, Profile = CodecProfile.Auto, BitRate = 0, BitsPerPixel = 0 }; + } + else + { + warnings.Add("Export.Warning.UnknownCodec"); + } + } + if (o.Container is not null && !ContainerMatches(o.Container, v.Container)) warnings.Add("Export.Warning.ContainerIgnored"); + if (o.Profile is not null) + { + if (Enum.TryParse(o.Profile, ignoreCase: true, out var profile) && Enum.IsDefined(profile)) v = v with { Profile = profile }; + else warnings.Add("Export.Warning.UnknownProfile"); + } + if (o.BitDepth is { } depth) v = v with { BitDepth = depth }; + if (o.Width is { } width) v = v with { Width = int.Max(0, width) }; + if (o.Height is { } height) v = v with { Height = int.Max(0, height) }; + if (o.FrameRate is not null) + { + if (FrameRateText.TryParse(o.FrameRate, out var rate)) + { + // A preset's GOP is defined in seconds: keep its duration at the new rate unless the GOP is overridden too. + var seconds = v.GopFrames / v.FrameRate.Value; + v = v with { FrameRate = rate, GopFrames = int.Max(1, (int)double.Round(seconds * rate.Value)) }; + } + else + { + warnings.Add("Export.Warning.UnknownFrameRate"); + } + } + if (o.BitRate is { } bitRate) v = v with { BitRate = long.Max(0, bitRate) }; + if (o.GopFrames is { } gop) v = v with { GopFrames = int.Max(1, gop) }; + if (o.BFrames is { } bFrames) v = v with { BFrames = int.Max(0, bFrames) }; + if (o.Quality is { } quality) v = v with { Quality = int.Clamp(quality, 1, 100) }; + if (o.RateControl is not null) + { + if (Enum.TryParse(o.RateControl, ignoreCase: true, out var rc) && Enum.IsDefined(rc)) v = v with { RateControl = rc }; + else warnings.Add("Export.Warning.UnknownRateControl"); + } + if (o.Encoder is not null) v = v with { Encoder = string.IsNullOrWhiteSpace(o.Encoder) ? null : o.Encoder }; + return v; + } + + private static bool ContainerMatches(string text, ContainerFormat container) => + Enum.TryParse(text, ignoreCase: true, out var parsed) && parsed == container; + + /// Equal export values; bit rates compare as effective rates when the size is fixed. + private static bool Matches(ResolvedExport a, ResolvedExport b) + { + if (a.Codec != b.Codec || a.Profile != b.Profile || a.BitDepth != b.BitDepth || a.Width != b.Width || a.Height != b.Height + || !FrameRateText.AreEqual(a.FrameRate, b.FrameRate) || a.GopFrames != b.GopFrames || a.BFrames != b.BFrames + || a.Quality != b.Quality || a.RateControl != b.RateControl || a.Encoder != b.Encoder) return false; + return a.Width > 0 && a.Height > 0 + ? a.EffectiveBitRate(a.Width, a.Height) == b.EffectiveBitRate(b.Width, b.Height) + : a.BitRate == b.BitRate && a.BitsPerPixel == b.BitsPerPixel; + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs b/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs new file mode 100644 index 00000000..7da50b5e --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportEstimateTests.cs @@ -0,0 +1,61 @@ +using Titano.Core.Export; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportEstimateTests +{ + private static ExportWorkload Workload(int frames = 600, int width = 3840, int height = 2160, int flow = 0, int analysis = 0, bool hardware = true) => + new(frames, frames, frames / 24.0, width, height, (long)width * height, flow, analysis, hardware); + + private static ResolvedExport Preset(string id) => ExportResolver.FromPreset(ExportPresets.Find(id)!); + + [Test] + public void VideoSizeIsBitRateTimesDuration() + { + var export = Preset("4k-h264"); + var bytes = ExportEstimator.EstimateBytes(export, Workload()); + var expected = 0.10 * 3840 * 2160 * 24 * 25 / 8 * 1.01; + Assert.Approximately(expected, bytes, 1); + Assert.InRange(bytes / 1e6, 60, 70); // ≈ 63 MB for 25 s of 4K at 19.9 Mb/s + } + + [Test] + public void FrameBasedSizesScaleWithPicturesAndDepth() + { + var png8 = ExportResolver.FromPreset(ExportPresets.Find("png-sequence")!) with { Width = 1920, Height = 1080 }; + var png16 = png8 with { BitDepth = 16 }; + var w = Workload(240, 1920, 1080) with { OutputPeriods = 480 }; + Assert.Equal(2 * ExportEstimator.EstimateBytes(png8, Workload(240, 1920, 1080)), ExportEstimator.EstimateBytes(png8, w)); + Assert.Greater(ExportEstimator.EstimateBytes(png16, w), 2 * ExportEstimator.EstimateBytes(png8, w)); + var gif = Preset("gif-preview"); + Assert.Less(ExportEstimator.EstimateBytes(gif, Workload(240, 480, 270)), ExportEstimator.EstimateBytes(Preset("apng"), Workload(240, 480, 270))); + Assert.Monotonic(Enumerable.Range(1, 100).Select(q => ExportEstimator.JpegBitsPerPixel(q)), strict: true); + Assert.Approximately(2.8, ExportEstimator.JpegBitsPerPixel(90), 1e-12); + var mjpeg = Preset("mjpeg-avi"); + Assert.Greater(ExportEstimator.EstimateBytes(mjpeg, Workload()), ExportEstimator.EstimateBytes(Preset("4k-hevc10-archive"), Workload())); + } + + [Test] + public void TimeGrowsWithWorkAndCalibrationRescalesIt() + { + var export = Preset("4k-hevc"); + var model = ThroughputModel.Default; + var plain = ExportEstimator.EstimateTime(export.Codec, Workload(), model); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(flow: 600), model).TotalSeconds, 2 * plain.TotalSeconds); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(analysis: 600), model).TotalSeconds, plain.TotalSeconds); + Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(hardware: false), model).TotalSeconds, plain.TotalSeconds); + Assert.InRange(plain.TotalSeconds, 30, 600); // ≈ 4 frames per second of 4K on the default model + + var faster = model.Calibrate(plain, plain / 2, weight: 1); + Assert.Approximately(2.0, faster.Scale, 1e-9); + Assert.Approximately(plain.TotalSeconds / 2, ExportEstimator.EstimateTime(export.Codec, Workload(), faster).TotalSeconds, 1e-6); + Assert.Approximately(Math.Sqrt(2), model.Calibrate(plain, plain / 2).Scale, 1e-9); + Assert.Same(model, model.Calibrate(TimeSpan.Zero, plain)); + + var estimate = ExportEstimator.Estimate(export, Workload()); + Assert.Equal(ExportEstimator.EstimateBytes(export, Workload()), estimate.Bytes); + Assert.Equal(plain, estimate.Time); + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportNamingTests.cs b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs new file mode 100644 index 00000000..c4c69054 --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs @@ -0,0 +1,71 @@ +using Titano.Core.Export; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportNamingTests +{ + private readonly TestContext _context; + + public ExportNamingTests(TestContext context) => _context = context; + + private static ExportNameContext Context(VideoCodec codec = VideoCodec.Hevc, string? title = "Harbour sunset") => new() + { + Date = new DateTime(2024, 6, 21, 19, 30, 0), + Title = title, + PresetName = "4K UHD HEVC", + Width = 3840, + Height = 2160, + FrameRate = Rational.Fps2997, + Codec = codec, + }; + + [Test] + public void DefaultTemplateNamesTheRender() + { + var name = ExportNaming.Expand("{date} {title} - {preset}", Context()); + Assert.Equal("2024-06-21 Harbour sunset - 4K UHD HEVC", name.Name); + Assert.True(name.IsValid); + } + + [Test] + public void EveryTokenExpands() + { + var name = ExportNaming.Expand("{date:yyyyMMdd}_{width}x{height}_{fps}fps_{codec}_{{raw}}", Context()); + Assert.Equal("20240621_3840x2160_29.97fps_HEVC_{raw}", name.Name); + Assert.Equal("PNG", ExportNaming.CodecLabel(VideoCodec.PngSequence)); + Assert.Equal("H.264", ExportNaming.CodecLabel(VideoCodec.H264)); + } + + [Test] + public void IllegalCharactersAndProblemsAreReported() + { + var name = ExportNaming.Expand("{title} {bogus} {", Context(title: "a/b:c*d?")); + Assert.Equal("a-b_c_d_ {", name.Name); + Assert.Count(2, name.Errors); + Assert.Equal("UnknownToken", name.Errors[0].Code); + Assert.Equal("UnclosedBrace", name.Errors[1].Code); + Assert.Equal(ExportNaming.FallbackName, ExportNaming.Expand("{title}", Context(title: null)).Name); + Assert.Equal("2024-06-21 - 4K UHD HEVC", ExportNaming.Expand("{date} {title} - {preset}", Context(title: null)).Name); + } + + [Test] + public void CollisionsGetANumberedSuffix() + { + var dir = _context.CreateTempDirectory(); + var first = ExportNaming.OutputPath(dir, "{title}", Context()); + Assert.Equal(Path.Combine(dir, "Harbour sunset.mp4"), first); + File.WriteAllBytes(first, [1]); + var second = ExportNaming.OutputPath(dir, "{title}", Context()); + Assert.Equal(Path.Combine(dir, "Harbour sunset (2).mp4"), second); + File.WriteAllBytes(second, [1]); + Assert.Equal(Path.Combine(dir, "Harbour sunset (3).mp4"), ExportNaming.OutputPath(dir, "{title}", Context())); + + var sequence = ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence)); + Assert.Equal(Path.Combine(dir, "Harbour sunset"), sequence); + Directory.CreateDirectory(sequence); + Assert.Equal(Path.Combine(dir, "Harbour sunset (2)"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence))); + Assert.Equal(Path.Combine(dir, "Harbour sunset.gif"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.Gif))); + } +} diff --git a/tests/Titano.Core.Tests/Export/ExportResolverTests.cs b/tests/Titano.Core.Tests/Export/ExportResolverTests.cs new file mode 100644 index 00000000..c934f4be --- /dev/null +++ b/tests/Titano.Core.Tests/Export/ExportResolverTests.cs @@ -0,0 +1,131 @@ +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class ExportResolverTests +{ + private static ExportSettings Export(string preset, ExportOverrides? overrides = null) => + new() { Preset = new Auto().WithManual(preset), Overrides = overrides ?? new ExportOverrides() }; + + [Test] + public void EveryBuiltInPresetResolvesToItself() + { + foreach (var preset in ExportPresets.BuiltIn) + { + var resolved = ExportResolver.Resolve(Export(preset.Id)); + Assert.Equal(preset.Id, resolved.PresetId); + Assert.False(resolved.IsCustom); + Assert.Equal(preset.NameKey, resolved.NameKey); + Assert.Equal(preset.Codec, resolved.Codec); + Assert.Empty(resolved.Warnings); + } + } + + [Test] + public void EditingAValueMakesTheExportCustom() + { + var resolved = ExportResolver.Resolve(Export("4k-hevc", new ExportOverrides { BitRate = 50_000_000 })); + Assert.True(resolved.IsCustom); + Assert.Equal(ExportResolver.CustomId, resolved.PresetId); + Assert.Equal("4k-hevc", resolved.BasePresetId); + Assert.Null(resolved.NameKey); + Assert.Equal(50_000_000L, resolved.EffectiveBitRate(3840, 2160)); + Assert.Equal(3840, resolved.Width); + } + + [Test] + public void ValuesEqualToThePresetRestoreItsName() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides + { + Codec = "h.264", + Container = "mp4", + Width = 1920, + Height = 1080, + FrameRate = "30", + BitRate = 6_220_800, // the preset's 0.10 bpp at 1920×1080×30 + GopFrames = 30, + Profile = "H264High", + RateControl = "vbr", + })); + Assert.Equal("1080p-h264", resolved.PresetId); + Assert.Empty(resolved.Warnings); + } + + [Test] + public void ValuesEqualToAnotherPresetTakeItsName() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { FrameRate = "60" })); + Assert.Equal("1080p60", resolved.PresetId); + Assert.Equal(60, resolved.GopFrames); + Assert.Equal("1080p-h264", resolved.BasePresetId); + } + + [Test] + public void FractionalRatesAndGopFollowTheOverride() + { + var resolved = ExportResolver.Resolve(Export("4k-h264", new ExportOverrides { FrameRate = "24000/1001" })); + Assert.True(resolved.IsCustom); + Assert.Equal(Rational.Fps23976, resolved.FrameRate); + Assert.Equal(24, resolved.GopFrames); + var settings = resolved.ToEncodeSettings("x.mp4", 3840, 2160); + Assert.Equal(24, settings.GopLength); + Assert.Equal((long)Math.Round(0.10 * 3840 * 2160 * 24000 / 1001.0), settings.BitRate); + Assert.Equal(CodecProfile.H264High, settings.Profile); + } + + [Test] + public void BadOverridesAreIgnoredWithWarnings() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "divx", FrameRate = "fast", Container = "avi", Profile = "ultra", RateControl = "magic" })); + Assert.Equal("1080p-h264", resolved.PresetId); + Assert.SequenceEqual(new[] { "Export.Warning.UnknownCodec", "Export.Warning.ContainerIgnored", "Export.Warning.UnknownProfile", "Export.Warning.UnknownFrameRate", "Export.Warning.UnknownRateControl" }, resolved.Warnings); + } + + [Test] + public void UnknownOrCustomSelectionsStartFromTheDefaultPreset() + { + var unknown = ExportResolver.Resolve(Export("deleted-user-preset")); + Assert.Equal(ExportResolver.DefaultPresetId, unknown.PresetId); + Assert.Contains("Export.Warning.UnknownPreset", unknown.Warnings); + + var custom = ExportResolver.Resolve(Export("custom", new ExportOverrides { Codec = "png", Width = 0, Height = 0, BitDepth = 16, FrameRate = "30", GopFrames = 30, BFrames = 0, Quality = 92 })); + Assert.Empty(custom.Warnings); + Assert.Equal(VideoCodec.PngSequence, custom.Codec); + Assert.True(custom.IsCustom); + + var auto = ExportResolver.Resolve(new ExportSettings()); + Assert.Equal(ExportResolver.DefaultPresetId, auto.PresetId); + } + + [Test] + public void ChangingTheCodecResetsCodecSpecificValues() + { + var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "HEVC" })); + Assert.Equal(VideoCodec.Hevc, resolved.Codec); + Assert.Equal(CodecProfile.Auto, resolved.Profile); + Assert.Equal((long)Math.Round(0.07 * 1920 * 1080 * 30), resolved.EffectiveBitRate(1920, 1080)); + Assert.True(resolved.IsCustom); + Assert.True(ExportResolver.TryParseCodec("TIFF-16", out var tiff) && tiff == VideoCodec.Tiff16Sequence); + Assert.False(ExportResolver.TryParseCodec("", out _)); + } + + [Test] + public void FrameRateTextRoundTrips() + { + Assert.True(FrameRateText.TryParse("30000/1001", out var ntsc)); + Assert.Equal(Rational.Fps2997, ntsc); + Assert.True(FrameRateText.TryParse("29.97", out var decimalNtsc)); + Assert.Equal(Rational.Fps2997, decimalNtsc); + Assert.True(FrameRateText.TryParse(" 25 ", out var pal)); + Assert.Equal("25", FrameRateText.Format(pal)); + Assert.Equal("24000/1001", FrameRateText.Format(Rational.Fps23976)); + Assert.True(FrameRateText.AreEqual(new Rational(48000, 2002), Rational.Fps23976)); + Assert.False(FrameRateText.TryParse("0", out _)); + Assert.False(FrameRateText.TryParse("1/0", out _)); + Assert.False(FrameRateText.TryParse(null, out _)); + } +} From f9c83af609f106ca9f69dc3cbbb59067f67f1f78 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:48:34 +0000 Subject: [PATCH 129/188] feat(export): encoder selection with hardware preference, fallbacks and level caps Client renders prefer hardware Media Foundation encoders, fall back from HEVC/AV1 to H.264, drop to 8-bit and cap size/bit rate with reason keys; the server reports that MP4 codecs need a render node. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Export/EncoderSelector.cs | 227 ++++++++++++++++++ .../Export/EncoderSelectorTests.cs | 146 +++++++++++ .../Render/CapturingEncoderProvider.cs | 57 +++++ 3 files changed, 430 insertions(+) create mode 100644 src/Titano.Core/Export/EncoderSelector.cs create mode 100644 tests/Titano.Core.Tests/Export/EncoderSelectorTests.cs create mode 100644 tests/Titano.Core.Tests/Render/CapturingEncoderProvider.cs diff --git a/src/Titano.Core/Export/EncoderSelector.cs b/src/Titano.Core/Export/EncoderSelector.cs new file mode 100644 index 00000000..a318a06d --- /dev/null +++ b/src/Titano.Core/Export/EncoderSelector.cs @@ -0,0 +1,227 @@ +using System.Globalization; +using Titano.Core.Video; +using Titano.Core.Video.Managed; + +namespace Titano.Core.Export; + +/// Where a render runs: clients have platform encoders, the server only managed ones (BRIEF §4.2, §14.7). +public enum EncoderHost +{ + Client, + Server, +} + +public enum EncoderSelectionStatus +{ + /// An encoder accepts the (possibly adjusted) settings. + Ready, + + /// The codec needs a platform encoder: delegate the job to a render node (server). + NeedsRenderNode, + + /// No encoder on this machine can produce the codec. + Unavailable, +} + +/// A localisable explanation of a selection decision; arguments are invariant-culture strings. +public sealed record EncoderNotice(string Key, IReadOnlyList Args) +{ + public EncoderNotice(string key, params string[] args) : this(key, (IReadOnlyList)args) + { + } +} + +/// Result of . +public sealed record EncoderSelection +{ + public required EncoderSelectionStatus Status { get; init; } + + /// The settings to open the encoder with (codec, size, bit depth or bit rate may differ from the request). + public required EncodeSettings Settings { get; init; } + + public IVideoEncoderProvider? Provider { get; init; } + + /// The capability expected to serve the encode (the provider makes the final choice). + public EncoderCapability? Capability { get; init; } + + /// Lowest codec level the final settings fit (video codecs only). + public CodecLevel? Level { get; init; } + + public IReadOnlyList Notices { get; init; } = []; + + public bool IsReady => Status == EncoderSelectionStatus.Ready; + + /// Opens the session; only valid when . + public IVideoEncoderSession Open() => + Provider is not null && IsReady ? Provider.Open(Settings) : throw new InvalidOperationException($"No encoder is ready ({Status})"); +} + +/// Notice keys produced by . +public static class EncoderNotices +{ + public const string NeedsRenderNode = "Export.Encoder.NeedsRenderNode"; + public const string NoEncoder = "Export.Encoder.NoEncoder"; + public const string FallbackToH264 = "Export.Encoder.FallbackToH264"; + public const string SoftwareOnly = "Export.Encoder.SoftwareOnly"; + public const string TenBitUnavailable = "Export.Encoder.TenBitUnavailable"; + public const string BitDepthAdjusted = "Export.Encoder.BitDepthAdjusted"; + public const string ResolutionCappedByLevel = "Export.Encoder.ResolutionCappedByLevel"; + public const string ResolutionCappedByEncoder = "Export.Encoder.ResolutionCappedByEncoder"; + public const string BitRateCapped = "Export.Encoder.BitRateCapped"; +} + +/// +/// Picks the encoder for an export (BRIEF §11.3). Providers are given in priority order (client: Media Foundation, then +/// managed; server: managed only). +/// +/// Managed codecs go to the first provider that accepts them; an unsupported bit depth becomes the shallowest +/// supported depth that keeps all its precision (or the deepest available). +/// H.264/HEVC/AV1 on the server need a render node. On a client the capability is chosen by named encoder, then +/// 10-bit support when asked, then hardware (or software) as preferred, then provider order. HEVC and AV1 without any +/// encoder fall back to H.264 8-bit (bit rate scaled by the bits-per-pixel defaults), 10-bit without a 10-bit encoder +/// drops to 8-bit, and the size is capped to the highest codec level and to the encoder's maximum (aspect kept, even +/// sizes), the bit rate to the level's ceiling. Every adjustment carries a notice. +/// +/// +public static class EncoderSelector +{ + public static EncoderSelection Select(EncodeSettings requested, IReadOnlyList providers, EncoderHost host) + { + ArgumentNullException.ThrowIfNull(requested); + ArgumentNullException.ThrowIfNull(providers); + var notices = new List(); + return VideoCodecInfo.IsManaged(requested.Codec) + ? SelectManaged(requested, providers, notices) + : SelectVideo(requested, providers, host, notices); + } + + private static EncoderSelection SelectManaged(EncodeSettings settings, IReadOnlyList providers, List notices) + { + var depths = ManagedEncoderProvider.BitDepths(settings.Codec); + if (depths.Count > 0 && !depths.Contains(settings.BitDepth)) + { + var deeper = depths.Where(d => d >= settings.BitDepth).ToList(); + var depth = deeper.Count > 0 ? deeper.Min() : depths.Max(); + notices.Add(new EncoderNotice(EncoderNotices.BitDepthAdjusted, Invariant(settings.BitDepth), Invariant(depth))); + settings = settings with { BitDepth = depth }; + } + foreach (var provider in providers) + { + if (!provider.CanEncode(settings)) continue; + return new EncoderSelection + { + Status = EncoderSelectionStatus.Ready, + Settings = settings, + Provider = provider, + Capability = provider.Capabilities.FirstOrDefault(c => c.Codec == settings.Codec), + Notices = notices, + }; + } + notices.Add(new EncoderNotice(EncoderNotices.NoEncoder, settings.Codec.ToString())); + return new EncoderSelection { Status = EncoderSelectionStatus.Unavailable, Settings = settings, Notices = notices }; + } + + private static EncoderSelection SelectVideo(EncodeSettings settings, IReadOnlyList providers, EncoderHost host, List notices) + { + if (host == EncoderHost.Server) + { + notices.Add(new EncoderNotice(EncoderNotices.NeedsRenderNode, settings.Codec.ToString())); + return new EncoderSelection { Status = EncoderSelectionStatus.NeedsRenderNode, Settings = settings, Notices = notices }; + } + if (settings.Codec != VideoCodec.H264 && Candidates(providers, settings.Codec).Count == 0) + { + notices.Add(new EncoderNotice(EncoderNotices.FallbackToH264, settings.Codec.ToString())); + var factor = ExportPreset.DefaultBitsPerPixel(VideoCodec.H264) / ExportPreset.DefaultBitsPerPixel(settings.Codec); + settings = settings with + { + Codec = VideoCodec.H264, + Profile = CodecProfile.H264High, + BitDepth = 8, + BitRate = (long)double.Round(settings.BitRate * factor), + }; + } + if (settings.Codec == VideoCodec.H264 && settings.BitDepth != 8) + { + notices.Add(new EncoderNotice(EncoderNotices.BitDepthAdjusted, Invariant(settings.BitDepth), "8")); + settings = settings with { BitDepth = 8 }; + } + + var candidates = Candidates(providers, settings.Codec); + if (candidates.Count == 0) + { + notices.Add(new EncoderNotice(EncoderNotices.NoEncoder, settings.Codec.ToString())); + return new EncoderSelection { Status = EncoderSelectionStatus.Unavailable, Settings = settings, Notices = notices }; + } + var wantsTenBit = settings.BitDepth > 8; + var ordered = candidates + .Select((c, order) => (c.Provider, c.Capability, Order: order)) + .OrderByDescending(c => settings.EncoderName is not null && c.Capability.Name == settings.EncoderName) + .ThenByDescending(c => wantsTenBit && c.Capability.SupportsTenBit) + .ThenByDescending(c => c.Capability.Hardware == settings.PreferHardware) + .ThenBy(c => c.Order) + .ToList(); + + foreach (var (provider, capability, _) in ordered) + { + var local = new List(notices); + var adjusted = Fit(settings, capability, local); + if (!provider.CanEncode(adjusted)) continue; + if (settings.PreferHardware && !capability.Hardware) local.Add(new EncoderNotice(EncoderNotices.SoftwareOnly, capability.Name)); + var check = CodecLimits.Check(adjusted.Codec, adjusted.Width, adjusted.Height, adjusted.FrameRate.Value, adjusted.BitRate, adjusted.Profile); + return new EncoderSelection + { + Status = EncoderSelectionStatus.Ready, + Settings = adjusted, + Provider = provider, + Capability = capability, + Level = check.Level, + Notices = local, + }; + } + notices.Add(new EncoderNotice(EncoderNotices.NoEncoder, settings.Codec.ToString())); + return new EncoderSelection { Status = EncoderSelectionStatus.Unavailable, Settings = settings, Notices = notices }; + } + + private static List<(IVideoEncoderProvider Provider, EncoderCapability Capability)> Candidates(IReadOnlyList providers, VideoCodec codec) => + [.. providers.SelectMany(p => p.Capabilities.Where(c => c.Codec == codec).Select(c => (p, c)))]; + + /// Applies bit-depth, level and encoder-size limits for one capability. + private static EncodeSettings Fit(EncodeSettings s, EncoderCapability capability, List notices) + { + if (s.BitDepth > 8 && !capability.SupportsTenBit) + { + notices.Add(new EncoderNotice(EncoderNotices.TenBitUnavailable, capability.Name)); + s = s with { BitDepth = 8, Profile = s.Profile == CodecProfile.HevcMain10 ? CodecProfile.HevcMain : s.Profile }; + } + var even = (Width: s.Width & ~1, Height: s.Height & ~1); + s = s with { Width = int.Max(2, even.Width), Height = int.Max(2, even.Height) }; + + var fps = s.FrameRate.Value; + var check = CodecLimits.Check(s.Codec, s.Width, s.Height, fps, 0, s.Profile); + if (!check.Fits && check.SuggestedWidth > 0) + { + s = s with { Width = check.SuggestedWidth, Height = check.SuggestedHeight }; + notices.Add(new EncoderNotice(EncoderNotices.ResolutionCappedByLevel, check.HighestLevel.Name, Size(s))); + } + if (s.Width > capability.MaxWidth || s.Height > capability.MaxHeight) + { + var scale = double.Min((double)capability.MaxWidth / s.Width, (double)capability.MaxHeight / s.Height); + var width = int.Max(2, (int)(s.Width * scale) & ~1); + var height = int.Max(2, (int)double.Round(width * (double)s.Height / s.Width / 2) * 2); + if (height > capability.MaxHeight) height = capability.MaxHeight & ~1; + s = s with { Width = width, Height = height }; + notices.Add(new EncoderNotice(EncoderNotices.ResolutionCappedByEncoder, capability.Name, Size(s))); + } + var limits = CodecLimits.Check(s.Codec, s.Width, s.Height, fps, 0, s.Profile); + if (s.BitRate > limits.MaxBitRate) + { + s = s with { BitRate = limits.MaxBitRate }; + notices.Add(new EncoderNotice(EncoderNotices.BitRateCapped, limits.HighestLevel.Name, Invariant(limits.MaxBitRate))); + } + return s; + } + + private static string Size(EncodeSettings s) => string.Create(CultureInfo.InvariantCulture, $"{s.Width}×{s.Height}"); + + private static string Invariant(long value) => value.ToString(CultureInfo.InvariantCulture); +} diff --git a/tests/Titano.Core.Tests/Export/EncoderSelectorTests.cs b/tests/Titano.Core.Tests/Export/EncoderSelectorTests.cs new file mode 100644 index 00000000..31af272f --- /dev/null +++ b/tests/Titano.Core.Tests/Export/EncoderSelectorTests.cs @@ -0,0 +1,146 @@ +using Titano.Core.Export; +using Titano.Core.Tests.Render; +using Titano.Core.Video; +using Titano.Core.Video.Managed; +using Titano.Testing; + +namespace Titano.Core.Tests.Export; + +public sealed class EncoderSelectorTests +{ + private static readonly EncoderCapability SoftwareH264 = new(VideoCodec.H264, "Microsoft H.264", false, 4096, 2304, false); + private static readonly EncoderCapability HardwareH264 = new(VideoCodec.H264, "NVENC H.264", true, 4096, 4096, false, "NVIDIA"); + private static readonly EncoderCapability HardwareHevc = new(VideoCodec.Hevc, "NVENC HEVC", true, 8192, 8192, true, "NVIDIA"); + private static readonly EncoderCapability HardwareHevc8 = new(VideoCodec.Hevc, "QSV HEVC", true, 8192, 8192, false, "Intel"); + + private static EncodeSettings Request(VideoCodec codec, int width = 3840, int height = 2160, int bitDepth = 8, long bitRate = 20_000_000, Rational? fps = null) => new() + { + OutputPath = "/exports/out" + VideoCodecInfo.FileExtension(codec), + Codec = codec, + Width = width, + Height = height, + FrameRate = fps ?? new Rational(30, 1), + BitDepth = bitDepth, + BitRate = bitRate, + Profile = bitDepth == 10 ? CodecProfile.HevcMain10 : CodecProfile.Auto, + }; + + private static IVideoEncoderProvider[] Client(params EncoderCapability[] capabilities) => + [new CapturingEncoderProvider("Media Foundation", capabilities), new ManagedEncoderProvider()]; + + [Test] + public void ManagedCodecsUseTheManagedProviderEverywhere() + { + foreach (var host in new[] { EncoderHost.Client, EncoderHost.Server }) + { + var selection = EncoderSelector.Select(Request(VideoCodec.Mjpeg, bitDepth: 8), Client(HardwareH264), host); + Assert.True(selection.IsReady); + Assert.Equal(ManagedEncoderProvider.ProviderName, selection.Provider!.Name); + Assert.Equal("Managed MJPEG", selection.Capability!.Name); + Assert.Empty(selection.Notices); + } + } + + [Test] + public void ManagedBitDepthsAreAdjustedWithANotice() + { + var png = EncoderSelector.Select(Request(VideoCodec.PngSequence, bitDepth: 10), [new ManagedEncoderProvider()], EncoderHost.Server); + Assert.Equal(16, png.Settings.BitDepth); + Assert.Equal(EncoderNotices.BitDepthAdjusted, png.Notices.Single().Key); + Assert.SequenceEqual(new[] { "10", "16" }, png.Notices.Single().Args); + var jpeg = EncoderSelector.Select(Request(VideoCodec.JpegSequence, bitDepth: 16), [new ManagedEncoderProvider()], EncoderHost.Server); + Assert.Equal(8, jpeg.Settings.BitDepth); + } + + [Test] + public void ServerNeedsARenderNodeForMp4() + { + var selection = EncoderSelector.Select(Request(VideoCodec.H264), [new ManagedEncoderProvider()], EncoderHost.Server); + Assert.Equal(EncoderSelectionStatus.NeedsRenderNode, selection.Status); + Assert.Null(selection.Provider); + Assert.Equal(EncoderNotices.NeedsRenderNode, selection.Notices.Single().Key); + Assert.Throws(() => selection.Open()); + } + + [Test] + public void HardwareIsPreferredUnlessSoftwareIsAsked() + { + var providers = Client(SoftwareH264, HardwareH264); + var hardware = EncoderSelector.Select(Request(VideoCodec.H264), providers, EncoderHost.Client); + Assert.True(hardware.IsReady); + Assert.Equal("NVENC H.264", hardware.Capability!.Name); + Assert.Empty(hardware.Notices); + Assert.Equal(new CodecLevel(VideoCodec.H264, 5, 1), hardware.Level); + + var software = EncoderSelector.Select(Request(VideoCodec.H264) with { PreferHardware = false }, providers, EncoderHost.Client); + Assert.Equal("Microsoft H.264", software.Capability!.Name); + + var named = EncoderSelector.Select(Request(VideoCodec.H264) with { EncoderName = "Microsoft H.264" }, providers, EncoderHost.Client); + Assert.Equal("Microsoft H.264", named.Capability!.Name); + Assert.Equal(EncoderNotices.SoftwareOnly, named.Notices.Single().Key); + } + + [Test] + public void HevcFallsBackToH264WhenNoEncoderExists() + { + var selection = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10, bitRate: 14_000_000), Client(SoftwareH264), EncoderHost.Client); + Assert.True(selection.IsReady); + Assert.Equal(VideoCodec.H264, selection.Settings.Codec); + Assert.Equal(8, selection.Settings.BitDepth); + Assert.Equal(CodecProfile.H264High, selection.Settings.Profile); + Assert.Equal(20_000_000L, selection.Settings.BitRate); + Assert.Equal(EncoderNotices.FallbackToH264, selection.Notices[0].Key); + Assert.SequenceEqual(new[] { "Hevc" }, selection.Notices[0].Args); + Assert.Contains(selection.Notices, n => n.Key == EncoderNotices.SoftwareOnly); + Assert.Equal(".mp4", Path.GetExtension(selection.Settings.OutputPath)); + } + + [Test] + public void TenBitNeedsATenBitEncoder() + { + var eightOnly = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10), Client(HardwareHevc8), EncoderHost.Client); + Assert.Equal(8, eightOnly.Settings.BitDepth); + Assert.Equal(CodecProfile.HevcMain, eightOnly.Settings.Profile); + Assert.Equal(EncoderNotices.TenBitUnavailable, eightOnly.Notices.Single().Key); + + var tenBit = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10), Client(HardwareHevc8, HardwareHevc), EncoderHost.Client); + Assert.Equal("NVENC HEVC", tenBit.Capability!.Name); + Assert.Equal(10, tenBit.Settings.BitDepth); + Assert.Empty(tenBit.Notices); + } + + [Test] + public void SizeIsCappedByEncoderAndLevel() + { + var encoder = EncoderSelector.Select(Request(VideoCodec.H264, 7680, 4320), Client(HardwareH264), EncoderHost.Client); + Assert.Equal((4096, 2304), (encoder.Settings.Width, encoder.Settings.Height)); + Assert.Equal(EncoderNotices.ResolutionCappedByEncoder, encoder.Notices.Single().Key); + Assert.SequenceEqual(new[] { "NVENC H.264", "4096×2304" }, encoder.Notices.Single().Args); + + var level = EncoderSelector.Select(Request(VideoCodec.Hevc, 7680, 4320, fps: new Rational(240, 1)), Client(HardwareHevc), EncoderHost.Client); + Assert.Equal(EncoderNotices.ResolutionCappedByLevel, level.Notices[0].Key); + Assert.Less(level.Settings.Width, 7680); + Assert.Equal(0, level.Settings.Width % 2); + Assert.Approximately(16.0 / 9, level.Settings.Width / (double)level.Settings.Height, 0.01); + Assert.True(CodecLimits.Check(VideoCodec.Hevc, level.Settings.Width, level.Settings.Height, 240, level.Settings.BitRate).Fits); + + var odd = EncoderSelector.Select(Request(VideoCodec.H264, 1081, 607), Client(HardwareH264), EncoderHost.Client); + Assert.Equal((1080, 606), (odd.Settings.Width, odd.Settings.Height)); + } + + [Test] + public void BitRateIsCappedByTheHighestLevel() + { + var selection = EncoderSelector.Select(Request(VideoCodec.H264, 1920, 1080, bitRate: 2_000_000_000), Client(HardwareH264), EncoderHost.Client); + Assert.Equal(1_000_000_000L, selection.Settings.BitRate); + Assert.Equal(EncoderNotices.BitRateCapped, selection.Notices.Single().Key); + } + + [Test] + public void NoVideoEncoderMeansUnavailable() + { + var selection = EncoderSelector.Select(Request(VideoCodec.Av1), [new ManagedEncoderProvider()], EncoderHost.Client); + Assert.Equal(EncoderSelectionStatus.Unavailable, selection.Status); + Assert.SequenceEqual(new[] { EncoderNotices.FallbackToH264, EncoderNotices.NoEncoder }, selection.Notices.Select(n => n.Key)); + } +} diff --git a/tests/Titano.Core.Tests/Render/CapturingEncoderProvider.cs b/tests/Titano.Core.Tests/Render/CapturingEncoderProvider.cs new file mode 100644 index 00000000..cd5e3404 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/CapturingEncoderProvider.cs @@ -0,0 +1,57 @@ +using Titano.Core.Imaging; +using Titano.Core.Video; + +namespace Titano.Core.Tests.Render; + +/// One encode recorded by . +internal sealed class CapturedEncode(EncodeSettings settings) +{ + public EncodeSettings Settings { get; } = settings; + public List Frames { get; } = []; + public List Durations { get; } = []; + public bool Completed { get; set; } + public bool Disposed { get; set; } +} + +/// Test encoder: keeps a copy of every frame, can pretend to be hardware or to fail at a given frame. +internal sealed class CapturingEncoderProvider(string name, params EncoderCapability[] capabilities) : IVideoEncoderProvider +{ + public string Name => name; + + public IReadOnlyList Capabilities => capabilities; + + public List Encodes { get; } = []; + + /// When set, WriteFrame throws this for the frame with that zero-based index. + public (int Frame, Exception Error)? FailAt { get; set; } + + public bool CanEncode(EncodeSettings settings) => capabilities.Any(c => + c.Codec == settings.Codec && settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight && (settings.BitDepth == 8 || c.SupportsTenBit)); + + public IVideoEncoderSession Open(EncodeSettings settings) + { + var encode = new CapturedEncode(settings); + Encodes.Add(encode); + var capability = capabilities.First(c => c.Codec == settings.Codec); + return new Session(this, encode, capability); + } + + private sealed class Session(CapturingEncoderProvider owner, CapturedEncode encode, EncoderCapability capability) : IVideoEncoderSession + { + public string EncoderName => capability.Name; + + public bool IsHardware => capability.Hardware; + + public void WriteFrame(ImageBuffer frame, long duration90k) + { + if (owner.FailAt is { } fail && fail.Frame == encode.Frames.Count) throw fail.Error; + if (frame.Width != encode.Settings.Width || frame.Height != encode.Settings.Height) throw new ArgumentException("size"); + encode.Frames.Add(frame.Clone()); + encode.Durations.Add(duration90k); + } + + public void Complete() => encode.Completed = true; + + public void Dispose() => encode.Disposed = true; + } +} From c6ad6e750de583b5210c46adcd28f86bf1139694 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:49:23 +0000 Subject: [PATCH 130/188] ci(docker): build with the built-in Dockerfile frontend The external docker/dockerfile:1 frontend is pulled from Docker Hub, whose auth endpoint returned 502 and failed the image build. Nothing in the Dockerfile needs it; base images come from mcr.microsoft.com. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- deploy/docker/Dockerfile | 1 - docs/DECISIONS.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index f3bd6889..b55c8971 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -1,4 +1,3 @@ -# syntax=docker/dockerfile:1 # Titano Server — multi-stage, multi-arch (linux/amd64, linux/arm64). BRIEF §14.9. FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7f814c0d..df6a5afa 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -79,3 +79,4 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Delete-after-upload also requires size and write time unchanged since hashing. | Server confirmation alone | BRIEF rule 8. | | 2026-10-02 | Uploader settings are an in-window panel; single instance via a per-session mutex and a current-user named pipe; native tray menu (`TrackPopupMenuEx`). | Dialog / WM_COPYDATA / WPF ContextMenu | §12.1 allows modals only for login and destructive confirmations; works while hidden in the tray; dismisses reliably. | | 2026-10-02 | Network watch folders are polled (default 5 min); local folders every 60 s plus `FileSystemWatcher` hints. | Watcher everywhere | SMB change notifications are unreliable. | +| 2026-10-02 | The Dockerfile uses BuildKit's built-in frontend (no `# syntax=docker/dockerfile:1`). | Pinned external frontend | Every feature used is built in; the build no longer depends on Docker Hub (a 502 there failed CI). Base images come from mcr.microsoft.com. | From 24579d729398f9fee10419b0c03e130e6b190d76 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:52:08 +0000 Subject: [PATCH 131/188] fix(analysis): measure noise robustly and count only consistent flow vectors Median-based Immerkaer noise ignores stars and edges, so star detection and the noise column no longer read star fields as noise; motion statistics keep only vectors that pass the forward-backward check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/Deep/DeepAnalysisReport.cs | 2 +- src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs | 34 ++++++++++--- src/Titano.Core/Analysis/Deep/DeepFrame.cs | 3 ++ src/Titano.Core/Analysis/Deep/FrameProbe.cs | 7 ++- .../Analysis/Deep/StarFieldDetector.cs | 49 ++++++++++++++++--- 5 files changed, 79 insertions(+), 16 deletions(-) diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs b/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs index 78c9810f..34268978 100644 --- a/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs +++ b/src/Titano.Core/Analysis/Deep/DeepAnalysisReport.cs @@ -33,7 +33,7 @@ public sealed record DeepFrameColumns /// Correlated colour temperature in kelvin, null when not near-Planckian. public double?[] Kelvin { get; init; } = []; - /// Laplacian variance and noise σ of sRGB-encoded luminance, two significant digits. + /// Laplacian variance and robust noise σ of sRGB-encoded luminance, two significant digits. public double?[] Sharpness { get; init; } = []; public double?[] Noise { get; init; } = []; diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs index e0e55593..052fce12 100644 --- a/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs +++ b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs @@ -102,6 +102,8 @@ public static class DeepAnalyzer private sealed class SequentialState(DeepAnalysisOptions options) : IDisposable { private const int MinimumStabilizerSize = 16; + private const float ReliableError = 0.5f; + private const double MinimumReliable = 0.05; private readonly OpticalFlowEngine _flow = new(FlowQuality.Draft); private Stabilizer? _stabilizer; private FrameStatistics? _previous; @@ -121,6 +123,7 @@ public static class DeepAnalyzer frame = frame with { Flags = frame.Flags | (duplicate ? DeepFrameFlags.Duplicate : DeepFrameFlags.None), + Noise = probe.Noise, ShiftX = shiftX, ShiftY = shiftY, MotionMedian = motionMedian, @@ -165,7 +168,6 @@ public static class DeepAnalyzer BlueRatio = stats.MeanBlue > 0 && green > 0 ? double.Log2(stats.MeanBlue / green) : double.NaN, Kelvin = stats.ColorTemperature?.Kelvin ?? double.NaN, Sharpness = stats.Sharpness, - Noise = stats.Noise, }; } @@ -189,8 +191,12 @@ public static class DeepAnalyzer return ((x - cx) * probe.CorrelationScale, (y - cy) * probe.CorrelationScale); } - /// Draft flow from the previous frame with the current frame brought to the previous mean level, so - /// flicker and exposure steps do not read as motion; magnitudes in source pixels per frame. + /// + /// Draft flow from the previous frame, with the current frame brought to the previous mean level so flicker and + /// exposure steps do not read as motion. Only vectors that pass the forward–backward check (error ≤ + /// flow pixels) count, so flat noisy areas do not either; NaN when under + /// of the vectors are reliable. Magnitudes in source pixels per frame. + /// private (double Median, double P95) Motion(FrameProbe probe, FrameStatistics stats, CancellationToken cancellationToken) { if (probe.Index % options.FlowEvery != 0 || _previousIndex != probe.Index - 1) return (double.NaN, double.NaN); @@ -202,9 +208,25 @@ public static class DeepAnalyzer { foreach (ref var v in levelled.Data) v *= gain; } - using var field = _flow.Compute(previous, levelled, cancellationToken); - var statistics = field.Statistics(); - return (statistics.MedianMagnitude * probe.FlowScale, statistics.P95Magnitude * probe.FlowScale); + var (forward, backward) = _flow.ComputeBidirectional(previous, levelled, cancellationToken); + using (forward) + using (backward) + { + var u = forward.U; + var w = forward.V; + var error = forward.Error; + var magnitudes = new float[forward.Count]; + var count = 0; + for (var i = 0; i < magnitudes.Length; i++) + { + if (error[i] <= ReliableError) magnitudes[count++] = float.Hypot(u[i], w[i]); + } + if (count < MinimumReliable * magnitudes.Length) return (double.NaN, double.NaN); + var reliable = magnitudes.AsSpan(0, count); + var median = PlaneOps.Median(reliable); + var p95 = PlaneOps.Select(reliable, int.Max(0, (int)double.Ceiling(0.95 * count) - 1)); + return (median * probe.FlowScale, p95 * probe.FlowScale); + } } } } diff --git a/src/Titano.Core/Analysis/Deep/DeepFrame.cs b/src/Titano.Core/Analysis/Deep/DeepFrame.cs index f2884ef4..3e6e131c 100644 --- a/src/Titano.Core/Analysis/Deep/DeepFrame.cs +++ b/src/Titano.Core/Analysis/Deep/DeepFrame.cs @@ -50,7 +50,10 @@ public sealed record DeepFrame /// Correlated colour temperature of the mean colour; NaN when not near-Planckian. public double Kelvin { get; init; } = double.NaN; + /// Laplacian variance of encoded luminance (). public double Sharpness { get; init; } = double.NaN; + + /// Robust noise σ of encoded luminance (), usable frames only. public double Noise { get; init; } = double.NaN; /// Content motion from the previous decoded frame at the image centre (nine-patch similarity fit). diff --git a/src/Titano.Core/Analysis/Deep/FrameProbe.cs b/src/Titano.Core/Analysis/Deep/FrameProbe.cs index b74fb9f9..04ae9643 100644 --- a/src/Titano.Core/Analysis/Deep/FrameProbe.cs +++ b/src/Titano.Core/Analysis/Deep/FrameProbe.cs @@ -32,6 +32,9 @@ internal sealed class FrameProbe : IDisposable /// Source pixels per flow-image pixel. public double FlowScale { get; private set; } = 1; + /// Robust encoded-luminance noise σ (); usable frames only. + public double Noise { get; private set; } = double.NaN; + public double StarDensity { get; private set; } = double.NaN; public double CloudCoverage { get; private set; } = double.NaN; public double SkyLogLuminance { get; private set; } = double.NaN; @@ -83,7 +86,9 @@ internal sealed class FrameProbe : IDisposable Statistics = stats; if (!IsUsable) return; - if (stats.MeanLogLuminance <= options.DarkLogLuminance) StarDensity = StarFieldDetector.Density(analysis, stats.Noise); + var encoded = StarFieldDetector.EncodedLuminance(analysis); + Noise = StarFieldDetector.RobustNoise(encoded, analysis.Width, analysis.Height); + if (stats.MeanLogLuminance <= options.DarkLogLuminance) StarDensity = StarFieldDetector.Density(encoded, analysis.Width, analysis.Height, Noise); if (mask is not null) { diff --git a/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs b/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs index 00cbe6f8..15bdf8ec 100644 --- a/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs +++ b/src/Titano.Core/Analysis/Deep/StarFieldDetector.cs @@ -1,4 +1,5 @@ using Titano.Core.Imaging; +using Titano.Core.Motion; namespace Titano.Core.Analysis.Deep; @@ -14,18 +15,19 @@ public static class StarFieldDetector public const double NoiseFactor = 6; public const double MinimumContrast = 0.05; - /// Point sources per megapixel of ; is the encoded-luminance - /// noise σ (e.g. ). + /// Point sources per megapixel of a linear-light image; is the encoded-luminance noise σ. public static double Density(ImageBuffer image, double noiseSigma) { ArgumentNullException.ThrowIfNull(image); - int w = image.Width, h = image.Height; - if (w < 5 || h < 5) return 0; - var e = new float[image.PlaneLength]; - ColorSpace.Luminance(image, e); - for (var i = 0; i < e.Length; i++) e[i] = ColorSpace.EncodeFast(e[i]); - var threshold = double.Max(NoiseFactor * (double.IsFinite(noiseSigma) ? noiseSigma : 0), MinimumContrast); + return Density(EncodedLuminance(image), image.Width, image.Height, noiseSigma); + } + /// Point sources per megapixel of a row-major sRGB-encoded luminance plane. + public static double Density(ReadOnlySpan e, int w, int h, double noiseSigma) + { + if (e.Length < w * h) throw new ArgumentException("The plane is smaller than width × height.", nameof(e)); + if (w < 5 || h < 5) return 0; + var threshold = double.Max(NoiseFactor * (double.IsFinite(noiseSigma) ? noiseSigma : 0), MinimumContrast); var count = 0; for (var y = 2; y < h - 2; y++) { @@ -54,4 +56,35 @@ public static class StarFieldDetector } return count * 1e6 / ((double)w * h); } + + /// + /// Noise σ of an encoded-luminance plane from the median |Immerkær (1996) response| on every second pixel of every + /// second row: σ = 1.4826 · median / 6 (the kernel's L2 norm). Unlike the mean-based estimate, stars, edges and + /// texture covering under half the image do not raise it. + /// + public static double RobustNoise(ReadOnlySpan e, int w, int h) + { + if (w < 3 || h < 3) return 0; + var responses = new float[((w - 1) / 2) * ((h - 1) / 2)]; + var n = 0; + for (var y = 1; y < h - 1; y += 2) + { + for (var x = 1; x < w - 1; x += 2) + { + var i = y * w + x; + responses[n++] = float.Abs(e[i - w - 1] + e[i - w + 1] + e[i + w - 1] + e[i + w + 1] + - 2 * (e[i - w] + e[i + w] + e[i - 1] + e[i + 1]) + 4 * e[i]); + } + } + return n > 0 ? 1.482602218505602 * PlaneOps.Median(responses.AsSpan(0, n)) / 6 : 0; + } + + /// sRGB-encoded Rec.709 luminance of an image. + public static float[] EncodedLuminance(ImageBuffer image) + { + ArgumentNullException.ThrowIfNull(image); + var e = new float[image.PlaneLength]; + PlaneOps.PerceptualLuminance(image, e); + return e; + } } From 727b5cb4884c2eedab6f4154b2fd98f3d8b7d471 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:52:08 +0000 Subject: [PATCH 132/188] feat(i18n): add Advisor area with findings, reasons and preset names English and Italian texts for every light and deep finding, every advisor reason and missing-data note, and the sequence preset names; resx comments document each placeholder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Advisor.resx | 107 ++++++++++++++++++++++++++++++++++++++++ i18n/it/Advisor.it.resx | 107 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 214 insertions(+) create mode 100644 i18n/en/Advisor.resx create mode 100644 i18n/it/Advisor.it.resx diff --git a/i18n/en/Advisor.resx b/i18n/en/Advisor.resx new file mode 100644 index 00000000..fad2d883 --- /dev/null +++ b/i18n/en/Advisor.resx @@ -0,0 +1,107 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0} frames are black (lens cap or missed exposure).{0} frame count + The camera body changes {0} times.{0} change count + The camera clock jumps {0} times (largest jump {1:0} s).{0} jump count; {1} largest jump in seconds, signed + Clouds cover about {0:0}% of the sky on average.{0} mean cloud coverage in percent + Covers day and night: {0} day, {1} twilight and {2} night frames.{0} day frames; {1} twilight frames; {2} night frames + {0} frames repeat the previous frame.{0} frame count + {0} frames share their capture time with the previous frame.{0} frame count + {0} exposure changes, typically {1:0} frames apart, {2:+0.0;-0.0;0} EV in total.{0} step count; {1} median frames between steps (0 with one step); {2} summed camera EV change + Brightness flickers by {0:0.###} EV around its smooth course.{0} RMS flicker in EV + {0} gaps in the cadence; the longest lasts {1:0} s.{0} gap count; {1} longest gap in seconds + Intervals vary by {0:0.##} s around {1:0.##} s.{0} interval jitter (median absolute deviation) in seconds; {1} median interval in seconds + The lens changes {0} times.{0} change count + {0} frames have no shutter time or aperture in their metadata.{0} frame count + {0} frames have a different orientation.{0} frame count + {0} frames differ from the main size {1}×{2}.{0} frame count; {1} main width in pixels; {2} main height in pixels + Only {0} of {1} frames have a capture time, so cadence and gaps cannot be measured.{0} frames with a capture time; {1} frames in total + {0} frames are out of time order.{0} frame count + The view drifts by {0:0.##} px per frame (pan or slider).{0} drift in source pixels per frame + The view jumps at {0} frames (camera moved or bumped).{0} frame count + Shot in {0} separate sessions.{0} session count + The camera shakes by {0:0.##} px RMS; hiding it costs {1:0.#}% of the frame.{0} shake RMS in source pixels; {1} crop cost in percent of the area + Stars are visible on {0} frames.{0} frame count + {0} logged exposure changes never reached the pixels.{0} step count + No time zone recorded; a UTC offset of {0} min was estimated from the longitude.{0} UTC offset in minutes + {0} frames could not be decoded.{0} frame count + Colour balance jumps by {0:0.#}% between frames.{0} RMS colour-ratio jitter in percent + {0} frames are blown out to white.{0} frame count + Needs the deep analysis of the pixels, which has not run yet; nothing was changed.no placeholders + Shutter time or aperture is missing from the metadata, so this cannot be decided; nothing was changed.no placeholders + Too few frame pairs to measure motion; nothing was changed.no placeholders + Shake was measurable on only {0}% of the frames (too little texture); nothing was changed.{0} percent of frame pairs with a measured shift + The source resolution is unknown; nothing was changed.no placeholders + Only {0} of {1} frames have a capture time, so this cannot be measured; nothing was changed.{0} frames with a capture time; {1} frames in total + Construction cam — {0} {1} {2} fps, adaptive timing{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate + Holy grail sunset — {0} {1} {2} fps, transitions {3}{0} resolution label such as 4K; {1} codec label such as HEVC; {2} frame rate; {3} transition length in frames + Night sky — {0} {1} {2} fps, deflicker {3}{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames + Night sky — {0} {1} {2} fps, deflicker {3}, stabilise{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames + Social vertical {0}×{1}{0} width in pixels; {1} height in pixels + Standard — {0} {1} {2} fps{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate + {0} sessions over {1} days with pauses: adaptive timing in a widely compatible 1080p file.{0} session count; {1} capture span in days + {0} exposure steps across a {1} EV change of light: smooth day-to-night transitions.{0} received step count; {1} change of scene brightness in EV + Stars or a dark sky on {0}% of the frames: dark gradients need 10 bits and steady brightness.{0} percent of frames with stars, or of dark frames + A 9:16 crop for phones and social feeds.no placeholders + General settings for this sequence.no placeholders + The {0}×{1} source cropped to 16:9 keeps {2}% of its height.{0} source width in pixels; {1} source height in pixels; {2} kept height in percent + The source is already 16:9.no placeholders + Portrait source: 9:16 fills a phone screen.no placeholders + The {0}×{1} source cropped to 16:9 keeps {2}% of its width.{0} source width in pixels; {1} source height in pixels; {2} kept width in percent + Flicker is {0} EV, below the visible 0.02 EV: deflicker stays off.{0} RMS flicker in EV + Brightness deviates by {0} EV from its smooth course: deflicker removes the flicker.{0} RMS flicker in EV + {0} black, white, duplicate or unreadable frames would flash or stutter in the video: excluded.{0} frame count + Night sky: 10-bit HEVC keeps dark gradients free of banding.no placeholders + Best preset for a {0}×{1} output with the available encoders.{0} output width in pixels; {1} output height in pixels + Portrait framing: vertical 1080×1920 for phones.no placeholders + The plan is scaled so the {0} frames last {1} s at {2} fps.{0} frame count; {1} target duration in seconds; {2} frame rate + Balanced flow quality is enough for motion blur and previews.no placeholders + Interpolated frames need per-pixel motion: best flow quality.no placeholders + Moderate motion ({0} px per frame): the 24 fps cinema rate gives a {1} s clip.{0} speed of moving content in output pixels per frame; {1} clip duration in seconds + Slow or unmeasured motion: 30 fps gives a {0} s clip.{0} clip duration in seconds + Fast motion ({0} px per frame): 24 fps slows it down; the clip lasts {1} s.{0} speed of moving content in output pixels per frame; {1} clip duration in seconds + {0} frames fill {1} s best at {2} fps.{0} frame count; {1} target duration in seconds; {2} frame rate + {0} frames: 60 fps keeps the clip to {1} s.{0} frame count; {1} clip duration in seconds + Capture over several sessions: 30 fps gives a {0} s clip.{0} clip duration in seconds + Only {0} frames: 24 fps keeps the clip {1} s long.{0} frame count; {1} clip duration in seconds + The horizon sits {0}% from the top: the crop places it on the nearest third.{0} horizon position in percent of the source height + Frame {0} is sharp and well exposed, without clipped highlights.{0} frame number, counted from 1 + {0} exposure changes in the metadata (pixels not checked yet): each is spread over a smooth transition.{0} logged step count + Exposure settings never change: no transitions needed.no placeholders + The camera logged {0} exposure changes but the pixels show none: no transitions needed.{0} logged step count + {0} exposure changes reached the pixels: each is spread over a smooth transition.{0} received step count + The exposure already gives a {0}° shutter angle, at least the {1}° target: no synthetic blur needed.{0} real shutter angle in degrees; {1} target angle in degrees + Content moves only {0} px per frame: blur would be invisible, so it stays off.{0} speed of moving content in output pixels per frame + Real shutter angle {0}° and motion of {1} px per frame: blurring to {2}° adds {3} px trails that hide strobing.{0} real shutter angle in degrees; {1} speed of moving content in output pixels per frame; {2} target angle in degrees; {3} added trail in output pixels + Horizon found with {0}% confidence: sky and land are deflickered separately.{0} mask confidence in percent + Sky separated by brightness with {0}% confidence: sky and land are deflickered separately.{0} mask confidence in percent + The sky/land split is only {0}% reliable: one curve for the whole frame is safer.{0} mask confidence in percent + The {0} encoder handles at most {1}×{2}.{0} encoder name; {1} maximum width in pixels; {2} maximum height in pixels + {0} frames decode only as {1}×{2} embedded previews, which cap the output.{0} frame count; {1} preview width in pixels; {2} preview height in pixels + Largest standard size within the {0}×{1} source.{0} source width in pixels; {1} source height in pixels + 180° is the film look; the real shutter angle is {0}° ({1} s exposure every {2} s).{0} real shutter angle in degrees; {1} median exposure time in seconds; {2} median interval in seconds + Shake of {0} px at output size, but hiding it crops {1}% of the frame: check the framing.{0} shake RMS in output pixels; {1} crop cost in percent of the area + Measured shake of {0} px at output size (0.3 px or less): the camera was steady.{0} shake RMS in output pixels + Measured shake of {0} px at output size (above 0.3 px): stabilisation crops {1}% of the frame area.{0} shake RMS in output pixels; {1} crop cost in percent of the area + Smoothing the camera path over {0} frames removes shake and keeps deliberate pans.{0} smoothing sigma in frames + Strong flicker ({0} EV): every frame lands on the smooth curve.{0} RMS flicker in EV + Mild flicker ({0} EV): reliable frames keep 20% of their own variation.{0} RMS flicker in EV + Intervals vary by {0} s around {1} s: adaptive timing follows the capture clock so motion stays even.{0} interval jitter in seconds; {1} median interval in seconds + {0} gaps in the cadence: adaptive timing keeps the output pace true to capture time.{0} gap count + Steady {0} s interval (jitter {1} s): each photo becomes one video frame.{0} median interval in seconds; {1} jitter in seconds + Shot in {0} sessions with pauses up to {1} h: adaptive timing keeps the pauses short and the pace even.{0} session count; {1} longest pause in hours + {0} short gaps, but motion is unmeasured or fast: constant timing skips them cleanly.{0} gap count + {0} short gaps and smooth motion ({1} px per frame): interpolated frames fill the gaps.{0} gap count; {1} speed of moving content in output pixels per frame + A single exposure step: a {0}-frame transition keeps the change gentle.{0} transition length in frames + Exposure steps are {0} frames apart: transitions of half that ({1} frames) never overlap.{0} median frames between steps; {1} transition length in frames + Colour balance is steady ({0}% from frame to frame): no smoothing needed.{0} RMS colour-ratio jitter in percent + Colour balance jumps by {0}% from frame to frame: smoothing steadies it and keeps the slow drift.{0} RMS colour-ratio jitter in percent + Flicker stays correlated over {0} frames: a {1}-frame window spans four times that.{0} correlation length in frames; {1} window in frames + Flicker drifts over {0} frames: the window is capped at {1} frames so real changes of light survive.{0} flicker period or correlation length in frames; {1} window in frames + Flicker changes from frame to frame without a rhythm: the shortest robust window, {0} frames, removes it.{0} window in frames + Flicker repeats every {0} frames: a {1}-frame window averages four cycles.{0} flicker period in frames; {1} window in frames + diff --git a/i18n/it/Advisor.it.resx b/i18n/it/Advisor.it.resx new file mode 100644 index 00000000..88685171 --- /dev/null +++ b/i18n/it/Advisor.it.resx @@ -0,0 +1,107 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0} fotogrammi sono neri (tappo sull'obiettivo o scatto mancato). + Il corpo macchina cambia {0} volte. + L'orologio della fotocamera salta {0} volte (salto maggiore {1:0} s). + Le nuvole coprono in media circa il {0:0}% del cielo. + Copre giorno e notte: {0} fotogrammi di giorno, {1} al crepuscolo e {2} di notte. + {0} fotogrammi ripetono il precedente. + {0} fotogrammi hanno lo stesso orario di scatto del precedente. + {0} cambi di esposizione, di solito ogni {1:0} fotogrammi, {2:+0.0;-0.0;0} EV in totale. + La luminosità sfarfalla di {0:0.###} EV attorno al suo andamento regolare. + {0} pause nella cadenza; la più lunga dura {1:0} s. + Gli intervalli variano di {0:0.##} s attorno a {1:0.##} s. + L'obiettivo cambia {0} volte. + {0} fotogrammi non hanno tempo di scatto o diaframma nei metadati. + {0} fotogrammi hanno un orientamento diverso. + {0} fotogrammi hanno dimensioni diverse da {1}×{2}. + Solo {0} fotogrammi su {1} hanno un orario di scatto: cadenza e pause non sono misurabili. + {0} fotogrammi sono fuori ordine temporale. + L'inquadratura scorre di {0:0.##} px per fotogramma (panoramica o slider). + L'inquadratura salta in {0} fotogrammi (fotocamera spostata o urtata). + Ripreso in {0} sessioni separate. + La fotocamera vibra di {0:0.##} px RMS; compensarla costa il {1:0.#}% dell'inquadratura. + Le stelle sono visibili in {0} fotogrammi. + {0} cambi di esposizione registrati non hanno raggiunto i pixel. + Fuso orario non registrato; uno scostamento UTC di {0} min è stato stimato dalla longitudine. + {0} fotogrammi non sono decodificabili. + Il bilanciamento del colore varia del {0:0.#}% tra un fotogramma e l'altro. + {0} fotogrammi sono completamente bruciati. + Serve l'analisi approfondita dei pixel, non ancora eseguita; nulla è stato cambiato. + Tempo di scatto o diaframma mancano nei metadati, quindi non si può decidere; nulla è stato cambiato. + Troppo poche coppie di fotogrammi per misurare il movimento; nulla è stato cambiato. + La vibrazione era misurabile solo sul {0}% dei fotogrammi (poca texture); nulla è stato cambiato. + La risoluzione della sorgente è sconosciuta; nulla è stato cambiato. + Solo {0} fotogrammi su {1} hanno un orario di scatto, quindi non è misurabile; nulla è stato cambiato. + Cantiere — {0} {1} {2} fps, temporizzazione adattiva + Tramonto holy grail — {0} {1} {2} fps, transizioni {3} + Cielo notturno — {0} {1} {2} fps, deflicker {3} + Cielo notturno — {0} {1} {2} fps, deflicker {3}, stabilizza + Social verticale {0}×{1} + Standard — {0} {1} {2} fps + {0} sessioni in {1} giorni con pause: temporizzazione adattiva in un file 1080p ampiamente compatibile. + {0} cambi di esposizione su una variazione di luce di {1} EV: transizioni morbide tra giorno e notte. + Stelle o cielo scuro nel {0}% dei fotogrammi: i gradienti scuri richiedono 10 bit e luminosità stabile. + Un ritaglio 9:16 per telefoni e social. + Impostazioni generali per questa sequenza. + La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% dell'altezza. + La sorgente è già in 16:9. + Sorgente verticale: il 9:16 riempie lo schermo di un telefono. + La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% della larghezza. + Lo sfarfallio è di {0} EV, sotto gli 0,02 EV visibili: il deflicker resta spento. + La luminosità si discosta di {0} EV dal suo andamento regolare: il deflicker elimina lo sfarfallio. + {0} fotogrammi neri, bianchi, duplicati o illeggibili lampeggerebbero o farebbero scattare il video: esclusi. + Cielo notturno: HEVC a 10 bit evita le bande nei gradienti scuri. + Il preset migliore per un'uscita {0}×{1} con i codificatori disponibili. + Inquadratura verticale: 1080×1920 per telefoni. + Il piano viene scalato perché i {0} fotogrammi durino {1} s a {2} fps. + La qualità del flusso bilanciata basta per la sfocatura di movimento e le anteprime. + I fotogrammi interpolati richiedono il movimento per pixel: qualità del flusso massima. + Movimento moderato ({0} px per fotogramma): la cadenza cinema di 24 fps dà una clip di {1} s. + Movimento lento o non misurato: a 30 fps la clip dura {0} s. + Movimento rapido ({0} px per fotogramma): a 24 fps rallenta; la clip dura {1} s. + {0} fotogrammi riempiono al meglio {1} s a {2} fps. + {0} fotogrammi: a 60 fps la clip dura {1} s. + Ripresa in più sessioni: a 30 fps la clip dura {0} s. + Solo {0} fotogrammi: a 24 fps la clip dura {1} s. + L'orizzonte è al {0}% dall'alto: il ritaglio lo porta sul terzo più vicino. + Il fotogramma {0} è nitido e ben esposto, senza alte luci bruciate. + {0} cambi di esposizione nei metadati (pixel non ancora verificati): ognuno viene distribuito su una transizione morbida. + Le impostazioni di esposizione non cambiano mai: nessuna transizione necessaria. + La fotocamera ha registrato {0} cambi di esposizione ma i pixel non ne mostrano: nessuna transizione necessaria. + {0} cambi di esposizione hanno raggiunto i pixel: ognuno viene distribuito su una transizione morbida. + L'esposizione dà già un angolo di {0}°, almeno i {1}° previsti: nessuna sfocatura sintetica necessaria. + Il contenuto si sposta solo di {0} px per fotogramma: la sfocatura sarebbe invisibile, quindi resta spenta. + Angolo reale {0}° e movimento di {1} px per fotogramma: la sfocatura a {2}° aggiunge scie di {3} px che nascondono gli scatti. + Orizzonte trovato con affidabilità del {0}%: cielo e terreno vengono corretti separatamente. + Cielo separato per luminosità con affidabilità del {0}%: cielo e terreno vengono corretti separatamente. + La separazione cielo/terreno è affidabile solo al {0}%: una curva unica per tutta l'immagine è più sicura. + Il codificatore {0} gestisce al massimo {1}×{2}. + {0} fotogrammi si decodificano solo come anteprime incorporate {1}×{2}, che limitano l'uscita. + La dimensione standard più grande entro la sorgente {0}×{1}. + 180° è l'aspetto cinematografico; l'angolo d'otturatore reale è {0}° (esposizione di {1} s ogni {2} s). + Vibrazione di {0} px alla risoluzione di uscita, ma compensarla ritaglia il {1}% dell'inquadratura: controlla il taglio. + Vibrazione misurata di {0} px alla risoluzione di uscita (al massimo 0,3 px): la fotocamera era stabile. + Vibrazione misurata di {0} px alla risoluzione di uscita (oltre 0,3 px): la stabilizzazione ritaglia il {1}% dell'area. + Smussare il percorso della fotocamera su {0} fotogrammi elimina la vibrazione e conserva le panoramiche volute. + Sfarfallio forte ({0} EV): ogni fotogramma viene portato sulla curva regolare. + Sfarfallio lieve ({0} EV): i fotogrammi affidabili conservano il 20% della propria variazione. + Gli intervalli variano di {0} s attorno a {1} s: la temporizzazione adattiva segue l'orario di scatto e rende il movimento uniforme. + {0} pause nella cadenza: la temporizzazione adattiva mantiene il ritmo fedele all'orario di scatto. + Intervallo costante di {0} s (variazione {1} s): ogni foto diventa un fotogramma del video. + Ripreso in {0} sessioni con pause fino a {1} h: la temporizzazione adattiva accorcia le pause e mantiene il ritmo. + {0} brevi pause, ma il movimento non è misurato o è rapido: la temporizzazione costante le salta in modo pulito. + {0} brevi pause e movimento regolare ({1} px per fotogramma): i fotogrammi interpolati riempiono le pause. + Un solo cambio di esposizione: una transizione di {0} fotogrammi lo rende graduale. + I cambi di esposizione distano {0} fotogrammi: transizioni lunghe la metà ({1} fotogrammi) non si sovrappongono mai. + Il bilanciamento del colore è stabile ({0}% tra fotogrammi): nessuno smussamento necessario. + Il bilanciamento del colore varia del {0}% tra fotogrammi: lo smussamento lo stabilizza e mantiene la deriva lenta. + Lo sfarfallio resta correlato per {0} fotogrammi: una finestra di {1} fotogrammi ne copre quattro volte tanto. + Lo sfarfallio varia su {0} fotogrammi: la finestra è limitata a {1} fotogrammi per conservare i veri cambi di luce. + Lo sfarfallio cambia da un fotogramma all'altro senza ritmo: la finestra robusta più corta, {0} fotogrammi, lo elimina. + Lo sfarfallio si ripete ogni {0} fotogrammi: una finestra di {1} fotogrammi media quattro cicli. + From d8d25f187741da096d440979c0380c9a50c17843 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:52:08 +0000 Subject: [PATCH 133/188] feat(advisor): add recommendations, apply, optimise and sequence presets Rules for timing, frame rate, motion blur, deflicker, regions, holy-grail transitions, white balance, stabilisation, aspect, output size and export preset, each with a localisable reason and confidence; Apply fills Auto values without touching manual ones; Optimise takes per-section module decisions and reports changes; content-driven presets round-trip as JSON. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Advisor/Advisor.cs | 91 ++++ src/Titano.Core/Advisor/AdvisorKeys.cs | 97 ++++ src/Titano.Core/Advisor/AdvisorRules.cs | 507 ++++++++++++++++++ src/Titano.Core/Advisor/AdvisorTypes.cs | 177 ++++++ src/Titano.Core/Advisor/ParameterBindings.cs | 137 +++++ src/Titano.Core/Advisor/SequencePresets.cs | 217 ++++++++ .../Advisor/AdvisorLocalizationTests.cs | 132 +++++ .../Titano.Core.Tests/Advisor/AdvisorTests.cs | 349 ++++++++++++ 8 files changed, 1707 insertions(+) create mode 100644 src/Titano.Core/Advisor/Advisor.cs create mode 100644 src/Titano.Core/Advisor/AdvisorKeys.cs create mode 100644 src/Titano.Core/Advisor/AdvisorRules.cs create mode 100644 src/Titano.Core/Advisor/AdvisorTypes.cs create mode 100644 src/Titano.Core/Advisor/ParameterBindings.cs create mode 100644 src/Titano.Core/Advisor/SequencePresets.cs create mode 100644 tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs create mode 100644 tests/Titano.Core.Tests/Advisor/AdvisorTests.cs diff --git a/src/Titano.Core/Advisor/Advisor.cs b/src/Titano.Core/Advisor/Advisor.cs new file mode 100644 index 00000000..40eca224 --- /dev/null +++ b/src/Titano.Core/Advisor/Advisor.cs @@ -0,0 +1,91 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Localization; +using Titano.Core.Project; + +namespace Titano.Core.Advisor; + +/// +/// The analysis advisor (BRIEF §10.3, §10.4): turns the light and deep analyses into explained recommendations +/// (), stores them as Auto values without touching manual ones (), and takes +/// the heavier per-section decisions on request (). Deterministic; every reason is a resource +/// key plus arguments. +/// +public static class Advisor +{ + /// + /// Recommendations for every parameter the rules cover (see ), in section order, plus + /// every finding of both analyses. Without a deep report, pixel-based parameters get missing-data recommendations. + /// + public static AdvisorResult Recommend(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context) + { + ArgumentNullException.ThrowIfNull(light); + ArgumentNullException.ThrowIfNull(context); + var findings = new List(light.Findings); + if (deep is not null) findings.AddRange(deep.Findings.Select(f => f.ToFinding())); + return new AdvisorResult(new AdvisorRules(light, deep, context).Run(), findings); + } + + /// + /// Fills , and of every + /// advised parameter. Manual values stay in force; missing data changes no value (its reason is stored only where no + /// advice exists yet). Plain, non-Auto settings are left to . + /// + public static ProjectSettings Apply(ProjectSettings settings, AdvisorResult result) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(result); + foreach (var recommendation in result.Recommendations) + { + if (ParameterBindings.Find(recommendation.Parameter)?.Advise is { } advise) settings = advise(settings, recommendation); + } + return settings; + } + + /// + /// "Optimise section" (BRIEF §10.4): applies the section's advice, returns module switches (deflicker, regions, holy + /// grail, white balance, motion blur, stabilisation, timing mode, export preset) to Auto where the advice differs + /// from the value in force, and takes the plain decisions (fit-to duration, hero frame when unset, exclusions added + /// to the user's, crop placement when centred, output size cap). Missing data changes nothing. + /// Returns every effective value that changed, with its reason. + /// + public static OptimiseResult Optimise(AdvisorSection section, ProjectSettings settings, AdvisorResult result) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(result); + var optimised = settings; + var changes = new List(); + foreach (var binding in ParameterBindings.All) + { + if (binding.Section != section || result.Find(binding.Parameter) is not { } recommendation) continue; + if (binding.Advise is { } advise) optimised = advise(optimised, recommendation); + if (recommendation.Value is null) continue; + if (binding.IsModuleSwitch && !ParameterBindings.SameValue(binding.Effective(optimised), recommendation.Value)) optimised = binding.ResetToAuto!(optimised); + if (binding.Set is { } set) optimised = set(optimised, recommendation); + var before = binding.Effective(settings); + var after = binding.Effective(optimised); + if (!ParameterBindings.SameValue(before, after)) + changes.Add(new SettingChange(binding.Parameter, before, after, recommendation.ReasonKey, recommendation.ReasonArgs)); + } + return new OptimiseResult(optimised, changes); + } + + /// Localised text of a recommendation in the current UI culture. + public static string Explain(Recommendation recommendation) + { + ArgumentNullException.ThrowIfNull(recommendation); + return Loc.L(recommendation.ReasonKey, [.. recommendation.ReasonArgs]); + } + + /// + /// Localised text of a stored reason (/): numeric + /// arguments, stored culture-neutral, are parsed back so they format with the current culture. + /// + public static string Explain(string reasonKey, IReadOnlyList? reasonArgs) + { + ArgumentNullException.ThrowIfNull(reasonKey); + var args = (reasonArgs ?? []).Select(a => double.TryParse(a, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? (object)number : a).ToArray(); + return Loc.L(reasonKey, args); + } +} diff --git a/src/Titano.Core/Advisor/AdvisorKeys.cs b/src/Titano.Core/Advisor/AdvisorKeys.cs new file mode 100644 index 00000000..26688e9a --- /dev/null +++ b/src/Titano.Core/Advisor/AdvisorKeys.cs @@ -0,0 +1,97 @@ +namespace Titano.Core.Advisor; + +/// +/// Resource keys (area Advisor) of the advisor's reasons, missing-data notes and sequence presets. Each key is +/// written through LocKey(…) so Titano.Tools i18n check verifies it exists in every required culture; +/// the resx comment of each key says what its placeholders hold. +/// +public static class AdvisorKeys +{ + /// Every missing-data key starts with this; such a reason never carries a value. + public const string MissingPrefix = "Advisor.Missing."; + + public static string MissingTimestamps { get; } = LocKey("Advisor.Missing.Timestamps"); + public static string MissingExposure { get; } = LocKey("Advisor.Missing.Exposure"); + public static string MissingDeep { get; } = LocKey("Advisor.Missing.Deep"); + public static string MissingMotion { get; } = LocKey("Advisor.Missing.Motion"); + public static string MissingShake { get; } = LocKey("Advisor.Missing.Shake"); + public static string MissingSourceSize { get; } = LocKey("Advisor.Missing.SourceSize"); + + public static string TimingSessions { get; } = LocKey("Advisor.Reason.Timing.Sessions"); + public static string TimingIrregular { get; } = LocKey("Advisor.Reason.Timing.Irregular"); + public static string TimingSparseGapsSmooth { get; } = LocKey("Advisor.Reason.Timing.SparseGapsSmooth"); + public static string TimingSparseGaps { get; } = LocKey("Advisor.Reason.Timing.SparseGaps"); + public static string TimingManyGaps { get; } = LocKey("Advisor.Reason.Timing.ManyGaps"); + public static string TimingRegular { get; } = LocKey("Advisor.Reason.Timing.Regular"); + + public static string FrameRateFit { get; } = LocKey("Advisor.Reason.FrameRate.Fit"); + public static string FrameRateShort { get; } = LocKey("Advisor.Reason.FrameRate.Short"); + public static string FrameRateLong { get; } = LocKey("Advisor.Reason.FrameRate.Long"); + public static string FrameRateSessions { get; } = LocKey("Advisor.Reason.FrameRate.Sessions"); + public static string FrameRateFastMotion { get; } = LocKey("Advisor.Reason.FrameRate.FastMotion"); + public static string FrameRateCinematic { get; } = LocKey("Advisor.Reason.FrameRate.Cinematic"); + public static string FrameRateDefault { get; } = LocKey("Advisor.Reason.FrameRate.Default"); + public static string FitToSeconds { get; } = LocKey("Advisor.Reason.FitToSeconds"); + + public static string ShutterAngle { get; } = LocKey("Advisor.Reason.ShutterAngle"); + public static string MotionBlurOn { get; } = LocKey("Advisor.Reason.MotionBlur.On"); + public static string MotionBlurAlready { get; } = LocKey("Advisor.Reason.MotionBlur.Already"); + public static string MotionBlurLittle { get; } = LocKey("Advisor.Reason.MotionBlur.Little"); + public static string FlowBest { get; } = LocKey("Advisor.Reason.Flow.Best"); + public static string FlowBalanced { get; } = LocKey("Advisor.Reason.Flow.Balanced"); + public static string StabilizeOn { get; } = LocKey("Advisor.Reason.Stabilize.On"); + public static string StabilizeHighCrop { get; } = LocKey("Advisor.Reason.Stabilize.HighCrop"); + public static string StabilizeOff { get; } = LocKey("Advisor.Reason.Stabilize.Off"); + public static string StabilizeSmoothing { get; } = LocKey("Advisor.Reason.Stabilize.Smoothing"); + + public static string DeflickerOn { get; } = LocKey("Advisor.Reason.Deflicker.On"); + public static string DeflickerOff { get; } = LocKey("Advisor.Reason.Deflicker.Off"); + public static string WindowPeriod { get; } = LocKey("Advisor.Reason.Window.Period"); + public static string WindowCorrelation { get; } = LocKey("Advisor.Reason.Window.Correlation"); + public static string WindowMinimum { get; } = LocKey("Advisor.Reason.Window.Minimum"); + public static string WindowMaximum { get; } = LocKey("Advisor.Reason.Window.Maximum"); + public static string StrengthFull { get; } = LocKey("Advisor.Reason.Strength.Full"); + public static string StrengthPartial { get; } = LocKey("Advisor.Reason.Strength.Partial"); + public static string RegionsHorizon { get; } = LocKey("Advisor.Reason.Regions.Horizon"); + public static string RegionsLuminance { get; } = LocKey("Advisor.Reason.Regions.Luminance"); + public static string RegionsOff { get; } = LocKey("Advisor.Reason.Regions.Off"); + public static string HolyGrailReceived { get; } = LocKey("Advisor.Reason.HolyGrail.Received"); + public static string HolyGrailNotReceived { get; } = LocKey("Advisor.Reason.HolyGrail.NotReceived"); + public static string HolyGrailNone { get; } = LocKey("Advisor.Reason.HolyGrail.None"); + public static string HolyGrailMetadata { get; } = LocKey("Advisor.Reason.HolyGrail.Metadata"); + public static string TransitionSpacing { get; } = LocKey("Advisor.Reason.Transition.Spacing"); + public static string TransitionSingle { get; } = LocKey("Advisor.Reason.Transition.Single"); + public static string WhiteBalanceOn { get; } = LocKey("Advisor.Reason.WhiteBalance.On"); + public static string WhiteBalanceOff { get; } = LocKey("Advisor.Reason.WhiteBalance.Off"); + + public static string AspectLandscape { get; } = LocKey("Advisor.Reason.Aspect.Landscape"); + public static string AspectWide { get; } = LocKey("Advisor.Reason.Aspect.Wide"); + public static string AspectNative { get; } = LocKey("Advisor.Reason.Aspect.Native"); + public static string AspectPortrait { get; } = LocKey("Advisor.Reason.Aspect.Portrait"); + public static string FramingHorizon { get; } = LocKey("Advisor.Reason.Framing.Horizon"); + + public static string Hero { get; } = LocKey("Advisor.Reason.Hero"); + public static string Exclude { get; } = LocKey("Advisor.Reason.Exclude"); + + public static string ResolutionSource { get; } = LocKey("Advisor.Reason.Resolution.Source"); + public static string ResolutionPreview { get; } = LocKey("Advisor.Reason.Resolution.Preview"); + public static string ResolutionCodec { get; } = LocKey("Advisor.Reason.Resolution.Codec"); + public static string ExportNight { get; } = LocKey("Advisor.Reason.Export.Night"); + public static string ExportStandard { get; } = LocKey("Advisor.Reason.Export.Standard"); + public static string ExportVertical { get; } = LocKey("Advisor.Reason.Export.Vertical"); + + public static string PresetNightSky { get; } = LocKey("Advisor.Preset.NightSky"); + public static string PresetNightSkyStabilised { get; } = LocKey("Advisor.Preset.NightSkyStabilised"); + public static string PresetHolyGrail { get; } = LocKey("Advisor.Preset.HolyGrail"); + public static string PresetConstruction { get; } = LocKey("Advisor.Preset.Construction"); + public static string PresetSocialVertical { get; } = LocKey("Advisor.Preset.SocialVertical"); + public static string PresetStandard { get; } = LocKey("Advisor.Preset.Standard"); + public static string PresetReasonNightSky { get; } = LocKey("Advisor.PresetReason.NightSky"); + public static string PresetReasonHolyGrail { get; } = LocKey("Advisor.PresetReason.HolyGrail"); + public static string PresetReasonConstruction { get; } = LocKey("Advisor.PresetReason.Construction"); + public static string PresetReasonSocialVertical { get; } = LocKey("Advisor.PresetReason.SocialVertical"); + public static string PresetReasonStandard { get; } = LocKey("Advisor.PresetReason.Standard"); + + /// Identity function that marks a literal as a resource key for the i18n check. + private static string LocKey(string key) => key; +} diff --git a/src/Titano.Core/Advisor/AdvisorRules.cs b/src/Titano.Core/Advisor/AdvisorRules.cs new file mode 100644 index 00000000..4c3888ab --- /dev/null +++ b/src/Titano.Core/Advisor/AdvisorRules.cs @@ -0,0 +1,507 @@ +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Export; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Advisor; + +/// +/// The recommendation rules of BRIEF §10.3, one method per parameter group. Output size is decided first because +/// shake and motion are judged in output pixels: deep-analysis pixels (source resolution) are scaled by output long +/// edge / source long edge. Every rule states its thresholds; missing inputs yield a null value with a +/// reason. +/// +internal sealed class AdvisorRules +{ + /// Visible shake threshold in output pixels (BRIEF §10.3). + public const double ShakeThresholdPx = 0.3; + + /// Film-look target shutter angle in degrees. + public const double TargetShutterAngle = 180; + + /// Path smoothing σ in frames (as StabilizerOptions.SmoothingSigma). + public const double StabilizeSigma = 12; + + private const double RegionConfidence = 0.6; + private const double StrongFlickerEv = 0.08; + private const double CropCostLimit = 0.15; + + private static readonly (int Width, int Height)[] Landscape = [(3840, 2160), (2560, 1440), (1920, 1080), (1280, 720)]; + private static readonly (int Width, int Height)[] Portrait = [(1080, 1920), (720, 1280)]; + + private readonly LightAnalysisReport _light; + private readonly DeepAnalysisReport? _deep; + private readonly SequenceContext _context; + private readonly List _result = []; + private readonly int _frames; + private readonly (int Width, int Height) _source; + private (int Width, int Height) _output; + private TimingMode? _timing; + + public AdvisorRules(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context) + { + _light = light; + _deep = deep; + _context = context; + _frames = context.FrameCount > 0 ? context.FrameCount : light.FrameCount; + _source = context.SourceWidth > 0 && context.SourceHeight > 0 + ? (context.SourceWidth, context.SourceHeight) + : light.DominantSize ?? (deep is { SourceWidth: > 0, SourceHeight: > 0 } ? (deep.SourceWidth, deep.SourceHeight) : (0, 0)); + } + + public List Run() + { + Export(); + Frames(); + Timing(); + Exposure(); + Motion(); + Camera(); + return [.. _result.OrderBy(r => r.Section)]; + } + + /// Converts deep-analysis pixels (source resolution) to output pixels. + private double ToOutput(double sourcePixels) + { + var deepLong = _deep is { SourceWidth: > 0, SourceHeight: > 0 } d ? int.Max(d.SourceWidth, d.SourceHeight) : _deep?.AnalysisLongEdge ?? 0; + var outputLong = int.Max(_output.Width, _output.Height); + return deepLong > 0 && outputLong > 0 ? sourcePixels * outputLong / deepLong : sourcePixels; + } + + private void Add(AdvisorSection section, string parameter, object? value, double confidence, string reason, params object[] args) => + _result.Add(new Recommendation(section, parameter, value, value is null ? 0 : double.Round(confidence, 2), reason, args)); + + private void Missing(AdvisorSection section, string parameter, string reason, params object[] args) => Add(section, parameter, null, 0, reason, args); + + /// + /// Output size and preset: standard 16:9 sizes (9:16 for portrait sources; 4K UHD at most) are tried from the + /// largest that fits inside the source cropped to that aspect — or inside the embedded previews when frames decode + /// only as previews — downwards, and the first whose preset the encoders can produce wins. Preset per size: 10-bit + /// HEVC archive for star fields and night skies (dark gradients band in 8 bit), HEVC, then H.264 at 4K; the H.264 + /// preset of the size below 4K; vertical social for portrait sources. + /// + private void Export() + { + if (_source.Width <= 0 || _source.Height <= 0) + { + Missing(AdvisorSection.Export, AdvisorParameters.Resolution, AdvisorKeys.MissingSourceSize); + Missing(AdvisorSection.Export, AdvisorParameters.ExportPreset, AdvisorKeys.MissingSourceSize); + return; + } + var portrait = _source.Height > _source.Width; + var ratio = portrait ? 9.0 / 16 : 16.0 / 9; + var cap = Fit(_source.Width, _source.Height, ratio); + var reason = AdvisorKeys.ResolutionSource; + object[] args = [_source.Width, _source.Height]; + if (_context is { PreviewOnlyCount: > 0, PreviewWidth: > 0, PreviewHeight: > 0 }) + { + var preview = Fit(_context.PreviewWidth, _context.PreviewHeight, ratio); + if (preview.Width < cap.Width) + { + cap = preview; + reason = AdvisorKeys.ResolutionPreview; + args = [_context.PreviewOnlyCount, _context.PreviewWidth, _context.PreviewHeight]; + } + } + + var sizes = (portrait ? Portrait : Landscape).Where(s => s.Width <= cap.Width && s.Height <= cap.Height).ToList(); + if (sizes.Count == 0) sizes.Add((int.Max(2, cap.Width & ~1), int.Max(2, cap.Height & ~1))); + EncoderCapability? limiting = null; + foreach (var size in sizes) + { + foreach (var (preset, key) in Candidates(size, portrait)) + { + var codec = ExportPresets.Find(preset)!.Codec; + if (!Fits(codec, size, out var capability)) + { + limiting ??= capability; + continue; + } + _output = size; + if (limiting is not null) + { + reason = AdvisorKeys.ResolutionCodec; + args = [limiting.Name, limiting.MaxWidth, limiting.MaxHeight]; + } + Add(AdvisorSection.Export, AdvisorParameters.Resolution, ParameterBindings.Size(size.Width, size.Height), 0.9, reason, args); + if (key == AdvisorKeys.ExportStandard) Add(AdvisorSection.Export, AdvisorParameters.ExportPreset, preset, 0.7, key, size.Width, size.Height); + else Add(AdvisorSection.Export, AdvisorParameters.ExportPreset, preset, key == AdvisorKeys.ExportNight ? 0.8 : 0.7, key); + return; + } + } + // No listed encoder can produce any standard size: keep the source-derived size and leave the preset alone. + _output = sizes[0]; + Add(AdvisorSection.Export, AdvisorParameters.Resolution, ParameterBindings.Size(_output.Width, _output.Height), 0.5, reason, args); + } + + /// Presets for one output size in order of preference, with the reason each one carries. + private IEnumerable<(string Preset, string Reason)> Candidates((int Width, int Height) size, bool portrait) + { + if (portrait) + { + yield return ("vertical-1080x1920", AdvisorKeys.ExportVertical); + yield break; + } + if (size.Width >= 3840) + { + if (IsNightSky() && HasTenBitHevc()) yield return ("4k-hevc10-archive", AdvisorKeys.ExportNight); + yield return ("4k-hevc", AdvisorKeys.ExportStandard); + yield return ("4k-h264", AdvisorKeys.ExportStandard); + } + else if (size.Width >= 2560) yield return ("1440p-h264", AdvisorKeys.ExportStandard); + else if (size.Width >= 1920) yield return ("1080p-h264", AdvisorKeys.ExportStandard); + else yield return ("720p-preview", AdvisorKeys.ExportStandard); + } + + /// Whether an encoder for handles the size (either orientation); with no + /// capability list everything fits. is the codec's largest capability, if any. + private bool Fits(VideoCodec codec, (int Width, int Height) size, out EncoderCapability? largest) + { + largest = null; + if (_context.Codecs.Count == 0) return true; + var available = _context.Codecs.Where(c => c.Codec == codec).ToList(); + largest = available.MaxBy(c => (long)c.MaxWidth * c.MaxHeight); + return available.Any(c => c.MaxWidth <= 0 || c.MaxHeight <= 0 + || (size.Width <= c.MaxWidth && size.Height <= c.MaxHeight) + || (size.Height <= c.MaxWidth && size.Width <= c.MaxHeight)); + } + + /// Hero frame from the deep analysis; exclusion of undecodable, black, white and duplicate frames. + private void Frames() + { + if (_deep is null) + { + Missing(AdvisorSection.Frames, AdvisorParameters.Hero, AdvisorKeys.MissingDeep); + Missing(AdvisorSection.Frames, AdvisorParameters.Excluded, AdvisorKeys.MissingDeep); + return; + } + if (_deep.HeroIndex is { } hero) Add(AdvisorSection.Frames, AdvisorParameters.Hero, hero, 0.6, AdvisorKeys.Hero, hero + 1); + var excluded = _deep.Issues.Excludable(); + if (excluded.Length > 0) Add(AdvisorSection.Frames, AdvisorParameters.Excluded, excluded, 0.9, AdvisorKeys.Exclude, excluded.Length); + } + + /// + /// Timing mode, in order: several capture sessions (pauses ≥ the session gap) → Adaptive; jitter above 10 % of the + /// median interval → Adaptive; gaps that are sparse (≤ 2 % of intervals, each ≤ 10 × median) with smooth measured + /// motion (95th percentile ≤ 1 % of the long edge per frame) → Interpolated, or Constant when motion is unknown or + /// fast; denser gaps → Adaptive; otherwise Constant. Frame rate, in order: "fit to N s" target → the standard rate + /// nearest frames/N; under 240 frames → 24 (clip ≥ 10 s); over 10 min at 30 fps → 60; several sessions → 30; fast + /// motion (≥ 1 % of the long edge per frame) → 24; measured moderate motion (≥ 0.2 %) → 24; otherwise 30. + /// + private void Timing() + { + if (_light.MedianIntervalSeconds is not { } median) + { + Missing(AdvisorSection.Timing, AdvisorParameters.TimingMode, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount); + _timing = null; + } + else + { + ChooseTimingMode(median); + } + FrameRate(); + } + + private void ChooseTimingMode(double median) + { + var jitter = _light.JitterSeconds ?? 0; + var breaks = _light.Intervals.Where(i => i.Kind == IntervalKind.SessionBreak).ToList(); + var gaps = _light.Intervals.Where(i => i.Kind == IntervalKind.Gap).ToList(); + var section = AdvisorSection.Timing; + var parameter = AdvisorParameters.TimingMode; + if (_light.Sessions.Count >= 2 && breaks.Count > 0) + { + _timing = TimingMode.Adaptive; + Add(section, parameter, _timing, 0.85, AdvisorKeys.TimingSessions, _light.Sessions.Count, R(breaks.Max(b => b.Seconds) / 3600, 1)); + } + else if (jitter > 0.1 * median) + { + _timing = TimingMode.Adaptive; + Add(section, parameter, _timing, 0.7, AdvisorKeys.TimingIrregular, R(jitter, 2), R(median, 2)); + } + else if (gaps.Count > 0) + { + var sparse = gaps.Count <= double.Max(1, 0.02 * _light.Intervals.Count) && gaps.All(g => g.Seconds <= 10 * median); + var motion = MotionFraction(); + if (sparse && motion is <= 0.01) + { + _timing = TimingMode.Interpolated; + Add(section, parameter, _timing, 0.65, AdvisorKeys.TimingSparseGapsSmooth, gaps.Count, R(ToOutput(_deep!.Motion.P95Px!.Value), 1)); + } + else if (sparse) + { + _timing = TimingMode.Constant; + Add(section, parameter, _timing, 0.6, AdvisorKeys.TimingSparseGaps, gaps.Count); + } + else + { + _timing = TimingMode.Adaptive; + Add(section, parameter, _timing, 0.7, AdvisorKeys.TimingManyGaps, gaps.Count); + } + } + else + { + _timing = TimingMode.Constant; + Add(section, parameter, _timing, 0.9, AdvisorKeys.TimingRegular, R(median, 2), R(jitter, 2)); + } + } + + private void FrameRate() + { + var section = AdvisorSection.Timing; + var parameter = AdvisorParameters.FrameRate; + if (_frames <= 0) return; + double Seconds(int fps) => R((double)_frames / fps, 1); + var motion = MotionFraction(); + if (_context.TargetDurationSeconds is > 0 and var target) + { + var wanted = _frames / target; + var fps = new[] { 24, 25, 30, 60 }.MinBy(f => double.Abs(double.Log(f / wanted))); + Add(section, parameter, Rate(fps), 0.8, AdvisorKeys.FrameRateFit, _frames, R(target, 1), fps); + Add(section, AdvisorParameters.FitToSeconds, target, 0.8, AdvisorKeys.FitToSeconds, _frames, R(target, 1), fps); + } + else if (_frames < 240) Add(section, parameter, Rate(24), 0.7, AdvisorKeys.FrameRateShort, _frames, Seconds(24)); + else if (_frames > 30 * 600) Add(section, parameter, Rate(60), 0.6, AdvisorKeys.FrameRateLong, _frames, Seconds(60)); + else if (_light.Sessions.Count >= 2) Add(section, parameter, Rate(30), 0.7, AdvisorKeys.FrameRateSessions, Seconds(30)); + else if (motion >= 0.01) Add(section, parameter, Rate(24), 0.6, AdvisorKeys.FrameRateFastMotion, R(ToOutput(_deep!.Motion.P95Px!.Value), 1), Seconds(24)); + else if (motion >= 0.002) Add(section, parameter, Rate(24), 0.5, AdvisorKeys.FrameRateCinematic, R(ToOutput(_deep!.Motion.P95Px!.Value), 1), Seconds(24)); + else Add(section, parameter, Rate(30), 0.5, AdvisorKeys.FrameRateDefault, Seconds(30)); + } + + /// + /// Deflicker on when the step-free luminance deviates from its smooth curve by ≥ 0.02 EV RMS; window = the + /// spectrum's 4 × flicker period (or correlation length), odd, clamped to 15–151 (the reason says when it was + /// clamped); strength 1 for ≥ 0.08 EV, else 0.8. + /// Regions follow the mask method when its confidence is ≥ 0.6. Holy grail on when metadata exposure steps reached + /// the pixels (all metadata steps when pixels were not analysed); transition = half the median spacing of the + /// received steps (12 frames for a single step). White-balance smoothing on when the colour ratios jitter by + /// ≥ 0.01 log2 RMS around their smoothed course. + /// + private void Exposure() + { + HolyGrail(); + var section = AdvisorSection.Exposure; + if (_deep is null) + { + foreach (var p in new[] { AdvisorParameters.Deflicker, AdvisorParameters.DeflickerWindow, AdvisorParameters.DeflickerStrength, AdvisorParameters.Regions, AdvisorParameters.WhiteBalanceSmoothing }) + Missing(section, p, AdvisorKeys.MissingDeep); + return; + } + var flicker = _deep.Flicker; + var amplitude = R(flicker.AmplitudeEv, 3); + if (flicker.AmplitudeEv >= DeepSequenceAnalysis.VisibleFlickerEv) + Add(section, AdvisorParameters.Deflicker, true, double.Min(0.95, 0.5 + 10 * flicker.AmplitudeEv), AdvisorKeys.DeflickerOn, amplitude); + else Add(section, AdvisorParameters.Deflicker, false, 0.7, AdvisorKeys.DeflickerOff, amplitude); + var scale = flicker.PeriodFrames ?? flicker.CorrelationLength; + var window = flicker.RecommendedWindow; + if (4 * scale < FlickerSpectrumOptions.Default.MinimumWindow) Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowMinimum, window); + else if (4 * scale > FlickerSpectrumOptions.Default.MaximumWindow) Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowMaximum, R(scale, 1), window); + else if (flicker.PeriodFrames is not null) Add(section, AdvisorParameters.DeflickerWindow, window, 0.75, AdvisorKeys.WindowPeriod, R(scale, 1), window); + else Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowCorrelation, R(scale, 1), window); + if (flicker.AmplitudeEv >= StrongFlickerEv) Add(section, AdvisorParameters.DeflickerStrength, 1.0, 0.6, AdvisorKeys.StrengthFull, amplitude); + else Add(section, AdvisorParameters.DeflickerStrength, 0.8, 0.6, AdvisorKeys.StrengthPartial, amplitude); + + if (_deep.Regions is not { } regions) Missing(section, AdvisorParameters.Regions, AdvisorKeys.MissingDeep); + else + { + var percent = R(100 * regions.Confidence, 0); + if (regions.Confidence < RegionConfidence) Add(section, AdvisorParameters.Regions, RegionMode.Off, 0.7, AdvisorKeys.RegionsOff, percent); + else if (regions.Method == RegionMethod.Horizon) Add(section, AdvisorParameters.Regions, RegionMode.Horizon, regions.Confidence, AdvisorKeys.RegionsHorizon, percent); + else Add(section, AdvisorParameters.Regions, RegionMode.Luminance, regions.Confidence, AdvisorKeys.RegionsLuminance, percent); + } + + var jitter = _deep.WhiteBalance.JitterLog2; + var jitterPercent = R(100 * (double.Exp2(jitter) - 1), 1); + if (jitter >= DeepSequenceAnalysis.VisibleWhiteBalanceJitter) Add(section, AdvisorParameters.WhiteBalanceSmoothing, true, 0.7, AdvisorKeys.WhiteBalanceOn, jitterPercent); + else Add(section, AdvisorParameters.WhiteBalanceSmoothing, false, 0.7, AdvisorKeys.WhiteBalanceOff, jitterPercent); + } + + private void HolyGrail() + { + var section = AdvisorSection.Exposure; + if (!_light.ExposureValues.Any(v => v is not null)) + { + Missing(section, AdvisorParameters.HolyGrail, AdvisorKeys.MissingExposure); + Missing(section, AdvisorParameters.TransitionLength, AdvisorKeys.MissingExposure); + return; + } + if (_deep is { Exposure: var exposure }) + { + if (exposure.MetadataSteps == 0) Add(section, AdvisorParameters.HolyGrail, false, 0.9, AdvisorKeys.HolyGrailNone); + else if (exposure.ReceivedSteps == 0) Add(section, AdvisorParameters.HolyGrail, false, 0.8, AdvisorKeys.HolyGrailNotReceived, exposure.MetadataSteps); + else + { + Add(section, AdvisorParameters.HolyGrail, true, 0.85, AdvisorKeys.HolyGrailReceived, exposure.ReceivedSteps); + Transition(exposure.TypicalSpacing, exposure.TransitionLength!.Value, 0.8); + } + return; + } + if (_light.ExposureSteps.Count == 0) + { + Add(section, AdvisorParameters.HolyGrail, false, 0.9, AdvisorKeys.HolyGrailNone); + return; + } + Add(section, AdvisorParameters.HolyGrail, true, 0.6, AdvisorKeys.HolyGrailMetadata, _light.ExposureSteps.Count); + var spacing = _light.TypicalStepDistance; + var length = spacing is { } s ? int.Max(2, (int)double.Round(s / 2)) : HolyGrailOptions.Default.SingleStepTransitionFrames; + Transition(spacing, length, 0.5); + } + + private void Transition(double? spacing, int length, double confidence) + { + if (spacing is { } s) Add(AdvisorSection.Exposure, AdvisorParameters.TransitionLength, length, confidence, AdvisorKeys.TransitionSpacing, R(s, 0), length); + else Add(AdvisorSection.Exposure, AdvisorParameters.TransitionLength, length, confidence, AdvisorKeys.TransitionSingle, length); + } + + /// + /// Target shutter angle 180° (film look); real angle = 360 × median exposure / median interval. Motion blur off when + /// the real angle already reaches the target or the moving content (95th-percentile flow, output pixels) moves + /// under 1 px per frame; otherwise on, adding √(180² − real²)/360 × motion px of trail. Flow quality Best for + /// interpolated timing (per-pixel vectors), else Balanced. Stabilisation on when the shake RMS exceeds 0.3 output + /// pixels (lower confidence when hiding it costs over 15 % of the frame); path smoothing σ = 12 frames. + /// + private void Motion() + { + var section = AdvisorSection.Motion; + var interval = _light.MedianIntervalSeconds; + var exposure = _context.MedianExposureSeconds; + if (interval is null) + { + Missing(section, AdvisorParameters.TargetShutterAngle, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount); + Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount); + } + else if (exposure is null) + { + Missing(section, AdvisorParameters.TargetShutterAngle, AdvisorKeys.MissingExposure); + Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingExposure); + } + else + { + var real = double.Min(360, 360 * exposure.Value / interval.Value); + Add(section, AdvisorParameters.TargetShutterAngle, TargetShutterAngle, 0.8, AdvisorKeys.ShutterAngle, R(real, 0), Significant(exposure.Value), R(interval.Value, 2)); + MotionBlur(real); + } + + var best = _timing == TimingMode.Interpolated; + Add(section, AdvisorParameters.FlowQuality, best ? FlowQualitySetting.Best : FlowQualitySetting.Balanced, 0.6, best ? AdvisorKeys.FlowBest : AdvisorKeys.FlowBalanced); + Stabilize(); + } + + private void MotionBlur(double real) + { + var section = AdvisorSection.Motion; + if (real >= TargetShutterAngle) + { + Add(section, AdvisorParameters.MotionBlur, false, 0.9, AdvisorKeys.MotionBlurAlready, R(real, 0), TargetShutterAngle); + return; + } + if (_deep is null) + { + Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingDeep); + return; + } + if (_deep.Motion.P95Px is not { } p95) + { + Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingMotion); + return; + } + var motion = ToOutput(p95); + if (motion < 1) + { + Add(section, AdvisorParameters.MotionBlur, false, 0.8, AdvisorKeys.MotionBlurLittle, R(motion, 1)); + return; + } + var trail = motion * double.Sqrt(TargetShutterAngle * TargetShutterAngle - real * real) / 360; + Add(section, AdvisorParameters.MotionBlur, true, 0.75, AdvisorKeys.MotionBlurOn, R(real, 0), R(motion, 1), TargetShutterAngle, R(trail, 1)); + } + + private void Stabilize() + { + var section = AdvisorSection.Motion; + if (_deep is null) + { + Missing(section, AdvisorParameters.Stabilize, AdvisorKeys.MissingDeep); + Missing(section, AdvisorParameters.StabilizeSmoothing, AdvisorKeys.MissingDeep); + return; + } + var shake = _deep.Shake; + if (shake.MeasuredFraction < 0.5) + { + Missing(section, AdvisorParameters.Stabilize, AdvisorKeys.MissingShake, R(100 * shake.MeasuredFraction, 0)); + return; + } + var rms = ToOutput(shake.RmsPx); + var crop = R(100 * shake.CropCost, 1); + if (rms <= ShakeThresholdPx) Add(section, AdvisorParameters.Stabilize, false, 0.8, AdvisorKeys.StabilizeOff, R(rms, 2)); + else if (shake.CropCost <= CropCostLimit) Add(section, AdvisorParameters.Stabilize, true, 0.8, AdvisorKeys.StabilizeOn, R(rms, 2), crop); + else Add(section, AdvisorParameters.Stabilize, true, 0.5, AdvisorKeys.StabilizeHighCrop, R(rms, 2), crop); + Add(section, AdvisorParameters.StabilizeSmoothing, StabilizeSigma, 0.6, AdvisorKeys.StabilizeSmoothing, StabilizeSigma); + } + + /// + /// Aspect 16:9 for landscape sources (the reason says how much height or width the crop keeps), 9:16 for portrait + /// ones. When a confident horizon exists and the crop gives up + /// height, the crop is placed so the horizon sits on the nearest third of the output frame (recommended only when the + /// placement moves at least a fifth of the slack away from centred). + /// + private void Camera() + { + var section = AdvisorSection.Camera; + if (_source.Width <= 0 || _source.Height <= 0) + { + Missing(section, AdvisorParameters.Aspect, AdvisorKeys.MissingSourceSize); + return; + } + if (_source.Height > _source.Width) + { + Add(section, AdvisorParameters.Aspect, "9:16", 0.7, AdvisorKeys.AspectPortrait); + return; + } + var ratio = (double)_source.Width / _source.Height / (16.0 / 9); + var kept = double.Min(1, ratio); + if (double.Abs(ratio - 1) < 0.01) Add(section, AdvisorParameters.Aspect, "16:9", 0.9, AdvisorKeys.AspectNative); + else if (ratio < 1) Add(section, AdvisorParameters.Aspect, "16:9", 0.7, AdvisorKeys.AspectLandscape, _source.Width, _source.Height, R(100 * ratio, 0)); + else Add(section, AdvisorParameters.Aspect, "16:9", 0.6, AdvisorKeys.AspectWide, _source.Width, _source.Height, R(100 / ratio, 0)); + + if (kept >= 0.99 || _deep?.Regions is not { Method: RegionMethod.Horizon, Confidence: >= RegionConfidence, Horizon: { Length: > 0 } horizon }) return; + var row = horizon.Average(); + var slack = 1 - kept; + var third = double.Abs(row - (slack / 2 + kept / 3)) <= double.Abs(row - (slack / 2 + 2 * kept / 3)) ? 1.0 / 3 : 2.0 / 3; + var top = double.Clamp(row - third * kept, 0, slack); + var offset = R(2 * top / slack - 1, 2); + if (double.Abs(offset) >= 0.2) Add(section, AdvisorParameters.OffsetY, offset, 0.5, AdvisorKeys.FramingHorizon, R(100 * row, 0)); + } + + /// Night content: a star field, or a sequence the deep analysis or GPS phases call night. + private bool IsNightSky() => _deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night); + + /// Speed of moving content as a fraction of the frame's long edge per frame; null without motion data. + private double? MotionFraction() + { + if (_deep?.Motion.P95Px is not { } p95) return null; + var deepLong = _deep.SourceWidth > 0 ? int.Max(_deep.SourceWidth, _deep.SourceHeight) : _deep.AnalysisLongEdge; + return deepLong > 0 ? p95 / deepLong : null; + } + + private bool HasTenBitHevc() => _context.Codecs.Count == 0 || _context.Codecs.Any(c => c.Codec == VideoCodec.Hevc && c.SupportsTenBit); + + private static (int Width, int Height) Fit(int width, int height, double ratio) + { + var crop = AspectRatio.FitCrop(RectD.FromSize(width, height), ratio); + return ((int)double.Floor(crop.Width + 1e-9), (int)double.Floor(crop.Height + 1e-9)); + } + + private static string Rate(int fps) => fps.ToString(CultureInfo.InvariantCulture); + + private static double R(double value, int decimals) => double.Round(value, decimals, MidpointRounding.AwayFromZero); + + private static double Significant(double value) + { + if (!(value > 0)) return value; + var decimals = 2 - (int)double.Floor(double.Log10(value)); + return decimals is >= 0 and <= 15 ? R(value, decimals) : value; + } +} diff --git a/src/Titano.Core/Advisor/AdvisorTypes.cs b/src/Titano.Core/Advisor/AdvisorTypes.cs new file mode 100644 index 00000000..427dca10 --- /dev/null +++ b/src/Titano.Core/Advisor/AdvisorTypes.cs @@ -0,0 +1,177 @@ +using Titano.Core.Analysis; +using Titano.Core.Mathematics; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Advisor; + +/// Sequence-editor section a recommendation belongs to (BRIEF §12.3). +public enum AdvisorSection +{ + Frames, + Timing, + Exposure, + Motion, + Camera, + + /// No automatic advice: a temporal median erases stars that move between frames, so stacking stays a user choice. + Stack, + + Export, +} + +/// +/// Stable ids of the parameters the advisor decides, named after their path. +/// Value types: see each constant. +/// +public static class AdvisorParameters +{ + /// frame index. + public const string Hero = "Frames.Hero"; + + /// [] frame indices to exclude. + public const string Excluded = "Frames.Excluded"; + + /// . + public const string TimingMode = "Timing.Mode"; + + /// frame rate ("24", "25", "30", "60"). + public const string FrameRate = "Timing.FrameRate"; + + /// seconds. + public const string FitToSeconds = "Timing.FitToSeconds"; + + /// . + public const string Deflicker = "Exposure.Deflicker"; + + /// frames (odd). + public const string DeflickerWindow = "Exposure.DeflickerWindow"; + + /// 0..1. + public const string DeflickerStrength = "Exposure.DeflickerStrength"; + + /// . + public const string Regions = "Exposure.Regions"; + + /// . + public const string HolyGrail = "Exposure.HolyGrail"; + + /// frames. + public const string TransitionLength = "Exposure.TransitionLength"; + + /// . + public const string WhiteBalanceSmoothing = "Exposure.WhiteBalanceSmoothing"; + + /// . + public const string MotionBlur = "Motion.MotionBlur"; + + /// degrees. + public const string TargetShutterAngle = "Motion.TargetShutterAngle"; + + /// . + public const string FlowQuality = "Motion.FlowQuality"; + + /// . + public const string Stabilize = "Motion.Stabilize"; + + /// σ in frames. + public const string StabilizeSmoothing = "Motion.StabilizeSmoothing"; + + /// aspect ("16:9", "9:16", …). + public const string Aspect = "Camera.Aspect"; + + /// crop placement −1..1 (0 = centred). + public const string OffsetY = "Camera.OffsetY"; + + /// built-in export preset id. + public const string ExportPreset = "Export.Preset"; + + /// output size "WxH" (the cap from source, previews and encoder). + public const string Resolution = "Export.Resolution"; +} + +/// +/// One advisor decision (BRIEF §10.3). is null when data is missing; the reason then says what is +/// missing and nothing is changed. are numbers (already rounded for display) or plain tokens, +/// formatted by the caller with its culture: Loc.L(ReasonKey, [.. ReasonArgs]). +/// +/// 0..1: how strongly the measurements support the value. +public sealed record Recommendation( + AdvisorSection Section, + string Parameter, + object? Value, + double Confidence, + string ReasonKey, + IReadOnlyList ReasonArgs) +{ + public bool IsMissingData => Value is null; +} + +/// Output of : recommendations in section order plus every finding. +public sealed record AdvisorResult(IReadOnlyList Recommendations, IReadOnlyList Findings) +{ + public Recommendation? Find(string parameter) => Recommendations.FirstOrDefault(r => r.Parameter == parameter); + + public IEnumerable In(AdvisorSection section) => Recommendations.Where(r => r.Section == section); +} + +/// What the advisor knows about the sequence besides the analyses. +public sealed record SequenceContext +{ + public int FrameCount { get; init; } + + /// Oriented full-resolution size (0 = take the light analysis' dominant size). + public int SourceWidth { get; init; } + + public int SourceHeight { get; init; } + + /// Frames that decode only through their embedded preview (BRIEF §8.2 tier 2). + public int PreviewOnlyCount { get; init; } + + /// Oriented size of those embedded previews (0 = unknown). + public int PreviewWidth { get; init; } + + public int PreviewHeight { get; init; } + + /// Median shutter time in seconds, for the real shutter angle. + public double? MedianExposureSeconds { get; init; } + + /// Encoders available on the rendering machine; empty = unknown (no codec is ruled out). + public IReadOnlyList Codecs { get; init; } = []; + + /// Wanted video length ("fit to N seconds"), when the user set one. + public double? TargetDurationSeconds { get; init; } + + /// Context from the archive's frame rows: count, dominant oriented size, preview-only count, median shutter time. + public static SequenceContext FromFrames(IReadOnlyList frames, IReadOnlyList? codecs = null) + { + ArgumentNullException.ThrowIfNull(frames); + var sizes = new Dictionary<(int, int), int>(); + var exposures = new List(); + var previewOnly = 0; + foreach (var f in frames) + { + var size = f.Orientation is >= 5 and <= 8 ? (f.Height, f.Width) : (f.Width, f.Height); + if (size.Item1 > 0 && size.Item2 > 0) sizes[size] = sizes.GetValueOrDefault(size) + 1; + if (f.ExposureTime is > 0 and var t) exposures.Add(t); + if ((f.Flags & FrameFlags.PreviewOnly) != 0) previewOnly++; + } + var (width, height) = sizes.Count > 0 ? sizes.MaxBy(kv => kv.Value).Key : (0, 0); + return new SequenceContext + { + FrameCount = frames.Count, + SourceWidth = width, + SourceHeight = height, + PreviewOnlyCount = previewOnly, + MedianExposureSeconds = exposures.Count > 0 ? Statistics.Median(exposures.ToArray()) : null, + Codecs = codecs ?? [], + }; + } +} + +/// A value changed: effective value before and after, and why. +public sealed record SettingChange(string Parameter, object? Before, object? After, string ReasonKey, IReadOnlyList ReasonArgs); + +/// Settings after and the report of what changed. +public sealed record OptimiseResult(ProjectSettings Settings, IReadOnlyList Changes); diff --git a/src/Titano.Core/Advisor/ParameterBindings.cs b/src/Titano.Core/Advisor/ParameterBindings.cs new file mode 100644 index 00000000..831a62e1 --- /dev/null +++ b/src/Titano.Core/Advisor/ParameterBindings.cs @@ -0,0 +1,137 @@ +using System.Collections; +using System.Globalization; +using Titano.Core.Export; +using Titano.Core.Project; + +namespace Titano.Core.Advisor; + +/// How one advisor parameter reads and writes . +internal sealed class ParameterBinding +{ + public required string Parameter { get; init; } + public required AdvisorSection Section { get; init; } + + /// A module on/off decision: returns it to Auto when the advice differs. + public bool IsModuleSwitch { get; init; } + + /// The value in force (manual, else advised), null when neither exists. + public required Func Effective { get; init; } + + /// Auto fields: stores the advice and its reason, never touching a manual value. + public Func? Advise { get; init; } + + /// Auto fields: drops the manual value so the advice applies. + public Func? ResetToAuto { get; init; } + + /// Plain fields: the heavier decision takes (each guards user choices). + public Func? Set { get; init; } +} + +/// The binding of every id, in section order. +internal static class ParameterBindings +{ + public static IReadOnlyList All { get; } = + [ + new() + { + Parameter = AdvisorParameters.Hero, Section = AdvisorSection.Frames, + Effective = s => s.HeroFrame, + Set = (s, r) => s.HeroFrame is null ? s with { HeroFrame = (int)r.Value! } : s, + }, + new() + { + Parameter = AdvisorParameters.Excluded, Section = AdvisorSection.Frames, + Effective = s => s.ExcludedFrames, + Set = (s, r) => s with { ExcludedFrames = [.. s.ExcludedFrames.Union((int[])r.Value!).Order()] }, + }, + AutoField(AdvisorParameters.TimingMode, AdvisorSection.Timing, true, s => s.Timing.Mode, (s, a) => s with { Timing = s.Timing with { Mode = a } }), + AutoField(AdvisorParameters.FrameRate, AdvisorSection.Timing, false, s => s.Timing.FrameRate, (s, a) => s with { Timing = s.Timing with { FrameRate = a } }), + new() + { + Parameter = AdvisorParameters.FitToSeconds, Section = AdvisorSection.Timing, + Effective = s => s.Timing.FitToSeconds, + Set = (s, r) => s with { Timing = s.Timing with { FitToSeconds = (double)r.Value! } }, + }, + AutoField(AdvisorParameters.Deflicker, AdvisorSection.Exposure, true, s => s.Exposure.Deflicker, (s, a) => s with { Exposure = s.Exposure with { Deflicker = a } }), + AutoField(AdvisorParameters.DeflickerWindow, AdvisorSection.Exposure, false, s => s.Exposure.DeflickerWindow, (s, a) => s with { Exposure = s.Exposure with { DeflickerWindow = a } }), + AutoField(AdvisorParameters.DeflickerStrength, AdvisorSection.Exposure, false, s => s.Exposure.DeflickerStrength, (s, a) => s with { Exposure = s.Exposure with { DeflickerStrength = a } }), + AutoField(AdvisorParameters.Regions, AdvisorSection.Exposure, true, s => s.Exposure.Regions, (s, a) => s with { Exposure = s.Exposure with { Regions = a } }), + AutoField(AdvisorParameters.HolyGrail, AdvisorSection.Exposure, true, s => s.Exposure.HolyGrail, (s, a) => s with { Exposure = s.Exposure with { HolyGrail = a } }), + AutoField(AdvisorParameters.TransitionLength, AdvisorSection.Exposure, false, s => s.Exposure.TransitionLength, (s, a) => s with { Exposure = s.Exposure with { TransitionLength = a } }), + AutoField(AdvisorParameters.WhiteBalanceSmoothing, AdvisorSection.Exposure, true, s => s.Exposure.WhiteBalanceSmoothing, (s, a) => s with { Exposure = s.Exposure with { WhiteBalanceSmoothing = a } }), + AutoField(AdvisorParameters.MotionBlur, AdvisorSection.Motion, true, s => s.Motion.MotionBlur, (s, a) => s with { Motion = s.Motion with { MotionBlur = a } }), + AutoField(AdvisorParameters.TargetShutterAngle, AdvisorSection.Motion, false, s => s.Motion.TargetShutterAngle, (s, a) => s with { Motion = s.Motion with { TargetShutterAngle = a } }), + AutoField(AdvisorParameters.FlowQuality, AdvisorSection.Motion, false, s => s.Motion.FlowQuality, (s, a) => s with { Motion = s.Motion with { FlowQuality = a } }), + AutoField(AdvisorParameters.Stabilize, AdvisorSection.Motion, true, s => s.Motion.Stabilize, (s, a) => s with { Motion = s.Motion with { Stabilize = a } }), + AutoField(AdvisorParameters.StabilizeSmoothing, AdvisorSection.Motion, false, s => s.Motion.StabilizeSmoothing, (s, a) => s with { Motion = s.Motion with { StabilizeSmoothing = a } }), + AutoField(AdvisorParameters.Aspect, AdvisorSection.Camera, false, s => s.Camera.Aspect, (s, a) => s with { Camera = s.Camera with { Aspect = a } }), + new() + { + Parameter = AdvisorParameters.OffsetY, Section = AdvisorSection.Camera, + Effective = s => s.Camera.OffsetY, + Set = (s, r) => s.Camera.OffsetY == 0 ? s with { Camera = s.Camera with { OffsetY = (double)r.Value! } } : s, + }, + AutoField(AdvisorParameters.ExportPreset, AdvisorSection.Export, true, s => s.Export.Preset, (s, a) => s with { Export = s.Export with { Preset = a } }), + new() + { + Parameter = AdvisorParameters.Resolution, Section = AdvisorSection.Export, + Effective = s => s.Export.Overrides is { Width: { } w, Height: { } h } ? Size(w, h) : null, + Set = CapResolution, + }, + ]; + + public static ParameterBinding? Find(string parameter) => All.FirstOrDefault(b => b.Parameter == parameter); + + /// Value equality that compares lists element by element. + public static bool SameValue(object? a, object? b) + { + if (a is IEnumerable x && b is IEnumerable y && a is not string && b is not string) return x.Cast().SequenceEqual(y.Cast()); + return Equals(a, b); + } + + /// Recommendation arguments as stored in (culture-neutral text). + public static string[] Strings(IReadOnlyList args) => [.. args.Select(a => Convert.ToString(a, CultureInfo.InvariantCulture) ?? string.Empty)]; + + public static string Size(int width, int height) => string.Create(CultureInfo.InvariantCulture, $"{width}x{height}"); + + public static bool HasAdvice(Auto auto) => typeof(T).IsValueType + ? auto.ReasonKey is not null && !auto.ReasonKey.StartsWith(AdvisorKeys.MissingPrefix, StringComparison.Ordinal) + : auto.AutoValue is not null; + + private static ParameterBinding AutoField(string parameter, AdvisorSection section, bool module, Func> get, Func, ProjectSettings> set) => new() + { + Parameter = parameter, + Section = section, + IsModuleSwitch = module, + Effective = s => EffectiveOf(get(s)), + Advise = (s, r) => set(s, Advise(get(s), r)), + ResetToAuto = s => set(s, get(s).Reset()), + }; + + private static object? EffectiveOf(Auto auto) => !auto.IsAuto && auto.Manual is not null ? auto.Manual : HasAdvice(auto) ? auto.AutoValue : null; + + /// + /// Stores a value with its reason. Missing data changes no value: the missing-data reason is stored only when the + /// parameter has no advice yet, so the Auto tooltip can say why it is empty. + /// + private static Auto Advise(Auto auto, Recommendation recommendation) + { + var args = Strings(recommendation.ReasonArgs); + if (recommendation.Value is null) + return HasAdvice(auto) ? auto : auto with { ReasonKey = recommendation.ReasonKey, ReasonArgs = args }; + if (recommendation.Value is not T value) + throw new InvalidOperationException($"{recommendation.Parameter} expects {typeof(T).Name}, got {recommendation.Value.GetType().Name}."); + return auto.WithAdvice(value, recommendation.ReasonKey, args); + } + + /// Overrides the output size when the preset in force is larger than the recommended cap. + private static ProjectSettings CapResolution(ProjectSettings settings, Recommendation recommendation) + { + var parts = ((string)recommendation.Value!).Split('x'); + var width = int.Parse(parts[0], CultureInfo.InvariantCulture); + var height = int.Parse(parts[1], CultureInfo.InvariantCulture); + var id = EffectiveOf(settings.Export.Preset) as string; + if (id is null || ExportPresets.Find(id) is not { Width: > 0 } preset || (preset.Width <= width && preset.Height <= height)) return settings; + return settings with { Export = settings.Export with { Overrides = settings.Export.Overrides with { Width = width, Height = height } } }; + } +} diff --git a/src/Titano.Core/Advisor/SequencePresets.cs b/src/Titano.Core/Advisor/SequencePresets.cs new file mode 100644 index 00000000..87e55389 --- /dev/null +++ b/src/Titano.Core/Advisor/SequencePresets.cs @@ -0,0 +1,217 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Export; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Advisor; + +/// +/// A one-click bundle (BRIEF §10.3): full project settings plus an export preset, named by a resource key and +/// arguments (culture-neutral numbers or tokens) or, for user presets, by the user's own . +/// +public sealed record SequencePreset +{ + /// "night-sky", "holy-grail", "construction", "social-vertical", "standard", or a user id. + public required string Id { get; init; } + + public required string NameKey { get; init; } + public IReadOnlyList NameArgs { get; init; } = []; + + /// The user's name for a saved preset; overrides . + public string? Name { get; init; } + + public string? ReasonKey { get; init; } + public IReadOnlyList ReasonArgs { get; init; } = []; + public required ProjectSettings Settings { get; init; } + public required string ExportPresetId { get; init; } + + /// 0..1: how well the measured content matches the preset. + public double Confidence { get; init; } + + public bool IsUser { get; init; } + + public string DisplayName() => Name ?? Advisor.Explain(NameKey, NameArgs); + + /// A copy saved under the user's name. + public SequencePreset AsUserPreset(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + return this with { Id = Guid.CreateVersion7().ToString("N"), Name = name.Trim(), IsUser = true }; + } + + public string ToJson() => JsonSerializer.Serialize(this, AdvisorJson.Default.SequencePreset); + + public static SequencePreset FromJson(string json) => + JsonSerializer.Deserialize(json, AdvisorJson.Default.SequencePreset) ?? throw new InvalidDataException("Preset JSON is empty."); +} + +/// +/// Generates the sequence presets that fit the measured content, best match first: Night sky (star field or night, +/// 4K 10-bit HEVC 24 fps, deflicker, stabilise when shaky), Holy grail sunset (received exposure steps across a +/// day/night change, 4K HEVC 30 fps, transitions), Construction cam (several sessions over at least a day, 1080p +/// H.264 30 fps, adaptive timing), Standard when none of these match, and Social vertical (1080×1920) always last. +/// A preset's export choice gives way to the advised one when the source, previews or encoders cannot reach it. +/// Content values stay Auto with the advisor's reasons; the preset's own choices are stored as manual values. +/// +public static class SequencePresets +{ + public static IReadOnlyList Generate(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context) + { + ArgumentNullException.ThrowIfNull(light); + ArgumentNullException.ThrowIfNull(context); + var advice = Advisor.Recommend(light, deep, context); + var advised = Advisor.Apply(new ProjectSettings(), advice); + var exportId = advice.Find(AdvisorParameters.ExportPreset)?.Value as string ?? "1080p-h264"; + var presets = new List(); + + if (deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night)) + { + var id = Pick(exportId, "4k-hevc10-archive", context); + var window = advised.Exposure.DeflickerWindow.AutoValue; + var shaky = advice.Find(AdvisorParameters.Stabilize)?.Value is true; + var settings = Manual(advised, id, "24") with { Exposure = advised.Exposure with { Deflicker = advised.Exposure.Deflicker.WithManual(true) } }; + if (shaky) settings = settings with { Motion = settings.Motion with { Stabilize = settings.Motion.Stabilize.WithManual(true) } }; + var stars = d.Sky.StarField ? 100.0 * d.Sky.StarFrames / int.Max(1, d.FrameCount) : 0; + presets.Add(new SequencePreset + { + Id = "night-sky", + NameKey = shaky ? AdvisorKeys.PresetNightSkyStabilised : AdvisorKeys.PresetNightSky, + NameArgs = [Label(id), CodecLabel(id), "24", Text(window)], + ReasonKey = AdvisorKeys.PresetReasonNightSky, + ReasonArgs = [Text(double.Round(stars))], + Settings = settings, + ExportPresetId = id, + Confidence = d.Sky.StarField ? 0.9 : 0.7, + }); + } + + var received = deep?.Exposure.ReceivedSteps ?? (light.ExposureValues.Any(v => v is not null) ? light.ExposureSteps.Count : 0); + var lightChange = deep is not null + ? deep.Sky.Light is DayNight.DayToNight or DayNight.NightToDay || deep.Exposure.SceneRangeEv >= 3 + : light.Findings.Any(f => f.Key == FindingKeys.DayNightTransition); + if (received > 0 && lightChange) + { + var id = Pick(exportId, "4k-hevc", context); + var transitions = advised.Exposure.TransitionLength.AutoValue; + var range = deep?.Exposure.SceneRangeEv ?? 0; + var settings = Manual(advised, id, "30") with + { + Exposure = advised.Exposure with + { + HolyGrail = advised.Exposure.HolyGrail.WithManual(true), + Deflicker = advised.Exposure.Deflicker.WithManual(true), + }, + }; + presets.Add(new SequencePreset + { + Id = "holy-grail", + NameKey = AdvisorKeys.PresetHolyGrail, + NameArgs = [Label(id), CodecLabel(id), "30", Text(transitions)], + ReasonKey = AdvisorKeys.PresetReasonHolyGrail, + ReasonArgs = [Text(received), Text(double.Round(range, 1))], + Settings = settings, + ExportPresetId = id, + Confidence = 0.85, + }); + } + + if (light.Sessions.Count >= 2 && light.CaptureSpan >= TimeSpan.FromDays(1)) + { + var id = Pick(exportId, "1080p-h264", context); + var settings = Manual(advised, id, "30"); + settings = settings with { Timing = settings.Timing with { Mode = settings.Timing.Mode.WithManual(TimingMode.Adaptive) } }; + presets.Add(new SequencePreset + { + Id = "construction", + NameKey = AdvisorKeys.PresetConstruction, + NameArgs = [Label(id), CodecLabel(id), "30"], + ReasonKey = AdvisorKeys.PresetReasonConstruction, + ReasonArgs = [Text(light.Sessions.Count), Text(double.Round(light.CaptureSpan.TotalDays, 1))], + Settings = settings, + ExportPresetId = id, + Confidence = 0.8, + }); + } + + if (presets.Count == 0) + { + var fps = advised.Timing.FrameRate.AutoValue ?? ExportPresets.Find(exportId)?.FrameRate.ToString() ?? "30"; + presets.Add(new SequencePreset + { + Id = "standard", + NameKey = AdvisorKeys.PresetStandard, + NameArgs = [Label(exportId), CodecLabel(exportId), fps], + ReasonKey = AdvisorKeys.PresetReasonStandard, + Settings = Manual(advised, exportId, null), + ExportPresetId = exportId, + Confidence = 0.6, + }); + } + + const string vertical = "vertical-1080x1920"; + var social = Manual(advised, vertical, "30") with { Camera = advised.Camera with { Aspect = advised.Camera.Aspect.WithManual("9:16"), OffsetY = 0 } }; + presets.Add(new SequencePreset + { + Id = "social-vertical", + NameKey = AdvisorKeys.PresetSocialVertical, + NameArgs = ["1080", "1920"], + ReasonKey = AdvisorKeys.PresetReasonSocialVertical, + Settings = social, + ExportPresetId = vertical, + Confidence = 0.4, + }); + return [.. presets.OrderByDescending(p => p.Confidence)]; + } + + /// The preset's own export choice when the advised size reaches 4K, else the advised (capped) preset. + private static string Pick(string advised, string wanted, SequenceContext context) + { + var cap = ExportPresets.Find(advised); + var target = ExportPresets.Find(wanted)!; + var codecOk = context.Codecs.Count == 0 || context.Codecs.Any(c => c.Codec == target.Codec && (target.BitDepth <= 8 || c.SupportsTenBit)); + return cap is not null && cap.Width >= target.Width && cap.Height >= target.Height && codecOk ? wanted : advised; + } + + /// Export preset and (optionally) frame rate as the preset's manual choices. + private static ProjectSettings Manual(ProjectSettings settings, string exportId, string? frameRate) + { + settings = settings with { Export = settings.Export with { Preset = settings.Export.Preset.WithManual(exportId) } }; + return frameRate is null ? settings : settings with { Timing = settings.Timing with { FrameRate = settings.Timing.FrameRate.WithManual(frameRate) } }; + } + + /// Resolution label of an export preset ("4K", "1440p", "1080p", …). + private static string Label(string exportId) => ExportPresets.Find(exportId) switch + { + { Width: >= 3840 } => "4K", + { Width: > 0 } p => string.Create(CultureInfo.InvariantCulture, $"{int.Min(p.Width, p.Height)}p"), + _ => exportId, + }; + + /// Codec label of an export preset ("HEVC Main10", "HEVC", "H.264", "AV1"): technical names, not translated. + private static string CodecLabel(string exportId) => ExportPresets.Find(exportId) switch + { + { Codec: VideoCodec.Hevc, BitDepth: >= 10 } => "HEVC Main10", + { Codec: VideoCodec.Hevc } => "HEVC", + { Codec: VideoCodec.Av1 } => "AV1", + { Codec: VideoCodec.H264 } => "H.264", + { } p => p.Codec.ToString(), + _ => exportId, + }; + + private static string Text(T value) => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; +} + +/// Source-generated JSON for saved sequence presets. +[JsonSourceGenerationOptions( + WriteIndented = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + UseStringEnumConverter = true, + PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(SequencePreset))] +internal sealed partial class AdvisorJson : JsonSerializerContext; diff --git a/tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs b/tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs new file mode 100644 index 00000000..bd5b610f --- /dev/null +++ b/tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs @@ -0,0 +1,132 @@ +using System.Collections; +using System.Globalization; +using System.Reflection; +using System.Resources; +using System.Text.RegularExpressions; +using Titano.Core.Advisor; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Core.Tests.Analysis.Deep; +using Titano.Testing; + +namespace Titano.Core.Tests.Advisor; + +using AdvisorApi = Titano.Core.Advisor.Advisor; + +public sealed partial class AdvisorLocalizationTests(TestContext context) +{ + private static readonly CultureInfo English = CultureInfo.GetCultureInfo("en"); + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it"); + + [Test] + public void EveryAdvisorKeyHasEnglishAndItalianTextWithTheSamePlaceholders() + { + var manager = new ResourceManager("Titano.Core.i18n.Advisor", typeof(Loc).Assembly); + var english = Entries(manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: false)!); + var italian = Entries(manager.GetResourceSet(Italian, createIfNotExists: true, tryParents: false)!); + var keys = Keys(typeof(AdvisorKeys)).Concat(Keys(typeof(FindingKeys))).Concat(Keys(typeof(DeepFindingKeys))).ToList(); + Assert.Greater(keys.Count, 90); + foreach (var key in keys) + { + Assert.True(english.TryGetValue(key, out var en), $"English text missing for {key}"); + Assert.True(italian.TryGetValue(key, out var it), $"Italian text missing for {key}"); + Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), key); + Assert.LessOrEqual(en!.Length, 200); + } + Assert.Equal(english.Count, keys.Count); + } + + [Test] + public async Task EveryReasonAndFindingOfTheGoldenScenesFormatsInBothLanguages() + { + var scenes = new List<(SyntheticFrameSource Source, DeepAnalysisReport? Deep)> + { + (new SyntheticFrameSource(DeepScenes.NightSky()), await DeepReports.Night), + (new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), await DeepReports.NightJitter), + (new SyntheticFrameSource(DeepScenes.HolyGrail()), await DeepReports.HolyGrail), + (new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true }, null), + }; + var rendered = 0; + foreach (var (source, deep) in scenes) + { + var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList(); + var light = LightAnalyzer.Analyze(frames); + var sequence = new SequenceContext { FrameCount = frames.Count, SourceWidth = 6000, SourceHeight = 4000, MedianExposureSeconds = 1.0 / 250 }; + var result = AdvisorApi.Recommend(light, deep, sequence); + foreach (var r in result.Recommendations) rendered += Render(r.ReasonKey, [.. r.ReasonArgs]); + foreach (var f in result.Findings) rendered += Render(f.Key, f.Arguments); + foreach (var p in SequencePresets.Generate(light, deep, sequence)) + { + rendered += Render(p.NameKey, [.. p.NameArgs]); + rendered += Render(p.ReasonKey!, [.. p.ReasonArgs]); + } + // Stored reasons (culture-neutral strings) render with the current culture's numbers. + var applied = AdvisorApi.Apply(new ProjectSettings(), result); + Assert.DoesNotContain('⟦', AdvisorApi.Explain(applied.Exposure.HolyGrail.ReasonKey!, applied.Exposure.HolyGrail.ReasonArgs)); + } + context.Log($"{rendered} texts rendered"); + Assert.Greater(rendered, 80); + } + + [Test] + public void StoredNumericArgumentsAreLocalisedWhenExplained() + { + var text = Format(Loc.Get(AdvisorKeys.DeflickerOn, Italian)!, Italian, 0.125); + Assert.Contains("0,125", text); + Assert.Contains("0.125", Format(Loc.Get(AdvisorKeys.DeflickerOn, English)!, English, 0.125)); + } + + [Test] + public async Task PresetsRoundTripAsJsonAndSaveAsUserPresets() + { + var source = new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2); + var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList(); + var presets = SequencePresets.Generate(LightAnalyzer.Analyze(frames), await DeepReports.NightJitter, new SequenceContext { SourceWidth = 6000, SourceHeight = 4000 }); + foreach (var preset in presets) + { + var json = preset.ToJson(); + Assert.Equal(json, SequencePreset.FromJson(json).ToJson()); + } + var user = presets[0].AsUserPreset(" My night "); + Assert.True(user.IsUser); + Assert.Equal("My night", user.Name); + Assert.NotEqual(presets[0].Id, user.Id); + var restored = SequencePreset.FromJson(user.ToJson()); + Assert.Equal("My night", restored.DisplayName()); + Assert.Equal(presets[0].Settings.ToJson(), restored.Settings.ToJson()); + Assert.Equal(presets[0].ExportPresetId, restored.ExportPresetId); + } + + private static int Render(string key, object?[] args) + { + foreach (var culture in new[] { English, Italian }) + { + var format = Loc.Get(key, culture); + Assert.NotNull(format); + var text = Format(format!, culture, args); + Assert.False(text.Contains('{'), $"{key} left a placeholder: {text}"); + } + return 1; + } + + private static string Format(string format, CultureInfo culture, params object?[] args) => string.Format(culture, format, args); + + private static Dictionary Entries(ResourceSet set) + { + var entries = new Dictionary(StringComparer.Ordinal); + foreach (DictionaryEntry entry in set) entries[(string)entry.Key] = (string)entry.Value!; + return entries; + } + + private static IEnumerable Keys(Type type) => + type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string) && f.Name != nameof(AdvisorKeys.MissingPrefix)).Select(f => (string)f.GetRawConstantValue()!) + .Concat(type.GetProperties(BindingFlags.Public | BindingFlags.Static).Where(p => p.PropertyType == typeof(string)).Select(p => (string)p.GetValue(null)!)); + + private static IEnumerable Placeholders(string text) => PlaceholderRegex().Matches(text).Select(m => m.Groups[1].Value).Order(); + + [GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")] + private static partial Regex PlaceholderRegex(); +} diff --git a/tests/Titano.Core.Tests/Advisor/AdvisorTests.cs b/tests/Titano.Core.Tests/Advisor/AdvisorTests.cs new file mode 100644 index 00000000..e0f23c1f --- /dev/null +++ b/tests/Titano.Core.Tests/Advisor/AdvisorTests.cs @@ -0,0 +1,349 @@ +using Titano.Core.Advisor; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Mathematics; +using Titano.Core.Project; +using Titano.Core.Tests.Analysis.Deep; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Advisor; + +// The class shares its name with the namespace, which an enclosing Titano.Core.* namespace would resolve first. +using AdvisorApi = Titano.Core.Advisor.Advisor; + +public sealed class AdvisorTests(TestContext context) +{ + [Test] + public async Task NightSkyGetsTheNightPresetDeflickerAndNoStabilisation() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); + var deep = await DeepReports.Night; + var result = AdvisorApi.Recommend(light, deep, sequence); + Log(result); + + Assert.Equal(true, Value(result, AdvisorParameters.Deflicker)); + Assert.Equal(15, Value(result, AdvisorParameters.DeflickerWindow)); + Assert.Equal(false, Value(result, AdvisorParameters.Stabilize)); + Assert.Equal(AdvisorKeys.StabilizeOff, result.Find(AdvisorParameters.Stabilize)!.ReasonKey); + Assert.Equal("3840x2160", Value(result, AdvisorParameters.Resolution)); + Assert.Equal("4k-hevc10-archive", Value(result, AdvisorParameters.ExportPreset)); + // 15 s exposures every 20 s are a 270° shutter: already beyond the 180° target. + Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur)); + Assert.Equal(AdvisorKeys.MotionBlurAlready, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey); + Assert.Equal(TimingMode.Constant, Value(result, AdvisorParameters.TimingMode)); + Assert.Equal("24", Value(result, AdvisorParameters.FrameRate)); + Assert.Equal(AdvisorKeys.WindowMinimum, result.Find(AdvisorParameters.DeflickerWindow)!.ReasonKey); + + var presets = SequencePresets.Generate(light, deep, sequence); + var night = presets[0]; + Assert.Equal("night-sky", night.Id); + Assert.Equal(AdvisorKeys.PresetNightSky, night.NameKey); + Assert.SequenceEqual(["4K", "HEVC Main10", "24", "15"], night.NameArgs); + Assert.Equal("4k-hevc10-archive", night.ExportPresetId); + Assert.Equal("24", night.Settings.Timing.FrameRate.Resolve("30")); + Assert.True(night.Settings.Exposure.Deflicker.Resolve(false)); + Assert.False(night.Settings.Motion.Stabilize.Resolve(true)); + Assert.Equal("social-vertical", presets[^1].Id); + Assert.DoesNotContain("holy-grail", presets.Select(p => p.Id)); + } + + [Test] + public async Task InjectedJitterTurnsStabilisationOn() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2)); + var deep = await DeepReports.NightJitter; + var result = AdvisorApi.Recommend(light, deep, sequence); + var stabilize = result.Find(AdvisorParameters.Stabilize)!; + Assert.Equal(true, stabilize.Value); + Assert.Equal(AdvisorKeys.StabilizeOn, stabilize.ReasonKey); + // 2 px RMS on a 160-px source is 48 px at 3840 px. + Assert.InRange((double)stabilize.ReasonArgs[0], 40, 60); + Assert.Equal(12.0, Value(result, AdvisorParameters.StabilizeSmoothing)); + + var night = SequencePresets.Generate(light, deep, sequence)[0]; + Assert.Equal(AdvisorKeys.PresetNightSkyStabilised, night.NameKey); + Assert.False(night.Settings.Motion.Stabilize.IsAuto); + Assert.True(night.Settings.Motion.Stabilize.Manual); + } + + [Test] + public async Task HolyGrailSunsetGetsTransitionsOfHalfTheStepSpacing() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail())); + var deep = await DeepReports.HolyGrail; + var result = AdvisorApi.Recommend(light, deep, sequence); + Log(result); + var holyGrail = result.Find(AdvisorParameters.HolyGrail)!; + Assert.Equal(true, holyGrail.Value); + Assert.Equal(AdvisorKeys.HolyGrailReceived, holyGrail.ReasonKey); + Assert.SequenceEqual([5], holyGrail.ReasonArgs.Cast()); + var transition = result.Find(AdvisorParameters.TransitionLength)!; + Assert.Equal(20, transition.Value); + Assert.Equal(AdvisorKeys.TransitionSpacing, transition.ReasonKey); + Assert.SequenceEqual([40.0, 20.0], transition.ReasonArgs.Select(Convert.ToDouble)); + Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur)); + Assert.Equal(AdvisorKeys.MotionBlurLittle, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey); + + var presets = SequencePresets.Generate(light, deep, sequence); + var grail = presets[0]; + Assert.Equal("holy-grail", grail.Id); + Assert.SequenceEqual(["4K", "HEVC", "30", "20"], grail.NameArgs); + Assert.Equal("4k-hevc", grail.ExportPresetId); + Assert.True(grail.Settings.Exposure.HolyGrail.Resolve(false)); + Assert.Equal(20, grail.Settings.Exposure.TransitionLength.Resolve(0)); + + // Without pixels the metadata steps are trusted, with the same spacing rule and less confidence. + var metadataOnly = AdvisorApi.Recommend(light, null, sequence); + Assert.Equal(AdvisorKeys.HolyGrailMetadata, metadataOnly.Find(AdvisorParameters.HolyGrail)!.ReasonKey); + Assert.Equal(20, Value(metadataOnly, AdvisorParameters.TransitionLength)); + Assert.Less(metadataOnly.Find(AdvisorParameters.HolyGrail)!.Confidence, holyGrail.Confidence); + } + + [Test] + public void IrregularCadenceWithNightlyPausesIsAdaptive() + { + const double night = 14 * 3600; + var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 300, IntervalSeconds = 600, IntervalJitterSeconds = 20, + TimeShifts = [new(60, night), new(120, night), new(180, night), new(240, night)], + })); + var (light, sequence) = Inputs(source); + var result = AdvisorApi.Recommend(light, null, sequence); + Log(result); + var mode = result.Find(AdvisorParameters.TimingMode)!; + Assert.Equal(TimingMode.Adaptive, mode.Value); + Assert.Equal(AdvisorKeys.TimingSessions, mode.ReasonKey); + Assert.Equal(5, mode.ReasonArgs[0]); + Assert.Approximately(14.2, (double)mode.ReasonArgs[1], 0.051); + Assert.Equal("30", Value(result, AdvisorParameters.FrameRate)); + // Pixel-based parameters wait for the deep analysis. + foreach (var parameter in new[] { AdvisorParameters.Deflicker, AdvisorParameters.Stabilize, AdvisorParameters.Regions, AdvisorParameters.Hero }) + { + var missing = result.Find(parameter)!; + Assert.True(missing.IsMissingData); + Assert.Equal(AdvisorKeys.MissingDeep, missing.ReasonKey); + } + + var presets = SequencePresets.Generate(light, null, sequence); + Assert.SequenceEqual(["construction", "social-vertical"], presets.Select(p => p.Id)); + Assert.Equal(TimingMode.Adaptive, presets[0].Settings.Timing.Mode.Resolve(TimingMode.Constant)); + Assert.Equal("1080p-h264", presets[0].ExportPresetId); + } + + [Test] + public async Task SparseGapsWithStillContentAreInterpolated() + { + var gapped = SyntheticSequence.Create(DeepScenes.HolyGrail().Options with { TimeShifts = [new(100, 40)] }); + var (light, sequence) = Inputs(new SyntheticFrameSource(gapped)); + var result = AdvisorApi.Recommend(light, await DeepReports.HolyGrail, sequence); + Assert.Equal(TimingMode.Interpolated, Value(result, AdvisorParameters.TimingMode)); + Assert.Equal(FlowQualitySetting.Best, Value(result, AdvisorParameters.FlowQuality)); + Assert.Equal(TimingMode.Constant, Value(AdvisorApi.Recommend(light, null, sequence), AdvisorParameters.TimingMode)); + } + + [Test] + public async Task PeriodicFlickerWindowIsFourPeriods() + { + var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = 8, + })); + var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options); + var (light, sequence) = Inputs(source); + var window = AdvisorApi.Recommend(light, deep, sequence).Find(AdvisorParameters.DeflickerWindow)!; + Assert.Equal(33, window.Value); + Assert.Equal(AdvisorKeys.WindowPeriod, window.ReasonKey); + Assert.Equal(8.0, window.ReasonArgs[0]); + } + + [Test] + public void MissingExposureMetadataIsReportedAndChangesNothing() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true }); + Assert.True(light.ExposureValues.All(v => v is null)); + var result = AdvisorApi.Recommend(light, null, sequence); + foreach (var parameter in new[] { AdvisorParameters.HolyGrail, AdvisorParameters.TransitionLength, AdvisorParameters.TargetShutterAngle, AdvisorParameters.MotionBlur }) + { + var missing = result.Find(parameter)!; + Assert.Null(missing.Value); + Assert.Equal(0.0, missing.Confidence); + Assert.Equal(AdvisorKeys.MissingExposure, missing.ReasonKey); + } + + var advised = new ProjectSettings + { + Exposure = new ExposureSettings + { + HolyGrail = new Auto().WithAdvice(true, AdvisorKeys.HolyGrailReceived, "5"), + TransitionLength = new Auto().WithAdvice(20, AdvisorKeys.TransitionSpacing, "40", "20"), + }, + }; + var applied = AdvisorApi.Apply(advised, result); + Assert.Same(advised.Exposure.HolyGrail, applied.Exposure.HolyGrail); + Assert.Same(advised.Exposure.TransitionLength, applied.Exposure.TransitionLength); + Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Exposure, advised, result).Changes.Where(c => c.Parameter is AdvisorParameters.HolyGrail or AdvisorParameters.TransitionLength)); + + // A fresh project keeps its values and learns why there is no advice. + var fresh = AdvisorApi.Apply(new ProjectSettings(), result); + Assert.False(fresh.Exposure.HolyGrail.AutoValue); + Assert.Equal(AdvisorKeys.MissingExposure, fresh.Exposure.HolyGrail.ReasonKey); + Assert.Equal(0, fresh.Exposure.TransitionLength.AutoValue); + Assert.Equal(0.0, fresh.Motion.TargetShutterAngle.AutoValue); + Assert.Equal(AdvisorKeys.MissingExposure, fresh.Motion.TargetShutterAngle.ReasonKey); + } + + [Test] + public async Task ApplyNeverOverwritesManualValues() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); + var result = AdvisorApi.Recommend(light, await DeepReports.Night, sequence); + var manual = new ProjectSettings + { + Timing = new TimingSettings { FrameRate = new Auto().WithManual("50") }, + Exposure = new ExposureSettings + { + Deflicker = new Auto().WithManual(false), + DeflickerWindow = new Auto().WithManual(99), + }, + HeroFrame = 7, + ExcludedFrames = [3], + }; + var applied = AdvisorApi.Apply(manual, result); + Assert.False(applied.Exposure.Deflicker.IsAuto); + Assert.False(applied.Exposure.Deflicker.Resolve(true)); + Assert.True(applied.Exposure.Deflicker.AutoValue); + Assert.Equal(99, applied.Exposure.DeflickerWindow.Resolve(0)); + Assert.Equal(15, applied.Exposure.DeflickerWindow.AutoValue); + Assert.Equal("50", applied.Timing.FrameRate.Resolve("30")); + Assert.Equal("24", applied.Timing.FrameRate.AutoValue); + Assert.Equal(7, applied.HeroFrame); + Assert.SequenceEqual([3], applied.ExcludedFrames); + // Auto values carry the reason with culture-neutral arguments. + Assert.Equal(AdvisorKeys.WindowMinimum, applied.Exposure.DeflickerWindow.ReasonKey); + Assert.SequenceEqual(["15"], applied.Exposure.DeflickerWindow.ReasonArgs!); + Assert.True(applied.Motion.Stabilize.ReasonKey == AdvisorKeys.StabilizeOff && !applied.Motion.Stabilize.AutoValue); + Assert.Equal(applied.ToJson(), ProjectSettings.FromJson(applied.ToJson()).ToJson()); + } + + [Test] + public async Task OptimiseTakesModuleDecisionsAndReportsChanges() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2)); + var result = AdvisorApi.Recommend(light, await DeepReports.NightJitter, sequence); + var settings = new ProjectSettings + { + Motion = new MotionSettings { Stabilize = new Auto().WithManual(false), StabilizeSmoothing = new Auto().WithManual(30) }, + ExcludedFrames = [3], + }; + + var motion = AdvisorApi.Optimise(AdvisorSection.Motion, settings, result); + Assert.True(motion.Settings.Motion.Stabilize.IsAuto); + Assert.True(motion.Settings.Motion.Stabilize.Resolve(false)); + Assert.Equal(30.0, motion.Settings.Motion.StabilizeSmoothing.Resolve(12)); + var change = motion.Changes.Single(c => c.Parameter == AdvisorParameters.Stabilize); + Assert.Equal(false, change.Before); + Assert.Equal(true, change.After); + Assert.Equal(AdvisorKeys.StabilizeOn, change.ReasonKey); + Assert.DoesNotContain(AdvisorParameters.StabilizeSmoothing, motion.Changes.Select(c => c.Parameter)); + Assert.Null(motion.Settings.HeroFrame); + + var frames = AdvisorApi.Optimise(AdvisorSection.Frames, settings, result); + Assert.Equal(result.Find(AdvisorParameters.Hero)!.Value, frames.Settings.HeroFrame); + Assert.SequenceEqual([AdvisorParameters.Hero], frames.Changes.Select(c => c.Parameter)); + Assert.SequenceEqual([3], frames.Settings.ExcludedFrames); + + var exposure = AdvisorApi.Optimise(AdvisorSection.Exposure, settings, result); + var deflicker = exposure.Changes.Single(c => c.Parameter == AdvisorParameters.Deflicker); + Assert.Null(deflicker.Before); + Assert.Equal(true, deflicker.After); + Assert.Equal(settings.Motion, exposure.Settings.Motion); + + // Optimising again changes nothing. + Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Motion, motion.Settings, result).Changes); + } + + [Test] + public async Task OptimiseExcludesFlaggedFramesAndCapsTheOutput() + { + var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, BlackFrames = [5], DuplicateFrames = [9], + })); + var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options); + var (light, sequence) = Inputs(source); + var result = AdvisorApi.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 }); + + var frames = AdvisorApi.Optimise(AdvisorSection.Frames, new ProjectSettings { ExcludedFrames = [2] }, result); + Assert.SequenceEqual([2, 5, 9], frames.Settings.ExcludedFrames); + Assert.Equal(AdvisorKeys.Exclude, frames.Changes.Single(c => c.Parameter == AdvisorParameters.Excluded).ReasonKey); + + var resolution = result.Find(AdvisorParameters.Resolution)!; + Assert.Equal("1280x720", resolution.Value); + Assert.Equal(AdvisorKeys.ResolutionPreview, resolution.ReasonKey); + var big = new ProjectSettings { Export = new ExportSettings { Preset = new Auto().WithManual("4k-hevc") } }; + var export = AdvisorApi.Optimise(AdvisorSection.Export, big, result); + Assert.Equal("720p-preview", export.Settings.Export.Preset.Resolve("4k-hevc")); + Assert.Null(export.Settings.Export.Overrides.Width); + } + + [Test] + public void OutputSizeFollowsSourceShapeAndEncoders() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail())); + var h264Only = sequence with { Codecs = [new EncoderCapability(VideoCodec.H264, "Software H.264", false, 1920, 1088, false)] }; + var limited = AdvisorApi.Recommend(light, null, h264Only); + Assert.Equal("1920x1080", Value(limited, AdvisorParameters.Resolution)); + Assert.Equal(AdvisorKeys.ResolutionCodec, limited.Find(AdvisorParameters.Resolution)!.ReasonKey); + Assert.Equal("1080p-h264", Value(limited, AdvisorParameters.ExportPreset)); + + var portrait = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000 }); + Assert.Equal("9:16", Value(portrait, AdvisorParameters.Aspect)); + Assert.Equal("1080x1920", Value(portrait, AdvisorParameters.Resolution)); + Assert.Equal("vertical-1080x1920", Value(portrait, AdvisorParameters.ExportPreset)); + + var landscape = AdvisorApi.Recommend(light, null, sequence); + Assert.Equal("16:9", Value(landscape, AdvisorParameters.Aspect)); + Assert.SequenceEqual([6000.0, 4000.0, 84.0], landscape.Find(AdvisorParameters.Aspect)!.ReasonArgs.Select(Convert.ToDouble)); + + var wide = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 6000, SourceHeight = 2500 }); + Assert.Equal(AdvisorKeys.AspectWide, wide.Find(AdvisorParameters.Aspect)!.ReasonKey); + Assert.Equal(74.0, wide.Find(AdvisorParameters.Aspect)!.ReasonArgs[2]); + Assert.Equal("3840x2160", Value(wide, AdvisorParameters.Resolution)); + } + + [Test] + public async Task RecommendationsAreDeterministic() + { + var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); + var deep = await DeepReports.Night; + var first = AdvisorApi.Recommend(light, deep, sequence); + var second = AdvisorApi.Recommend(light, DeepAnalysisReport.FromJson(deep.ToJson()), sequence); + Assert.SequenceEqual(first.Recommendations.Select(Describe), second.Recommendations.Select(Describe)); + } + + private static (LightAnalysisReport Light, SequenceContext Context) Inputs(SyntheticFrameSource source, int width = 6000, int height = 4000) + { + var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList(); + var exposures = frames.Where(f => f.ExposureTime is > 0).Select(f => f.ExposureTime!.Value).ToArray(); + return (LightAnalyzer.Analyze(frames), new SequenceContext + { + FrameCount = frames.Count, + SourceWidth = width, + SourceHeight = height, + MedianExposureSeconds = exposures.Length > 0 ? Statistics.Median(exposures) : null, + }); + } + + private static object? Value(AdvisorResult result, string parameter) => (result.Find(parameter) ?? throw new InvalidOperationException(parameter + " not recommended")).Value; + + private static string Describe(Recommendation r) => + $"{r.Parameter}={(r.Value is int[] list ? string.Join(",", list) : r.Value)} {r.Confidence} {r.ReasonKey} [{string.Join(";", r.ReasonArgs)}]"; + + private void Log(AdvisorResult result) + { + foreach (var r in result.Recommendations) context.Log(Describe(r)); + } +} From 16b00296bf226270a1caf47a4c8277dfc63a9aa9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:55:38 +0000 Subject: [PATCH 134/188] test(analysis): cover empty and fully unreadable deep-analysis sources Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Analysis/Deep/DeepAnalyzerTests.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs index b198d41c..eccb6818 100644 --- a/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs +++ b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs @@ -219,6 +219,22 @@ public sealed class DeepAnalyzerTests(TestContext context) Assert.Equal(TimeSpan.Zero, reports[^1].Eta); } + [Test] + public async Task EmptyAndUnreadableSequencesGiveEmptyReports() + { + var empty = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(new SyntheticFrameSource(DeepScenes.HolyGrail()), null!, 0) { Count = 0 }, DeepScenes.Options); + Assert.Equal(0, empty.FrameCount); + Assert.Equal(DayNight.Unknown, empty.Sky.Light); + Assert.Empty(empty.Findings); + + var unreadable = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 3 })) { Undecodable = [0, 1, 2] }, DeepScenes.Options); + Assert.Equal(DayNight.Unknown, unreadable.Sky.Light); + Assert.Null(unreadable.HeroIndex); + Assert.Null(unreadable.Regions); + Assert.SequenceEqual([0, 1, 2], unreadable.Issues.Undecodable); + Assert.Equal(unreadable.ToJson(), DeepAnalysisReport.FromJson(unreadable.ToJson()).ToJson()); + } + [Test] public void StarDetectorCountsPointsButNotBlobs() { @@ -283,7 +299,7 @@ public sealed class DeepAnalyzerTests(TestContext context) /// Frames of before , then frames of . private sealed class SplicedSource(IFrameSource first, IFrameSource second, int cut) : IFrameSource { - public int Count => first.Count; + public int Count { get; init; } = first.Count; public LightFrame Metadata(int index) => first.Metadata(index); From f14994a2f7f9c3c8ffcb47567cf6a11914bbb3cd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:55:50 +0000 Subject: [PATCH 135/188] test(data): measure query cancellation latency from the cancel signal The test timed from before CancelAfter, so a thread-pool timer firing late on a busy 4-core Windows runner (parallel tests block pool threads in synchronous SQLite steps) counted as interrupt latency. A dedicated thread now records the moment it cancels. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Data.Tests/Sessions/SessionTests.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tests/Titano.Data.Tests/Sessions/SessionTests.cs b/tests/Titano.Data.Tests/Sessions/SessionTests.cs index 72b7706b..fc9ca0f6 100644 --- a/tests/Titano.Data.Tests/Sessions/SessionTests.cs +++ b/tests/Titano.Data.Tests/Sessions/SessionTests.cs @@ -240,10 +240,21 @@ public abstract class SessionTests(TestContext context) : DatabaseTest(context) "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", "SELECT pg_sleep(10)"); using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); - cts.CancelAfter(300); var watch = Stopwatch.StartNew(); + var cancelledAt = TimeSpan.Zero; + // A dedicated thread, not CancelAfter: a timer on a busy thread pool can fire late and skew the measurement. + var canceller = new Thread(() => + { + Thread.Sleep(300); + cancelledAt = watch.Elapsed; + cts.Cancel(); + }) + { IsBackground = true }; + canceller.Start(); await Assert.ThrowsAsync(() => session.ExecuteAsync(sql, [], cts.Token)); - Assert.Less(watch.Elapsed.TotalSeconds, 2.0, "cancellation latency"); + var stoppedAt = watch.Elapsed; + canceller.Join(); + Assert.Less((stoppedAt - cancelledAt).TotalSeconds, 1.0, "cancellation latency"); Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); } } From 28cbc5ded7071cc2bd653e71b3f19a56336823f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:56:10 +0000 Subject: [PATCH 136/188] refactor(analysis): tidy flow hand-over in deep analysis state Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs index 052fce12..d7ff6e7a 100644 --- a/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs +++ b/src/Titano.Core/Analysis/Deep/DeepAnalyzer.cs @@ -8,8 +8,8 @@ namespace Titano.Core.Analysis.Deep; /// Deep analysis (BRIEF §10.2): one streaming pass over every frame. A pre-pass segments sky and land on a sample of /// thumbnails; then frames are probed in parallel batches (: statistics, stars, region /// luminance, clouds) and compared in order with the previous usable frame (nine-patch phase-correlation shift, duplicate -/// test, exposure-aligned histogram distance, Draft optical flow on every -th -/// pair). Memory is one batch of analysis images plus the previous frame's reduced planes. After every batch the new +/// test, exposure-aligned histogram distance, consistency-checked Draft optical flow on every +/// -th pair). Memory is one batch of analysis images plus the previous frame's reduced planes. After every batch the new /// s go to the checkpoint, so an interrupted run resumes after the last persisted frame with /// identical results. Sequence-level results are computed by . /// @@ -138,7 +138,6 @@ public static class DeepAnalyzer _previous = stats; _previousIndex = probe.Index; _previousFlow?.Dispose(); - _previousFlow = null; _previousFlow = probe.TakeFlow(); return frame; } From 1b3a691f761e99fa990f4ad84861d78424aad7a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:56:34 +0000 Subject: [PATCH 137/188] feat(raw): DNG development pipeline with AHD demosaic, opcodes and DNG colour Reads CFA and LinearRaw DNGs (compression 1/7/8/34892), linearises with LinearizationTable, BlackLevel (repeat + deltas) and WhiteLevel over the ActiveArea, applies OpcodeList1-3 (GainMap, WarpRectilinear, FixVignetteRadial, FixBadPixels*, TrimBounds, MapTable/MapPolynomial, Delta/ScalePer*), solves white balance per DNG 1.6 chapter 6 (CCT interpolation, ForwardMatrix, Bradford to D65), demosaics with AHD (Hirakawa & Parks 2005), bilinear, a neighbourhood interpolation for non-Bayer CFAs or binning, and reconstructs clipped highlights. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Dng/DngColorProfile.cs | 239 ++++++ src/Titano.Core/Codecs/Dng/DngOpcodes.cs | 712 ++++++++++++++++++ src/Titano.Core/Codecs/Dng/DngReader.cs | 247 ++++++ src/Titano.Core/Codecs/Raw/AhdDemosaic.cs | 245 ++++++ src/Titano.Core/Codecs/Raw/CfaPattern.cs | 143 ++++ src/Titano.Core/Codecs/Raw/Demosaic.cs | 202 +++++ .../Codecs/Raw/HighlightReconstruction.cs | 120 +++ src/Titano.Core/Codecs/Raw/RawDecoder.cs | 126 ++++ src/Titano.Core/Codecs/Raw/RawDeveloper.cs | 316 ++++++++ src/Titano.Core/Codecs/Raw/RawFrame.cs | 141 ++++ .../Titano.Core.Tests/Raw/DngDecoderTests.cs | 224 ++++++ tests/Titano.Core.Tests/Raw/DngOpcodeTests.cs | 221 ++++++ tests/Titano.Core.Tests/Raw/HighlightTests.cs | 75 ++ .../Raw/RawPerformanceTests.cs | 94 +++ tests/Titano.Core.Tests/Raw/SyntheticRaw.cs | 454 +++++++++++ 15 files changed, 3559 insertions(+) create mode 100644 src/Titano.Core/Codecs/Dng/DngColorProfile.cs create mode 100644 src/Titano.Core/Codecs/Dng/DngOpcodes.cs create mode 100644 src/Titano.Core/Codecs/Dng/DngReader.cs create mode 100644 src/Titano.Core/Codecs/Raw/AhdDemosaic.cs create mode 100644 src/Titano.Core/Codecs/Raw/CfaPattern.cs create mode 100644 src/Titano.Core/Codecs/Raw/Demosaic.cs create mode 100644 src/Titano.Core/Codecs/Raw/HighlightReconstruction.cs create mode 100644 src/Titano.Core/Codecs/Raw/RawDecoder.cs create mode 100644 src/Titano.Core/Codecs/Raw/RawDeveloper.cs create mode 100644 src/Titano.Core/Codecs/Raw/RawFrame.cs create mode 100644 tests/Titano.Core.Tests/Raw/DngDecoderTests.cs create mode 100644 tests/Titano.Core.Tests/Raw/DngOpcodeTests.cs create mode 100644 tests/Titano.Core.Tests/Raw/HighlightTests.cs create mode 100644 tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs create mode 100644 tests/Titano.Core.Tests/Raw/SyntheticRaw.cs diff --git a/src/Titano.Core/Codecs/Dng/DngColorProfile.cs b/src/Titano.Core/Codecs/Dng/DngColorProfile.cs new file mode 100644 index 00000000..dfc7cdd0 --- /dev/null +++ b/src/Titano.Core/Codecs/Dng/DngColorProfile.cs @@ -0,0 +1,239 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Codecs.Dng; + +/// Result of : white balance and the matrix to linear Rec.709. +/// Camera response to the scene white, largest entry 1 (white-balance multipliers are its reciprocals). +/// Scene white chromaticity found by the iterative solve. +/// Correlated colour temperature of (Robertson), in kelvin. +/// White-balanced camera RGB (raw ÷ neutral) → linear Rec.709 (D65), BaselineExposure included. +/// White-balanced camera RGB → CIE XYZ (D65 adapted, Y = 1 at white), for demosaic metrics. +public sealed record DngColorSolution(Vector3D CameraNeutral, Chromaticity White, double Temperature, Matrix3 BalancedToRec709, Matrix3 BalancedToXyz); + +/// +/// Camera colour description of a DNG (or of a native RAW with a tabulated matrix) and the colour math of DNG 1.6 +/// chapter 6 "Mapping Camera Color Space to CIE XYZ Space": ColorMatrix1/2 and CameraCalibration1/2 interpolated by +/// inverse correlated colour temperature between CalibrationIlluminant1/2, AnalogBalance, the iterative white solve for +/// AsShotNeutral (or the neutral implied by AsShotWhiteXY), ForwardMatrix1/2 when present, then Bradford adaptation from +/// the D50 profile connection space to D65 and the XYZ → Rec.709 matrix. +/// +public sealed class DngColorProfile +{ + /// Default scene white when the file records none: D55, as the DNG SDK assumes. + public static Chromaticity DefaultWhite { get; } = new(0.3324, 0.3474); + + public Matrix3? ColorMatrix1 { get; init; } + public Matrix3? ColorMatrix2 { get; init; } + public Matrix3? CameraCalibration1 { get; init; } + public Matrix3? CameraCalibration2 { get; init; } + public Matrix3? ForwardMatrix1 { get; init; } + public Matrix3? ForwardMatrix2 { get; init; } + + /// Exif LightSource codes of the two calibrations (0 = unknown). + public int CalibrationIlluminant1 { get; init; } + + public int CalibrationIlluminant2 { get; init; } + public Vector3D AnalogBalance { get; init; } = new(1, 1, 1); + public Vector3D? AsShotNeutral { get; init; } + public Chromaticity? AsShotWhite { get; init; } + + /// Exposure offset in EV applied to the rendered values (DNG BaselineExposure). + public double BaselineExposure { get; init; } + + /// Solves white balance and builds the output matrices. + /// No usable colour matrix (missing, singular or non-finite). + public DngColorSolution Solve(ICollection warnings) + { + if (ColorMatrix1 is not { } cm1 || !Usable(cm1)) throw new InvalidDataException("DNG: ColorMatrix1 missing or singular"); + Chromaticity white; + Vector3D neutral; + if (AsShotNeutral is { } asShot && asShot.X > 0 && asShot.Y > 0 && asShot.Z > 0) + { + neutral = Normalize(asShot); + white = NeutralToXy(neutral); + } + else + { + if (AsShotWhite is { } xy && xy.X > 0 && xy.Y > 0 && xy.X + xy.Y < 1) + { + white = xy; + } + else + { + white = DefaultWhite; + warnings.Add("DNG: no as-shot white balance; D55 assumed"); + } + neutral = Normalize(XyzToCamera(white) * white.ToXyz()); + } + // Clamp like the DNG SDK so a degenerate neutral cannot produce infinite multipliers. + neutral = new Vector3D(double.Clamp(neutral.X, 0.001, 1), double.Clamp(neutral.Y, 0.001, 1), double.Clamp(neutral.Z, 0.001, 1)); + + var cameraToPcs = CameraToPcs(white, neutral); + var d50 = Chromaticity.D50.ToXyz(); + var d65 = Chromaticity.D65.ToXyz(); + var balancedToD65 = Matrix3.BradfordAdaptation(d50, d65) * cameraToPcs * Matrix3.Diagonal(neutral.X, neutral.Y, neutral.Z); + var gain = double.Exp2(BaselineExposure); + var toRec709 = Scale(Matrix3.XyzToRec709 * balancedToD65, gain); + return new DngColorSolution(neutral, white, Temperature(white), toRec709, balancedToD65); + } + + /// XYZ → camera at the given scene white: AnalogBalance · CameraCalibration · ColorMatrix, both interpolated + /// by the white's inverse temperature (DNG §6 "Translating White Balance xy Coordinates to Camera Neutral"). + public Matrix3 XyzToCamera(Chromaticity white) + { + var g = Weight(white); + var cm = Blend(ColorMatrix1!.Value, ColorMatrix2, g); + var cc = Blend(CameraCalibration1 ?? Matrix3.Identity, CameraCalibration2 ?? (CameraCalibration1 is null ? null : Matrix3.Identity), g); + return Matrix3.Diagonal(AnalogBalance.X, AnalogBalance.Y, AnalogBalance.Z) * cc * cm; + } + + /// Iterative white solve of DNG §6 "Translating Camera Neutral Coordinates to White Balance xy Coordinates": + /// start at D50, map the neutral through the inverse of the matrix interpolated at the current estimate, repeat until it + /// moves less than 1e-7 (30 passes at most; a two-value oscillation is averaged). + public Chromaticity NeutralToXy(Vector3D neutral) + { + const int maxPasses = 30; + var last = Chromaticity.D50; + for (var pass = 0; pass < maxPasses; pass++) + { + if (!XyzToCamera(last).TryInvert(out var cameraToXyz)) return last; + var next = Chromaticity.FromXyz(cameraToXyz * neutral); + if (!double.IsFinite(next.X) || !double.IsFinite(next.Y) || next.Y <= 0) return last; + if (double.Abs(next.X - last.X) + double.Abs(next.Y - last.Y) < 1e-7) return next; + if (pass == maxPasses - 1) next = new Chromaticity((last.X + next.X) / 2, (last.Y + next.Y) / 2); + last = next; + } + return last; + } + + /// Camera → XYZ(D50) with the white-balanced neutral mapping to the D50 white (Y = 1): through the + /// interpolated ForwardMatrix when present, otherwise the inverse of ColorMatrix adapted from D50 to the scene white + /// (DNG §6 "Camera to XYZ (D50) Transform"). + private Matrix3 CameraToPcs(Chromaticity white, Vector3D neutral) + { + var d50 = Chromaticity.D50.ToXyz(); + if (ForwardMatrix1 is { } fm1 && Usable(fm1)) + { + var g = Weight(white); + var fm = NormalizeForward(Blend(fm1, ForwardMatrix2 is { } fm2 && Usable(fm2) ? fm2 : null, g), d50); + var cc = Blend(CameraCalibration1 ?? Matrix3.Identity, CameraCalibration2 ?? (CameraCalibration1 is null ? null : Matrix3.Identity), g); + var individualToReference = (Matrix3.Diagonal(AnalogBalance.X, AnalogBalance.Y, AnalogBalance.Z) * cc).Inverse(); + var reference = individualToReference * neutral; + return fm * Matrix3.Diagonal(1 / reference.X, 1 / reference.Y, 1 / reference.Z) * individualToReference; + } + var pcsToCamera = XyzToCamera(white) * Matrix3.BradfordAdaptation(d50, white.ToXyz()); + var atWhite = pcsToCamera * d50; + var scale = double.Max(atWhite.X, double.Max(atWhite.Y, atWhite.Z)); + if (!(scale > 0)) throw new InvalidDataException("DNG: colour matrix maps white outside the camera gamut"); + return Scale(pcsToCamera, 1 / scale).Inverse(); + } + + /// Weight of calibration 1 for a scene white: 1 at or below its temperature, 0 at or above calibration 2's, + /// linear in inverse temperature between (DNG §6 "Linear Interpolation Based on Correlated Color Temperature"). + private double Weight(Chromaticity white) + { + if (ColorMatrix2 is null) return 1; + var t1 = IlluminantTemperature(CalibrationIlluminant1); + var t2 = IlluminantTemperature(CalibrationIlluminant2); + if (t1 <= 0 || t2 <= 0 || t1 == t2) return 1; + var t = Temperature(white); + var swap = t1 > t2; + var (lo, hi) = swap ? (t2, t1) : (t1, t2); + double g; + if (t <= lo) g = 1; + else if (t >= hi) g = 0; + else g = (1 / t - 1 / hi) / (1 / lo - 1 / hi); + return swap ? 1 - g : g; + } + + /// Temperatures the DNG SDK assigns to the Exif LightSource codes (fluorescents use the band centre); 0 when unknown. + public static double IlluminantTemperature(int lightSource) => lightSource switch + { + 17 or 3 => 2850, + 24 => 3200, + 23 => 5000, + 20 or 1 or 9 or 4 or 18 => 5500, + 21 or 19 or 10 => 6500, + 22 or 11 => 7500, + 12 => (5700 + 7100) / 2.0, + 13 => (4600 + 5500) / 2.0, + 14 or 2 => (3800 + 4500) / 2.0, + 15 => (3250 + 3800) / 2.0, + 16 => (2600 + 3250) / 2.0, + _ => 0, + }; + + /// Correlated colour temperature by Robertson's method (isotemperature lines in CIE 1960 uv, + /// Wyszecki & Stiles table) as the DNG SDK computes it; results clamp to 1 667–100 000 K. + public static double Temperature(Chromaticity xy) + { + var d = 1.5 - xy.X + 6 * xy.Y; + var u = 2 * xy.X / d; + var v = 3 * xy.Y / d; + double lastDt = 0; + var table = Robertson; + for (var i = 1; i < table.Length; i++) + { + var (_, tu, tv, slope) = table[i]; + var len = double.Sqrt(1 + slope * slope); + double du = 1 / len, dv = slope / len; + var dt = -(u - tu) * dv + (v - tv) * du; + if (dt <= 0 || i == table.Length - 1) + { + if (dt > 0) dt = 0; + dt = -dt; + var f = i == 1 ? 0 : dt / (lastDt + dt); + return 1e6 / (table[i - 1].Mired * f + table[i].Mired * (1 - f)); + } + lastDt = dt; + } + return 1e6 / table[^1].Mired; + } + + /// Robertson (1968) isotemperature lines: mired, u, v, slope. + private static readonly (double Mired, double U, double V, double Slope)[] Robertson = + [ + (0, 0.18006, 0.26352, -0.24341), (10, 0.18066, 0.26589, -0.25479), (20, 0.18133, 0.26846, -0.26876), + (30, 0.18208, 0.27119, -0.28539), (40, 0.18293, 0.27407, -0.30470), (50, 0.18388, 0.27709, -0.32675), + (60, 0.18494, 0.28021, -0.35156), (70, 0.18611, 0.28342, -0.37915), (80, 0.18740, 0.28668, -0.40955), + (90, 0.18880, 0.28997, -0.44278), (100, 0.19032, 0.29326, -0.47888), (125, 0.19462, 0.30141, -0.58204), + (150, 0.19962, 0.30921, -0.70471), (175, 0.20525, 0.31647, -0.84901), (200, 0.21142, 0.32312, -1.0182), + (225, 0.21807, 0.32909, -1.2168), (250, 0.22511, 0.33439, -1.4512), (275, 0.23247, 0.33904, -1.7298), + (300, 0.24010, 0.34308, -2.0637), (325, 0.24702, 0.34655, -2.4681), (350, 0.25591, 0.34951, -2.9641), + (375, 0.26400, 0.35200, -3.5814), (400, 0.27218, 0.35407, -4.3633), (425, 0.28039, 0.35577, -5.3762), + (450, 0.28863, 0.35714, -6.7262), (475, 0.29685, 0.35823, -8.5955), (500, 0.30505, 0.35907, -11.324), + (525, 0.31320, 0.35968, -15.628), (550, 0.32129, 0.36011, -23.325), (575, 0.32931, 0.36038, -40.770), + (600, 0.33724, 0.36051, -116.45), + ]; + + /// Rows scaled so that the camera neutral (1, 1, 1) maps exactly to the D50 white (DNG SDK NormalizeForwardMatrix). + private static Matrix3 NormalizeForward(Matrix3 m, Vector3D d50) + { + var one = m * new Vector3D(1, 1, 1); + if (!(one.X > 0 && one.Y > 0 && one.Z > 0)) return m; + return Matrix3.Diagonal(d50.X / one.X, d50.Y / one.Y, d50.Z / one.Z) * m; + } + + private static Matrix3 Blend(Matrix3 a, Matrix3? b, double weightA) + { + if (b is not { } m || weightA >= 1) return a; + var wb = 1 - weightA; + return new Matrix3( + a.M11 * weightA + m.M11 * wb, a.M12 * weightA + m.M12 * wb, a.M13 * weightA + m.M13 * wb, + a.M21 * weightA + m.M21 * wb, a.M22 * weightA + m.M22 * wb, a.M23 * weightA + m.M23 * wb, + a.M31 * weightA + m.M31 * wb, a.M32 * weightA + m.M32 * wb, a.M33 * weightA + m.M33 * wb); + } + + private static Matrix3 Scale(Matrix3 m, double s) => new( + m.M11 * s, m.M12 * s, m.M13 * s, m.M21 * s, m.M22 * s, m.M23 * s, m.M31 * s, m.M32 * s, m.M33 * s); + + private static Vector3D Normalize(Vector3D v) + { + var max = double.Max(v.X, double.Max(v.Y, v.Z)); + if (!(max > 0) || !double.IsFinite(max)) throw new InvalidDataException("DNG: camera neutral is not positive"); + return new Vector3D(v.X / max, v.Y / max, v.Z / max); + } + + private static bool Usable(Matrix3 m) => + double.IsFinite(m.Determinant) && m.TryInvert(out _); +} diff --git a/src/Titano.Core/Codecs/Dng/DngOpcodes.cs b/src/Titano.Core/Codecs/Dng/DngOpcodes.cs new file mode 100644 index 00000000..ca0dba5f --- /dev/null +++ b/src/Titano.Core/Codecs/Dng/DngOpcodes.cs @@ -0,0 +1,712 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Dng; + +/// +/// Image an opcode list runs on (DNG 1.6 §7): list 1 sees the stored raw values divided by 65535, list 2 the linearised +/// mosaic (0 = black, 1 = white), list 3 the demosaiced planes. Coordinates of opcode parameters are full-resolution +/// stage coordinates; a binned (half-size) image covers stage pixels per buffer pixel. +/// +internal sealed class OpcodeImage(ImageBuffer pixels, int left, int top, int step, CfaPattern? cfa) +{ + public ImageBuffer Pixels { get; set; } = pixels; + + /// Stage coordinates of buffer pixel (0, 0)'s block. + public int Left { get; set; } = left; + + public int Top { get; set; } = top; + + /// Stage pixels per buffer pixel along each axis (1 at full resolution). + public int Step { get; } = step; + + /// CFA of a mosaic, anchored at buffer pixel (0, 0); null for planar images. + public CfaPattern? Cfa { get; set; } = cfa; + + /// Per-pixel clip flags that must stay aligned with (trimmed together). + public byte[]? ClipMask { get; set; } + + public int Width => Pixels.Width; + public int Height => Pixels.Height; + + /// Stage bounds covered by the buffer. + public RawRect Bounds => new(Left, Top, Left + Width * Step, Top + Height * Step); + + /// Stage coordinate of a buffer column's centre (integer at full resolution). + public double StageX(int x) => Left + x * Step + (Step - 1) / 2.0; + + public double StageY(int y) => Top + y * Step + (Step - 1) / 2.0; + + /// Buffer coordinate of a stage coordinate. + public double BufferX(double stageX) => (stageX - Left - (Step - 1) / 2.0) / Step; + + public double BufferY(double stageY) => (stageY - Top - (Step - 1) / 2.0) / Step; +} + +/// One parsed opcode. Flag bit 0 marks it optional, bit 1 "may be skipped for previews". +internal abstract class DngOpcode(uint id, uint flags) +{ + public uint Id { get; } = id; + public uint Flags { get; } = flags; + public bool Optional => (Flags & 1) != 0; + + /// True when the opcode works on value magnitudes in a way that does not commute with white-balance scaling. + public virtual bool NeedsUnbalancedValues => false; + + public abstract string Name { get; } + + public abstract void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken); +} + +/// +/// DNG opcode lists (DNG 1.6 chapter 7, big-endian): WarpRectilinear (1), FixVignetteRadial (3), FixBadPixelsConstant (4), +/// FixBadPixelsList (5), TrimBounds (6), MapTable (7), MapPolynomial (8), GainMap (9), DeltaPerRow/Column (10/11) and +/// ScalePerRow/Column (12/13). Other opcodes (WarpFisheye, WarpRectilinear2, vendor extensions) are skipped with a warning +/// that says whether the file marked them optional. +/// +internal static class DngOpcodes +{ + private const int MaxOpcodes = 256; + private const long MaxGainMapPoints = 1 << 22; + + /// Parses an OpcodeList tag value; malformed opcodes are dropped with a warning. + public static List Parse(byte[]? data, int list, ICollection warnings) + { + var result = new List(); + if (data is null || data.Length < 4) return result; + var count = BinaryPrimitives.ReadUInt32BigEndian(data); + var pos = 4; + for (var i = 0; i < count && i < MaxOpcodes; i++) + { + if (pos + 16 > data.Length) + { + warnings.Add($"DNG: opcode list {list} truncated"); + break; + } + var id = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos)); + var flags = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos + 8)); + var size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos + 12)); + pos += 16; + if (size > data.Length - pos) + { + warnings.Add($"DNG: opcode list {list} truncated"); + break; + } + var reader = new ParamReader(data.AsSpan(pos, (int)size)); + pos += (int)size; + var op = Create(id, flags, ref reader); + if (op is null) + { + warnings.Add((flags & 1) != 0 + ? $"DNG: optional opcode {id} in list {list} not supported; skipped" + : $"DNG: required opcode {id} in list {list} not supported; skipped, rendering may differ"); + } + else if (!reader.Ok) + { + warnings.Add($"DNG: opcode {op.Name} in list {list} has malformed parameters; skipped"); + } + else + { + result.Add(op); + } + } + return result; + } + + /// Applies every opcode in order. + public static void Apply(IReadOnlyList opcodes, OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + foreach (var op in opcodes) + { + cancellationToken.ThrowIfCancellationRequested(); + op.Apply(image, warnings, cancellationToken); + } + } + + private static DngOpcode? Create(uint id, uint flags, ref ParamReader r) => id switch + { + 1 => WarpRectilinear.Read(flags, ref r), + 3 => new FixVignetteRadial(flags, r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64()), + 4 => FixBadPixelsConstant.Read(flags, ref r), + 5 => FixBadPixelsList.Read(flags, ref r), + 6 => TrimBounds.Read(flags, ref r), + 7 => MapTable.Read(flags, ref r), + 8 => MapPolynomial.Read(flags, ref r), + 9 => GainMap.Read(flags, ref r), + 10 or 11 or 12 or 13 => PerLine.Read(id, flags, ref r), + _ => null, + }; + + /// Big-endian parameter reader that turns overruns into = false instead of throwing. + internal ref struct ParamReader(ReadOnlySpan data) + { + private readonly ReadOnlySpan _data = data; + private int _pos; + + public bool Ok { get; private set; } = true; + public int Remaining => _data.Length - _pos; + + public uint U32() => Take(4) ? BinaryPrimitives.ReadUInt32BigEndian(_data[(_pos - 4)..]) : 0; + + /// A 32-bit coordinate limited to the int range. + public uint Bounded() + { + var v = U32(); + if (v > int.MaxValue / 4) Ok = false; + return v; + } + + public ushort U16() => Take(2) ? BinaryPrimitives.ReadUInt16BigEndian(_data[(_pos - 2)..]) : (ushort)0; + + public float F32() => Take(4) ? BinaryPrimitives.ReadSingleBigEndian(_data[(_pos - 4)..]) : 0; + + public double F64() + { + var v = Take(8) ? BinaryPrimitives.ReadDoubleBigEndian(_data[(_pos - 8)..]) : 0; + if (!double.IsFinite(v)) Ok = false; + return v; + } + + public void Fail() => Ok = false; + + private bool Take(int n) + { + if (!Ok || _pos + n > _data.Length) + { + Ok = false; + return false; + } + _pos += n; + return true; + } + } + + /// Area of effect shared by the per-pixel opcodes: rectangle, plane range and row/column pitch. + internal readonly record struct AreaSpec(RawRect Area, int Plane, int Planes, int RowPitch, int ColPitch) + { + public static AreaSpec Read(ref ParamReader r) + { + var top = (int)r.Bounded(); + var left = (int)r.Bounded(); + var bottom = (int)r.Bounded(); + var right = (int)r.Bounded(); + var plane = (int)r.Bounded(); + var planes = (int)r.Bounded(); + var rowPitch = (int)r.Bounded(); + var colPitch = (int)r.Bounded(); + if (rowPitch < 1 || colPitch < 1 || planes < 1) r.Fail(); + return new AreaSpec(new RawRect(left, top, right, bottom), plane, planes, rowPitch, colPitch); + } + + /// Visits every affected (plane, buffer x, buffer y, stage x, stage y) on the pitch grid; rows run in + /// parallel, so may only touch its own pixel. + public void ForEach(OpcodeImage image, Action pixel, ICollection warnings, string name, CancellationToken cancellationToken) + { + if (image.Step != 1 && (RowPitch != 1 || ColPitch != 1)) + { + warnings.Add($"DNG: {name} with pitch cannot apply to a binned image; skipped"); + return; + } + var area = Area.Intersect(image.Bounds); + if (area.IsEmpty) return; + var lastPlane = int.Min(image.Pixels.Channels, Plane + Planes); + var firstRow = Area.Top + Ceil(area.Top - Area.Top, RowPitch); + var firstCol = Area.Left + Ceil(area.Left - Area.Left, ColPitch); + var rowStep = RowPitch * image.Step; + var colStep = ColPitch * image.Step; + var rows = (area.Bottom - firstRow + rowStep - 1) / rowStep; + if (rows <= 0 || firstCol >= area.Right) return; + var plane = Plane; + Parallel.For(0, rows, new ParallelOptions { CancellationToken = cancellationToken }, k => + { + var sy = firstRow + k * rowStep; + var y = (int)double.Round(image.BufferY(sy)); + if ((uint)y >= (uint)image.Height) return; + for (var p = plane; p < lastPlane; p++) + { + for (var sx = firstCol; sx < area.Right; sx += colStep) + { + var x = (int)double.Round(image.BufferX(sx)); + if ((uint)x < (uint)image.Width) pixel(p, x, y, sx, sy); + } + } + }); + } + + private static int Ceil(int offset, int pitch) => (offset + pitch - 1) / pitch * pitch; + } + + /// Distance from the normalised optical centre to the farthest corner of the stage bounds. + private static (double Cx, double Cy, double MaxDistance) Centre(RawRect bounds, double cx, double cy) + { + var x = bounds.Left + cx * bounds.Width; + var y = bounds.Top + cy * bounds.Height; + var m = 0.0; + foreach (var (px, py) in (ReadOnlySpan<(int, int)>)[(bounds.Left, bounds.Top), (bounds.Right, bounds.Top), (bounds.Left, bounds.Bottom), (bounds.Right, bounds.Bottom)]) + m = double.Max(m, double.Hypot(px - x, py - y)); + return (x, y, double.Max(m, 1e-9)); + } + + /// WarpRectilinear: radial (kr0–kr3) and tangential (kt0, kt1) distortion per plane, mapping each corrected + /// pixel to its source position; resampled with Catmull-Rom. + private sealed class WarpRectilinear(uint flags, double[][] coefficients, double cx, double cy) : DngOpcode(1, flags) + { + public override string Name => "WarpRectilinear"; + + public static WarpRectilinear? Read(uint flags, ref ParamReader r) + { + var n = r.U32(); + if (n is < 1 or > 4) + { + r.Fail(); + return new WarpRectilinear(flags, [], 0, 0); + } + var k = new double[n][]; + for (var i = 0; i < n; i++) k[i] = [r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64()]; + return new WarpRectilinear(flags, k, r.F64(), r.F64()); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + if (image.Cfa is not null) + { + warnings.Add("DNG: WarpRectilinear on mosaic data is not supported; skipped"); + return; + } + var src = image.Pixels; + var dst = new ImageBuffer(src.Width, src.Height, src.Channels, clear: false); + var (cxs, cys, m) = Centre(image.Bounds, cx, cy); + Parallel.For(0, src.Height, new ParallelOptions { CancellationToken = cancellationToken }, y => + { + var sy = image.StageY(y); + for (var p = 0; p < src.Channels; p++) + { + var k = coefficients[int.Min(p, coefficients.Length - 1)]; + var plane = src.Plane(p); + var row = dst.Row(p, y); + for (var x = 0; x < src.Width; x++) + { + var dx = (image.StageX(x) - cxs) / m; + var dy = (sy - cys) / m; + var r2 = dx * dx + dy * dy; + var f = k[0] + r2 * (k[1] + r2 * (k[2] + r2 * k[3])); + var tx = k[4] * 2 * dx * dy + k[5] * (r2 + 2 * dx * dx); + var ty = k[5] * 2 * dx * dy + k[4] * (r2 + 2 * dy * dy); + var xs = image.BufferX(cxs + m * (f * dx + tx)); + var ys = image.BufferY(cys + m * (f * dy + ty)); + row[x] = Sampling.CatmullRom(plane, src.Width, src.Height, xs, ys); + } + } + }); + src.Dispose(); + image.Pixels = dst; + } + } + + /// FixVignetteRadial: gain 1 + k0·r² + k1·r⁴ + k2·r⁶ + k3·r⁸ + k4·r¹⁰ about the normalised centre. + private sealed class FixVignetteRadial(uint flags, double k0, double k1, double k2, double k3, double k4, double cx, double cy) : DngOpcode(3, flags) + { + public override string Name => "FixVignetteRadial"; + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var (cxs, cys, m) = Centre(image.Bounds, cx, cy); + var pixels = image.Pixels; + Parallel.For(0, pixels.Height, new ParallelOptions { CancellationToken = cancellationToken }, y => + { + var dy = (image.StageY(y) - cys) / m; + for (var x = 0; x < pixels.Width; x++) + { + var dx = (image.StageX(x) - cxs) / m; + var r2 = dx * dx + dy * dy; + var gain = (float)(1 + r2 * (k0 + r2 * (k1 + r2 * (k2 + r2 * (k3 + r2 * k4))))); + for (var p = 0; p < pixels.Channels; p++) pixels.Row(p, y)[x] *= gain; + } + }); + } + } + + /// FixBadPixelsConstant: pixels whose 16-bit value equals the constant are replaced from good neighbours. + /// The BayerPhase parameter is not needed: the frame's own CFA pattern identifies same-colour neighbours. + private sealed class FixBadPixelsConstant(uint flags, uint constant) : DngOpcode(4, flags) + { + public override string Name => "FixBadPixelsConstant"; + public override bool NeedsUnbalancedValues => true; + + public static FixBadPixelsConstant Read(uint flags, ref ParamReader r) + { + var constant = r.U32(); + r.U32(); + return new FixBadPixelsConstant(flags, constant); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + if (constant > 65535) return; + var pixels = image.Pixels; + var bad = new List<(int X, int Y)>(); + for (var y = 0; y < pixels.Height; y++) + { + for (var x = 0; x < pixels.Width; x++) + { + for (var p = 0; p < pixels.Channels; p++) + { + if (Sampling.Code16(pixels.Row(p, y)[x]) != constant) continue; + bad.Add((x, y)); + break; + } + } + } + BadPixelRepair.Repair(image, bad); + } + } + + /// FixBadPixelsList: listed points (row, column) and rectangles are replaced from good neighbours. + private sealed class FixBadPixelsList(uint flags, (int Row, int Col)[] points, RawRect[] rects) : DngOpcode(5, flags) + { + private const int MaxEntries = 1 << 22; + + public override string Name => "FixBadPixelsList"; + + public static FixBadPixelsList Read(uint flags, ref ParamReader r) + { + r.U32(); + var pointCount = r.U32(); + var rectCount = r.U32(); + if (pointCount > MaxEntries || rectCount > MaxEntries || (long)pointCount * 8 + (long)rectCount * 16 > r.Remaining) + { + r.Fail(); + return new FixBadPixelsList(flags, [], []); + } + var points = new (int, int)[pointCount]; + for (var i = 0; i < points.Length; i++) points[i] = ((int)r.Bounded(), (int)r.Bounded()); + var rects = new RawRect[rectCount]; + for (var i = 0; i < rects.Length; i++) + { + var top = (int)r.Bounded(); + var left = (int)r.Bounded(); + var bottom = (int)r.Bounded(); + var right = (int)r.Bounded(); + rects[i] = new RawRect(left, top, right, bottom); + } + return new FixBadPixelsList(flags, points, rects); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + if (image.Step != 1) + { + warnings.Add("DNG: FixBadPixelsList cannot apply to a binned image; skipped"); + return; + } + var bad = new List<(int X, int Y)>(); + var bounds = image.Bounds; + foreach (var (row, col) in points) + { + if (col >= bounds.Left && col < bounds.Right && row >= bounds.Top && row < bounds.Bottom) bad.Add((col - image.Left, row - image.Top)); + } + foreach (var rect in rects) + { + var r = rect.Intersect(bounds); + for (var y = r.Top; y < r.Bottom && bad.Count < MaxEntries; y++) + { + for (var x = r.Left; x < r.Right; x++) bad.Add((x - image.Left, y - image.Top)); + } + } + BadPixelRepair.Repair(image, bad); + } + } + + /// TrimBounds: crops the image to a stage rectangle. + private sealed class TrimBounds(uint flags, RawRect bounds) : DngOpcode(6, flags) + { + public override string Name => "TrimBounds"; + + public static TrimBounds Read(uint flags, ref ParamReader r) + { + var top = (int)r.Bounded(); + var left = (int)r.Bounded(); + var bottom = (int)r.Bounded(); + var right = (int)r.Bounded(); + return new TrimBounds(flags, new RawRect(left, top, right, bottom)); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var b = bounds.Intersect(image.Bounds); + var x0 = (int)double.Ceiling(image.BufferX(b.Left) - 1e-9); + var y0 = (int)double.Ceiling(image.BufferY(b.Top) - 1e-9); + var x1 = int.Min(image.Width, (int)double.Floor(image.BufferX(b.Right - 1) + 1e-9) + 1); + var y1 = int.Min(image.Height, (int)double.Floor(image.BufferY(b.Bottom - 1) + 1e-9) + 1); + x0 = int.Max(0, x0); + y0 = int.Max(0, y0); + if (x1 - x0 <= 0 || y1 - y0 <= 0) + { + warnings.Add("DNG: TrimBounds outside the image; skipped"); + return; + } + if (x0 == 0 && y0 == 0 && x1 == image.Width && y1 == image.Height) return; + var src = image.Pixels; + var dst = new ImageBuffer(x1 - x0, y1 - y0, src.Channels, clear: false); + for (var p = 0; p < src.Channels; p++) + { + for (var y = y0; y < y1; y++) src.Row(p, y).Slice(x0, x1 - x0).CopyTo(dst.Row(p, y - y0)); + } + if (image.ClipMask is { } mask) + { + var trimmed = new byte[dst.PlaneLength]; + for (var y = y0; y < y1; y++) mask.AsSpan(y * src.Width + x0, x1 - x0).CopyTo(trimmed.AsSpan((y - y0) * dst.Width)); + image.ClipMask = trimmed; + } + if (image.Cfa is { } cfa) image.Cfa = cfa.Shift(x0, y0); + image.Left += x0 * image.Step; + image.Top += y0 * image.Step; + src.Dispose(); + image.Pixels = dst; + } + } + + /// MapTable: 16-bit lookup over the area (inputs beyond the table use its last entry). + private sealed class MapTable(uint flags, AreaSpec area, ushort[] table) : DngOpcode(7, flags) + { + public override string Name => "MapTable"; + public override bool NeedsUnbalancedValues => true; + + public static MapTable Read(uint flags, ref ParamReader r) + { + var area = AreaSpec.Read(ref r); + var size = r.U32(); + if (size is < 1 or > 65536 || size * 2 > r.Remaining) + { + r.Fail(); + return new MapTable(flags, area, [0]); + } + var table = new ushort[size]; + for (var i = 0; i < table.Length; i++) table[i] = r.U16(); + return new MapTable(flags, area, table); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var pixels = image.Pixels; + var last = table.Length - 1; + area.ForEach(image, (p, x, y, _, _) => + { + var row = pixels.Row(p, y); + row[x] = table[int.Min(Sampling.Code16(row[x]), last)] / 65535f; + }, warnings, Name, cancellationToken); + } + } + + /// MapPolynomial: out = Σ cᵢ·inⁱ on normalised values. + private sealed class MapPolynomial(uint flags, AreaSpec area, double[] coefficients) : DngOpcode(8, flags) + { + public override string Name => "MapPolynomial"; + public override bool NeedsUnbalancedValues => true; + + public static MapPolynomial Read(uint flags, ref ParamReader r) + { + var area = AreaSpec.Read(ref r); + var degree = r.U32(); + if (degree > 8) + { + r.Fail(); + return new MapPolynomial(flags, area, [0]); + } + var c = new double[degree + 1]; + for (var i = 0; i < c.Length; i++) c[i] = r.F64(); + return new MapPolynomial(flags, area, c); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var pixels = image.Pixels; + area.ForEach(image, (p, x, y, _, _) => + { + var row = pixels.Row(p, y); + double v = row[x], acc = 0; + for (var i = coefficients.Length - 1; i >= 0; i--) acc = acc * v + coefficients[i]; + row[x] = (float)acc; + }, warnings, Name, cancellationToken); + } + } + + /// GainMap: a grid of gains (normalised origin and spacing over the image bounds), bilinearly interpolated + /// and clamped at the grid edges, multiplied into the area. + private sealed class GainMap(uint flags, AreaSpec area, int pointsV, int pointsH, double spacingV, double spacingH, double originV, double originH, int mapPlanes, float[] gains) : DngOpcode(9, flags) + { + public override string Name => "GainMap"; + + public static GainMap Read(uint flags, ref ParamReader r) + { + var area = AreaSpec.Read(ref r); + var pv = r.U32(); + var ph = r.U32(); + var sv = r.F64(); + var sh = r.F64(); + var ov = r.F64(); + var oh = r.F64(); + var planes = r.U32(); + var count = (long)pv * ph * planes; + if (pv < 1 || ph < 1 || planes < 1 || count > MaxGainMapPoints || count * 4 > r.Remaining || !(sv > 0) || !(sh > 0)) + { + r.Fail(); + return new GainMap(flags, area, 1, 1, 1, 1, 0, 0, 1, [1]); + } + var gains = new float[count]; + for (var i = 0; i < gains.Length; i++) gains[i] = r.F32(); + return new GainMap(flags, area, (int)pv, (int)ph, sv, sh, ov, oh, (int)planes, gains); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var pixels = image.Pixels; + var bounds = image.Bounds; + area.ForEach(image, (p, x, y, _, _) => + { + var plane = int.Min(p - area.Plane, mapPlanes - 1); + var (r0, r1, fr) = Index((image.StageY(y) - bounds.Top) / bounds.Height, originV, spacingV, pointsV); + var (c0, c1, fc) = Index((image.StageX(x) - bounds.Left) / bounds.Width, originH, spacingH, pointsH); + var g00 = gains[(r0 * pointsH + c0) * mapPlanes + plane]; + var g01 = gains[(r0 * pointsH + c1) * mapPlanes + plane]; + var g10 = gains[(r1 * pointsH + c0) * mapPlanes + plane]; + var g11 = gains[(r1 * pointsH + c1) * mapPlanes + plane]; + var top = g00 + (g01 - g00) * fc; + var bottom = g10 + (g11 - g10) * fc; + pixels.Row(p, y)[x] *= (float)(top + (bottom - top) * fr); + }, warnings, Name, cancellationToken); + } + + private static (int I0, int I1, double Fraction) Index(double position, double origin, double spacing, int points) + { + var f = (position - origin) / spacing; + if (!(f > 0)) return (0, 0, 0); + if (f >= points - 1) return (points - 1, points - 1, 0); + var i = (int)f; + return (i, i + 1, f - i); + } + } + + /// DeltaPerRow/Column (offsets, normalised units) and ScalePerRow/Column (gains), one value per pitch step. + private sealed class PerLine(uint id, uint flags, AreaSpec area, float[] values) : DngOpcode(id, flags) + { + public override string Name => Id switch { 10 => "DeltaPerRow", 11 => "DeltaPerColumn", 12 => "ScalePerRow", _ => "ScalePerColumn" }; + public override bool NeedsUnbalancedValues => Id is 10 or 11; + + public static PerLine Read(uint id, uint flags, ref ParamReader r) + { + var area = AreaSpec.Read(ref r); + var count = r.U32(); + if (count > 1 << 20 || count * 4 > r.Remaining) + { + r.Fail(); + return new PerLine(id, flags, area, []); + } + var values = new float[count]; + for (var i = 0; i < values.Length; i++) values[i] = r.F32(); + return new PerLine(id, flags, area, values); + } + + public override void Apply(OpcodeImage image, ICollection warnings, CancellationToken cancellationToken) + { + var pixels = image.Pixels; + var perRow = Id is 10 or 12; + var add = Id is 10 or 11; + area.ForEach(image, (p, x, y, sx, sy) => + { + var index = perRow ? (sy - area.Area.Top) / area.RowPitch : (sx - area.Area.Left) / area.ColPitch; + if ((uint)index >= (uint)values.Length) return; + ref var v = ref pixels.Row(p, y)[x]; + v = add ? v + values[index] : v * values[index]; + }, warnings, Name, cancellationToken); + } + } +} + +/// Bad-pixel replacement shared by the FixBadPixels opcodes: mean of the nearest good pixels of the same CFA colour +/// (5×5, widened to 9×9 when needed), or of the 8 neighbours per plane for planar images. +internal static class BadPixelRepair +{ + public static void Repair(OpcodeImage image, List<(int X, int Y)> bad) + { + if (bad.Count == 0) return; + var pixels = image.Pixels; + int w = pixels.Width, h = pixels.Height; + var isBad = new HashSet(bad.Count); + foreach (var (x, y) in bad) isBad.Add((long)y * w + x); + var replacements = new float[bad.Count * pixels.Channels]; + for (var i = 0; i < bad.Count; i++) + { + var (x, y) = bad[i]; + for (var p = 0; p < pixels.Channels; p++) + { + var plane = pixels.Plane(p); + var value = plane[y * w + x]; + for (var radius = image.Cfa is null ? 1 : 2; radius <= 4; radius += 2) + { + double sum = 0; + var n = 0; + for (var dy = -radius; dy <= radius; dy++) + { + for (var dx = -radius; dx <= radius; dx++) + { + int nx = x + dx, ny = y + dy; + if ((dx | dy) == 0 || (uint)nx >= (uint)w || (uint)ny >= (uint)h || isBad.Contains((long)ny * w + nx)) continue; + if (image.Cfa is { } cfa && cfa.ColorAt(nx, ny) != cfa.ColorAt(x, y)) continue; + sum += plane[ny * w + nx]; + n++; + } + } + if (n > 0) + { + value = (float)(sum / n); + break; + } + } + replacements[i * pixels.Channels + p] = value; + } + } + for (var i = 0; i < bad.Count; i++) + { + var (x, y) = bad[i]; + for (var p = 0; p < pixels.Channels; p++) pixels.Plane(p)[y * w + x] = replacements[i * pixels.Channels + p]; + // A repaired sample no longer carries the sensor's clipping (a hot pixel is not a highlight). + if (image.ClipMask is { } mask) mask[y * w + x] = 0; + } + } +} + +/// Sampling helpers for the opcode and pipeline stages. +internal static class Sampling +{ + /// Normalised value → 16-bit code (rounded, clamped), the integer domain of MapTable and FixBadPixelsConstant. + public static int Code16(float v) => v >= 1f ? 65535 : v > 0f ? (int)(v * 65535f + 0.5f) : 0; + + /// Catmull-Rom interpolation of a plane at a fractional position (edges clamped; far outside reads the edge). + public static float CatmullRom(ReadOnlySpan plane, int width, int height, double x, double y) + { + x = double.Clamp(x, -2, width + 1); + y = double.Clamp(y, -2, height + 1); + var ix = (int)double.Floor(x); + var iy = (int)double.Floor(y); + var (x0, x1, x2, x3) = Weights((float)(x - ix)); + var (y0, y1, y2, y3) = Weights((float)(y - iy)); + int c0 = int.Clamp(ix - 1, 0, width - 1), c1 = int.Clamp(ix, 0, width - 1), c2 = int.Clamp(ix + 1, 0, width - 1), c3 = int.Clamp(ix + 2, 0, width - 1); + var sum = 0f; + for (var j = 0; j < 4; j++) + { + var o = int.Clamp(iy - 1 + j, 0, height - 1) * width; + var r = x0 * plane[o + c0] + x1 * plane[o + c1] + x2 * plane[o + c2] + x3 * plane[o + c3]; + sum += r * (j switch { 0 => y0, 1 => y1, 2 => y2, _ => y3 }); + } + return sum; + } + + private static (float, float, float, float) Weights(float t) + { + var t2 = t * t; + var t3 = t2 * t; + return (0.5f * (-t3 + 2 * t2 - t), 0.5f * (3 * t3 - 5 * t2 + 2), 0.5f * (-3 * t3 + 4 * t2 + t), 0.5f * (t3 - t2)); + } +} diff --git a/src/Titano.Core/Codecs/Dng/DngReader.cs b/src/Titano.Core/Codecs/Dng/DngReader.cs new file mode 100644 index 00000000..786793d5 --- /dev/null +++ b/src/Titano.Core/Codecs/Dng/DngReader.cs @@ -0,0 +1,247 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Dng; + +/// +/// Reads the raw image description of a DNG (DNG 1.6 chapters 4–6) into a : the full-resolution +/// CFA (PhotometricInterpretation 32803) or LinearRaw (34892) IFD among IFD0 and its SubIFDs; compression 1, 7 (lossless +/// JPEG, including two-component interleaved tiles), 8 (Deflate with integer or floating-point predictors) and 34892 +/// (lossy JPEG); CFA pattern and plane colours; LinearizationTable; BlackLevel with BlackLevelRepeatDim and DeltaH/V; +/// WhiteLevel; ActiveArea; DefaultCropOrigin/Size and DefaultScale; the colour tags; OpcodeList1–3; Orientation. +/// Raster tags are taken from the raw IFD (falling back to IFD0), colour tags from IFD0 (falling back to the raw IFD). +/// +internal static class DngReader +{ + private const uint PhotometricCfa = 32803, PhotometricLinearRaw = 34892; + private const ushort CameraCalibrationSignature = 0xC6F3, ProfileCalibrationSignature = 0xC6F4; + private const long MaxPixels = 1L << 28; + private const int MaxSubIfds = 16; + + /// Not a DNG, no supported raw IFD, or inconsistent tags. + public static RawFrame Read(Stream stream) + { + var r = TiffReader.Open(stream) ?? throw new InvalidDataException("DNG: missing TIFF header"); + var chain = r.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("DNG: no image directory"); + var ifd0 = chain[0]; + if (!ifd0.Has(TiffTags.DngVersion)) throw new InvalidDataException("DNG: DNGVersion missing"); + var raw = FindRawIfd(r, chain) ?? throw new InvalidDataException("DNG: no full-resolution CFA or LinearRaw image"); + + var width = (int)long.Min(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, int.MaxValue); + var height = (int)long.Min(r.GetUInt(raw, TiffTags.ImageLength) ?? 0, int.MaxValue); + if (width <= 0 || height <= 0 || (long)width * height > MaxPixels) throw new InvalidDataException($"DNG: unsupported raster size {width}x{height}"); + var spp = (int)(r.GetUInt(raw, TiffTags.SamplesPerPixel) ?? 1); + var photometric = r.GetUInt(raw, TiffTags.PhotometricInterpretation); + var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1; + if (compression is not (1 or 7 or 8 or 34892)) throw new InvalidDataException($"DNG: compression {compression} is not supported"); + var floating = (r.GetUInt(raw, TiffTags.SampleFormat) ?? 1) == 3; + var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 16); + + CfaPattern? cfa = null; + if (photometric == PhotometricCfa) + { + if (spp != 1) throw new InvalidDataException("DNG: CFA data must have one sample per pixel"); + cfa = ReadCfa(r, raw); + } + else if (spp is not (1 or 3)) + { + throw new InvalidDataException($"DNG: LinearRaw with {spp} samples per pixel is not supported"); + } + + var activeArea = new RawRect(0, 0, width, height); + if (Values(r, raw, ifd0, TiffTags.ActiveArea, 4) is [var top, var left, var bottom, var right, ..]) + { + activeArea = new RawRect((int)left, (int)top, (int)right, (int)bottom).Intersect(activeArea); + if (activeArea.IsEmpty) throw new InvalidDataException("DNG: empty ActiveArea"); + } + + var warnings = new List(); + var frame = new RawFrame + { + Decoder = "managed-dng", + Width = width, + Height = height, + SamplesPerPixel = spp, + Cfa = cfa, + ActiveArea = activeArea, + DefaultCrop = ReadCrop(r, raw, ifd0, activeArea), + DefaultScale = Values(r, raw, ifd0, TiffTags.DefaultScale, 2) is [var sh, var sv, ..] && sh > 0 && sv > 0 && sh < 16 && sv < 16 ? (sh, sv) : (1, 1), + Linearization = ReadLinearization(r, raw, ifd0), + Black = ReadBlack(r, raw, ifd0, spp, activeArea, warnings), + White = ReadWhite(r, raw, ifd0, spp, floating ? 1.0 : bits is >= 1 and <= 16 ? (1 << bits) - 1 : 65535), + Color = ReadColor(r, ifd0, raw, spp == 1 && cfa is null, warnings), + OpcodeList1 = Bytes(r, raw, ifd0, TiffTags.OpcodeList1), + OpcodeList2 = Bytes(r, raw, ifd0, TiffTags.OpcodeList2), + OpcodeList3 = Bytes(r, raw, ifd0, TiffTags.OpcodeList3), + Orientation = (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1) is var o and >= 1 and <= 8 ? o : 1, + Make = r.GetString(ifd0, TiffTags.Make), + Model = r.GetString(ifd0, TiffTags.Model) ?? r.GetString(ifd0, TiffTags.UniqueCameraModel), + Loader = new TiffRasterLoader(r, raw), + }; + frame.Warnings.AddRange(warnings); + frame.Warnings.AddRange(r.Warnings); + return frame; + } + + /// First IFD with NewSubfileType 0 and a CFA/LinearRaw photometric: IFD0, its SubIFDs (two levels), the chain. + private static Ifd? FindRawIfd(TiffReader r, IReadOnlyList chain) + { + var visited = new HashSet(); + foreach (var ifd in chain) visited.Add(ifd.Position); + var queue = new List<(Ifd Ifd, int Depth)> { (chain[0], 0) }; + for (var i = 0; i < queue.Count; i++) + { + var (ifd, depth) = queue[i]; + if (IsRaw(r, ifd)) return ifd; + if (depth < 2 && ifd.Entries.TryGetValue(TiffTags.SubIfds, out var sub) && sub.Count <= MaxSubIfds) + { + foreach (var offset in r.GetUInts(sub) ?? []) + { + if (r.ReadIfd(offset, visited) is { } child) queue.Add((child, depth + 1)); + } + } + } + foreach (var ifd in chain) + { + if (IsRaw(r, ifd)) return ifd; + } + return null; + } + + private static bool IsRaw(TiffReader r, Ifd ifd) => + (r.GetUInt(ifd, TiffTags.NewSubfileType) ?? 0) == 0 + && r.GetUInt(ifd, TiffTags.PhotometricInterpretation) is PhotometricCfa or PhotometricLinearRaw; + + private static CfaPattern ReadCfa(TiffReader r, Ifd raw) + { + if ((r.GetUInt(raw, TiffTags.CfaLayout) ?? 1) != 1) throw new InvalidDataException("DNG: non-rectangular CFA layouts are not supported"); + var dim = IfdValue.UInts(r, raw, TiffTags.CfaRepeatPatternDim) ?? [2, 2]; + if (dim.Length < 2) throw new InvalidDataException("DNG: bad CFARepeatPatternDim"); + int rows = (int)dim[0], cols = (int)dim[1]; + if (rows is < 1 or > CfaPattern.MaxSize || cols is < 1 or > CfaPattern.MaxSize) throw new InvalidDataException($"DNG: CFA pattern {rows}x{cols} is not supported"); + var pattern = IfdValue.UInts(r, raw, TiffTags.CfaPattern) ?? throw new InvalidDataException("DNG: CFAPattern missing"); + if (pattern.Length < rows * cols) throw new InvalidDataException("DNG: CFAPattern too short"); + var planeColor = IfdValue.UInts(r, raw, TiffTags.CfaPlaneColor) ?? [0, 1, 2]; + var colors = new byte[rows * cols]; + for (var i = 0; i < colors.Length; i++) + { + // CFAPattern holds colour codes (0 red, 1 green, 2 blue, 3+ CMY/white); CFAPlaneColor names the planes. + var code = pattern[i]; + if (code > 2 || planeColor.Length != 3 || Array.IndexOf(planeColor, code) < 0) + throw new InvalidDataException("DNG: only red/green/blue CFAs are supported"); + colors[i] = (byte)code; + } + return new CfaPattern(cols, rows, colors); + } + + private static RawRect? ReadCrop(TiffReader r, Ifd raw, Ifd ifd0, RawRect active) + { + if (Values(r, raw, ifd0, TiffTags.DefaultCropOrigin, 2) is not [var ox, var oy, ..] || Values(r, raw, ifd0, TiffTags.DefaultCropSize, 2) is not [var cw, var ch, ..]) + return null; + var crop = new RawRect((int)double.Round(ox), (int)double.Round(oy), (int)double.Round(ox + cw), (int)double.Round(oy + ch)) + .Intersect(new RawRect(0, 0, active.Width, active.Height)); + return crop.IsEmpty ? null : crop; + } + + private static ushort[]? ReadLinearization(TiffReader r, Ifd raw, Ifd ifd0) + { + var ifd = raw.Has(TiffTags.LinearizationTable) ? raw : ifd0; + if (!ifd.Entries.TryGetValue(TiffTags.LinearizationTable, out var e) || e.Count is 0 or > 65536) return null; + return r.GetUInts(e) is { } values ? Array.ConvertAll(values, v => (ushort)uint.Min(v, 65535)) : null; + } + + private static RawBlackLevel ReadBlack(TiffReader r, Ifd raw, Ifd ifd0, int spp, RawRect active, ICollection warnings) + { + var dim = Values(r, raw, ifd0, TiffTags.BlackLevelRepeatDim, 2) is [var dr, var dc, ..] ? ((int)dr, (int)dc) : (1, 1); + var (rows, cols) = dim; + if (rows is < 1 or > 64 || cols is < 1 or > 64) + { + warnings.Add("DNG: bad BlackLevelRepeatDim ignored"); + (rows, cols) = (1, 1); + } + var values = new float[rows * cols * spp]; + if (Doubles(r, raw, ifd0, TiffTags.BlackLevel, 1 << 14) is { Length: > 0 } black) + { + if (black.Length != values.Length && black.Length != 1) warnings.Add($"DNG: BlackLevel has {black.Length} values, {values.Length} expected"); + for (var i = 0; i < values.Length; i++) values[i] = (float)black[black.Length == values.Length ? i : i % black.Length]; + } + var deltaH = Doubles(r, raw, ifd0, TiffTags.BlackLevelDeltaH, 1 << 20) is { } h && h.Length >= active.Width ? Array.ConvertAll(h, v => (float)v) : null; + var deltaV = Doubles(r, raw, ifd0, TiffTags.BlackLevelDeltaV, 1 << 20) is { } v && v.Length >= active.Height ? Array.ConvertAll(v, x => (float)x) : null; + return new RawBlackLevel(rows, cols, values, deltaH, deltaV); + } + + private static double[] ReadWhite(TiffReader r, Ifd raw, Ifd ifd0, int spp, double fallback) + { + var white = new double[spp]; + var tag = Doubles(r, raw, ifd0, TiffTags.WhiteLevel, 16); + for (var i = 0; i < spp; i++) white[i] = tag is { Length: > 0 } t ? t[int.Min(i, t.Length - 1)] : fallback; + return white; + } + + private static DngColorProfile ReadColor(TiffReader r, Ifd ifd0, Ifd raw, bool monochrome, ICollection warnings) + { + Matrix3? M(ushort tag) => Doubles(r, ifd0, raw, tag, 64) is { Length: 9 } m ? new Matrix3(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]) : null; + Mathematics.Vector3D? V(ushort tag) => Doubles(r, ifd0, raw, tag, 16) is { Length: 3 } v ? new Mathematics.Vector3D(v[0], v[1], v[2]) : null; + var baseline = Doubles(r, ifd0, raw, TiffTags.BaselineExposure, 1) is [var b] && double.Abs(b) < 16 ? b : 0; + if (monochrome) return new DngColorProfile { BaselineExposure = baseline }; + + // CameraCalibration only applies when its signature matches the profile's (DNG §6, "CameraCalibrationSignature"). + var useCalibration = r.GetString(ifd0, CameraCalibrationSignature) == r.GetString(ifd0, ProfileCalibrationSignature); + if (!useCalibration && (ifd0.Has(TiffTags.CameraCalibration1) || ifd0.Has(TiffTags.CameraCalibration2))) + warnings.Add("DNG: CameraCalibration ignored (signature does not match the profile)"); + var cm1 = M(TiffTags.ColorMatrix1) ?? throw new InvalidDataException("DNG: ColorMatrix1 missing"); + return new DngColorProfile + { + ColorMatrix1 = cm1, + ColorMatrix2 = M(TiffTags.ColorMatrix2), + CameraCalibration1 = useCalibration ? M(TiffTags.CameraCalibration1) : null, + CameraCalibration2 = useCalibration ? M(TiffTags.CameraCalibration2) : null, + ForwardMatrix1 = M(TiffTags.ForwardMatrix1), + ForwardMatrix2 = M(TiffTags.ForwardMatrix2), + CalibrationIlluminant1 = (int)(r.GetUInt(ifd0, TiffTags.CalibrationIlluminant1) ?? 0), + CalibrationIlluminant2 = (int)(r.GetUInt(ifd0, TiffTags.CalibrationIlluminant2) ?? 0), + AnalogBalance = V(TiffTags.AnalogBalance) is { } ab && ab.X > 0 && ab.Y > 0 && ab.Z > 0 ? ab : new(1, 1, 1), + AsShotNeutral = V(TiffTags.AsShotNeutral), + AsShotWhite = Doubles(r, ifd0, raw, TiffTags.AsShotWhiteXy, 2) is [var x, var y] ? new Chromaticity(x, y) : null, + BaselineExposure = baseline, + }; + } + + private static byte[]? Bytes(TiffReader r, Ifd raw, Ifd ifd0, ushort tag) + { + var ifd = raw.Has(tag) ? raw : ifd0; + return ifd.Entries.TryGetValue(tag, out var e) ? r.ReadBytes(e) : null; + } + + /// Finite numeric values of a tag from the first IFD that has it, or null (also when there are more than ). + private static double[]? Doubles(TiffReader r, Ifd first, Ifd second, ushort tag, int max) + { + var ifd = first.Has(tag) ? first : second; + if (!ifd.Entries.TryGetValue(tag, out var e) || e.Count == 0 || e.Count > max) return null; + var values = r.GetDoubles(e); + if (values is null) return null; + foreach (var v in values) + { + if (!double.IsFinite(v)) return null; + } + return values; + } + + private static double[]? Values(TiffReader r, Ifd first, Ifd second, ushort tag, int count) => + Doubles(r, first, second, tag, 16) is { } v && v.Length >= count && v.All(x => x >= 0 && x < int.MaxValue / 2) ? v : null; +} + +/// Loads a TIFF/DNG raster IFD through . +internal sealed class TiffRasterLoader(TiffReader reader, Ifd ifd) : RawLoader +{ + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var raster = TiffImageReader.ReadRaster(reader, ifd, new TiffDecodeOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }); + var samples = new RawSamples(raster.Width, raster.Height, raster.SamplesPerPixel, raster.Samples, raster.FloatSamples); + samples.Warnings.AddRange(raster.Warnings); + return samples; + } +} diff --git a/src/Titano.Core/Codecs/Raw/AhdDemosaic.cs b/src/Titano.Core/Codecs/Raw/AhdDemosaic.cs new file mode 100644 index 00000000..79008691 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/AhdDemosaic.cs @@ -0,0 +1,245 @@ +using System.Buffers; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Adaptive Homogeneity-Directed demosaicing (K. Hirakawa, T. W. Parks, "Adaptive homogeneity-directed demosaicing +/// algorithm", IEEE Trans. Image Processing 14(3), 2005), in the formulation of dcraw's ahd_interpolate: +/// green is interpolated horizontally and vertically (gradient-corrected, limited to its two neighbours), red and blue +/// follow by colour-difference interpolation in each direction, both candidates are converted to CIELab, and each pixel +/// takes the direction whose 3×3 neighbourhood is most homogeneous (Lab distances within adaptive luminance and chroma +/// thresholds), or the average on a tie. Works on float data in tiles processed in parallel; a 5-pixel border is +/// bilinear. +/// +internal static unsafe class AhdDemosaic +{ + private const int Ts = 256; + private const int LutSize = 1 << 16; + private const float LutScale = LutSize / 2f; + + /// CIELab f(t) for t in [0, 2): cube root above (6/29)³, the linear toe below. + private static readonly float[] LabF = BuildLabF(); + + /// White-balanced camera RGB → XYZ (white at Y = 1), used only for the Lab metric. + public static ImageBuffer Run(ImageBuffer mosaic, CfaPattern cfa, Matrix3 balancedToXyz, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + if (!cfa.IsBayer) throw new ArgumentException("Bayer pattern expected", nameof(cfa)); + int w = mosaic.Width, h = mosaic.Height; + if (w < 16 || h < 16) return Demosaic.Bilinear(mosaic, cfa, maxDegreeOfParallelism, cancellationToken); + var output = new ImageBuffer(w, h, 3, clear: false); + Demosaic.BilinearBorder(mosaic, cfa, output, 5); + + // Rows of the matrix are divided by the white's XYZ so that Lab sees X/Xn, Y/Yn, Z/Zn directly. + var white = balancedToXyz * new Vector3D(1, 1, 1); + var m = new float[9]; + double[] rows = [balancedToXyz.M11, balancedToXyz.M12, balancedToXyz.M13, balancedToXyz.M21, balancedToXyz.M22, balancedToXyz.M23, balancedToXyz.M31, balancedToXyz.M32, balancedToXyz.M33]; + double[] whites = [white.X, white.Y, white.Z]; + for (var i = 0; i < 9; i++) m[i] = (float)(rows[i] / (whites[i / 3] > 0 ? whites[i / 3] : 1)); + + var tops = new List(); + for (var top = 2; top < h - 5; top += Ts - 6) tops.Add(top); + var lefts = new List(); + for (var left = 2; left < w - 5; left += Ts - 6) lefts.Add(left); + var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }; + var colors = new int[4]; + for (var i = 0; i < 4; i++) colors[i] = cfa.ColorAt(i & 1, i >> 1); + Parallel.For(0, tops.Count * lefts.Count, options, () => new Workspace(), (t, _, ws) => + { + Tile(mosaic, output, colors, m, tops[t / lefts.Count], lefts[t % lefts.Count], ws); + return ws; + }, ws => ws.Dispose()); + return output; + } + + /// Per-thread tile buffers: two directional RGB and Lab images plus homogeneity counts. + private sealed class Workspace : IDisposable + { + public readonly float[] Rgb = ArrayPool.Shared.Rent(6 * Ts * Ts); + public readonly float[] Lab = ArrayPool.Shared.Rent(6 * Ts * Ts); + public readonly byte[] Homo = ArrayPool.Shared.Rent(2 * Ts * Ts); + + public void Dispose() + { + ArrayPool.Shared.Return(Rgb); + ArrayPool.Shared.Return(Lab); + ArrayPool.Shared.Return(Homo); + } + } + + private static void Tile(ImageBuffer mosaic, ImageBuffer output, int[] colors, float[] xyz, int top, int left, Workspace ws) + { + int w = mosaic.Width, h = mosaic.Height; + const int plane = Ts * Ts; + fixed (float* image = mosaic.Storage, rgbBase = ws.Rgb, labBase = ws.Lab, mat = xyz, lut = LabF) + fixed (byte* homoBase = ws.Homo) + fixed (float* outBase = output.Storage) + { + // Direction d: R, G, B planes at rgbBase + (3d + c)·plane; Lab likewise. + var rowEnd = int.Min(top + Ts, h - 2); + var colEnd = int.Min(left + Ts, w - 2); + + // 1. Green horizontally and vertically at red/blue sites. + for (var row = top; row < rowEnd; row++) + { + var col = left + (Color(colors, left, row) == 1 ? 1 : 0); + var gh = rgbBase + plane + (row - top) * Ts - left; + var gv = rgbBase + 4 * plane + (row - top) * Ts - left; + for (; col < colEnd; col += 2) + { + var pix = image + row * w + col; + var val = ((pix[-1] + pix[0] + pix[1]) * 2 - pix[-2] - pix[2]) * 0.25f; + gh[col] = Limit(val, pix[-1], pix[1]); + val = ((pix[-w] + pix[0] + pix[w]) * 2 - pix[-2 * w] - pix[2 * w]) * 0.25f; + gv[col] = Limit(val, pix[-w], pix[w]); + } + } + + // 2. Red and blue in each direction, then CIELab. + rowEnd = int.Min(top + Ts - 1, h - 3); + colEnd = int.Min(left + Ts - 1, w - 3); + for (var d = 0; d < 2; d++) + { + var rgb = rgbBase + 3 * d * plane; + var lab = labBase + 3 * d * plane; + for (var row = top + 1; row < rowEnd; row++) + { + for (var col = left + 1; col < colEnd; col++) + { + var pix = image + row * w + col; + var i = (row - top) * Ts + col - left; + var r = rgb + i; + var own = Color(colors, col, row); + float red, green, blue; + if (own == 1) + { + // Colour of the vertical neighbours; the horizontal ones carry the other one. + var vertical = Color(colors, col, row + 1); + var h0 = pix[0] + (pix[-1] + pix[1] - r[plane - 1] - r[plane + 1]) * 0.5f; + var v0 = pix[0] + (pix[-w] + pix[w] - r[plane - Ts] - r[plane + Ts]) * 0.5f; + green = pix[0]; + if (vertical == 0) (red, blue) = (v0, h0); + else (red, blue) = (h0, v0); + } + else + { + green = r[plane]; + var opposite = green + (pix[-w - 1] + pix[-w + 1] + pix[w - 1] + pix[w + 1] + - r[plane - Ts - 1] - r[plane - Ts + 1] - r[plane + Ts - 1] - r[plane + Ts + 1]) * 0.25f; + (red, blue) = own == 0 ? (pix[0], opposite) : (opposite, pix[0]); + } + red = float.Max(red, 0f); + blue = float.Max(blue, 0f); + r[0] = red; + r[plane] = green; + r[2 * plane] = blue; + var fx = F(lut, mat[0] * red + mat[1] * green + mat[2] * blue); + var fy = F(lut, mat[3] * red + mat[4] * green + mat[5] * blue); + var fz = F(lut, mat[6] * red + mat[7] * green + mat[8] * blue); + var l = lab + i; + l[0] = 116f * fy - 16f; + l[plane] = 500f * (fx - fy); + l[2 * plane] = 200f * (fy - fz); + } + } + } + + // 3. Homogeneity: neighbours within adaptive luminance and chroma thresholds. + new Span(homoBase, 2 * plane).Clear(); + rowEnd = int.Min(top + Ts - 2, h - 4); + colEnd = int.Min(left + Ts - 2, w - 4); + var labH = labBase; + var labV = labBase + 3 * plane; + for (var row = top + 2; row < rowEnd; row++) + { + for (var col = left + 2; col < colEnd; col++) + { + var i = (row - top) * Ts + col - left; + var lh = labH + i; + var lv = labV + i; + float lh0 = Diff(lh, -1), lh1 = Diff(lh, 1), lh2 = Diff(lh, -Ts), lh3 = Diff(lh, Ts); + float lv0 = Diff(lv, -1), lv1 = Diff(lv, 1), lv2 = Diff(lv, -Ts), lv3 = Diff(lv, Ts); + float ah0 = Chroma(lh, -1, plane), ah1 = Chroma(lh, 1, plane), ah2 = Chroma(lh, -Ts, plane), ah3 = Chroma(lh, Ts, plane); + float av0 = Chroma(lv, -1, plane), av1 = Chroma(lv, 1, plane), av2 = Chroma(lv, -Ts, plane), av3 = Chroma(lv, Ts, plane); + var leps = float.Min(float.Max(lh0, lh1), float.Max(lv2, lv3)); + var abeps = float.Min(float.Max(ah0, ah1), float.Max(av2, av3)); + homoBase[i] = (byte)(Count(lh0, ah0, leps, abeps) + Count(lh1, ah1, leps, abeps) + Count(lh2, ah2, leps, abeps) + Count(lh3, ah3, leps, abeps)); + homoBase[plane + i] = (byte)(Count(lv0, av0, leps, abeps) + Count(lv1, av1, leps, abeps) + Count(lv2, av2, leps, abeps) + Count(lv3, av3, leps, abeps)); + } + } + + // 4. Most homogeneous direction over 3×3 (average on a tie). + rowEnd = int.Min(top + Ts - 3, h - 5); + colEnd = int.Min(left + Ts - 3, w - 5); + var outPlane = w * h; + for (var row = top + 3; row < rowEnd; row++) + { + for (var col = left + 3; col < colEnd; col++) + { + var i = (row - top) * Ts + col - left; + int hm0 = 0, hm1 = 0; + for (var k = -Ts; k <= Ts; k += Ts) + { + var p = homoBase + i + k; + hm0 += p[-1] + p[0] + p[1]; + hm1 += p[plane - 1] + p[plane] + p[plane + 1]; + } + var o = outBase + row * w + col; + var a = rgbBase + i; + var b = rgbBase + 3 * plane + i; + if (hm0 > hm1) + { + o[0] = a[0]; + o[outPlane] = a[plane]; + o[2 * outPlane] = a[2 * plane]; + } + else if (hm1 > hm0) + { + o[0] = b[0]; + o[outPlane] = b[plane]; + o[2 * outPlane] = b[2 * plane]; + } + else + { + o[0] = (a[0] + b[0]) * 0.5f; + o[outPlane] = (a[plane] + b[plane]) * 0.5f; + o[2 * outPlane] = (a[2 * plane] + b[2 * plane]) * 0.5f; + } + } + } + } + } + + private static int Color(int[] colors, int x, int y) => colors[(y & 1) << 1 | x & 1]; + + private static float Limit(float v, float a, float b) => a < b ? float.Clamp(v, a, b) : float.Clamp(v, b, a); + + private static float F(float* lut, float t) + { + var i = (int)(t * LutScale); + return lut[i < 0 ? 0 : i >= LutSize ? LutSize - 1 : i]; + } + + private static float Diff(float* l, int offset) => float.Abs(l[0] - l[offset]); + + private static float Chroma(float* l, int offset, int plane) + { + var da = l[plane] - l[plane + offset]; + var db = l[2 * plane] - l[2 * plane + offset]; + return da * da + db * db; + } + + private static int Count(float l, float ab, float leps, float abeps) => l <= leps && ab <= abeps ? 1 : 0; + + private static float[] BuildLabF() + { + var lut = new float[LutSize]; + for (var i = 0; i < LutSize; i++) + { + var t = i / (double)LutScale; + lut[i] = (float)(t > 216.0 / 24389 ? double.Cbrt(t) : (24389.0 / 27 * t + 16) / 116); + } + return lut; + } +} diff --git a/src/Titano.Core/Codecs/Raw/CfaPattern.cs b/src/Titano.Core/Codecs/Raw/CfaPattern.cs new file mode 100644 index 00000000..5ec30b97 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/CfaPattern.cs @@ -0,0 +1,143 @@ +using System.Text; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Colour filter array layout (DNG 1.6 §"CFARepeatPatternDim"/"CFAPattern"): the colour of every cell of a pattern +/// that repeats over the image, 0 = red, 1 = green, 2 = blue. The origin is the top-left pixel of the image the pattern +/// is attached to (the DNG active area); re-anchors it for a sub-image. +/// +public sealed class CfaPattern +{ + public const int MaxSize = 8; + + private readonly byte[] _colors; + + /// The size is outside 1–8, a colour is not 0–2, or a primary is missing. + public CfaPattern(int width, int height, ReadOnlySpan colors) + { + if (width is < 1 or > MaxSize || height is < 1 or > MaxSize || colors.Length < width * height) + throw new InvalidDataException($"CFA: unsupported pattern size {width}x{height}"); + Span seen = stackalloc bool[3]; + foreach (var c in colors[..(width * height)]) + { + if (c > 2) throw new InvalidDataException($"CFA: colour {c} is not red, green or blue"); + seen[c] = true; + } + if (!seen[0] || !seen[1] || !seen[2]) throw new InvalidDataException("CFA: pattern lacks a primary colour"); + (Width, Height, _colors) = Reduce(width, height, colors[..(width * height)]); + } + + /// Repeat width after reduction to the smallest period (a 4×4 Bayer description becomes 2×2). + public int Width { get; } + + public int Height { get; } + + /// A 2×2 pattern with one red, one blue and two diagonal greens. + public bool IsBayer => Width == 2 && Height == 2 && (_colors[0] == 1 && _colors[3] == 1 || _colors[1] == 1 && _colors[2] == 1); + + /// Block edge for colour binning (half-size decoding): 2 for Bayer, 3 when every aligned 3×3 block holds all + /// three primaries (X-Trans), 0 when the pattern cannot be binned. + public int BinSize + { + get + { + if (IsBayer) return 2; + if (Width % 3 != 0 || Height % 3 != 0) return 0; + for (var by = 0; by < Height; by += 3) + { + for (var bx = 0; bx < Width; bx += 3) + { + var mask = 0; + for (var y = 0; y < 3; y++) + { + for (var x = 0; x < 3; x++) mask |= 1 << ColorAt(bx + x, by + y); + } + if (mask != 7) return 0; + } + } + return 3; + } + } + + /// Colour at image coordinates (non-negative). + public int ColorAt(int x, int y) => _colors[y % Height * Width + x % Width]; + + /// Pattern of the sub-image whose top-left pixel is (, ) here. + public CfaPattern Shift(int dx, int dy) + { + var colors = new byte[Width * Height]; + for (var y = 0; y < Height; y++) + { + for (var x = 0; x < Width; x++) colors[y * Width + x] = (byte)ColorAt(x + PositiveModulo(dx, Width), y + PositiveModulo(dy, Height)); + } + return new CfaPattern(Width, Height, colors); + } + + /// Bayer pattern from its top-left 2×2 letters ("RGGB", "BGGR", "GRBG", "GBRG"). + public static CfaPattern Bayer(string layout) + { + if (layout.Length != 4) throw new ArgumentException("Four letters expected", nameof(layout)); + var colors = new byte[4]; + for (var i = 0; i < 4; i++) + { + colors[i] = char.ToUpperInvariant(layout[i]) switch + { + 'R' => 0, + 'G' => 1, + 'B' => 2, + _ => throw new ArgumentException("Letters must be R, G or B", nameof(layout)), + }; + } + return new CfaPattern(2, 2, colors); + } + + public override string ToString() + { + var sb = new StringBuilder(Width * Height + 8); + for (var i = 0; i < Width * Height; i++) sb.Append("RGB"[_colors[i]]); + return Width == 2 && Height == 2 ? sb.ToString() : $"{Width}x{Height}:{sb}"; + } + + private static int PositiveModulo(int value, int m) => (value % m + m) % m; + + private static (int Width, int Height, byte[] Colors) Reduce(int width, int height, ReadOnlySpan colors) + { + var w = width; + for (var p = 1; p < width; p++) + { + if (width % p == 0 && Periodic(colors, width, height, p, 0)) + { + w = p; + break; + } + } + var h = height; + for (var p = 1; p < height; p++) + { + if (height % p == 0 && Periodic(colors, width, height, 0, p)) + { + h = p; + break; + } + } + var reduced = new byte[w * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) reduced[y * w + x] = colors[y * width + x]; + } + return (w, h, reduced); + } + + private static bool Periodic(ReadOnlySpan colors, int width, int height, int px, int py) + { + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + if (colors[y * width + x] != colors[(y + py) % height * width + (x + px) % width]) return false; + } + } + return true; + } +} diff --git a/src/Titano.Core/Codecs/Raw/Demosaic.cs b/src/Titano.Core/Codecs/Raw/Demosaic.cs new file mode 100644 index 00000000..ee3987a6 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/Demosaic.cs @@ -0,0 +1,202 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Fast CFA reconstructions: bilinear for Bayer mosaics (Draft quality), a colour-difference neighbourhood interpolation +/// for any other pattern (X-Trans), and colour binning (half/third size). Inputs are single-plane mosaics with the pattern +/// anchored at pixel (0, 0); outputs are R, G, B planes. +/// +internal static class Demosaic +{ + /// Bilinear interpolation of a Bayer mosaic: missing greens from the 4 orthogonal neighbours, red/blue from the + /// 2 or 4 nearest of their colour. Borders mirror around the edge pixel, which preserves the CFA phase. + public static ImageBuffer Bilinear(ImageBuffer mosaic, CfaPattern cfa, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + if (!cfa.IsBayer) throw new ArgumentException("Bayer pattern expected", nameof(cfa)); + int w = mosaic.Width, h = mosaic.Height; + var output = new ImageBuffer(w, h, 3, clear: false); + var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }; + Parallel.For(0, h, options, y => + { + var interior = y >= 1 && y < h - 1; + for (var x = 0; x < w; x++) + { + if (interior && x >= 1 && x < w - 1) BilinearInterior(mosaic, cfa, output, x, y); + else BilinearAt(mosaic, cfa, output, x, y); + } + }); + return output; + } + + /// Bilinear values for the pixels within of the border (AHD leaves them to this). + public static void BilinearBorder(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int band) + { + int w = mosaic.Width, h = mosaic.Height; + for (var y = 0; y < h; y++) + { + var edgeRow = y < band || y >= h - band; + for (var x = 0; x < w; x++) + { + if (!edgeRow && x == band) x = int.Max(x, w - band); + if (x < w) BilinearAt(mosaic, cfa, output, x, y); + } + } + } + + private static void BilinearInterior(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int x, int y) + { + var m = mosaic.Plane(0); + var w = mosaic.Width; + var i = y * w + x; + var c = cfa.ColorAt(x, y); + float r, g, b; + if (c == 1) + { + var horizontal = (m[i - 1] + m[i + 1]) * 0.5f; + var vertical = (m[i - w] + m[i + w]) * 0.5f; + g = m[i]; + if (cfa.ColorAt(x + 1, y) == 0) (r, b) = (horizontal, vertical); + else (r, b) = (vertical, horizontal); + } + else + { + g = (m[i - 1] + m[i + 1] + m[i - w] + m[i + w]) * 0.25f; + var diagonal = (m[i - w - 1] + m[i - w + 1] + m[i + w - 1] + m[i + w + 1]) * 0.25f; + (r, b) = c == 0 ? (m[i], diagonal) : (diagonal, m[i]); + } + output.Plane(0)[i] = r; + output.Plane(1)[i] = g; + output.Plane(2)[i] = b; + } + + private static void BilinearAt(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int x, int y) + { + Span sum = stackalloc float[3]; + Span count = stackalloc int[3]; + var own = cfa.ColorAt(x, y); + for (var dy = -1; dy <= 1; dy++) + { + for (var dx = -1; dx <= 1; dx++) + { + // Greens come from orthogonal neighbours only; the diagonal ones belong to the other green rows. + var sx = Mirror(x + dx, mosaic.Width); + var sy = Mirror(y + dy, mosaic.Height); + var c = cfa.ColorAt(sx, sy); + if (c == own && (dx | dy) != 0) continue; + if (c == 1 && dx != 0 && dy != 0) continue; + sum[c] += mosaic.Plane(0)[sy * mosaic.Width + sx]; + count[c]++; + } + } + var i = y * mosaic.Width + x; + for (var c = 0; c < 3; c++) output.Plane(c)[i] = count[c] > 0 ? sum[c] / count[c] : 0f; + } + + private static int Mirror(int v, int size) => v < 0 ? int.Min(-v, size - 1) : v >= size ? int.Max(2 * size - 2 - v, 0) : v; + + /// + /// Colour-difference interpolation for any CFA (used for X-Trans): green from the greens of the 3×3 neighbourhood, then + /// red and blue as interpolated green plus the mean (colour − green) difference of their own 3×3 samples (5×5 when the + /// 3×3 holds none). Simpler than Markesteijn's X-Trans algorithm but artefact-free on smooth content. + /// + public static ImageBuffer Neighbourhood(ImageBuffer mosaic, CfaPattern cfa, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + int w = mosaic.Width, h = mosaic.Height; + var output = new ImageBuffer(w, h, 3, clear: false); + var m = mosaic.Storage; + var green = output.Storage.AsMemory(w * h, w * h); + var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }; + Parallel.For(0, h, options, y => + { + var g = green.Span; + for (var x = 0; x < w; x++) + { + g[y * w + x] = cfa.ColorAt(x, y) == 1 ? m[y * w + x] : Mean(m, w, h, cfa, x, y, 1, null); + } + }); + Parallel.For(0, h, options, y => + { + var g = green.Span; + var red = output.Row(0, y); + var blue = output.Row(2, y); + for (var x = 0; x < w; x++) + { + var own = cfa.ColorAt(x, y); + var gv = g[y * w + x]; + red[x] = own == 0 ? m[y * w + x] : float.Max(0f, gv + Mean(m, w, h, cfa, x, y, 0, g)); + blue[x] = own == 2 ? m[y * w + x] : float.Max(0f, gv + Mean(m, w, h, cfa, x, y, 2, g)); + } + }); + return output; + } + + /// Mean of colour samples around (x, y) — of (sample − green) when + /// is given — over 3×3, widened to 5×5 when the 3×3 holds none. + private static float Mean(float[] m, int w, int h, CfaPattern cfa, int x, int y, int color, Span green) + { + for (var r = 1; r <= 2; r++) + { + var sum = 0f; + var n = 0; + for (var dy = -r; dy <= r; dy++) + { + var sy = y + dy; + if ((uint)sy >= (uint)h) continue; + for (var dx = -r; dx <= r; dx++) + { + var sx = x + dx; + if ((uint)sx >= (uint)w || (dx | dy) == 0 || cfa.ColorAt(sx, sy) != color) continue; + var i = sy * w + sx; + sum += green.IsEmpty ? m[i] : m[i] - green[i]; + n++; + } + } + if (n > 0) return sum / n; + } + return 0f; + } + + /// + /// Colour binning: each aligned × block becomes one RGB pixel holding the + /// mean of its samples of each colour (dcraw's half-size mode for Bayer; one third for X-Trans). Partial blocks at the + /// right/bottom edge are dropped. + /// + public static ImageBuffer Bin(ImageBuffer mosaic, CfaPattern cfa, int size, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + int w = mosaic.Width / size, h = mosaic.Height / size; + if (w < 1 || h < 1) throw new InvalidDataException("RAW: image too small to bin"); + var output = new ImageBuffer(w, h, 3, clear: false); + var src = mosaic.Storage; + var stride = mosaic.Width; + var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }; + Parallel.For(0, h, options, by => + { + Span sum = stackalloc float[3]; + Span count = stackalloc int[3]; + var r = output.Row(0, by); + var g = output.Row(1, by); + var b = output.Row(2, by); + for (var bx = 0; bx < w; bx++) + { + sum.Clear(); + count.Clear(); + for (var dy = 0; dy < size; dy++) + { + var y = by * size + dy; + for (var dx = 0; dx < size; dx++) + { + var x = bx * size + dx; + var c = cfa.ColorAt(x, y); + sum[c] += src[y * stride + x]; + count[c]++; + } + } + r[bx] = sum[0] / count[0]; + g[bx] = sum[1] / count[1]; + b[bx] = sum[2] / count[2]; + } + }); + return output; + } +} diff --git a/src/Titano.Core/Codecs/Raw/HighlightReconstruction.cs b/src/Titano.Core/Codecs/Raw/HighlightReconstruction.cs new file mode 100644 index 00000000..76c18f88 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/HighlightReconstruction.cs @@ -0,0 +1,120 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Clip-aware highlight reconstruction on white-balanced camera RGB. Per pixel, the channels whose raw samples clipped +/// (bit c of the clip map) are only known to be at least their clip level; they are raised to the mean of the unclipped +/// channels when that is larger (a near-white highlight that clipped green first comes back neutral instead of magenta), +/// then the pixel is desaturated toward a grey at its brightest channel as the unclipped channels approach their own clip +/// levels. Fully clipped pixels become that grey at no less than the highest clip level. Pixels without clipped samples +/// are untouched. +/// +internal static class HighlightReconstruction +{ + /// Fraction of its clip level at which an unclipped channel starts pulling the pixel toward white. + private const float DesaturationStart = 0.7f; + + /// White-balanced camera RGB, modified in place. + /// Per pixel: bit c set when channel c is built from clipped raw samples. + /// Clip level of each channel in 's units (the white-balance multipliers + /// when raw white is 1). + public static void Apply(ImageBuffer rgb, byte[] clipBits, ReadOnlySpan clipLevels, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var levels = clipLevels.ToArray(); + var top = float.Max(levels[0], float.Max(levels[1], levels[2])); + int w = rgb.Width; + Parallel.For(0, rgb.Height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, y => + { + var r = rgb.Row(0, y); + var g = rgb.Row(1, y); + var b = rgb.Row(2, y); + var bits = clipBits.AsSpan(y * w, w); + Span v = stackalloc float[3]; + for (var x = 0; x < w; x++) + { + var clipped = bits[x] & 7; + if (clipped == 0) continue; + v[0] = r[x]; + v[1] = g[x]; + v[2] = b[x]; + if (clipped == 7) + { + var level = float.Max(top, float.Max(v[0], float.Max(v[1], v[2]))); + r[x] = g[x] = b[x] = level; + continue; + } + float sum = 0, closeness = float.MaxValue; + var n = 0; + for (var c = 0; c < 3; c++) + { + if ((clipped & 1 << c) != 0) continue; + sum += v[c]; + n++; + closeness = float.Min(closeness, v[c] / levels[c]); + } + var estimate = sum / n; + for (var c = 0; c < 3; c++) + { + if ((clipped & 1 << c) != 0) v[c] = float.Max(v[c], estimate); + } + var t = float.Clamp((closeness - DesaturationStart) / (1 - DesaturationStart), 0f, 1f); + t = t * t * (3 - 2 * t); + var grey = float.Max(v[0], float.Max(v[1], v[2])); + r[x] = v[0] + (grey - v[0]) * t; + g[x] = v[1] + (grey - v[1]) * t; + b[x] = v[2] + (grey - v[2]) * t; + } + }); + } + + /// Channel clip bits of a demosaiced image: the OR of the mosaic's clip flags over each pixel's 3×3 + /// neighbourhood (the samples its interpolation draws on). + public static byte[] Dilate(byte[] mask, int width, int height) + { + var horizontal = new byte[mask.Length]; + for (var y = 0; y < height; y++) + { + var o = y * width; + for (var x = 0; x < width; x++) + { + var v = mask[o + x]; + if (x > 0) v |= mask[o + x - 1]; + if (x < width - 1) v |= mask[o + x + 1]; + horizontal[o + x] = v; + } + } + var result = new byte[mask.Length]; + for (var y = 0; y < height; y++) + { + var o = y * width; + for (var x = 0; x < width; x++) + { + var v = horizontal[o + x]; + if (y > 0) v |= horizontal[o - width + x]; + if (y < height - 1) v |= horizontal[o + width + x]; + result[o + x] = v; + } + } + return result; + } + + /// Clip bits of a binned image: the OR over each × block. + public static byte[] Bin(byte[] mask, int width, int size, int outWidth, int outHeight) + { + var result = new byte[outWidth * outHeight]; + for (var by = 0; by < outHeight; by++) + { + for (var bx = 0; bx < outWidth; bx++) + { + byte v = 0; + for (var dy = 0; dy < size; dy++) + { + for (var dx = 0; dx < size; dx++) v |= mask[(by * size + dy) * width + bx * size + dx]; + } + result[by * outWidth + bx] = v; + } + } + return result; + } +} diff --git a/src/Titano.Core/Codecs/Raw/RawDecoder.cs b/src/Titano.Core/Codecs/Raw/RawDecoder.cs new file mode 100644 index 00000000..9e1dff47 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/RawDecoder.cs @@ -0,0 +1,126 @@ +using Titano.Core.Codecs.Dng; +using Titano.Core.Imaging; +using Titano.Core.Metadata; + +namespace Titano.Core.Codecs.Raw; + +/// Demosaic quality: AHD for renders and proxies, bilinear for thumbnails and analysis. +public enum DemosaicQuality +{ + /// Bilinear (Bayer) — fast, slightly soft, some colour fringing on fine detail. + Draft, + + /// Adaptive homogeneity-directed (Bayer); X-Trans always uses the neighbourhood interpolation. + Best, +} + +/// Options for . +public sealed record RawDecodeOptions +{ + public static RawDecodeOptions Default { get; } = new(); + + public DemosaicQuality Quality { get; init; } = DemosaicQuality.Best; + + /// Bin CFA blocks into RGB pixels instead of demosaicing: half size for Bayer, one third for X-Trans. + /// Ignored for linear (already demosaiced) data and for patterns that cannot be binned. + public bool Binning { get; init; } + + /// Rotate/flip according to the file's orientation. + public bool ApplyOrientation { get; init; } = true; + + /// Worker limit (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// What a RAW container holds, read without decoding its pixels. +/// Container format. +/// Decoder that would develop it ("managed-dng", "managed-cr2"…). +/// Developed width at full size, after crop and orientation. +/// Developed height at full size, after crop and orientation. +/// CFA pattern ("RGGB", "6x6:…") or "linear". +/// Exif orientation applied when requested. +public sealed record RawImageInfo(ImageFileFormat Format, string Decoder, string? Make, string? Model, int Width, int Height, string Layout, int Orientation); + +/// Result of : native support plus the reason when unsupported. +public sealed record RawProbe(RawImageInfo? Info, string? Reason, IReadOnlyList Warnings) +{ + public bool IsSupported => Info is not null; +} + +/// A developed RAW: linear Rec.709 (D65) RGB, BaselineExposure applied. Dispose to return the pixels to the pool. +public sealed class RawDecodeResult(ImageBuffer image, RawImageInfo info, IReadOnlyList warnings) : IDisposable +{ + public ImageBuffer Image { get; } = image; + public RawImageInfo Info { get; } = info; + public IReadOnlyList Warnings { get; } = warnings; + + public void Dispose() => Image.Dispose(); +} + +/// +/// Managed RAW decoding (BRIEF §8.2): DNG (CFA and LinearRaw) through , +/// developed by the shared pipeline. Bodies or encodings +/// without support are reported by so callers can fall back to the embedded preview. +/// +public static class RawDecoder +{ + /// Formats with a managed decoder (individual files may still be unsupported). + public static IReadOnlyList Formats { get; } = + [ImageFileFormat.Dng]; + + /// Parses the container and decides whether it can be developed natively; never reads the pixel payload. + public static RawProbe Probe(Stream stream, string? fileName = null) + { + ArgumentNullException.ThrowIfNull(stream); + var warnings = new List(); + try + { + var (format, frame) = Open(stream, fileName); + warnings.AddRange(frame.Warnings); + return new RawProbe(Describe(format, frame, RawDecodeOptions.Default), null, warnings); + } + catch (InvalidDataException ex) + { + return new RawProbe(null, ex.Message, warnings); + } + catch (IOException ex) + { + return new RawProbe(null, "I/O error: " + ex.Message, warnings); + } + } + + /// Develops the RAW in (readable and seekable). + /// Breaks signature ties between formats sharing a container (see ). + /// Malformed file, or a body/encoding without native support. + public static RawDecodeResult Decode(Stream stream, string? fileName = null, RawDecodeOptions? options = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + var o = options ?? RawDecodeOptions.Default; + var (format, frame) = Open(stream, fileName); + cancellationToken.ThrowIfCancellationRequested(); + var samples = frame.Loader.Load(stream, o.MaxDegreeOfParallelism, cancellationToken); + var warnings = new List(frame.Warnings); + warnings.AddRange(samples.Warnings); + var image = RawDeveloper.Develop(frame, samples, o, warnings, cancellationToken); + return new RawDecodeResult(image, Describe(format, frame, o), warnings); + } + + private static (ImageFileFormat Format, RawFrame Frame) Open(Stream stream, string? fileName) + { + if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + var format = ImageSignature.Detect(stream, fileName); + var frame = format switch + { + ImageFileFormat.Dng => DngReader.Read(stream), + _ => throw new InvalidDataException($"RAW: no managed decoder for {format}"), + }; + return (format, frame); + } + + private static RawImageInfo Describe(ImageFileFormat format, RawFrame frame, RawDecodeOptions options) + { + var (w, h) = frame.OutputSize; + if (options.ApplyOrientation && frame.Orientation is >= 5 and <= 8) (w, h) = (h, w); + return new RawImageInfo(format, frame.Decoder, frame.Make, frame.Model, w, h, frame.Cfa?.ToString() ?? "linear", frame.Orientation); + } +} diff --git a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs new file mode 100644 index 00000000..94e0253d --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs @@ -0,0 +1,316 @@ +using Titano.Core.Codecs.Dng; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Codecs.Raw; + +/// +/// The raw development pipeline shared by DNG and the native RAW readers (BRIEF §8.2; DNG 1.6 chapter 5 "Mapping Raw +/// Values to Linear Reference Values" and chapter 6): OpcodeList1 on stored values → linearisation table, black level +/// (repeat pattern + row/column deltas) and white scaling to 0..1 over the active area, with a clip map of saturated +/// samples → OpcodeList2 → white-balance multipliers → demosaic (AHD, bilinear, neighbourhood or binning) → highlight +/// reconstruction → OpcodeList3 → default crop → camera → linear Rec.709 matrix with BaselineExposure → default scale → +/// orientation. +/// +internal static class RawDeveloper +{ + /// Normalised level at or above which a sample counts as clipped. + private const float ClipThreshold = 0.999f; + + /// LibRaw's adjust_maximum_thr: the data maximum replaces the nominal white level above this fraction of it. + private const double AdjustMaximumThreshold = 0.75; + + public static ImageBuffer Develop(RawFrame frame, RawSamples samples, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) + { + if (samples.Width != frame.Width || samples.Height != frame.Height || samples.SamplesPerPixel != frame.SamplesPerPixel) + throw new InvalidDataException("RAW: decoded payload does not match the declared raster"); + var dop = options.MaxDegreeOfParallelism; + var spp = frame.SamplesPerPixel; + var active = frame.ActiveArea; + var black = samples.MeasuredBlack ?? frame.Black; + var white = (double[])frame.White.Clone(); + if (frame.AdjustWhiteToData) AdjustWhite(samples, active, white, warnings); + + var list1 = DngOpcodes.Parse(frame.OpcodeList1, 1, warnings); + ImageBuffer? stage1 = null; + if (list1.Count > 0) + { + stage1 = ToStage1(samples, dop, cancellationToken); + var image = new OpcodeImage(stage1, 0, 0, 1, spp == 1 ? frame.Cfa?.Shift(-active.Left, -active.Top) : null); + DngOpcodes.Apply(list1, image, warnings, cancellationToken); + stage1 = image.Pixels; + if (stage1.Width != samples.Width || stage1.Height != samples.Height) + { + stage1.Dispose(); + throw new InvalidDataException("RAW: OpcodeList1 changed the raster size"); + } + } + + ImageBuffer linear; + byte[]? clip; + try + { + (linear, clip) = Linearize(frame, samples, stage1, black, white, dop, cancellationToken); + } + finally + { + stage1?.Dispose(); + } + + var stage = new OpcodeImage(linear, 0, 0, 1, frame.Cfa) { ClipMask = clip }; + try + { + DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList2, 2, warnings), stage, warnings, cancellationToken); + return frame.Cfa is null && spp == 1 + ? DevelopMonochrome(frame, stage, options, warnings, cancellationToken) + : DevelopColour(frame, stage, options, warnings, cancellationToken); + } + finally + { + stage.Pixels.Dispose(); + } + } + + private static ImageBuffer DevelopColour(RawFrame frame, OpcodeImage stage, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) + { + var dop = options.MaxDegreeOfParallelism; + var colour = frame.Color.Solve(warnings); + var n = colour.CameraNeutral; + float[] wb = [(float)(1 / n.X), (float)(1 / n.Y), (float)(1 / n.Z)]; + + ImageBuffer rgb; + byte[]? bits = null; + var step = 1; + if (stage.Cfa is { } cfa) + { + ScaleMosaic(stage.Pixels, cfa, wb, dop, cancellationToken); + var bin = options.Binning ? cfa.BinSize : 0; + if (bin > 0) + { + rgb = Demosaic.Bin(stage.Pixels, cfa, bin, dop, cancellationToken); + step = bin; + if (stage.ClipMask is { } mask) bits = HighlightReconstruction.Bin(mask, stage.Width, bin, rgb.Width, rgb.Height); + } + else + { + rgb = !cfa.IsBayer ? Demosaic.Neighbourhood(stage.Pixels, cfa, dop, cancellationToken) + : options.Quality == DemosaicQuality.Best ? AhdDemosaic.Run(stage.Pixels, cfa, colour.BalancedToXyz, dop, cancellationToken) + : Demosaic.Bilinear(stage.Pixels, cfa, dop, cancellationToken); + if (stage.ClipMask is { } mask) bits = HighlightReconstruction.Dilate(mask, stage.Width, stage.Height); + } + } + else + { + rgb = stage.Pixels.Clone(); + for (var c = 0; c < 3; c++) Scale(rgb.Plane(c), wb[c]); + bits = stage.ClipMask; + } + + var image = new OpcodeImage(rgb, stage.Left, stage.Top, step, null); + try + { + if (bits is not null) HighlightReconstruction.Apply(rgb, bits, wb, dop, cancellationToken); + var list3 = DngOpcodes.Parse(frame.OpcodeList3, 3, warnings); + if (list3.Count > 0) + { + // Value-mapping opcodes are defined on unbalanced camera values; gains and warps commute with the multipliers. + var unbalance = list3.Exists(o => o.NeedsUnbalancedValues); + if (unbalance) ScalePlanes(image.Pixels, [1 / wb[0], 1 / wb[1], 1 / wb[2]]); + DngOpcodes.Apply(list3, image, warnings, cancellationToken); + if (unbalance) ScalePlanes(image.Pixels, wb); + } + using var cropped = Crop(frame, image); + ApplyMatrix(cropped, colour.BalancedToRec709, dop, cancellationToken); + return Finish(frame, cropped, options); + } + finally + { + image.Pixels.Dispose(); + } + } + + private static ImageBuffer DevelopMonochrome(RawFrame frame, OpcodeImage stage, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) + { + var image = new OpcodeImage(stage.Pixels.Clone(), stage.Left, stage.Top, 1, null); + try + { + DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList3, 3, warnings), image, warnings, cancellationToken); + using var cropped = Crop(frame, image); + Scale(cropped.Plane(0), (float)double.Exp2(frame.Color.BaselineExposure)); + using var rgb = PixelConvert.GrayToRgb(cropped); + return Finish(frame, rgb, options); + } + finally + { + image.Pixels.Dispose(); + } + } + + /// Default scale, then orientation; always returns a new buffer. + private static ImageBuffer Finish(RawFrame frame, ImageBuffer image, RawDecodeOptions options) + { + var (sh, sv) = frame.DefaultScale; + ImageBuffer? scaled = null; + if (sh != sv && sh > 0 && sv > 0) + { + // Only the ratio matters for square output pixels; stretch the axis with the larger factor. + var ratio = sh / sv; + var (w, h) = ratio > 1 ? ((int)double.Round(image.Width * ratio), image.Height) : (image.Width, (int)double.Round(image.Height / ratio)); + scaled = Resampler.Resize(image, int.Max(1, w), int.Max(1, h)); + } + var source = scaled ?? image; + try + { + return options.ApplyOrientation && frame.Orientation is >= 2 and <= 8 + ? PixelConvert.ApplyOrientation(source, frame.Orientation) + : source.Clone(); + } + finally + { + scaled?.Dispose(); + } + } + + /// Stored values as floats divided by 65535 (the stage-1 domain of the opcodes), sample planes split. + private static ImageBuffer ToStage1(RawSamples samples, int dop, CancellationToken cancellationToken) + { + int w = samples.Width, h = samples.Height, spp = samples.SamplesPerPixel; + var image = new ImageBuffer(w, h, spp == 1 ? 1 : 3, clear: false); + Parallel.For(0, h, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y => + { + for (var s = 0; s < image.Channels; s++) + { + var row = image.Row(s, y); + var o = (long)y * w * spp + s; + for (var x = 0; x < w; x++) row[x] = samples[o + (long)x * spp] / 65535f; + } + }); + return image; + } + + /// Linear reference values over the active area plus a clip map (bit = CFA colour or sample plane), or null + /// when nothing clipped. + private static (ImageBuffer Image, byte[]? Clip) Linearize(RawFrame frame, RawSamples samples, ImageBuffer? stage1, RawBlackLevel black, double[] white, int dop, CancellationToken cancellationToken) + { + var active = frame.ActiveArea; + int w = active.Width, h = active.Height, spp = frame.SamplesPerPixel; + var planes = spp == 1 ? 1 : 3; + var image = new ImageBuffer(w, h, planes, clear: false); + var clip = new byte[w * h]; + var anyClip = 0; + var table = frame.Linearization; + var scale = new float[planes]; + for (var s = 0; s < planes; s++) + { + var range = white[int.Min(s, white.Length - 1)] - black.Max(s, spp); + if (!(range > 0)) throw new InvalidDataException("RAW: white level not above black level"); + scale[s] = (float)(1 / range); + } + var cfa = frame.Cfa; + Parallel.For(0, h, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y => + { + var sy = active.Top + y; + var blackRow = y % black.RepeatRows * black.RepeatColumns * spp; + var deltaV = black.DeltaV is { } dv && y < dv.Length ? dv[y] : 0f; + var rowClip = 0; + for (var s = 0; s < planes; s++) + { + var row = image.Row(s, y); + var source = stage1 is null ? default : stage1.Row(s, sy); + var o = (long)sy * samples.Width * spp + s; + for (var x = 0; x < w; x++) + { + var sx = active.Left + x; + var v = source.IsEmpty ? samples[o + (long)sx * spp] : source[sx] * 65535f; + if (table is not null) v = table[int.Clamp((int)(v + 0.5f), 0, table.Length - 1)]; + var b = black.Values[blackRow + x % black.RepeatColumns * spp + s] + deltaV + + (black.DeltaH is { } dh && x < dh.Length ? dh[x] : 0f); + var value = (v - b) * scale[s]; + row[x] = value; + if (value >= ClipThreshold) + { + clip[y * w + x] |= (byte)(1 << (cfa is null ? s : cfa.ColorAt(x, y))); + rowClip = 1; + } + } + } + if (rowClip != 0) Volatile.Write(ref anyClip, 1); + }); + return (image, anyClip != 0 ? clip : null); + } + + private static void AdjustWhite(RawSamples samples, RawRect active, double[] white, ICollection warnings) + { + var max = 0f; + for (var y = active.Top; y < active.Bottom; y++) + { + var o = (long)y * samples.Width * samples.SamplesPerPixel; + for (var x = active.Left * samples.SamplesPerPixel; x < active.Right * samples.SamplesPerPixel; x++) max = float.Max(max, samples[o + x]); + } + for (var s = 0; s < white.Length; s++) + { + if (max > 0 && max < white[s] && max > white[s] * AdjustMaximumThreshold) white[s] = max; + } + if (max > white.Max()) warnings.Add($"RAW: samples exceed the white level ({max} > {white.Max()})"); + } + + private static void ScaleMosaic(ImageBuffer mosaic, CfaPattern cfa, float[] wb, int dop, CancellationToken cancellationToken) + { + Parallel.For(0, mosaic.Height, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y => + { + var row = mosaic.Row(0, y); + Span phase = stackalloc float[CfaPattern.MaxSize]; + for (var i = 0; i < cfa.Width; i++) phase[i] = wb[cfa.ColorAt(i, y)]; + for (var x = 0; x < row.Length; x++) row[x] *= phase[x % cfa.Width]; + }); + } + + private static void ScalePlanes(ImageBuffer image, float[] factors) + { + for (var c = 0; c < 3; c++) Scale(image.Plane(c), factors[c]); + } + + private static void Scale(Span values, float factor) + { + for (var i = 0; i < values.Length; i++) values[i] *= factor; + } + + /// Default crop (stage coordinates relative to the active area) intersected with what the opcodes left. + private static ImageBuffer Crop(RawFrame frame, OpcodeImage image) + { + var crop = frame.DefaultCrop ?? new RawRect(0, 0, frame.ActiveArea.Width, frame.ActiveArea.Height); + var area = crop.Intersect(image.Bounds); + if (area.IsEmpty) area = image.Bounds; + var x0 = int.Clamp((int)double.Ceiling(image.BufferX(area.Left) - 1e-9), 0, image.Width - 1); + var y0 = int.Clamp((int)double.Ceiling(image.BufferY(area.Top) - 1e-9), 0, image.Height - 1); + var x1 = int.Clamp((int)double.Floor(image.BufferX(area.Right - 1) + 1e-9) + 1, x0 + 1, image.Width); + var y1 = int.Clamp((int)double.Floor(image.BufferY(area.Bottom - 1) + 1e-9) + 1, y0 + 1, image.Height); + var src = image.Pixels; + var dst = new ImageBuffer(x1 - x0, y1 - y0, src.Channels, clear: false); + for (var c = 0; c < src.Channels; c++) + { + for (var y = y0; y < y1; y++) src.Row(c, y).Slice(x0, x1 - x0).CopyTo(dst.Row(c, y - y0)); + } + return dst; + } + + private static void ApplyMatrix(ImageBuffer image, Matrix3 m, int dop, CancellationToken cancellationToken) + { + float m11 = (float)m.M11, m12 = (float)m.M12, m13 = (float)m.M13; + float m21 = (float)m.M21, m22 = (float)m.M22, m23 = (float)m.M23; + float m31 = (float)m.M31, m32 = (float)m.M32, m33 = (float)m.M33; + Parallel.For(0, image.Height, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y => + { + var r = image.Row(0, y); + var g = image.Row(1, y); + var b = image.Row(2, y); + for (var x = 0; x < r.Length; x++) + { + float vr = r[x], vg = g[x], vb = b[x]; + r[x] = m11 * vr + m12 * vg + m13 * vb; + g[x] = m21 * vr + m22 * vg + m23 * vb; + b[x] = m31 * vr + m32 * vg + m33 * vb; + } + }); + } +} diff --git a/src/Titano.Core/Codecs/Raw/RawFrame.cs b/src/Titano.Core/Codecs/Raw/RawFrame.cs new file mode 100644 index 00000000..9d5e940b --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/RawFrame.cs @@ -0,0 +1,141 @@ +using Titano.Core.Codecs.Dng; + +namespace Titano.Core.Codecs.Raw; + +/// Integer rectangle (left, top inclusive; right, bottom exclusive). +public readonly record struct RawRect(int Left, int Top, int Right, int Bottom) +{ + public int Width => Right - Left; + public int Height => Bottom - Top; + public bool IsEmpty => Width <= 0 || Height <= 0; + + public RawRect Intersect(RawRect other) => new( + int.Max(Left, other.Left), int.Max(Top, other.Top), int.Min(Right, other.Right), int.Min(Bottom, other.Bottom)); + + public override string ToString() => $"{Left},{Top} {Width}x{Height}"; +} + +/// Black level description (DNG BlackLevelRepeatDim, BlackLevel, BlackLevelDeltaH/V), relative to the active area. +internal sealed class RawBlackLevel +{ + public static RawBlackLevel Zero(int samplesPerPixel) => new(1, 1, new float[samplesPerPixel], null, null); + + public RawBlackLevel(int repeatRows, int repeatColumns, float[] values, float[]? deltaH, float[]? deltaV) + { + RepeatRows = repeatRows; + RepeatColumns = repeatColumns; + Values = values; + DeltaH = deltaH; + DeltaV = deltaV; + } + + public int RepeatRows { get; } + public int RepeatColumns { get; } + + /// rows × columns × samples-per-pixel values, sample index fastest. + public float[] Values { get; } + + public float[]? DeltaH { get; } + public float[]? DeltaV { get; } + + /// Largest black level of a sample plane, deltas included (the white-scaling reference of the DNG SDK). + public float Max(int sample, int samplesPerPixel) + { + var max = float.MinValue; + for (var i = sample; i < Values.Length; i += samplesPerPixel) max = float.Max(max, Values[i]); + return max + (DeltaH is { Length: > 0 } h ? MaxOf(h) : 0) + (DeltaV is { Length: > 0 } v ? MaxOf(v) : 0); + } + + private static float MaxOf(float[] values) + { + var max = float.MinValue; + foreach (var v in values) max = float.Max(max, v); + return max; + } +} + +/// Decoded raw samples as stored in the file: interleaved, × × +/// , integers or floats. +internal sealed class RawSamples(int width, int height, int samplesPerPixel, ushort[]? integers, float[]? floats) +{ + public int Width { get; } = width; + public int Height { get; } = height; + public int SamplesPerPixel { get; } = samplesPerPixel; + public ushort[]? Integers { get; } = integers; + public float[]? Floats { get; } = floats; + public List Warnings { get; } = []; + + /// Black level measured by the loader (e.g. from masked sensor columns), overriding the frame's own. + public RawBlackLevel? MeasuredBlack { get; set; } + + public float this[long index] => Integers is { } i ? i[index] : Floats![index]; +} + +/// Reads the pixel payload of one container; created by the container parser, run by the pipeline. +internal abstract class RawLoader +{ + /// The payload is malformed or uses an unsupported encoding. + public abstract RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken); +} + +/// +/// Everything the development pipeline needs about one raw image, independent of the container: raster geometry, CFA, +/// linearisation, black/white levels, crops, colour profile, opcode lists and orientation. Built by the DNG reader and the +/// native RAW readers without touching the pixel payload. +/// +internal sealed class RawFrame +{ + /// Decoder name for logs ("managed-dng", "managed-cr2"…). + public required string Decoder { get; init; } + + public required int Width { get; init; } + public required int Height { get; init; } + + /// 1 for CFA and monochrome data, 3 for LinearRaw RGB. + public int SamplesPerPixel { get; init; } = 1; + + /// CFA layout anchored at the active area's top-left; null for linear (already demosaiced) data. + public CfaPattern? Cfa { get; init; } + + /// Image area holding valid pixels, in stored coordinates. + public required RawRect ActiveArea { get; init; } + + /// Final crop relative to the active area (DNG DefaultCropOrigin/Size); null = the whole active area. + public RawRect? DefaultCrop { get; init; } + + /// DNG DefaultScale (horizontal, vertical) for non-square pixels. + public (double H, double V) DefaultScale { get; init; } = (1, 1); + + public ushort[]? Linearization { get; init; } + public required RawBlackLevel Black { get; init; } + + /// White level per sample plane, in linearised units. + public required double[] White { get; init; } + + /// Lower the white level to the data maximum when that exceeds 75 % of it (LibRaw adjust_maximum_thr): native + /// RAWs state a nominal bit-depth maximum while sensors saturate earlier. + public bool AdjustWhiteToData { get; init; } + + public required DngColorProfile Color { get; init; } + public byte[]? OpcodeList1 { get; init; } + public byte[]? OpcodeList2 { get; init; } + public byte[]? OpcodeList3 { get; init; } + + /// Exif orientation 1–8. + public int Orientation { get; init; } = 1; + + public string? Make { get; init; } + public string? Model { get; init; } + public required RawLoader Loader { get; init; } + public List Warnings { get; } = []; + + /// Size of the developed image before orientation (active area or default crop, default scale applied). + public (int Width, int Height) OutputSize + { + get + { + var crop = DefaultCrop ?? new RawRect(0, 0, ActiveArea.Width, ActiveArea.Height); + return (int.Max(1, (int)double.Round(crop.Width * DefaultScale.H)), int.Max(1, (int)double.Round(crop.Height * DefaultScale.V))); + } + } +} diff --git a/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs b/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs new file mode 100644 index 00000000..d0a47334 --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs @@ -0,0 +1,224 @@ +using Titano.Core.Codecs.Dng; +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Raw; + +/// Synthetic DNG round trips: a known linear scene is mosaicked through a known camera model, written with the +/// DNG feature under test, decoded, and compared with the scene. +public sealed class DngDecoderTests(TestContext context) +{ + private const int W = 96, H = 72; + + private static RawDecodeResult Decode(byte[] dng, RawDecodeOptions? options = null) => + RawDecoder.Decode(new MemoryStream(dng), "test.dng", options); + + [Theory] + [Case("RGGB")] + [Case("BGGR")] + [Case("GRBG")] + [Case("GBRG")] + public void BayerPatternsRoundTrip(string layout) + { + using var scene = SyntheticRaw.Smooth(W, H); + var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = CfaPattern.Bayer(layout) }); + using var result = Decode(dng); + Assert.Equal(W, result.Image.Width); + Assert.Equal(H, result.Image.Height); + Assert.Equal(layout, result.Info.Layout); + var psnr = SyntheticRaw.Psnr(scene, result.Image, 4); + var de = SyntheticRaw.MeanDeltaE(scene, result.Image, 4); + context.Log($"{layout}: PSNR {psnr:F1} dB, mean ΔE {de:F2}"); + Assert.GreaterOrEqual(psnr, 40); + Assert.Less(de, 1.0); + } + + [Theory] + [Case(1, false)] + [Case(7, false)] + [Case(7, true)] + [Case(8, false)] + public void CompressionsDecodeIdentically(int compression, bool twoComponents) + { + using var scene = SyntheticRaw.Smooth(W, H); + using var reference = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = 1 })); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = compression, TwoComponentTiles = twoComponents, RawInSubIfd = true })); + Assert.Empty(result.Warnings); + Assert.SequenceEqual(reference.Image.Data.ToArray(), result.Image.Data.ToArray()); + } + + [Test] + public void LinearRawRoundTripsExactly() + { + using var scene = SyntheticRaw.Smooth(W, H); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null })); + Assert.Equal("linear", result.Info.Layout); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 0), 60); + } + + [Test] + public void BlackLevelPatternAndDeltasAreSubtracted() + { + using var scene = SyntheticRaw.Smooth(W, H); + var deltaH = Enumerable.Range(0, W).Select(x => (double)(x % 7)).ToArray(); + var deltaV = Enumerable.Range(0, H).Select(y => y * 0.5).ToArray(); + var spec = new DngSpec { BlackRows = 2, BlackColumns = 2, Black = [500, 520, 530, 510], BlackDeltaH = deltaH, BlackDeltaV = deltaV, MarginLeft = 4, MarginTop = 2 }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40); + } + + [Test] + public void LinearizationTableIsApplied() + { + using var scene = SyntheticRaw.Smooth(W, H); + // 4096 codes covering 0..16383 with a square law: dense in the shadows, sparse in the highlights. + var table = Enumerable.Range(0, 4096).Select(i => (ushort)double.Round(16383.0 * i * i / (4095.0 * 4095.0))).ToArray(); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Linearization = table, Black = [0] })); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Test] + public void ActiveAreaAndDefaultCropSelectTheImage() + { + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec { MarginLeft = 6, MarginTop = 4, MarginRight = 2, MarginBottom = 3, Crop = new RawRect(8, 6, 8 + 64, 6 + 48) }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.Equal(64, result.Image.Width); + Assert.Equal(48, result.Image.Height); + Assert.Equal(64, result.Info.Width); + using var expected = Crop(scene, 8, 6, 64, 48); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 40); + } + + [Theory] + [Case(false)] + [Case(true)] + public void WhiteBalanceFromAsShotNeutralOrWhiteXy(bool whiteXy) + { + // Scene lit by tungsten (2850 K): decoding must adapt it back to the D65 scene. + using var scene = SyntheticRaw.Smooth(W, H); + var tungsten = new Chromaticity(0.44757, 0.40745); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { SceneWhite = tungsten, WriteWhiteXy = whiteXy })); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + Assert.Less(SyntheticRaw.MeanDeltaE(scene, result.Image, 4), 1.5); + } + + [Test] + public void DualIlluminantMatricesInterpolateByTemperature() + { + var profile = new DngColorProfile + { + ColorMatrix1 = SyntheticRaw.TungstenMatrix, + CalibrationIlluminant1 = 17, + ColorMatrix2 = SyntheticRaw.CameraMatrix, + CalibrationIlluminant2 = 21, + }; + var warm = new Chromaticity(0.44757, 0.40745); + var mid = ColorTemperatureXy(4200); + Assert.Approximately(2850, DngColorProfile.Temperature(warm), 15); + Assert.Approximately(6504, DngColorProfile.Temperature(Chromaticity.D65), 30); + AssertMatrix(SyntheticRaw.TungstenMatrix, profile.XyzToCamera(warm), 1e-3); + AssertMatrix(SyntheticRaw.CameraMatrix, profile.XyzToCamera(Chromaticity.D65), 1e-9); + // Between the calibrations the weight is linear in inverse temperature. + var t = DngColorProfile.Temperature(mid); + var g = (1 / t - 1 / 6500.0) / (1 / 2850.0 - 1 / 6500.0); + Assert.Approximately(g * SyntheticRaw.TungstenMatrix.M11 + (1 - g) * SyntheticRaw.CameraMatrix.M11, profile.XyzToCamera(mid).M11, 1e-9); + + // A DNG with both matrices, shot at 4200 K, decodes back to the scene. + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec + { + ColorMatrix1 = SyntheticRaw.TungstenMatrix, + Illuminant1 = 17, + ColorMatrix2 = SyntheticRaw.CameraMatrix, + Illuminant2 = 21, + CaptureMatrix = profile.XyzToCamera(mid), + SceneWhite = mid, + }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Test] + public void ForwardMatrixMapsNeutralToWhite() + { + // ForwardMatrix = Rec.709 → XYZ(D50) with camera = linear Rec.709: a gray scene must stay gray. + var fm = Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), Chromaticity.D50.ToXyz()) * Matrix3.Rec709ToXyz; + using var scene = new ImageBuffer(32, 32); + scene.Data.Fill(0.4f); + var spec = new DngSpec { Cfa = null, ColorMatrix1 = Matrix3.XyzToRec709, ForwardMatrix1 = fm }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + for (var c = 0; c < 3; c++) Assert.Approximately(0.4, result.Image[c, 16, 16], 2e-3); + } + + [Test] + public void BaselineExposureScalesOutput() + { + using var scene = SyntheticRaw.Smooth(W, H); + using var plain = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null })); + using var bright = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null, BaselineExposure = 1 })); + Assert.Approximately(2 * plain.Image[1, 40, 30], bright.Image[1, 40, 30], 1e-4); + } + + [Theory] + [Case((ushort)6)] + [Case((ushort)3)] + public void OrientationIsApplied(ushort orientation) + { + using var scene = SyntheticRaw.Smooth(W, H); + var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = null, Orientation = orientation }); + using var oriented = Decode(dng); + using var stored = Decode(dng, new RawDecodeOptions { ApplyOrientation = false }); + using var expected = PixelConvert.ApplyOrientation(stored.Image, orientation); + Assert.Equal(expected.Width, oriented.Image.Width); + Assert.Equal(expected.Width, oriented.Info.Width); + Assert.SequenceEqual(expected.Data.ToArray(), oriented.Image.Data.ToArray()); + } + + [Theory] + [Case(DemosaicQuality.Best)] + [Case(DemosaicQuality.Draft)] + public void BinningHalvesTheSize(DemosaicQuality quality) + { + using var scene = SyntheticRaw.Smooth(W, H); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec()), new RawDecodeOptions { Binning = true, Quality = quality }); + Assert.Equal(W / 2, result.Image.Width); + Assert.Equal(H / 2, result.Image.Height); + using var expected = Resampler.Resize(scene, W / 2, H / 2, ResampleFilter.Box); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 1), 34); + } + + [Test] + public void ProbeDescribesWithoutDecoding() + { + using var scene = SyntheticRaw.Smooth(W, H); + var dng = SyntheticDng.Write(scene, new DngSpec { Orientation = 6, Crop = new RawRect(2, 2, 66, 50) }); + var probe = RawDecoder.Probe(new MemoryStream(dng), "x.dng"); + Assert.True(probe.IsSupported); + Assert.Equal(48, probe.Info!.Width); + Assert.Equal(64, probe.Info.Height); + Assert.Equal("managed-dng", probe.Info.Decoder); + Assert.Equal("Synthetic", probe.Info.Model); + } + + internal static ImageBuffer Crop(ImageBuffer source, int x0, int y0, int w, int h) + { + var result = new ImageBuffer(w, h, source.Channels); + for (var c = 0; c < source.Channels; c++) + { + for (var y = 0; y < h; y++) source.Row(c, y0 + y).Slice(x0, w).CopyTo(result.Row(c, y)); + } + return result; + } + + private static Chromaticity ColorTemperatureXy(double kelvin) => Titano.Core.Analysis.ColorTemperature.PlanckianChromaticity(kelvin); + + private static void AssertMatrix(Matrix3 expected, Matrix3 actual, double tolerance) + { + double[] e = [expected.M11, expected.M12, expected.M13, expected.M21, expected.M22, expected.M23, expected.M31, expected.M32, expected.M33]; + double[] a = [actual.M11, actual.M12, actual.M13, actual.M21, actual.M22, actual.M23, actual.M31, actual.M32, actual.M33]; + for (var i = 0; i < 9; i++) Assert.Approximately(e[i], a[i], tolerance); + } +} diff --git a/tests/Titano.Core.Tests/Raw/DngOpcodeTests.cs b/tests/Titano.Core.Tests/Raw/DngOpcodeTests.cs new file mode 100644 index 00000000..07d242c2 --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/DngOpcodeTests.cs @@ -0,0 +1,221 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Raw; + +/// DNG opcode lists: raw data is distorted by the inverse of an opcode, the decoder must undo it. +public sealed class DngOpcodeTests(TestContext context) +{ + private const int W = 96, H = 72; + + private static RawDecodeResult Decode(byte[] dng) => RawDecoder.Decode(new MemoryStream(dng), "op.dng"); + + /// Bilinear grid interpolation as DNG §7 GainMap defines it (independent of the decoder's implementation). + private static double GainAt(double[,] grid, double spacingV, double spacingH, int x, int y) + { + int rows = grid.GetLength(0), cols = grid.GetLength(1); + double fr = double.Clamp(y / (double)H / spacingV, 0, rows - 1), fc = double.Clamp(x / (double)W / spacingH, 0, cols - 1); + int r0 = (int)fr, c0 = (int)fc, r1 = int.Min(r0 + 1, rows - 1), c1 = int.Min(c0 + 1, cols - 1); + double a = fr - r0, b = fc - c0; + return (grid[r0, c0] * (1 - b) + grid[r0, c1] * b) * (1 - a) + (grid[r1, c0] * (1 - b) + grid[r1, c1] * b) * a; + } + + [Test] + public void GainMapRestoresShading() + { + double[,] grid = { { 1.6, 1.3, 1.6 }, { 1.2, 1.0, 1.25 }, { 1.7, 1.35, 1.5 } }; + var ops = new OpcodeListBuilder().Add(9, 0, p => + { + OpcodeListBuilder.Area(p, 0, 0, H, W); + p.U32(3).U32(3).F64(0.5).F64(0.5).F64(0).F64(0).U32(1); + for (var r = 0; r < 3; r++) + { + for (var c = 0; c < 3; c++) p.F32((float)grid[r, c]); + } + }).Build(); + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => (float)(v / GainAt(grid, 0.5, 0.5, x, y)) }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.Empty(result.Warnings); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Test] + public void GainMapWithPitchTargetsOneCfaColour() + { + // Red sites of RGGB (even rows and columns) were attenuated by 1/1.5. + var ops = new OpcodeListBuilder().Add(9, 0, p => + { + OpcodeListBuilder.Area(p, 0, 0, H, W, rowPitch: 2, colPitch: 2); + p.U32(1).U32(1).F64(1).F64(1).F64(0).F64(0).U32(1).F32(1.5f); + }).Build(); + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => x % 2 == 0 && y % 2 == 0 ? v / 1.5f : v }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Test] + public void FixVignetteRadialRestoresFalloff() + { + double k0 = 0.4, k1 = 0.2; + var ops = new OpcodeListBuilder().Add(3, 0, p => p.F64(k0).F64(k1).F64(0).F64(0).F64(0).F64(0.5).F64(0.5)).Build(); + var m = double.Hypot(W / 2.0, H / 2.0); + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec + { + OpcodeList2 = ops, + RawTransform = (x, y, v) => + { + var r2 = ((x - W / 2.0) * (x - W / 2.0) + (y - H / 2.0) * (y - H / 2.0)) / (m * m); + return (float)(v / (1 + k0 * r2 + k1 * r2 * r2)); + }, + }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Theory] + [Case(false)] + [Case(true)] + public void WarpRectilinearMovesPointsToTheirCorrectedPositions(bool mosaic) + { + // Corrected position p maps to source position f(p) (radial + tangential model, DNG §7 WarpRectilinear). + const int w = 160, h = 120; + double[] k = [1.0, 0.06, -0.01, 0.0, 0.002, -0.0015]; + double cx = 0.48, cy = 0.53; + var ops = new OpcodeListBuilder().Add(1, 0, p => + { + p.U32(1); + foreach (var v in k) p.F64(v); + p.F64(cx).F64(cy); + }).Build(); + double ox = cx * w, oy = cy * h; + var m = new[] { (0.0, 0.0), (w, 0.0), (0.0, h), (w, h) }.Max(c => double.Hypot(c.Item1 - ox, c.Item2 - oy)); + (double X, double Y) Source(double x, double y) + { + double dx = (x - ox) / m, dy = (y - oy) / m, r2 = dx * dx + dy * dy; + var f = k[0] + r2 * (k[1] + r2 * (k[2] + r2 * k[3])); + return (ox + m * (f * dx + k[4] * 2 * dx * dy + k[5] * (r2 + 2 * dx * dx)), oy + m * (f * dy + k[5] * 2 * dx * dy + k[4] * (r2 + 2 * dy * dy))); + } + (double X, double Y)[] targets = [(20, 18), (130, 25), (80, 60), (30, 100), (140, 104), (60, 40)]; + using var distorted = new ImageBuffer(w, h); + foreach (var (tx, ty) in targets) + { + var (sx, sy) = Source(tx, ty); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var g = (float)(0.6 * double.Exp(-((x - sx) * (x - sx) + (y - sy) * (y - sy)) / (2 * 2.0 * 2.0))); + for (var c = 0; c < 3; c++) distorted[c, x, y] += g; + } + } + } + for (var i = 0; i < distorted.Data.Length; i++) distorted.Data[i] += 0.02f; + var spec = new DngSpec { Cfa = mosaic ? CfaPattern.Bayer("RGGB") : null, OpcodeList3 = ops }; + using var result = Decode(SyntheticDng.Write(distorted, spec)); + Assert.Empty(result.Warnings); + foreach (var (tx, ty) in targets) + { + var (x, y) = Centroid(result.Image, (int)tx, (int)ty, 6); + context.Log($"target ({tx}, {ty}) → ({x:F3}, {y:F3})"); + Assert.Within(tx, ty, x, y, mosaic ? 0.2 : 0.1); + } + } + + [Test] + public void TrimBoundsAndDefaultCropCompose() + { + var ops = new OpcodeListBuilder().Add(6, 0, p => p.U32(4).U32(10).U32(60).U32(90)).Build(); + using var scene = SyntheticRaw.Smooth(W, H); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops, Crop = new RawRect(0, 0, 80, 64) })); + Assert.Equal(70, result.Image.Width); + Assert.Equal(56, result.Image.Height); + using var expected = DngDecoderTests.Crop(scene, 10, 4, 70, 56); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 38); + } + + [Test] + public void FixBadPixelsConstantAndListRepairMosaic() + { + (int X, int Y)[] dead = [(10, 10), (41, 20), (70, 33)]; + (int X, int Y)[] hot = [(30, 50), (55, 12)]; + var list1 = new OpcodeListBuilder().Add(4, 0, p => p.U32(0).U32(0)).Build(); + var list2 = new OpcodeListBuilder().Add(5, 0, p => + { + p.U32(0).U32((uint)hot.Length).U32(1); + foreach (var (x, y) in hot) p.U32((uint)y).U32((uint)x); + p.U32(60).U32(80).U32(62).U32(83); + }).Build(); + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec + { + OpcodeList1 = list1, + OpcodeList2 = list2, + RawTransform = (x, y, v) => dead.Contains((x, y)) ? -1f : hot.Contains((x, y)) || (y is >= 60 and < 62 && x is >= 80 and < 83) ? 1f : v, + }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38); + } + + [Test] + public void MapTableAndMapPolynomialInvertEncodings() + { + // Raw stored as v² is mapped back by a square-root table; then halved values are doubled by a polynomial. + var table = Enumerable.Range(0, 65536).Select(i => (ushort)double.Round(double.Sqrt(i / 65535.0) * 65535)).ToArray(); + var ops = new OpcodeListBuilder() + .Add(7, 0, p => + { + OpcodeListBuilder.Area(p, 0, 0, H, W); + p.U32((uint)table.Length); + foreach (var t in table) p.U16(t); + }) + .Add(8, 0, p => + { + OpcodeListBuilder.Area(p, 0, 0, H, W); + p.U32(1).F64(0).F64(2); + }) + .Build(); + using var scene = SyntheticRaw.Smooth(W, H); + var spec = new DngSpec { Black = [0], OpcodeList2 = ops, RawTransform = (_, _, v) => float.Max(0, v / 2) * float.Max(0, v / 2) }; + using var result = Decode(SyntheticDng.Write(scene, spec)); + var psnr = SyntheticRaw.Psnr(scene, result.Image, 4); + context.Log($"MapTable+MapPolynomial PSNR {psnr:F1} dB"); + Assert.GreaterOrEqual(psnr, 36); + } + + [Test] + public void UnknownAndMalformedOpcodesWarnAndContinue() + { + var ops = new OpcodeListBuilder() + .Add(99, 1, p => p.U32(1)) + .Add(98, 0, p => p.U32(1)) + .Add(9, 0, p => p.U32(1)) + .Build(); + using var scene = SyntheticRaw.Smooth(W, H); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops })); + Assert.Contains(result.Warnings, w => w.Contains("optional opcode 99")); + Assert.Contains(result.Warnings, w => w.Contains("required opcode 98")); + Assert.Contains(result.Warnings, w => w.Contains("GainMap") && w.Contains("malformed")); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40); + } + + /// Intensity-weighted centroid above the background in a window around (x, y). + private static (double X, double Y) Centroid(ImageBuffer image, int cx, int cy, int radius) + { + double sum = 0, sx = 0, sy = 0; + for (var y = cy - radius; y <= cy + radius; y++) + { + for (var x = cx - radius; x <= cx + radius; x++) + { + var v = double.Max(0, image[1, x, y] - 0.05); + sum += v; + sx += v * x; + sy += v * y; + } + } + return (sx / sum, sy / sum); + } +} diff --git a/tests/Titano.Core.Tests/Raw/HighlightTests.cs b/tests/Titano.Core.Tests/Raw/HighlightTests.cs new file mode 100644 index 00000000..eb142ba6 --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/HighlightTests.cs @@ -0,0 +1,75 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Raw; + +/// Clip-aware highlight reconstruction on decoded DNGs. +public sealed class HighlightTests(TestContext context) +{ + private const int W = 96, H = 64; + + /// Scene with three gray patches: unclipped (0.4), green clipped only (1.3) and fully clipped (3.0). + private static ImageBuffer Patches() + { + var scene = new ImageBuffer(W, H); + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + var v = x < 32 ? 0.4f : x < 64 ? 1.3f : 3.0f; + for (var c = 0; c < 3; c++) scene[c, x, y] = v; + } + } + return scene; + } + + [Theory] + [Case(DemosaicQuality.Best, false)] + [Case(DemosaicQuality.Draft, true)] + public void ClippedGrayStaysNeutral(DemosaicQuality quality, bool binning) + { + using var scene = Patches(); + var dng = SyntheticDng.Write(scene, new DngSpec()); + using var result = RawDecoder.Decode(new MemoryStream(dng), "h.dng", new RawDecodeOptions { Quality = quality, Binning = binning }); + var s = binning ? 2 : 1; + var (r0, g0, b0) = Pixel(result.Image, 16 / s, 32 / s); + var (r1, g1, b1) = Pixel(result.Image, 48 / s, 32 / s); + var (r2, g2, b2) = Pixel(result.Image, 80 / s, 32 / s); + context.Log($"0.4 → ({r0:F3}, {g0:F3}, {b0:F3}); 1.3 → ({r1:F3}, {g1:F3}, {b1:F3}); 3.0 → ({r2:F3}, {g2:F3}, {b2:F3})"); + + // Unclipped: exact. + Assert.Approximately(0.4, g0, 0.01); + Assert.Approximately(r0, b0, 0.01); + + // Only green clipped: rebuilt from red and blue, neutral and at its true level (no magenta cast). + Assert.Approximately(1.3, g1, 0.03); + Assert.Approximately(1.3, r1, 0.03); + Assert.Approximately(1.3, b1, 0.03); + + // Everything clipped: neutral, at least as bright as the partially clipped patch. + Assert.Approximately(r2, g2, 1e-3); + Assert.Approximately(b2, g2, 1e-3); + Assert.GreaterOrEqual(g2, g1); + } + + [Test] + public void SaturatedColourKeepsItsHue() + { + // A red highlight clips the red channel while green and blue stay low: it must stay red, not turn white. + using var scene = new ImageBuffer(W, H); + for (var i = 0; i < scene.PlaneLength; i++) + { + scene.Plane(0)[i] = 5f; + scene.Plane(1)[i] = 0.15f; + scene.Plane(2)[i] = 0.1f; + } + using var result = RawDecoder.Decode(new MemoryStream(SyntheticDng.Write(scene, new DngSpec())), "red.dng"); + var (r, g, b) = Pixel(result.Image, W / 2, H / 2); + context.Log($"red highlight → ({r:F3}, {g:F3}, {b:F3})"); + Assert.Greater(r, 4 * g); + Assert.Greater(r, 4 * b); + } + + private static (float R, float G, float B) Pixel(ImageBuffer image, int x, int y) => (image[0, x, y], image[1, x, y], image[2, x, y]); +} diff --git a/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs b/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs new file mode 100644 index 00000000..0d2048ac --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs @@ -0,0 +1,94 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Reflection; +using Titano.Core.Codecs.Raw; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Metadata.Tiff; +using Titano.Testing; + +namespace Titano.Core.Tests.Raw; + +/// 24-megapixel Bayer DNG development timing: AHD at full size and binned Draft at half size, all cores. +[Serial] +[Category("Performance")] +public sealed class RawPerformanceTests(TestContext context) +{ + private const int W = 6000, H = 4000; + + [Test] + [Timeout(60_000)] + public void Develops24MegapixelDngWithinBudget() + { + // A Debug build disables the JIT optimiser in Titano.Core: timings would measure the build, not the pipeline. + if (typeof(RawDecoder).Assembly.GetCustomAttribute()?.IsJITOptimizerDisabled == true) + TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)"); + var dng = Mosaic(); + var ahd = Best(dng, RawDecodeOptions.Default, out var size); + Assert.Equal(W, size.Width); + var half = Best(dng, new RawDecodeOptions { Quality = DemosaicQuality.Draft, Binning = true }, out var halfSize); + Assert.Equal(W / 2, halfSize.Width); + context.Log($"24 MP DNG: AHD full size {ahd.TotalMilliseconds:F0} ms, binned half size {half.TotalMilliseconds:F0} ms ({Environment.ProcessorCount} cores)"); + Console.WriteLine($"[perf] {context.LogText.Trim()}"); + Assert.Less(ahd.TotalSeconds, 4.0); + Assert.Less(half.TotalSeconds, 1.0); + } + + /// Best of two runs (the machine is shared; the first run also pays JIT warm-up). + private static TimeSpan Best(byte[] dng, RawDecodeOptions options, out (int Width, int Height) size) + { + var best = TimeSpan.MaxValue; + size = default; + for (var run = 0; run < 2; run++) + { + var sw = Stopwatch.StartNew(); + using var result = RawDecoder.Decode(new MemoryStream(dng, writable: false), "perf.dng", options); + best = sw.Elapsed < best ? sw.Elapsed : best; + size = (result.Image.Width, result.Image.Height); + } + return best; + } + + /// Uncompressed 14-bit RGGB DNG with photo-like texture (smooth illumination plus detail and noise). + private static byte[] Mosaic() + { + var data = new byte[W * H * 2]; + Parallel.For(0, H, y => + { + var state = (uint)(y * 2654435761u + 7); + for (var x = 0; x < W; x++) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + var colour = (y & 1) * 2 + (x & 1); + var level = 1500 + 5000 * (0.5 + 0.5 * double.Sin(x * 0.01) * double.Cos(y * 0.013)) * (colour is 1 or 2 ? 1.0 : 0.6) + + 800 * double.Sin(x * 0.4 + y * 0.3) + (state & 127); + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan((y * W + x) * 2), (ushort)double.Clamp(level, 0, 16383)); + } + }); + using var output = new MemoryStream(); + output.Write("II*\0\0\0\0\0"u8); + var ifd = new TiffDirectory(); + ifd.Long(TiffTags.NewSubfileType, 0); + ifd.Long(TiffTags.ImageWidth, W); + ifd.Long(TiffTags.ImageLength, H); + ifd.Short(TiffTags.BitsPerSample, 16); + ifd.Short(TiffTags.Compression, 1); + ifd.Short(TiffTags.PhotometricInterpretation, 32803); + ifd.Short(TiffTags.SamplesPerPixel, 1); + ifd.Long(TiffTags.StripOffsets, 8); + ifd.Long(TiffTags.StripByteCounts, (uint)data.Length); + ifd.Long(TiffTags.RowsPerStrip, H); + ifd.Short(TiffTags.CfaRepeatPatternDim, 2, 2); + ifd.Bytes(TiffTags.CfaPattern, 0, 1, 1, 2); + ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0); + ifd.Short(TiffTags.BlackLevel, 1024); + ifd.Short(TiffTags.WhiteLevel, 16383); + ifd.SRational(TiffTags.ColorMatrix1, (6722, 10000), (-635, 10000), (-963, 10000), (-4287, 10000), (12460, 10000), (2028, 10000), (-908, 10000), (2162, 10000), (5668, 10000)); + ifd.Short(TiffTags.CalibrationIlluminant1, 21); + ifd.Rational(TiffTags.AsShotNeutral, (500u, 1000u), (1000u, 1000u), (700u, 1000u)); + output.Write(data); + TiffWriter.WriteDirectory(output, 0, ifd); + return output.ToArray(); + } +} diff --git a/tests/Titano.Core.Tests/Raw/SyntheticRaw.cs b/tests/Titano.Core.Tests/Raw/SyntheticRaw.cs new file mode 100644 index 00000000..0a47f74f --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/SyntheticRaw.cs @@ -0,0 +1,454 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Codecs.Dng; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Raw; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Raw; + +/// Synthetic scenes and the camera model used to turn them into raw data with known answers. +internal static class SyntheticRaw +{ + /// Canon EOS 5D Mark III ColorMatrix (XYZ → camera, D65), the adobe_coeff values divided by 10 000. + public static Matrix3 CameraMatrix { get; } = new(0.6722, -0.0635, -0.0963, -0.4287, 1.2460, 0.2028, -0.0908, 0.2162, 0.5668); + + /// A second (tungsten) matrix for interpolation tests: the D65 one with a warmer bias. + public static Matrix3 TungstenMatrix { get; } = new(0.7300, -0.1100, -0.0800, -0.4000, 1.2000, 0.2400, -0.0500, 0.1500, 0.7400); + + /// Smooth colourful linear Rec.709 scene with values in roughly 0.03–0.7. + public static ImageBuffer Smooth(int width, int height) + { + var image = new ImageBuffer(width, height); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + double u = x / (double)width, v = y / (double)height; + image[0, x, y] = (float)(0.25 + 0.2 * double.Sin(2 * double.Pi * (u * 1.3 + 0.1)) * double.Cos(2 * double.Pi * v * 0.7)); + image[1, x, y] = (float)(0.3 + 0.2 * double.Cos(2 * double.Pi * (u * 0.8 - v * 0.9))); + image[2, x, y] = (float)(0.2 + 0.15 * double.Sin(2 * double.Pi * (v * 1.1 + u * 0.4 + 0.3))); + } + } + return image; + } + + /// Gray scene with a sharp vertical edge (dark left, bright right) and a sharp horizontal one. + public static ImageBuffer Edges(int width, int height) + { + var image = new ImageBuffer(width, height); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var v = (x >= width / 2 ? 0.6f : 0.08f) * (y >= height / 2 ? 0.5f : 1f); + for (var c = 0; c < 3; c++) image[c, x, y] = v; + } + } + return image; + } + + /// Camera response of a scene lit by : Bradford(D65 → white) · Rec.709 → XYZ, then + /// XYZ → camera, scaled so the white's camera neutral peaks at 1. Returns per-pixel camera RGB and that neutral. + public static (float[][] Camera, Vector3D Neutral) ToCamera(ImageBuffer scene, Matrix3 xyzToCamera, Chromaticity white) + { + var whiteXyz = white.ToXyz(); + var neutral = xyzToCamera * whiteXyz; + var s = double.Max(neutral.X, double.Max(neutral.Y, neutral.Z)); + var m = xyzToCamera * Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), whiteXyz) * Matrix3.Rec709ToXyz; + var camera = new float[3][]; + for (var c = 0; c < 3; c++) camera[c] = new float[scene.PlaneLength]; + for (var i = 0; i < scene.PlaneLength; i++) + { + var v = m * new Vector3D(scene.Plane(0)[i], scene.Plane(1)[i], scene.Plane(2)[i]); + camera[0][i] = (float)(v.X / s); + camera[1][i] = (float)(v.Y / s); + camera[2][i] = (float)(v.Z / s); + } + return (camera, new Vector3D(neutral.X / s, neutral.Y / s, neutral.Z / s)); + } + + /// PSNR in dB between two RGB buffers on sRGB-encoded values, ignoring pixels. + public static double Psnr(ImageBuffer expected, ImageBuffer actual, int border) + { + double sum = 0; + long n = 0; + for (var c = 0; c < 3; c++) + { + for (var y = border; y < expected.Height - border; y++) + { + for (var x = border; x < expected.Width - border; x++) + { + var d = ColorSpace.EncodeFast(expected[c, x, y]) - ColorSpace.EncodeFast(actual[c, x, y]); + sum += d * d; + n++; + } + } + } + return 10 * double.Log10(1 / double.Max(sum / n, 1e-12)); + } + + /// Mean CIE76 ΔE between two linear Rec.709 buffers (D65 white), ignoring pixels. + public static double MeanDeltaE(ImageBuffer expected, ImageBuffer actual, int border) + { + double sum = 0; + long n = 0; + for (var y = border; y < expected.Height - border; y++) + { + for (var x = border; x < expected.Width - border; x++) + { + var a = Lab(expected, x, y); + var b = Lab(actual, x, y); + sum += double.Sqrt((a.L - b.L) * (a.L - b.L) + (a.A - b.A) * (a.A - b.A) + (a.B - b.B) * (a.B - b.B)); + n++; + } + } + return sum / n; + } + + private static (double L, double A, double B) Lab(ImageBuffer image, int x, int y) + { + var xyz = Matrix3.Rec709ToXyz * new Vector3D(image[0, x, y], image[1, x, y], image[2, x, y]); + var w = Chromaticity.D65.ToXyz(); + static double F(double t) => t > 216.0 / 24389 ? double.Cbrt(t) : (24389.0 / 27 * t + 16) / 116; + double fx = F(xyz.X / w.X), fy = F(xyz.Y / w.Y), fz = F(xyz.Z / w.Z); + return (116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)); + } +} + +/// Description of a synthetic DNG written by . +internal sealed record DngSpec +{ + /// CFA pattern anchored at the active area; null writes a 3-sample LinearRaw image. + public CfaPattern? Cfa { get; init; } = CfaPattern.Bayer("RGGB"); + + /// Masked border around the scene (active area offset); the crop is relative to the active area. + public int MarginLeft { get; init; } + + public int MarginTop { get; init; } + public int MarginRight { get; init; } + public int MarginBottom { get; init; } + + /// DefaultCrop relative to the active area (null: none). + public RawRect? Crop { get; init; } + + public int White { get; init; } = 16383; + + /// Black pattern (rows × columns) or a single value. + public int BlackRows { get; init; } = 1; + + public int BlackColumns { get; init; } = 1; + public double[] Black { get; init; } = [512]; + public double[]? BlackDeltaH { get; init; } + public double[]? BlackDeltaV { get; init; } + + /// Forward linearisation table (stored code → linear value). + public ushort[]? Linearization { get; init; } + + /// 1 (uncompressed), 7 (lossless JPEG) or 8 (Deflate with horizontal predictor). + public int Compression { get; init; } = 7; + + /// Lossless JPEG tiles encode CFA rows as two interleaved components at half width (as the DNG SDK does). + public bool TwoComponentTiles { get; init; } = true; + + public int TileSize { get; init; } = 64; + + public Matrix3 ColorMatrix1 { get; init; } = SyntheticRaw.CameraMatrix; + + /// XYZ → camera used to synthesise the raw values (default: ). + public Matrix3? CaptureMatrix { get; init; } + + public int Illuminant1 { get; init; } = 21; + public Matrix3? ColorMatrix2 { get; init; } + public int Illuminant2 { get; init; } + public Matrix3? ForwardMatrix1 { get; init; } + + /// Scene illuminant; the file records it as AsShotNeutral or, with , AsShotWhiteXY. + public Chromaticity SceneWhite { get; init; } = Chromaticity.D65; + + public bool WriteWhiteXy { get; init; } + public double BaselineExposure { get; init; } + public byte[]? OpcodeList1 { get; init; } + public byte[]? OpcodeList2 { get; init; } + public byte[]? OpcodeList3 { get; init; } + public ushort Orientation { get; init; } = 1; + + /// Put the raw image in a SubIFD behind an IFD0 thumbnail, like camera DNGs. + public bool RawInSubIfd { get; init; } + + /// Raw-value transform applied after mosaicking (e.g. the inverse of a gain map), stored-unit domain. + public Func? RawTransform { get; init; } +} + +/// Writes synthetic DNGs from a linear scene with a known camera model (test-side writer). +internal static class SyntheticDng +{ + public static byte[] Write(ImageBuffer scene, DngSpec spec) + { + var (camera, neutral) = SyntheticRaw.ToCamera(scene, spec.CaptureMatrix ?? spec.ColorMatrix1, spec.SceneWhite); + int sw = scene.Width, sh = scene.Height; + int w = sw + spec.MarginLeft + spec.MarginRight, h = sh + spec.MarginTop + spec.MarginBottom; + var spp = spec.Cfa is null ? 3 : 1; + var samples = new ushort[w * h * spp]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + int ax = x - spec.MarginLeft, ay = y - spec.MarginTop; + var inside = ax >= 0 && ay >= 0 && ax < sw && ay < sh; + for (var s = 0; s < spp; s++) + { + var black = BlackAt(spec, ax, ay, s, spp); + double linear = black; + if (inside) + { + var c = spec.Cfa?.ColorAt(ax, ay) ?? s; + var raw = camera[c][ay * sw + ax]; + if (spec.RawTransform is { } t) raw = t(ax, ay, raw); + linear = black + raw * (spec.White - black); + } + linear = double.Clamp(linear, 0, spec.White); + samples[(y * w + x) * spp + s] = spec.Linearization is { } table ? Inverse(table, linear) : (ushort)double.Round(linear); + } + } + } + return Assemble(spec, samples, w, h, spp, neutral); + } + + /// Black level of the spec at active-area coordinates (outside the area: the pattern without deltas). + public static double BlackAt(DngSpec spec, int ax, int ay, int s, int spp) + { + var row = ((ay % spec.BlackRows) + spec.BlackRows) % spec.BlackRows; + var col = ((ax % spec.BlackColumns) + spec.BlackColumns) % spec.BlackColumns; + var b = spec.Black.Length == 1 ? spec.Black[0] : spec.Black[(row * spec.BlackColumns + col) * spp + s]; + if (spec.BlackDeltaH is { } dh && ax >= 0 && ax < dh.Length) b += dh[ax]; + if (spec.BlackDeltaV is { } dv && ay >= 0 && ay < dv.Length) b += dv[ay]; + return b; + } + + private static ushort Inverse(ushort[] table, double value) + { + var best = 0; + for (var i = 1; i < table.Length; i++) + { + if (double.Abs(table[i] - value) < double.Abs(table[best] - value)) best = i; + } + return (ushort)best; + } + + private static byte[] Assemble(DngSpec spec, ushort[] samples, int w, int h, int spp, Vector3D neutral) + { + using var output = new MemoryStream(); + output.Write("II*\0\0\0\0\0"u8); + var raw = new TiffDirectory(); + raw.Long(TiffTags.NewSubfileType, 0); + raw.Long(TiffTags.ImageWidth, (uint)w); + raw.Long(TiffTags.ImageLength, (uint)h); + raw.Short(TiffTags.BitsPerSample, [.. Enumerable.Repeat((ushort)16, spp)]); + raw.Short(TiffTags.Compression, (ushort)spec.Compression); + raw.Short(TiffTags.PhotometricInterpretation, (ushort)(spec.Cfa is null ? 34892 : 32803)); + raw.Short(TiffTags.SamplesPerPixel, (ushort)spp); + raw.Short(TiffTags.PlanarConfiguration, 1); + if (spec.Compression == 8) raw.Short(TiffTags.Predictor, 2); + WriteData(spec, raw, output, samples, w, h, spp); + if (spec.Cfa is { } cfa) + { + raw.Short(TiffTags.CfaRepeatPatternDim, (ushort)cfa.Height, (ushort)cfa.Width); + var pattern = new byte[cfa.Width * cfa.Height]; + for (var i = 0; i < pattern.Length; i++) pattern[i] = (byte)cfa.ColorAt(i % cfa.Width, i / cfa.Width); + raw.Bytes(TiffTags.CfaPattern, pattern); + raw.Bytes(TiffTags.CfaPlaneColor, 0, 1, 2); + raw.Short(TiffTags.CfaLayout, 1); + } + if (spec.MarginLeft + spec.MarginTop + spec.MarginRight + spec.MarginBottom > 0) + raw.Long(TiffTags.ActiveArea, (uint)spec.MarginTop, (uint)spec.MarginLeft, (uint)(h - spec.MarginBottom), (uint)(w - spec.MarginRight)); + if (spec.Crop is { } crop) + { + raw.Long(TiffTags.DefaultCropOrigin, (uint)crop.Left, (uint)crop.Top); + raw.Long(TiffTags.DefaultCropSize, (uint)crop.Width, (uint)crop.Height); + } + if (spec.Linearization is { } table) raw.Short(TiffTags.LinearizationTable, table); + if (spec.BlackRows * spec.BlackColumns > 1) raw.Short(TiffTags.BlackLevelRepeatDim, (ushort)spec.BlackRows, (ushort)spec.BlackColumns); + raw.Rational(TiffTags.BlackLevel, [.. spec.Black.Select(b => ((uint)double.Round(b * 100), 100u))]); + if (spec.BlackDeltaH is { } dh) raw.SRational(TiffTags.BlackLevelDeltaH, [.. dh.Select(d => ((int)double.Round(d * 100), 100))]); + if (spec.BlackDeltaV is { } dv) raw.SRational(TiffTags.BlackLevelDeltaV, [.. dv.Select(d => ((int)double.Round(d * 100), 100))]); + raw.Long(TiffTags.WhiteLevel, [.. Enumerable.Repeat((uint)spec.White, spp)]); + if (spec.OpcodeList1 is { } o1) raw.Add(TiffTags.OpcodeList1, TiffType.Undefined, o1.Length, o1); + if (spec.OpcodeList2 is { } o2) raw.Add(TiffTags.OpcodeList2, TiffType.Undefined, o2.Length, o2); + if (spec.OpcodeList3 is { } o3) raw.Add(TiffTags.OpcodeList3, TiffType.Undefined, o3.Length, o3); + + var ifd0 = raw; + if (spec.RawInSubIfd) + { + ifd0 = new TiffDirectory(); + ifd0.Long(TiffTags.NewSubfileType, 1); + ifd0.Long(TiffTags.ImageWidth, 4); + ifd0.Long(TiffTags.ImageLength, 4); + ifd0.Short(TiffTags.BitsPerSample, 8, 8, 8); + ifd0.Short(TiffTags.Compression, 1); + ifd0.Short(TiffTags.PhotometricInterpretation, 2); + ifd0.Short(TiffTags.SamplesPerPixel, 3); + ifd0.Long(TiffTags.StripOffsets, 8); + ifd0.Long(TiffTags.StripByteCounts, 48); + ifd0.Child(TiffTags.SubIfds, raw); + } + ifd0.Ascii(TiffTags.Make, "Titano"); + ifd0.Ascii(TiffTags.Model, "Synthetic"); + ifd0.Short(TiffTags.Orientation, spec.Orientation); + ifd0.Bytes(TiffTags.DngVersion, 1, 6, 0, 0); + ifd0.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0); + ifd0.Ascii(TiffTags.UniqueCameraModel, "Titano Synthetic"); + ifd0.SRational(TiffTags.ColorMatrix1, Rationals(spec.ColorMatrix1)); + ifd0.Short(TiffTags.CalibrationIlluminant1, (ushort)spec.Illuminant1); + if (spec.ColorMatrix2 is { } cm2) + { + ifd0.SRational(TiffTags.ColorMatrix2, Rationals(cm2)); + ifd0.Short(TiffTags.CalibrationIlluminant2, (ushort)spec.Illuminant2); + } + if (spec.ForwardMatrix1 is { } fm) ifd0.SRational(TiffTags.ForwardMatrix1, Rationals(fm)); + if (spec.WriteWhiteXy) + { + ifd0.Rational(TiffTags.AsShotWhiteXy, ((uint)double.Round(spec.SceneWhite.X * 1e6), 1_000_000u), ((uint)double.Round(spec.SceneWhite.Y * 1e6), 1_000_000u)); + } + else + { + ifd0.Rational(TiffTags.AsShotNeutral, R(neutral.X), R(neutral.Y), R(neutral.Z)); + } + ifd0.SRational(TiffTags.BaselineExposure, ((int)double.Round(spec.BaselineExposure * 1000), 1000)); + TiffWriter.WriteDirectory(output, 0, ifd0); + return output.ToArray(); + } + + private static (uint, uint) R(double v) => ((uint)double.Round(v * 1_000_000), 1_000_000u); + + private static (int, int)[] Rationals(Matrix3 m) => + [.. new[] { m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33 }.Select(v => ((int)double.Round(v * 1_000_000), 1_000_000))]; + + private static void WriteData(DngSpec spec, TiffDirectory raw, Stream output, ushort[] samples, int w, int h, int spp) + { + if (spec.Compression == 7) + { + var t = spec.TileSize; + int across = (w + t - 1) / t, down = (h + t - 1) / t; + var offsets = new uint[across * down]; + var counts = new uint[across * down]; + for (var ty = 0; ty < down; ty++) + { + for (var tx = 0; tx < across; tx++) + { + var tile = new ushort[t * t * spp]; + for (var y = 0; y < t; y++) + { + for (var x = 0; x < t; x++) + { + int sx = int.Min(tx * t + x, w - 1), sy = int.Min(ty * t + y, h - 1); + for (var s = 0; s < spp; s++) tile[(y * t + x) * spp + s] = samples[(sy * w + sx) * spp + s]; + } + } + var twoComponents = spec.TwoComponentTiles && spp == 1; + var jpeg = twoComponents ? JpegLosslessEncoder.Encode(tile, t / 2, t, 2, 16) : JpegLosslessEncoder.Encode(tile, t, t, spp, 16); + offsets[ty * across + tx] = (uint)output.Position; + counts[ty * across + tx] = (uint)jpeg.Length; + output.Write(jpeg); + if (output.Position % 2 != 0) output.WriteByte(0); + } + } + raw.Long(TiffTags.TileWidth, (uint)t); + raw.Long(TiffTags.TileLength, (uint)t); + raw.Long(TiffTags.TileOffsets, offsets); + raw.Long(TiffTags.TileByteCounts, counts); + return; + } + var bytes = new byte[samples.Length * 2]; + if (spec.Compression == 8) + { + // Horizontal differencing per row (Predictor 2), then zlib. + var rowSamples = w * spp; + var diff = new ushort[samples.Length]; + for (var y = 0; y < h; y++) + { + for (var i = 0; i < rowSamples; i++) + { + var k = y * rowSamples + i; + diff[k] = i < spp ? samples[k] : (ushort)(samples[k] - samples[k - spp]); + } + } + for (var i = 0; i < diff.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), diff[i]); + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(bytes); + bytes = ms.ToArray(); + } + else + { + for (var i = 0; i < samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), samples[i]); + } + raw.Long(TiffTags.StripOffsets, (uint)output.Position); + raw.Long(TiffTags.StripByteCounts, (uint)bytes.Length); + raw.Long(TiffTags.RowsPerStrip, (uint)h); + output.Write(bytes); + } +} + +/// Big-endian opcode list builder for tests (DNG 1.6 chapter 7 layout). +internal sealed class OpcodeListBuilder +{ + private readonly List _ops = []; + + public OpcodeListBuilder Add(uint id, uint flags, Action parameters) + { + var p = new BigEndian(); + parameters(p); + var body = p.ToArray(); + var head = new BigEndian().U32(id).U32(0x01030000).U32(flags).U32((uint)body.Length).ToArray(); + _ops.Add([.. head, .. body]); + return this; + } + + public byte[] Build() => [.. new BigEndian().U32((uint)_ops.Count).ToArray(), .. _ops.SelectMany(o => o)]; + + /// Area spec (top, left, bottom, right, plane, planes, row pitch, column pitch). + public static void Area(BigEndian p, int top, int left, int bottom, int right, int plane = 0, int planes = 1, int rowPitch = 1, int colPitch = 1) => + p.U32((uint)top).U32((uint)left).U32((uint)bottom).U32((uint)right).U32((uint)plane).U32((uint)planes).U32((uint)rowPitch).U32((uint)colPitch); + + internal sealed class BigEndian + { + private readonly MemoryStream _ms = new(); + + public BigEndian U32(uint v) + { + Span b = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(b, v); + _ms.Write(b); + return this; + } + + public BigEndian U16(ushort v) + { + Span b = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(b, v); + _ms.Write(b); + return this; + } + + public BigEndian F32(float v) + { + Span b = stackalloc byte[4]; + BinaryPrimitives.WriteSingleBigEndian(b, v); + _ms.Write(b); + return this; + } + + public BigEndian F64(double v) + { + Span b = stackalloc byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(b, v); + _ms.Write(b); + return this; + } + + public byte[] ToArray() => _ms.ToArray(); + } +} From d40fdee35e2b02f915361856c1ac2b1bf5ca355f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:57:55 +0000 Subject: [PATCH 138/188] test(raw): demosaic accuracy, zipper and X-Trans gates AHD 48.2 dB and bilinear 44.1 dB PSNR on a photo-like scene (gates 38/32), no zipper or fringe along sharp edges for AHD, X-Trans neighbourhood interpolation 43.6 dB and third-size binning 39.1 dB. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Core.Tests/Raw/DemosaicTests.cs | 139 +++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 tests/Titano.Core.Tests/Raw/DemosaicTests.cs diff --git a/tests/Titano.Core.Tests/Raw/DemosaicTests.cs b/tests/Titano.Core.Tests/Raw/DemosaicTests.cs new file mode 100644 index 00000000..fda81076 --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/DemosaicTests.cs @@ -0,0 +1,139 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Raw; + +/// Demosaic accuracy against the full-colour scene a mosaic was sampled from. +public sealed class DemosaicTests(TestContext context) +{ + /// Fujifilm X-Trans layout (6×6). + internal static readonly CfaPattern XTrans = new(6, 6, + [ + 1, 1, 0, 1, 1, 2, + 1, 1, 2, 1, 1, 0, + 2, 0, 1, 0, 2, 1, + 1, 1, 2, 1, 1, 0, + 1, 1, 0, 1, 1, 2, + 0, 2, 1, 2, 0, 1, + ]); + + /// Smooth colour scene modelled like a photograph: luminance texture at 10–30 px periods multiplied by a + /// slowly varying chroma field (high frequencies correlate across channels, as in natural images). + private static ImageBuffer Scene(int w, int h) + { + var image = new ImageBuffer(w, h); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var l = 0.3 + 0.1 * double.Sin(x * 0.31 + y * 0.12) + 0.06 * double.Sin(y * 0.45 - x * 0.2) + 0.04 * double.Cos((x - y) * 0.6); + image[0, x, y] = (float)(l * (1 + 0.35 * double.Sin(x * 0.02 + 0.5))); + image[1, x, y] = (float)(l * (1 + 0.15 * double.Cos(y * 0.03))); + image[2, x, y] = (float)(l * (1 + 0.35 * double.Cos(x * 0.015 - y * 0.02))); + } + } + return image; + } + + internal static ImageBuffer Mosaic(ImageBuffer scene, CfaPattern cfa) + { + var m = new ImageBuffer(scene.Width, scene.Height, 1); + for (var y = 0; y < scene.Height; y++) + { + for (var x = 0; x < scene.Width; x++) m[0, x, y] = scene[cfa.ColorAt(x, y), x, y]; + } + return m; + } + + [Theory] + [Case("RGGB")] + [Case("GBRG")] + public void AhdAndBilinearMeetTheirAccuracyGates(string layout) + { + var cfa = CfaPattern.Bayer(layout); + using var scene = Scene(256, 192); + using var mosaic = Mosaic(scene, cfa); + using var ahd = AhdDemosaic.Run(mosaic, cfa, Matrix3.Rec709ToXyz, -1, default); + using var bilinear = Demosaic.Bilinear(mosaic, cfa, -1, default); + var pAhd = SyntheticRaw.Psnr(scene, ahd, 2); + var pBilinear = SyntheticRaw.Psnr(scene, bilinear, 2); + context.Log($"{layout}: AHD {pAhd:F1} dB, bilinear {pBilinear:F1} dB"); + Assert.GreaterOrEqual(pAhd, 38); + Assert.GreaterOrEqual(pBilinear, 32); + Assert.Greater(pAhd, pBilinear); + } + + [Test] + public void AhdDoesNotZipperAlongEdges() + { + var cfa = CfaPattern.Bayer("RGGB"); + using var scene = SyntheticRaw.Edges(128, 128); + using var mosaic = Mosaic(scene, cfa); + using var ahd = AhdDemosaic.Run(mosaic, cfa, Matrix3.Rec709ToXyz, -1, default); + using var bilinear = Demosaic.Bilinear(mosaic, cfa, -1, default); + var (zipAhd, fringeAhd) = EdgeArtefacts(ahd); + var (zipBilinear, fringeBilinear) = EdgeArtefacts(bilinear); + context.Log($"zipper AHD {zipAhd:F5} bilinear {zipBilinear:F5}; fringe AHD {fringeAhd:F5} bilinear {fringeBilinear:F5}"); + Assert.Less(zipAhd, 0.002); + Assert.Less(fringeAhd, 0.002); + Assert.Less(fringeAhd, fringeBilinear); + } + + [Test] + public void XTransNeighbourhoodInterpolationAndBinning() + { + using var scene = Scene(240, 180); + using var mosaic = Mosaic(scene, XTrans); + Assert.Equal(3, XTrans.BinSize); + Assert.False(XTrans.IsBayer); + using var full = Demosaic.Neighbourhood(mosaic, XTrans, -1, default); + var psnr = SyntheticRaw.Psnr(scene, full, 2); + using var third = Demosaic.Bin(mosaic, XTrans, 3, -1, default); + using var expected = Resampler.Resize(scene, 80, 60, ResampleFilter.Box); + var binned = SyntheticRaw.Psnr(expected, third, 1); + context.Log($"X-Trans neighbourhood {psnr:F1} dB, binned {binned:F1} dB"); + Assert.GreaterOrEqual(psnr, 34); + Assert.GreaterOrEqual(binned, 34); + } + + [Test] + public void PatternReductionAndShift() + { + var bayer = new CfaPattern(4, 4, [0, 1, 0, 1, 1, 2, 1, 2, 0, 1, 0, 1, 1, 2, 1, 2]); + Assert.Equal(2, bayer.Width); + Assert.True(bayer.IsBayer); + Assert.Equal("RGGB", bayer.ToString()); + Assert.Equal("GRBG", bayer.Shift(1, 0).ToString()); + Assert.Equal("BGGR", bayer.Shift(-1, -1).ToString()); + Assert.Throws(() => new CfaPattern(2, 2, [0, 1, 1, 1])); + Assert.Throws(() => new CfaPattern(2, 2, [0, 1, 3, 2])); + } + + /// Zipper: second difference along each edge; fringe: chroma |R−G| + |B−G| next to the edges of a gray scene. + private static (double Zipper, double Fringe) EdgeArtefacts(ImageBuffer image) + { + double zipper = 0, fringe = 0; + var n = 0; + int w = image.Width, h = image.Height; + for (var d = -2; d <= 1; d++) + { + for (var k = 8; k < h - 8; k++) + { + if (k is > 56 and < 72) continue; + // Vertical edge at x = w/2 (columns w/2-2 .. w/2+1), and horizontal edge at y = h/2. + int vx = w / 2 + d, hy = h / 2 + d; + for (var c = 0; c < 3; c++) + { + zipper += double.Abs(image[c, vx, k] - (image[c, vx, k - 1] + image[c, vx, k + 1]) / 2); + zipper += double.Abs(image[c, k, hy] - (image[c, k - 1, hy] + image[c, k + 1, hy]) / 2); + } + fringe += double.Abs(image[0, vx, k] - image[1, vx, k]) + double.Abs(image[2, vx, k] - image[1, vx, k]); + fringe += double.Abs(image[0, k, hy] - image[1, k, hy]) + double.Abs(image[2, k, hy] - image[1, k, hy]); + n += 2; + } + } + return (zipper / (3 * n), fringe / n); + } +} From 304ddf643db4f6ae8cbfe805939194c80df6a1a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:04:21 +0000 Subject: [PATCH 139/188] fix(data): never block the caller's thread and never lose a SQLite cancel SQLite steps ran synchronously on the calling thread, so a repository awaited on the WPF UI thread would freeze the window for the length of the query. Blocking calls now continue on the thread pool. A cancel that landed before sqlite3_step started the statement was lost (SQLite clears the interrupt when no statement is running) and the query ran to completion. Each connection now has a cancel flag polled by a progress handler; it is cleared outside every interruptible operation so a stale cancel cannot stop a later statement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 1 + src/Titano.Data/Sqlite/SqliteConnection.cs | 27 +++++++++++++-- src/Titano.Data/Sqlite/SqliteNative.cs | 1 + src/Titano.Data/Sqlite/SqliteSession.cs | 33 ++++++++++++++++--- src/Titano.Data/Sqlite/ThreadPoolHop.cs | 23 +++++++++++++ .../Sqlite/SqliteBindingTests.cs | 20 +++++++++++ 6 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 src/Titano.Data/Sqlite/ThreadPoolHop.cs diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index df6a5afa..69f01b5c 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -80,3 +80,4 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Uploader settings are an in-window panel; single instance via a per-session mutex and a current-user named pipe; native tray menu (`TrackPopupMenuEx`). | Dialog / WM_COPYDATA / WPF ContextMenu | §12.1 allows modals only for login and destructive confirmations; works while hidden in the tray; dismisses reliably. | | 2026-10-02 | Network watch folders are polled (default 5 min); local folders every 60 s plus `FileSystemWatcher` hints. | Watcher everywhere | SMB change notifications are unreliable. | | 2026-10-02 | The Dockerfile uses BuildKit's built-in frontend (no `# syntax=docker/dockerfile:1`). | Pinned external frontend | Every feature used is built in; the build no longer depends on Docker Hub (a 502 there failed CI). Base images come from mcr.microsoft.com. | +| 2026-10-02 | SQLite sessions run every blocking call on the thread pool (`ThreadPoolHop`) and cancel through a per-connection flag polled by `sqlite3_progress_handler` (every 1000 VM instructions) in addition to `sqlite3_interrupt`. | Callers offload themselves / interrupt only | A repository awaited on the UI thread never freezes it; an interrupt that lands before `sqlite3_step` starts was silently lost and the query ran to the end. | diff --git a/src/Titano.Data/Sqlite/SqliteConnection.cs b/src/Titano.Data/Sqlite/SqliteConnection.cs index b81c7f10..6d5d5761 100644 --- a/src/Titano.Data/Sqlite/SqliteConnection.cs +++ b/src/Titano.Data/Sqlite/SqliteConnection.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using System.Text; using static Titano.Data.Sqlite.SqliteNative; @@ -11,10 +12,20 @@ internal sealed unsafe class SqliteConnection : IDisposable "PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA temp_store=MEMORY; " + "PRAGMA cache_size=-65536; PRAGMA mmap_size=268435456;"; + // SQLite polls the cancel flag every ProgressInterval VM instructions. sqlite3_interrupt alone is lost when it + // lands before sqlite3_step starts the statement (SQLite clears it when no statement is running). + private const int ProgressInterval = 1000; + private readonly Dictionary> _cache = new(StringComparer.Ordinal); private readonly LinkedList _lru = new(); + private int* _cancel; - private SqliteConnection(nint handle) => Handle = handle; + private SqliteConnection(nint handle) + { + Handle = handle; + _cancel = (int*)NativeMemory.AllocZeroed(sizeof(int)); + sqlite3_progress_handler(handle, ProgressInterval, &OnProgress, (nint)_cancel); + } public nint Handle { get; private set; } @@ -111,7 +122,14 @@ internal sealed unsafe class SqliteConnection : IDisposable else statement.Dispose(); } - public void Interrupt() => sqlite3_interrupt(Handle); + /// Stops the running statement, or the next one if none has started yet, until . + public void Interrupt() + { + Volatile.Write(ref *_cancel, 1); + sqlite3_interrupt(Handle); + } + + public void ClearInterrupt() => Volatile.Write(ref *_cancel, 0); public SqliteException Error(int rc) => new(Utf8(sqlite3_errmsg(Handle)) ?? $"SQLite error {rc}", rc); @@ -123,8 +141,13 @@ internal sealed unsafe class SqliteConnection : IDisposable _cache.Clear(); sqlite3_close_v2(Handle); Handle = 0; + NativeMemory.Free(_cancel); + _cancel = null; } + [UnmanagedCallersOnly] + private static int OnProgress(nint cancel) => Volatile.Read(ref *(int*)cancel); + private SqliteStatement Prepare(string sql) { var bytes = Encoding.UTF8.GetBytes(SqliteSqlText.TranslatePlaceholders(sql)); diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs index b86a4c77..f485ce37 100644 --- a/src/Titano.Data/Sqlite/SqliteNative.cs +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -77,6 +77,7 @@ internal static unsafe class SqliteNative [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_free(void* p); [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db); [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_interrupt(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_progress_handler(nint db, int instructions, delegate* unmanaged callback, nint arg); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_changes(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_total_changes(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_get_autocommit(nint db); diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs index 4954f572..9045a39b 100644 --- a/src/Titano.Data/Sqlite/SqliteSession.cs +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -7,7 +7,7 @@ namespace Titano.Data.Sqlite; /// /// A pooled SQLite connection. Statements that write take the database write lock for their duration when no /// transaction holds it already; lock conflicts are retried (see ). Cancellation -/// interrupts the running statement with sqlite3_interrupt. +/// interrupts the running statement with sqlite3_interrupt. Blocking SQLite calls always run on the thread pool. /// internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession { @@ -21,6 +21,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) { + await default(ThreadPoolHop); ObjectDisposedException.ThrowIf(_disposed, this); cancellationToken.ThrowIfCancellationRequested(); var statement = connection.Rent(sql); @@ -50,6 +51,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) { + await default(ThreadPoolHop); ObjectDisposedException.ThrowIf(_disposed, this); cancellationToken.ThrowIfCancellationRequested(); var statement = connection.Rent(sql); @@ -82,6 +84,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co public async Task ExecuteScriptAsync(string script, CancellationToken cancellationToken) { + await default(ThreadPoolHop); ObjectDisposedException.ThrowIf(_disposed, this); cancellationToken.ThrowIfCancellationRequested(); var locked = _transaction is null; @@ -221,6 +224,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co private async Task InsertBufferedAsync(string table, IReadOnlyList columns, object?[] buffer, int rowCount, CancellationToken cancellationToken) { + await default(ThreadPoolHop); var statement = connection.Rent(InsertSql(table, columns, rowCount)); try { @@ -250,6 +254,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co private async Task RunAsync(string sql, CancellationToken cancellationToken) { + await default(ThreadPoolHop); var statement = connection.Rent(sql); try { @@ -272,6 +277,7 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co var busyRetries = 0; while (true) { + await default(ThreadPoolHop); // each row may be pulled from a UI thread var rc = statement.Step(); if (rc is SQLITE_ROW or SQLITE_DONE) return rc; var primary = rc & 0xFF; @@ -290,10 +296,27 @@ internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection co } } - private CancellationTokenRegistration RegisterInterrupt(CancellationToken cancellationToken) => - cancellationToken.CanBeCanceled - ? cancellationToken.UnsafeRegister(static state => ((SqliteConnection)state!).Interrupt(), connection) - : default; + private InterruptScope RegisterInterrupt(CancellationToken cancellationToken) => new(connection, cancellationToken); + + /// Interrupts the connection when the token is cancelled; the interrupt never outlives the scope. + private readonly struct InterruptScope : IDisposable + { + private readonly SqliteConnection _connection; + private readonly CancellationTokenRegistration _registration; + + public InterruptScope(SqliteConnection connection, CancellationToken cancellationToken) + { + _connection = connection; + connection.ClearInterrupt(); + _registration = cancellationToken.UnsafeRegister(static state => ((SqliteConnection)state!).Interrupt(), connection); + } + + public void Dispose() + { + _registration.Dispose(); // waits for a callback already running + _connection.ClearInterrupt(); + } + } } /// A BEGIN IMMEDIATE transaction holding the database write lock until it ends. diff --git a/src/Titano.Data/Sqlite/ThreadPoolHop.cs b/src/Titano.Data/Sqlite/ThreadPoolHop.cs new file mode 100644 index 00000000..23c47cb0 --- /dev/null +++ b/src/Titano.Data/Sqlite/ThreadPoolHop.cs @@ -0,0 +1,23 @@ +using System.Runtime.CompilerServices; + +namespace Titano.Data.Sqlite; + +/// +/// await default(ThreadPoolHop) continues on a thread-pool thread unless the caller already runs on one +/// without a synchronization context. SQLite calls block for as long as a statement runs, so they must never run on +/// a UI thread. +/// +internal readonly struct ThreadPoolHop : ICriticalNotifyCompletion +{ + public bool IsCompleted => SynchronizationContext.Current is null && Thread.CurrentThread.IsThreadPoolThread; + + public ThreadPoolHop GetAwaiter() => this; + + public void GetResult() + { + } + + public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(static c => c(), continuation, preferLocal: false); + + public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(static c => c(), continuation, preferLocal: false); +} diff --git a/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs index f0ddbc6b..f2d2b576 100644 --- a/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs +++ b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs @@ -27,6 +27,26 @@ public sealed class SqliteBindingTests(TestContext context) : DatabaseTest(conte Assert.Equal(268435456L, await session.ScalarAsync("PRAGMA mmap_size", [], Ct)); } + [Test] + public async Task CallsFromAUiThreadReturnBeforeTheStatementRuns() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); + Task? query = null; + var ui = new Thread(() => + { + // A UI thread: has a synchronization context and is not a pool thread. + SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); + query = session.ExecuteAsync( + "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", [], cts.Token); + }); + ui.Start(); + Assert.True(ui.Join(TimeSpan.FromSeconds(5)), "the calling thread was blocked by the statement"); + Assert.False(query!.IsCompleted); + await cts.CancelAsync(); + await Assert.ThrowsAsync(() => query); + } + [Test] public async Task RejectsScriptsAndWrongParameterCounts() { From 52cde1419b92992e7e11d148437928c96f7e7c8f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:07:02 +0000 Subject: [PATCH 140/188] refactor(core): name the advisor namespace Advice; record advisor decisions The Advisor class shared its namespace's name, forcing an alias in every Titano.Core caller. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 7 ++ .../{Advisor => Advice}/Advisor.cs | 2 +- .../{Advisor => Advice}/AdvisorKeys.cs | 2 +- .../{Advisor => Advice}/AdvisorRules.cs | 2 +- .../{Advisor => Advice}/AdvisorTypes.cs | 2 +- .../{Advisor => Advice}/ParameterBindings.cs | 2 +- .../{Advisor => Advice}/SequencePresets.cs | 2 +- .../AdvisorLocalizationTests.cs | 11 ++- .../{Advisor => Advice}/AdvisorTests.cs | 80 +++++++++++-------- .../Analysis/Deep/DeepAnalyzerTests.cs | 23 +++++- 10 files changed, 84 insertions(+), 49 deletions(-) rename src/Titano.Core/{Advisor => Advice}/Advisor.cs (99%) rename src/Titano.Core/{Advisor => Advice}/AdvisorKeys.cs (99%) rename src/Titano.Core/{Advisor => Advice}/AdvisorRules.cs (99%) rename src/Titano.Core/{Advisor => Advice}/AdvisorTypes.cs (99%) rename src/Titano.Core/{Advisor => Advice}/ParameterBindings.cs (99%) rename src/Titano.Core/{Advisor => Advice}/SequencePresets.cs (99%) rename tests/Titano.Core.Tests/{Advisor => Advice}/AdvisorLocalizationTests.cs (93%) rename tests/Titano.Core.Tests/{Advisor => Advice}/AdvisorTests.cs (84%) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 69f01b5c..024d4cc0 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -81,3 +81,10 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Network watch folders are polled (default 5 min); local folders every 60 s plus `FileSystemWatcher` hints. | Watcher everywhere | SMB change notifications are unreliable. | | 2026-10-02 | The Dockerfile uses BuildKit's built-in frontend (no `# syntax=docker/dockerfile:1`). | Pinned external frontend | Every feature used is built in; the build no longer depends on Docker Hub (a 502 there failed CI). Base images come from mcr.microsoft.com. | | 2026-10-02 | SQLite sessions run every blocking call on the thread pool (`ThreadPoolHop`) and cancel through a per-connection flag polled by `sqlite3_progress_handler` (every 1000 VM instructions) in addition to `sqlite3_interrupt`. | Callers offload themselves / interrupt only | A repository awaited on the UI thread never freezes it; an interrupt that lands before `sqlite3_step` starts was silently lost and the query ran to the end. | +| 2026-10-02 | Deep analysis persists per-frame shifts from the nine-patch `Stabilizer` and smooths the path itself; per-frame data is stored as columns (~80–110 bytes/frame) with a JSON-lines checkpoint that drops a torn last line. | `Stabilizer.Solve` / row objects | `Solve` cannot resume from a checkpoint; the report stays small for 100k-frame sequences. | +| 2026-10-02 | Sky/land mask from a pre-pass over 15 sampled frames before the main pass. | Segment after the pass | Cloud coverage and per-region luminance need the mask during the pass. | +| 2026-10-02 | Scene distance: chi-square on histograms smoothed by ⅛ EV and levelled to the same mean; flow statistics use brightness-levelled images and forward–backward-consistent vectors only; noise is median-based (Immerkær). | Raw chi-square / raw flow / mean noise | Flicker and exposure steps no longer read as scene changes or motion; stars no longer inflate noise. | +| 2026-10-02 | Shake and motion thresholds are judged in output pixels (stabilise above 0.3 px RMS). | Source pixels | That is what the viewer sees. | +| 2026-10-02 | Automatic output stops at 4K UHD; no automatic stacking advice. | 8K / temporal-median denoise | 8K stays a manual choice; a median erases moving stars and stillness cannot be verified reliably. | +| 2026-10-02 | Apply records a missing-data reason only where no advice exists; Optimise returns modules to Auto and only adds to the user's hero, exclusions, offset or output cap; a preset's own choices are stored as manual values, content-derived values stay Auto. | Overwrite | Manual values stay in force; re-analysis does not undo a chosen preset. | +| 2026-10-02 | Advisor namespace is `Titano.Core.Advice` (class `Advisor`). | `Titano.Core.Advisor` | A class named like its namespace needed an alias in every `Titano.Core.*` caller. | diff --git a/src/Titano.Core/Advisor/Advisor.cs b/src/Titano.Core/Advice/Advisor.cs similarity index 99% rename from src/Titano.Core/Advisor/Advisor.cs rename to src/Titano.Core/Advice/Advisor.cs index 40eca224..e1e5e38d 100644 --- a/src/Titano.Core/Advisor/Advisor.cs +++ b/src/Titano.Core/Advice/Advisor.cs @@ -4,7 +4,7 @@ using Titano.Core.Analysis.Deep; using Titano.Core.Localization; using Titano.Core.Project; -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// /// The analysis advisor (BRIEF §10.3, §10.4): turns the light and deep analyses into explained recommendations diff --git a/src/Titano.Core/Advisor/AdvisorKeys.cs b/src/Titano.Core/Advice/AdvisorKeys.cs similarity index 99% rename from src/Titano.Core/Advisor/AdvisorKeys.cs rename to src/Titano.Core/Advice/AdvisorKeys.cs index 26688e9a..305a8bd5 100644 --- a/src/Titano.Core/Advisor/AdvisorKeys.cs +++ b/src/Titano.Core/Advice/AdvisorKeys.cs @@ -1,4 +1,4 @@ -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// /// Resource keys (area Advisor) of the advisor's reasons, missing-data notes and sequence presets. Each key is diff --git a/src/Titano.Core/Advisor/AdvisorRules.cs b/src/Titano.Core/Advice/AdvisorRules.cs similarity index 99% rename from src/Titano.Core/Advisor/AdvisorRules.cs rename to src/Titano.Core/Advice/AdvisorRules.cs index 4c3888ab..00cef188 100644 --- a/src/Titano.Core/Advisor/AdvisorRules.cs +++ b/src/Titano.Core/Advice/AdvisorRules.cs @@ -6,7 +6,7 @@ using Titano.Core.Imaging.Geometry; using Titano.Core.Project; using Titano.Core.Video; -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// /// The recommendation rules of BRIEF §10.3, one method per parameter group. Output size is decided first because diff --git a/src/Titano.Core/Advisor/AdvisorTypes.cs b/src/Titano.Core/Advice/AdvisorTypes.cs similarity index 99% rename from src/Titano.Core/Advisor/AdvisorTypes.cs rename to src/Titano.Core/Advice/AdvisorTypes.cs index 427dca10..59c07f63 100644 --- a/src/Titano.Core/Advisor/AdvisorTypes.cs +++ b/src/Titano.Core/Advice/AdvisorTypes.cs @@ -4,7 +4,7 @@ using Titano.Core.Model; using Titano.Core.Project; using Titano.Core.Video; -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// Sequence-editor section a recommendation belongs to (BRIEF §12.3). public enum AdvisorSection diff --git a/src/Titano.Core/Advisor/ParameterBindings.cs b/src/Titano.Core/Advice/ParameterBindings.cs similarity index 99% rename from src/Titano.Core/Advisor/ParameterBindings.cs rename to src/Titano.Core/Advice/ParameterBindings.cs index 831a62e1..f3566556 100644 --- a/src/Titano.Core/Advisor/ParameterBindings.cs +++ b/src/Titano.Core/Advice/ParameterBindings.cs @@ -3,7 +3,7 @@ using System.Globalization; using Titano.Core.Export; using Titano.Core.Project; -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// How one advisor parameter reads and writes . internal sealed class ParameterBinding diff --git a/src/Titano.Core/Advisor/SequencePresets.cs b/src/Titano.Core/Advice/SequencePresets.cs similarity index 99% rename from src/Titano.Core/Advisor/SequencePresets.cs rename to src/Titano.Core/Advice/SequencePresets.cs index 87e55389..245aba51 100644 --- a/src/Titano.Core/Advisor/SequencePresets.cs +++ b/src/Titano.Core/Advice/SequencePresets.cs @@ -8,7 +8,7 @@ using Titano.Core.Localization; using Titano.Core.Project; using Titano.Core.Video; -namespace Titano.Core.Advisor; +namespace Titano.Core.Advice; /// /// A one-click bundle (BRIEF §10.3): full project settings plus an export preset, named by a resource key and diff --git a/tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs b/tests/Titano.Core.Tests/Advice/AdvisorLocalizationTests.cs similarity index 93% rename from tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs rename to tests/Titano.Core.Tests/Advice/AdvisorLocalizationTests.cs index bd5b610f..e32ec414 100644 --- a/tests/Titano.Core.Tests/Advisor/AdvisorLocalizationTests.cs +++ b/tests/Titano.Core.Tests/Advice/AdvisorLocalizationTests.cs @@ -3,7 +3,7 @@ using System.Globalization; using System.Reflection; using System.Resources; using System.Text.RegularExpressions; -using Titano.Core.Advisor; +using Titano.Core.Advice; using Titano.Core.Analysis; using Titano.Core.Analysis.Deep; using Titano.Core.Diagnostics.Synthetic; @@ -12,9 +12,8 @@ using Titano.Core.Project; using Titano.Core.Tests.Analysis.Deep; using Titano.Testing; -namespace Titano.Core.Tests.Advisor; +namespace Titano.Core.Tests.Advice; -using AdvisorApi = Titano.Core.Advisor.Advisor; public sealed partial class AdvisorLocalizationTests(TestContext context) { @@ -55,7 +54,7 @@ public sealed partial class AdvisorLocalizationTests(TestContext context) var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList(); var light = LightAnalyzer.Analyze(frames); var sequence = new SequenceContext { FrameCount = frames.Count, SourceWidth = 6000, SourceHeight = 4000, MedianExposureSeconds = 1.0 / 250 }; - var result = AdvisorApi.Recommend(light, deep, sequence); + var result = Advisor.Recommend(light, deep, sequence); foreach (var r in result.Recommendations) rendered += Render(r.ReasonKey, [.. r.ReasonArgs]); foreach (var f in result.Findings) rendered += Render(f.Key, f.Arguments); foreach (var p in SequencePresets.Generate(light, deep, sequence)) @@ -64,8 +63,8 @@ public sealed partial class AdvisorLocalizationTests(TestContext context) rendered += Render(p.ReasonKey!, [.. p.ReasonArgs]); } // Stored reasons (culture-neutral strings) render with the current culture's numbers. - var applied = AdvisorApi.Apply(new ProjectSettings(), result); - Assert.DoesNotContain('⟦', AdvisorApi.Explain(applied.Exposure.HolyGrail.ReasonKey!, applied.Exposure.HolyGrail.ReasonArgs)); + var applied = Advisor.Apply(new ProjectSettings(), result); + Assert.DoesNotContain('⟦', Advisor.Explain(applied.Exposure.HolyGrail.ReasonKey!, applied.Exposure.HolyGrail.ReasonArgs)); } context.Log($"{rendered} texts rendered"); Assert.Greater(rendered, 80); diff --git a/tests/Titano.Core.Tests/Advisor/AdvisorTests.cs b/tests/Titano.Core.Tests/Advice/AdvisorTests.cs similarity index 84% rename from tests/Titano.Core.Tests/Advisor/AdvisorTests.cs rename to tests/Titano.Core.Tests/Advice/AdvisorTests.cs index e0f23c1f..d5462052 100644 --- a/tests/Titano.Core.Tests/Advisor/AdvisorTests.cs +++ b/tests/Titano.Core.Tests/Advice/AdvisorTests.cs @@ -1,4 +1,4 @@ -using Titano.Core.Advisor; +using Titano.Core.Advice; using Titano.Core.Analysis; using Titano.Core.Analysis.Deep; using Titano.Core.Diagnostics.Synthetic; @@ -8,10 +8,9 @@ using Titano.Core.Tests.Analysis.Deep; using Titano.Core.Video; using Titano.Testing; -namespace Titano.Core.Tests.Advisor; +namespace Titano.Core.Tests.Advice; // The class shares its name with the namespace, which an enclosing Titano.Core.* namespace would resolve first. -using AdvisorApi = Titano.Core.Advisor.Advisor; public sealed class AdvisorTests(TestContext context) { @@ -20,7 +19,7 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); var deep = await DeepReports.Night; - var result = AdvisorApi.Recommend(light, deep, sequence); + var result = Advisor.Recommend(light, deep, sequence); Log(result); Assert.Equal(true, Value(result, AdvisorParameters.Deflicker)); @@ -54,7 +53,7 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2)); var deep = await DeepReports.NightJitter; - var result = AdvisorApi.Recommend(light, deep, sequence); + var result = Advisor.Recommend(light, deep, sequence); var stabilize = result.Find(AdvisorParameters.Stabilize)!; Assert.Equal(true, stabilize.Value); Assert.Equal(AdvisorKeys.StabilizeOn, stabilize.ReasonKey); @@ -73,7 +72,7 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail())); var deep = await DeepReports.HolyGrail; - var result = AdvisorApi.Recommend(light, deep, sequence); + var result = Advisor.Recommend(light, deep, sequence); Log(result); var holyGrail = result.Find(AdvisorParameters.HolyGrail)!; Assert.Equal(true, holyGrail.Value); @@ -95,7 +94,7 @@ public sealed class AdvisorTests(TestContext context) Assert.Equal(20, grail.Settings.Exposure.TransitionLength.Resolve(0)); // Without pixels the metadata steps are trusted, with the same spacing rule and less confidence. - var metadataOnly = AdvisorApi.Recommend(light, null, sequence); + var metadataOnly = Advisor.Recommend(light, null, sequence); Assert.Equal(AdvisorKeys.HolyGrailMetadata, metadataOnly.Find(AdvisorParameters.HolyGrail)!.ReasonKey); Assert.Equal(20, Value(metadataOnly, AdvisorParameters.TransitionLength)); Assert.Less(metadataOnly.Find(AdvisorParameters.HolyGrail)!.Confidence, holyGrail.Confidence); @@ -107,11 +106,15 @@ public sealed class AdvisorTests(TestContext context) const double night = 14 * 3600; var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 300, IntervalSeconds = 600, IntervalJitterSeconds = 20, + Width = 96, + Height = 64, + FrameCount = 300, + IntervalSeconds = 600, + IntervalJitterSeconds = 20, TimeShifts = [new(60, night), new(120, night), new(180, night), new(240, night)], })); var (light, sequence) = Inputs(source); - var result = AdvisorApi.Recommend(light, null, sequence); + var result = Advisor.Recommend(light, null, sequence); Log(result); var mode = result.Find(AdvisorParameters.TimingMode)!; Assert.Equal(TimingMode.Adaptive, mode.Value); @@ -138,10 +141,10 @@ public sealed class AdvisorTests(TestContext context) { var gapped = SyntheticSequence.Create(DeepScenes.HolyGrail().Options with { TimeShifts = [new(100, 40)] }); var (light, sequence) = Inputs(new SyntheticFrameSource(gapped)); - var result = AdvisorApi.Recommend(light, await DeepReports.HolyGrail, sequence); + var result = Advisor.Recommend(light, await DeepReports.HolyGrail, sequence); Assert.Equal(TimingMode.Interpolated, Value(result, AdvisorParameters.TimingMode)); Assert.Equal(FlowQualitySetting.Best, Value(result, AdvisorParameters.FlowQuality)); - Assert.Equal(TimingMode.Constant, Value(AdvisorApi.Recommend(light, null, sequence), AdvisorParameters.TimingMode)); + Assert.Equal(TimingMode.Constant, Value(Advisor.Recommend(light, null, sequence), AdvisorParameters.TimingMode)); } [Test] @@ -149,11 +152,15 @@ public sealed class AdvisorTests(TestContext context) { var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = 8, + Width = 96, + Height = 64, + FrameCount = 240, + FlickerEv = 0.15, + FlickerPeriodFrames = 8, })); var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options); var (light, sequence) = Inputs(source); - var window = AdvisorApi.Recommend(light, deep, sequence).Find(AdvisorParameters.DeflickerWindow)!; + var window = Advisor.Recommend(light, deep, sequence).Find(AdvisorParameters.DeflickerWindow)!; Assert.Equal(33, window.Value); Assert.Equal(AdvisorKeys.WindowPeriod, window.ReasonKey); Assert.Equal(8.0, window.ReasonArgs[0]); @@ -164,7 +171,7 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true }); Assert.True(light.ExposureValues.All(v => v is null)); - var result = AdvisorApi.Recommend(light, null, sequence); + var result = Advisor.Recommend(light, null, sequence); foreach (var parameter in new[] { AdvisorParameters.HolyGrail, AdvisorParameters.TransitionLength, AdvisorParameters.TargetShutterAngle, AdvisorParameters.MotionBlur }) { var missing = result.Find(parameter)!; @@ -181,13 +188,13 @@ public sealed class AdvisorTests(TestContext context) TransitionLength = new Auto().WithAdvice(20, AdvisorKeys.TransitionSpacing, "40", "20"), }, }; - var applied = AdvisorApi.Apply(advised, result); + var applied = Advisor.Apply(advised, result); Assert.Same(advised.Exposure.HolyGrail, applied.Exposure.HolyGrail); Assert.Same(advised.Exposure.TransitionLength, applied.Exposure.TransitionLength); - Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Exposure, advised, result).Changes.Where(c => c.Parameter is AdvisorParameters.HolyGrail or AdvisorParameters.TransitionLength)); + Assert.Empty(Advisor.Optimise(AdvisorSection.Exposure, advised, result).Changes.Where(c => c.Parameter is AdvisorParameters.HolyGrail or AdvisorParameters.TransitionLength)); // A fresh project keeps its values and learns why there is no advice. - var fresh = AdvisorApi.Apply(new ProjectSettings(), result); + var fresh = Advisor.Apply(new ProjectSettings(), result); Assert.False(fresh.Exposure.HolyGrail.AutoValue); Assert.Equal(AdvisorKeys.MissingExposure, fresh.Exposure.HolyGrail.ReasonKey); Assert.Equal(0, fresh.Exposure.TransitionLength.AutoValue); @@ -199,7 +206,7 @@ public sealed class AdvisorTests(TestContext context) public async Task ApplyNeverOverwritesManualValues() { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); - var result = AdvisorApi.Recommend(light, await DeepReports.Night, sequence); + var result = Advisor.Recommend(light, await DeepReports.Night, sequence); var manual = new ProjectSettings { Timing = new TimingSettings { FrameRate = new Auto().WithManual("50") }, @@ -211,7 +218,7 @@ public sealed class AdvisorTests(TestContext context) HeroFrame = 7, ExcludedFrames = [3], }; - var applied = AdvisorApi.Apply(manual, result); + var applied = Advisor.Apply(manual, result); Assert.False(applied.Exposure.Deflicker.IsAuto); Assert.False(applied.Exposure.Deflicker.Resolve(true)); Assert.True(applied.Exposure.Deflicker.AutoValue); @@ -232,14 +239,14 @@ public sealed class AdvisorTests(TestContext context) public async Task OptimiseTakesModuleDecisionsAndReportsChanges() { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2)); - var result = AdvisorApi.Recommend(light, await DeepReports.NightJitter, sequence); + var result = Advisor.Recommend(light, await DeepReports.NightJitter, sequence); var settings = new ProjectSettings { Motion = new MotionSettings { Stabilize = new Auto().WithManual(false), StabilizeSmoothing = new Auto().WithManual(30) }, ExcludedFrames = [3], }; - var motion = AdvisorApi.Optimise(AdvisorSection.Motion, settings, result); + var motion = Advisor.Optimise(AdvisorSection.Motion, settings, result); Assert.True(motion.Settings.Motion.Stabilize.IsAuto); Assert.True(motion.Settings.Motion.Stabilize.Resolve(false)); Assert.Equal(30.0, motion.Settings.Motion.StabilizeSmoothing.Resolve(12)); @@ -250,19 +257,19 @@ public sealed class AdvisorTests(TestContext context) Assert.DoesNotContain(AdvisorParameters.StabilizeSmoothing, motion.Changes.Select(c => c.Parameter)); Assert.Null(motion.Settings.HeroFrame); - var frames = AdvisorApi.Optimise(AdvisorSection.Frames, settings, result); + var frames = Advisor.Optimise(AdvisorSection.Frames, settings, result); Assert.Equal(result.Find(AdvisorParameters.Hero)!.Value, frames.Settings.HeroFrame); Assert.SequenceEqual([AdvisorParameters.Hero], frames.Changes.Select(c => c.Parameter)); Assert.SequenceEqual([3], frames.Settings.ExcludedFrames); - var exposure = AdvisorApi.Optimise(AdvisorSection.Exposure, settings, result); + var exposure = Advisor.Optimise(AdvisorSection.Exposure, settings, result); var deflicker = exposure.Changes.Single(c => c.Parameter == AdvisorParameters.Deflicker); Assert.Null(deflicker.Before); Assert.Equal(true, deflicker.After); Assert.Equal(settings.Motion, exposure.Settings.Motion); // Optimising again changes nothing. - Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Motion, motion.Settings, result).Changes); + Assert.Empty(Advisor.Optimise(AdvisorSection.Motion, motion.Settings, result).Changes); } [Test] @@ -270,13 +277,18 @@ public sealed class AdvisorTests(TestContext context) { var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, BlackFrames = [5], DuplicateFrames = [9], + Width = 96, + Height = 64, + FrameCount = 40, + FlickerEv = 0.05, + BlackFrames = [5], + DuplicateFrames = [9], })); var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options); var (light, sequence) = Inputs(source); - var result = AdvisorApi.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 }); + var result = Advisor.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 }); - var frames = AdvisorApi.Optimise(AdvisorSection.Frames, new ProjectSettings { ExcludedFrames = [2] }, result); + var frames = Advisor.Optimise(AdvisorSection.Frames, new ProjectSettings { ExcludedFrames = [2] }, result); Assert.SequenceEqual([2, 5, 9], frames.Settings.ExcludedFrames); Assert.Equal(AdvisorKeys.Exclude, frames.Changes.Single(c => c.Parameter == AdvisorParameters.Excluded).ReasonKey); @@ -284,7 +296,7 @@ public sealed class AdvisorTests(TestContext context) Assert.Equal("1280x720", resolution.Value); Assert.Equal(AdvisorKeys.ResolutionPreview, resolution.ReasonKey); var big = new ProjectSettings { Export = new ExportSettings { Preset = new Auto().WithManual("4k-hevc") } }; - var export = AdvisorApi.Optimise(AdvisorSection.Export, big, result); + var export = Advisor.Optimise(AdvisorSection.Export, big, result); Assert.Equal("720p-preview", export.Settings.Export.Preset.Resolve("4k-hevc")); Assert.Null(export.Settings.Export.Overrides.Width); } @@ -294,21 +306,21 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail())); var h264Only = sequence with { Codecs = [new EncoderCapability(VideoCodec.H264, "Software H.264", false, 1920, 1088, false)] }; - var limited = AdvisorApi.Recommend(light, null, h264Only); + var limited = Advisor.Recommend(light, null, h264Only); Assert.Equal("1920x1080", Value(limited, AdvisorParameters.Resolution)); Assert.Equal(AdvisorKeys.ResolutionCodec, limited.Find(AdvisorParameters.Resolution)!.ReasonKey); Assert.Equal("1080p-h264", Value(limited, AdvisorParameters.ExportPreset)); - var portrait = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000 }); + var portrait = Advisor.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000 }); Assert.Equal("9:16", Value(portrait, AdvisorParameters.Aspect)); Assert.Equal("1080x1920", Value(portrait, AdvisorParameters.Resolution)); Assert.Equal("vertical-1080x1920", Value(portrait, AdvisorParameters.ExportPreset)); - var landscape = AdvisorApi.Recommend(light, null, sequence); + var landscape = Advisor.Recommend(light, null, sequence); Assert.Equal("16:9", Value(landscape, AdvisorParameters.Aspect)); Assert.SequenceEqual([6000.0, 4000.0, 84.0], landscape.Find(AdvisorParameters.Aspect)!.ReasonArgs.Select(Convert.ToDouble)); - var wide = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 6000, SourceHeight = 2500 }); + var wide = Advisor.Recommend(light, null, sequence with { SourceWidth = 6000, SourceHeight = 2500 }); Assert.Equal(AdvisorKeys.AspectWide, wide.Find(AdvisorParameters.Aspect)!.ReasonKey); Assert.Equal(74.0, wide.Find(AdvisorParameters.Aspect)!.ReasonArgs[2]); Assert.Equal("3840x2160", Value(wide, AdvisorParameters.Resolution)); @@ -319,8 +331,8 @@ public sealed class AdvisorTests(TestContext context) { var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky())); var deep = await DeepReports.Night; - var first = AdvisorApi.Recommend(light, deep, sequence); - var second = AdvisorApi.Recommend(light, DeepAnalysisReport.FromJson(deep.ToJson()), sequence); + var first = Advisor.Recommend(light, deep, sequence); + var second = Advisor.Recommend(light, DeepAnalysisReport.FromJson(deep.ToJson()), sequence); Assert.SequenceEqual(first.Recommendations.Select(Describe), second.Recommendations.Select(Describe)); } diff --git a/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs index eccb6818..9c6e03f3 100644 --- a/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs +++ b/tests/Titano.Core.Tests/Analysis/Deep/DeepAnalyzerTests.cs @@ -66,7 +66,11 @@ public sealed class DeepAnalyzerTests(TestContext context) { var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = period, + Width = 96, + Height = 64, + FrameCount = 240, + FlickerEv = 0.15, + FlickerPeriodFrames = period, }); var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options); Assert.Approximately(period, report.Flicker.PeriodFrames!.Value, 0.05 * period); @@ -79,7 +83,13 @@ public sealed class DeepAnalyzerTests(TestContext context) { var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 60, FlickerEv = 0.02, BlackFrames = [10], WhiteFrames = [20], DuplicateFrames = [30], + Width = 96, + Height = 64, + FrameCount = 60, + FlickerEv = 0.02, + BlackFrames = [10], + WhiteFrames = [20], + DuplicateFrames = [30], }); var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence) { Undecodable = [40] }, DeepScenes.Options); Assert.SequenceEqual([10], report.Issues.Black); @@ -102,7 +112,14 @@ public sealed class DeepAnalyzerTests(TestContext context) var first = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05 })); var second = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { - Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05, Seed = 5, HorizonFraction = 0.75, SkyLevel = 0.6, LandLevel = 0.01, + Width = 96, + Height = 64, + FrameCount = 50, + FlickerEv = 0.05, + Seed = 5, + HorizonFraction = 0.75, + SkyLevel = 0.6, + LandLevel = 0.01, })); var report = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(first, second, 30), DeepScenes.Options); Assert.SequenceEqual([30], report.Issues.SceneChanges); From 222d9ec4ad04bdab5ca2ebfb408bf4ced3add3dc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:09:02 +0000 Subject: [PATCH 141/188] fix(video): size linear DNG tiles to small frames Edge padding of 256-pixel tiles tripled the size of small sequence frames. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Video/Managed/ManagedSessions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Titano.Core/Video/Managed/ManagedSessions.cs b/src/Titano.Core/Video/Managed/ManagedSessions.cs index da797ac2..d46a8e5d 100644 --- a/src/Titano.Core/Video/Managed/ManagedSessions.cs +++ b/src/Titano.Core/Video/Managed/ManagedSessions.cs @@ -264,7 +264,8 @@ internal sealed class ImageSequenceSession : ManagedSession VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)), VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal), VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }), - VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame), + // Tiles no larger than the frame: edge padding of a 256-pixel tile would dominate small outputs. + VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame, new LinearDngOptions { TileSize = int.Clamp((int.Max(frame.Width, frame.Height) + 15) / 16 * 16, 16, 256) }), _ => throw new NotSupportedException($"{Settings.Codec} is not an image sequence"), }; } From 3780105f36254a041b06400a84faade69d6e6309 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:09:02 +0000 Subject: [PATCH 142/188] feat(render): preparation pass, render geometry and pipeline RenderPreparation measures (or reuses cached) luminance, colour, region and camera-path series and turns them into per-frame corrections. RenderPipeline renders planned frames through exposure, one geometry resample, flow synthesis, motion blur, stacking and the knee, overlapping encoding with processing; cancellation and failures leave no output and no unobserved exceptions. Batch renders share one preparation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Render/Diagnostics/PatternFrameSource.cs | 105 ++++ .../Diagnostics/SyntheticFrameSource.cs | 83 ++++ src/Titano.Core/Render/FrameCaches.cs | 95 ++++ src/Titano.Core/Render/IRenderFrameSource.cs | 47 ++ src/Titano.Core/Render/ProjectValues.cs | 17 + src/Titano.Core/Render/RenderGeometry.cs | 206 ++++++++ src/Titano.Core/Render/RenderModels.cs | 127 +++++ src/Titano.Core/Render/RenderPipeline.cs | 461 ++++++++++++++++++ src/Titano.Core/Render/RenderPlan.cs | 2 +- src/Titano.Core/Render/RenderPreparation.cs | 445 +++++++++++++++++ src/Titano.Core/Render/RenderResult.cs | 71 +++ src/Titano.Core/Render/RenderSetup.cs | 82 ++++ .../Titano.Core.Tests/Render/RenderFixture.cs | 83 ++++ .../Render/RenderIsolationTests.cs | 69 +++ .../Render/RenderPipelineTests.cs | 208 ++++++++ .../Render/RenderProcessingTests.cs | 351 +++++++++++++ 16 files changed, 2451 insertions(+), 1 deletion(-) create mode 100644 src/Titano.Core/Render/Diagnostics/PatternFrameSource.cs create mode 100644 src/Titano.Core/Render/Diagnostics/SyntheticFrameSource.cs create mode 100644 src/Titano.Core/Render/FrameCaches.cs create mode 100644 src/Titano.Core/Render/IRenderFrameSource.cs create mode 100644 src/Titano.Core/Render/ProjectValues.cs create mode 100644 src/Titano.Core/Render/RenderGeometry.cs create mode 100644 src/Titano.Core/Render/RenderModels.cs create mode 100644 src/Titano.Core/Render/RenderPipeline.cs create mode 100644 src/Titano.Core/Render/RenderPreparation.cs create mode 100644 src/Titano.Core/Render/RenderResult.cs create mode 100644 src/Titano.Core/Render/RenderSetup.cs create mode 100644 tests/Titano.Core.Tests/Render/RenderFixture.cs create mode 100644 tests/Titano.Core.Tests/Render/RenderIsolationTests.cs create mode 100644 tests/Titano.Core.Tests/Render/RenderPipelineTests.cs create mode 100644 tests/Titano.Core.Tests/Render/RenderProcessingTests.cs diff --git a/src/Titano.Core/Render/Diagnostics/PatternFrameSource.cs b/src/Titano.Core/Render/Diagnostics/PatternFrameSource.cs new file mode 100644 index 00000000..e2a7bc90 --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/PatternFrameSource.cs @@ -0,0 +1,105 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Render.Diagnostics; + +/// +/// A continuous fractal value-noise texture (four octaves, periods 4–32 px, amplitude proportional to the period like +/// natural scenes) moved by a per-frame camera offset: exact sub-pixel motion and broadband texture for stabilisation, +/// flow and interpolation checks. Unlike per-pixel noise it passes the stabiliser's texture gate, and unlike sinusoids +/// it has no periodic ambiguity. +/// +public sealed class PatternFrameSource(int width, int height, int frameCount, Func? cameraMotion = null, double intervalSeconds = 10) + : IRenderFrameSource +{ + private static readonly DateTime Start = new(2024, 6, 21, 21, 0, 0); + + public int FrameCount { get; } = frameCount > 0 ? frameCount : throw new ArgumentOutOfRangeException(nameof(frameCount)); + + public int Width { get; } = width > 0 ? width : throw new ArgumentOutOfRangeException(nameof(width)); + + public int Height { get; } = height > 0 ? height : throw new ArgumentOutOfRangeException(nameof(height)); + + /// Content displacement of frame in full-resolution pixels. + public (double X, double Y) Offset(int index) => cameraMotion?.Invoke(index) ?? (0, 0); + + /// Regular capture times, 1/250 s exposures. + public SourceFrameInfo[] Metadata() + { + var result = new SourceFrameInfo[FrameCount]; + for (var i = 0; i < FrameCount; i++) result[i] = new SourceFrameInfo(Start.AddSeconds(i * intervalSeconds), 1.0 / 250, 10); + return result; + } + + /// The texture at full resolution displaced by (, ). + public ImageBuffer Render(double dx, double dy) + { + var image = new ImageBuffer(Width, Height, 3, clear: false); + var r = image.Plane(0); + var g = image.Plane(1); + var b = image.Plane(2); + for (var y = 0; y < Height; y++) + { + for (var x = 0; x < Width; x++) + { + double u = x - dx, v = y - dy; + var value = 0.06 + 0.4 * Texture(u, v); + var i = y * Width + x; + r[i] = (float)(value * (0.9 + 0.2 * ValueNoise(u / 48, v / 48, 101))); + g[i] = (float)value; + b[i] = (float)(value * (0.8 + 0.2 * ValueNoise(u / 48, v / 48, 102))); + } + } + return image; + } + + /// Fractal value noise in [0, 1): octaves of period 4, 8, 16, 32 px weighted by their period. + private static double Texture(double x, double y) + { + double sum = 0, weights = 0; + for (var octave = 0; octave < 4; octave++) + { + double period = 4 << octave; + sum += period * ValueNoise(x / period, y / period, octave); + weights += period; + } + return sum / weights; + } + + /// Hashed lattice values blended with a C1 smoothstep: continuous in x and y. + private static double ValueNoise(double x, double y, int seed) + { + var xi = (long)double.Floor(x); + var yi = (long)double.Floor(y); + var fx = x - xi; + var fy = y - yi; + fx = fx * fx * (3 - 2 * fx); + fy = fy * fy * (3 - 2 * fy); + var a = Hash(xi, yi, seed); + var b = Hash(xi + 1, yi, seed); + var c = Hash(xi, yi + 1, seed); + var d = Hash(xi + 1, yi + 1, seed); + var top = a + (b - a) * fx; + return top + (c + (d - c) * fx - top) * fy; + } + + /// Uniform [0, 1) from a SplitMix64 mix of the lattice point (stable across processes). + private static double Hash(long x, long y, int seed) + { + var z = unchecked((ulong)x * 0x9E3779B97F4A7C15UL ^ (ulong)y * 0xC2B2AE3D27D4EB4FUL ^ (ulong)(uint)seed * 0x165667B19E3779F9UL); + z = unchecked((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL); + z = unchecked((z ^ (z >> 27)) * 0x94D049BB133111EBUL); + z ^= z >> 31; + return (z >> 11) * (1.0 / (1UL << 53)); + } + + public ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, FrameCount); + cancellationToken.ThrowIfCancellationRequested(); + var (dx, dy) = Offset(index); + var frame = Render(dx, dy); + if (maxLongEdge <= 0 || int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult(frame); + using (frame) return ValueTask.FromResult(Resampler.Thumbnail(frame, maxLongEdge)); + } +} diff --git a/src/Titano.Core/Render/Diagnostics/SyntheticFrameSource.cs b/src/Titano.Core/Render/Diagnostics/SyntheticFrameSource.cs new file mode 100644 index 00000000..35b53542 --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/SyntheticFrameSource.cs @@ -0,0 +1,83 @@ +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; + +namespace Titano.Core.Render.Diagnostics; + +/// +/// over a (self-test and tests). An optional camera +/// motion translates each frame's content by a per-frame offset in pixels (pans, shake). Frames are rendered on demand, +/// so memory does not depend on the sequence length. +/// +public sealed class SyntheticFrameSource(SyntheticSequence sequence, Func? cameraMotion = null) : IRenderFrameSource +{ + private int _decodes; + private int _largestRequest; + + public SyntheticSequence Sequence { get; } = sequence ?? throw new ArgumentNullException(nameof(sequence)); + + public int FrameCount => Sequence.Count; + + public int Width => Sequence.Options.Width; + + public int Height => Sequence.Options.Height; + + /// Frames produced so far. + public int Decodes => Volatile.Read(ref _decodes); + + /// Largest long edge requested for rendering (0 = full size). + public int LargestRenderRequest => Volatile.Read(ref _largestRequest); + + /// Capture metadata of the sequence's frames. + public SourceFrameInfo[] Metadata() => SourceFrameInfo.From(Sequence.Frames); + + public ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Interlocked.Increment(ref _decodes); + if (purpose == DecodePurpose.Render) InterlockedMax(ref _largestRequest, maxLongEdge); + var frame = Sequence.Render(index); + try + { + if (cameraMotion is not null) + { + var (dx, dy) = cameraMotion(index); + var moved = new ImageBuffer(frame.Width, frame.Height, frame.Channels, clear: false); + try + { + GeometryStage.Warp(frame, moved, Affine2D.Translation(-dx, -dy), BorderMode.Clamp, cancellationToken); + } + catch + { + moved.Dispose(); + throw; + } + frame.Dispose(); + frame = moved; + } + if (maxLongEdge > 0 && int.Max(frame.Width, frame.Height) > maxLongEdge) + { + var small = Resampler.Thumbnail(frame, maxLongEdge); + frame.Dispose(); + frame = small; + } + return ValueTask.FromResult(frame); + } + catch + { + frame.Dispose(); + throw; + } + } + + private static void InterlockedMax(ref int target, int value) + { + var current = Volatile.Read(ref target); + while (value > current) + { + var seen = Interlocked.CompareExchange(ref target, value, current); + if (seen == current) return; + current = seen; + } + } +} diff --git a/src/Titano.Core/Render/FrameCaches.cs b/src/Titano.Core/Render/FrameCaches.cs new file mode 100644 index 00000000..356f27a1 --- /dev/null +++ b/src/Titano.Core/Render/FrameCaches.cs @@ -0,0 +1,95 @@ +using Titano.Core.Imaging; +using Titano.Core.Motion; + +namespace Titano.Core.Render; + +/// Least-recently-used cache of prepared (corrected and warped) frames by source index; owns its buffers. +internal sealed class PreparedFrameCache(int capacity) : IDisposable +{ + private readonly List<(int Index, ImageBuffer Frame)> _entries = new(capacity + 1); + + public bool TryGet(int index, out ImageBuffer frame) + { + for (var i = 0; i < _entries.Count; i++) + { + if (_entries[i].Index != index) continue; + var entry = _entries[i]; + _entries.RemoveAt(i); + _entries.Add(entry); + frame = entry.Frame; + return true; + } + frame = null!; + return false; + } + + public void Add(int index, ImageBuffer frame) + { + _entries.Add((index, frame)); + while (_entries.Count > capacity) + { + _entries[0].Frame.Dispose(); + _entries.RemoveAt(0); + } + } + + public void Dispose() + { + foreach (var (_, frame) in _entries) frame.Dispose(); + _entries.Clear(); + } +} + +/// Flow fields between two source frames (forward, and backward when synthesis needed it). +internal sealed record FlowPair(MotionField Forward, MotionField? Backward); + +/// Least-recently-used cache of flow fields by source pair; owns its fields. +internal sealed class FlowCache(int capacity) : IDisposable +{ + private readonly List<(int From, int To, FlowPair Flows)> _entries = new(capacity + 1); + + public bool TryGet(int from, int to, bool needBackward, out FlowPair flows) + { + for (var i = 0; i < _entries.Count; i++) + { + var entry = _entries[i]; + if (entry.From != from || entry.To != to) continue; + if (needBackward && entry.Flows.Backward is null) break; + _entries.RemoveAt(i); + _entries.Add(entry); + flows = entry.Flows; + return true; + } + flows = null!; + return false; + } + + /// Adds (or replaces) the flows of a pair. + public void Add(int from, int to, FlowPair flows) + { + var existing = _entries.FindIndex(e => e.From == from && e.To == to); + if (existing >= 0) + { + Release(_entries[existing].Flows); + _entries.RemoveAt(existing); + } + _entries.Add((from, to, flows)); + while (_entries.Count > capacity) + { + Release(_entries[0].Flows); + _entries.RemoveAt(0); + } + } + + public void Dispose() + { + foreach (var entry in _entries) Release(entry.Flows); + _entries.Clear(); + } + + private static void Release(FlowPair flows) + { + flows.Forward.Dispose(); + flows.Backward?.Dispose(); + } +} diff --git a/src/Titano.Core/Render/IRenderFrameSource.cs b/src/Titano.Core/Render/IRenderFrameSource.cs new file mode 100644 index 00000000..7aa5e8bf --- /dev/null +++ b/src/Titano.Core/Render/IRenderFrameSource.cs @@ -0,0 +1,47 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Core.Render; + +/// +/// Decoded source frames of a render by index. The application backs it with the image decoders and the sliding +/// FrameWindow (read-ahead, disk spill); tests and the self-test use synthetic sources. Sequential index order is +/// the common access pattern; neighbours may be requested again for flow and interpolation. +/// +public interface IRenderFrameSource +{ + int FrameCount { get; } + + /// Full-resolution width after orientation. + int Width { get; } + + /// Full-resolution height after orientation. + int Height { get; } + + /// + /// Frame in linear light, its long edge at most (0 = full size). + /// A source may return a smaller frame of the same aspect (e.g. an embedded preview). The caller owns the buffer. + /// + ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken); +} + +/// Capture metadata of one source frame used by the plan and the preparation. +/// Camera clock (clock-corrected when available); null when unknown. +/// Shutter time in seconds (real shutter angle for motion blur). +/// EV at ISO 100 (holy-grail steps). +public readonly record struct SourceFrameInfo(DateTime? CapturedAt, double? ExposureTime, double? ExposureValue) +{ + /// Metadata of archived frames, optionally with clock-corrected times (LightAnalysisReport.AdjustedTimes). + public static SourceFrameInfo[] From(IReadOnlyList frames, IReadOnlyList? adjustedTimes = null) + { + ArgumentNullException.ThrowIfNull(frames); + if (adjustedTimes is not null && adjustedTimes.Count != frames.Count) throw new ArgumentException("One time per frame is required.", nameof(adjustedTimes)); + var result = new SourceFrameInfo[frames.Count]; + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + result[i] = new SourceFrameInfo(adjustedTimes is null ? f.CapturedAt : adjustedTimes[i], f.ExposureTime, f.ExposureValue); + } + return result; + } +} diff --git a/src/Titano.Core/Render/ProjectValues.cs b/src/Titano.Core/Render/ProjectValues.cs new file mode 100644 index 00000000..67b3f40c --- /dev/null +++ b/src/Titano.Core/Render/ProjectValues.cs @@ -0,0 +1,17 @@ +using Titano.Core.Project; + +namespace Titano.Core.Render; + +/// +/// Reads value-type settings. For value types is never null (an +/// unconstrained T? is T), so returns default instead of the fallback +/// when there is no advice; here a default automatic value means "no advice" and yields the fallback. +/// +internal static class ProjectValues +{ + public static T Get(Auto setting, T fallback) where T : struct + { + if (!setting.IsAuto) return setting.Manual; + return EqualityComparer.Default.Equals(setting.AutoValue, default) ? fallback : setting.AutoValue; + } +} diff --git a/src/Titano.Core/Render/RenderGeometry.cs b/src/Titano.Core/Render/RenderGeometry.cs new file mode 100644 index 00000000..ae8db95a --- /dev/null +++ b/src/Titano.Core/Render/RenderGeometry.cs @@ -0,0 +1,206 @@ +using System.Globalization; +using Titano.Core.Export; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Render; + +/// +/// Output size, decode size and per-frame warp of a render. is a normalised +/// [x, y, width, height] rectangle of the camera view; the output aspect is the export's when it fixes both dimensions, +/// otherwise the camera aspect (source = frame aspect). Virtual-camera keyframes are keyed to source frame positions, so +/// they stay attached to the content when timing, frame rate or fitting change. The stabiliser correction, the camera +/// pose (zoomed by the stabilisation zoom) and the crop become one output→source map, resampled once. +/// +public sealed class RenderGeometry +{ + private static readonly CameraState Neutral = new(0.5, 0.5, 1, 0); + private readonly VirtualCamera? _camera; + private readonly RectD _crop; + private readonly double _offsetX; + private readonly double _offsetY; + private readonly double _stabilizationZoom; + private readonly double _fittedWidth; + private readonly double _fittedHeight; + private readonly double _maxZoom; + private readonly int _maxWorkingLongEdge; + + private RenderGeometry(VirtualCamera? camera, RectD crop, double offsetX, double offsetY, double stabilizationZoom, int sourceWidth, int sourceHeight, + int outputWidth, int outputHeight, double fittedWidth, double fittedHeight, double maxZoom, int maxWorkingLongEdge, IReadOnlyList warnings) + { + _camera = camera; + _crop = crop; + _offsetX = offsetX; + _offsetY = offsetY; + _stabilizationZoom = stabilizationZoom; + SourceWidth = sourceWidth; + SourceHeight = sourceHeight; + OutputWidth = outputWidth; + OutputHeight = outputHeight; + _fittedWidth = fittedWidth; + _fittedHeight = fittedHeight; + _maxZoom = maxZoom; + _maxWorkingLongEdge = maxWorkingLongEdge; + Warnings = warnings; + } + + public int SourceWidth { get; } + public int SourceHeight { get; } + public int OutputWidth { get; } + public int OutputHeight { get; } + + /// Remarks about ignored camera values. + public IReadOnlyList Warnings { get; } + + /// + /// Long edge to decode source frames at: enough that the most zoomed-in view still has one source pixel per output + /// pixel, never more than the source, capped by . + /// + public int WorkingLongEdge + { + get + { + var needed = double.Max(OutputWidth / _fittedWidth, OutputHeight / _fittedHeight) * _maxZoom; + var edge = (int)double.Ceiling(int.Max(SourceWidth, SourceHeight) * double.Min(1, needed)); + edge = int.Clamp(edge, int.Min(16, int.Max(SourceWidth, SourceHeight)), int.Max(SourceWidth, SourceHeight)); + return _maxWorkingLongEdge > 0 ? int.Min(edge, _maxWorkingLongEdge) : edge; + } + } + + /// Plans the geometry of for a source of the given full-resolution size. + /// Zoom that hides stabilisation borders (). + /// Decode-size cap (0 = none); it also caps source-sized outputs. + public static RenderGeometry Create(CameraSettings camera, ResolvedExport export, int sourceWidth, int sourceHeight, double stabilizationZoom = 1, int maxWorkingLongEdge = 0) + { + ArgumentNullException.ThrowIfNull(camera); + ArgumentNullException.ThrowIfNull(export); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight); + var warnings = new List(); + var crop = NormalisedCrop(camera.Crop, warnings); + if (!AspectRatio.TryParse(camera.Aspect.Resolve("source"), out var aspect)) + { + warnings.Add(new RenderWarning("Render.Warning.AspectIgnored", camera.Aspect.Resolve(string.Empty))); + aspect = AspectRatio.Source; + } + var fixedSize = export.Width > 0 && export.Height > 0; + var ratio = fixedSize ? export.Width / (double)export.Height : aspect.Resolve(sourceWidth, sourceHeight); + if (fixedSize && !aspect.IsSource && double.Abs(aspect.Resolve(sourceWidth, sourceHeight) / ratio - 1) > 0.01) + warnings.Add(new RenderWarning("Render.Warning.AspectFromPreset", aspect.ToString(), string.Create(CultureInfo.InvariantCulture, $"{export.Width}:{export.Height}"))); + var cropPixels = new RectD(crop.X * sourceWidth, crop.Y * sourceHeight, crop.Width * sourceWidth, crop.Height * sourceHeight); + var fitted = AspectRatio.FitCrop(cropPixels, ratio, camera.OffsetX, camera.OffsetY); + + int width, height; + if (fixedSize) (width, height) = (export.Width, export.Height); + else if (export.Width > 0) (width, height) = (export.Width, (int)double.Round(export.Width / ratio)); + else if (export.Height > 0) (width, height) = ((int)double.Round(export.Height * ratio), export.Height); + else + { + var scale = maxWorkingLongEdge > 0 ? double.Min(1, maxWorkingLongEdge / double.Max(fitted.Width, fitted.Height)) : 1; + (width, height) = ((int)double.Round(fitted.Width * scale), (int)double.Round(fitted.Height * scale)); + } + if (!VideoCodecInfo.IsManaged(export.Codec)) + { + width &= ~1; + height &= ~1; + } + width = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, width); + height = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, height); + + var cameraPath = Camera(camera.Keyframes, warnings); + var maxZoom = (cameraPath?.Keyframes.Max(k => k.Zoom) ?? 1) * stabilizationZoom; + return new RenderGeometry(cameraPath, crop, camera.OffsetX, camera.OffsetY, stabilizationZoom, sourceWidth, sourceHeight, width, height, + fitted.Width, fitted.Height, maxZoom, maxWorkingLongEdge, warnings); + } + + /// The same geometry rendering into a different output size (e.g. capped by the encoder). + public RenderGeometry WithOutputSize(int width, int height) => width == OutputWidth && height == OutputHeight + ? this + : new RenderGeometry(_camera, _crop, _offsetX, _offsetY, _stabilizationZoom, SourceWidth, SourceHeight, width, height, _fittedWidth, _fittedHeight, + _maxZoom, _maxWorkingLongEdge, Warnings); + + /// Camera pose at a (fractional) source position, including the stabilisation zoom. + public CameraState PoseAt(double sourcePosition) + { + var pose = _camera?.Evaluate(sourcePosition) ?? Neutral; + return pose with { Zoom = pose.Zoom * _stabilizationZoom }; + } + + /// Geometry of one decoded frame of × pixels. + /// The frame's stabiliser correction at this frame size (source → stabilised). + public GeometrySettings For(int frameWidth, int frameHeight, double sourcePosition, Affine2D stabilization) + { + var view = VirtualCamera.ViewToSource(PoseAt(sourcePosition), frameWidth, frameHeight); + return new GeometrySettings + { + Crop = new RectD(_crop.X * frameWidth, _crop.Y * frameHeight, _crop.Width * frameWidth, _crop.Height * frameHeight), + Aspect = AspectRatio.Source, + OffsetX = _offsetX, + OffsetY = _offsetY, + OutputWidth = OutputWidth, + OutputHeight = OutputHeight, + Warp = stabilization.IsIdentity() ? view : stabilization.Invert() * view, + Border = BorderMode.Clamp, + }; + } + + private static RectD NormalisedCrop(double[]? crop, List warnings) + { + var full = new RectD(0, 0, 1, 1); + if (crop is null) return full; + if (crop.Length != 4 || !crop.All(double.IsFinite)) + { + warnings.Add(new RenderWarning("Render.Warning.CropIgnored")); + return full; + } + var x = double.Clamp(crop[0], 0, 1); + var y = double.Clamp(crop[1], 0, 1); + var w = double.Min(crop[2], 1 - x); + var h = double.Min(crop[3], 1 - y); + if (w <= 1e-3 || h <= 1e-3) + { + warnings.Add(new RenderWarning("Render.Warning.CropIgnored")); + return full; + } + return new RectD(x, y, w, h); + } + + private static VirtualCamera? Camera(IReadOnlyList keys, List warnings) + { + if (keys.Count == 0) return null; + var frames = new Dictionary(); + foreach (var k in keys) + { + if (!double.IsFinite(k.CenterX + k.CenterY + k.Zoom + k.Rotation)) + { + warnings.Add(new RenderWarning("Render.Warning.KeyframeIgnored", k.Frame.ToString(CultureInfo.InvariantCulture))); + continue; + } + frames[k.Frame] = new CameraKeyframe(k.Frame, k.CenterX, k.CenterY, double.Max(1, k.Zoom), k.Rotation) { Easing = Easing(k.Easing, warnings) }; + } + return frames.Count == 0 ? null : new VirtualCamera(frames.Values); + } + + /// "Linear", "EaseIn", "EaseOut", "EaseInOut" or "x1,y1,x2,y2" control points (CSS cubic-bezier). + private static BezierEasing Easing(string? text, List warnings) + { + switch (text?.Trim().ToLowerInvariant()) + { + case null or "" or "easeinout": return BezierEasing.EaseInOut; + case "linear": return BezierEasing.Linear; + case "easein": return BezierEasing.EaseIn; + case "easeout": return BezierEasing.EaseOut; + } + var parts = text.Split(','); + if (parts.Length == 4 + && double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var x1) && x1 is >= 0 and <= 1 + && double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var y1) && double.IsFinite(y1) + && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var x2) && x2 is >= 0 and <= 1 + && double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var y2) && double.IsFinite(y2)) + return new BezierEasing(x1, y1, x2, y2); + warnings.Add(new RenderWarning("Render.Warning.EasingIgnored", text)); + return BezierEasing.EaseInOut; + } +} diff --git a/src/Titano.Core/Render/RenderModels.cs b/src/Titano.Core/Render/RenderModels.cs new file mode 100644 index 00000000..27f90c1c --- /dev/null +++ b/src/Titano.Core/Render/RenderModels.cs @@ -0,0 +1,127 @@ +using Titano.Core.Analysis; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Motion; +using Titano.Core.Project; + +namespace Titano.Core.Render; + +/// Everything a render of one sequence reads, shared by every preset of a batch. +public sealed record RenderInput +{ + public required IRenderFrameSource Source { get; init; } + + /// Capture metadata, one entry per source frame. + public required IReadOnlyList Frames { get; init; } + + public required ProjectSettings Project { get; init; } + + /// Cached deep-analysis results; missing parts are measured by the preparation pass. + public PrecomputedAnalysis? Analysis { get; init; } +} + +/// One output of a render: the resolved export values and where the file (or sequence folder) goes. +/// Full path of the file, or of the folder for image sequences (see ). +public sealed record RenderTarget(ResolvedExport Export, string OutputPath); + +/// Tuning of a render that is not part of the project. +public sealed record RenderOptions +{ + public static RenderOptions Default { get; } = new(); + + /// Long edge of the frames measured by the preparation pass. + public int AnalysisLongEdge { get; init; } = 512; + + /// Upper bound of the decode size (0 = as large as the output geometry needs); previews set a small value. + public int MaxWorkingLongEdge { get; init; } + + /// A downscaled copy of every n-th rendered frame is reported for the live preview (0 = never). + public int PreviewInterval { get; init; } + + public int PreviewLongEdge { get; init; } = 640; + + /// Prepared (exposure-corrected, warped) frames kept for flow and interpolation neighbours (at least 3). + public int CacheFrames { get; init; } = 4; + + public RenderPlanOptions Plan { get; init; } = RenderPlanOptions.Default; +} + +public enum RenderStage +{ + /// Measuring the sequence (luminance, colour, camera path). + Preparing, + + /// Rendering and encoding output frames. + Rendering, + + /// Flushing and committing the output. + Finishing, +} + +/// Progress of a render. (when present) belongs to the receiver, which disposes it. +/// Frames measured (Preparing) or output frames rendered (Rendering). +/// Frames of the current stage. +/// Recent throughput of the current stage. +/// Estimated time to the end of the stage; null until measurable. +public sealed record RenderProgress(RenderStage Stage, int Done, int Total, double FramesPerSecond, TimeSpan Elapsed, TimeSpan? Remaining, ImageBuffer? Preview = null) +{ + public double Fraction => Total > 0 ? (double)Done / Total : 0; +} + +/// +/// Results of the advisor's deep analysis reused by the preparation (all arrays have one entry per source frame). +/// Invalid or mismatched parts are ignored and measured again. +/// +public sealed record PrecomputedAnalysis +{ + /// Trimmed-mean log2 luminance (NaN = unusable frame). + public double[]? LogLuminance { get; init; } + + /// Mean linear red, green and blue (white-balance smoothing). + public double[]? MeanRed { get; init; } + + public double[]? MeanGreen { get; init; } + public double[]? MeanBlue { get; init; } + + /// Sky/land mask with the region series measured through it. + public RegionMask? Regions { get; init; } + + public double[]? SkyLogLuminance { get; init; } + public double[]? LandLogLuminance { get; init; } + + /// Stabilisation solved over the sequence, one correction per source frame, in pixels of a frame of + /// ×. + public StabilizationResult? Stabilization { get; init; } + + public int StabilizationWidth { get; init; } + public int StabilizationHeight { get; init; } + + /// Path smoothing σ the stabilisation was solved with; a different project value triggers a new solve. + public double StabilizationSmoothing { get; init; } +} + +/// A localisable remark about a render (key plus invariant-culture arguments). +public sealed record RenderWarning(string Key, IReadOnlyList Args) +{ + public RenderWarning(string key, params string[] args) : this(key, (IReadOnlyList)args) + { + } + + public override string ToString() => Args.Count == 0 ? Key : $"{Key}({string.Join(", ", Args)})"; +} + +/// A render that cannot start or continue for a reason the user can act on. +public sealed class RenderException : Exception +{ + public RenderException(string reasonKey, string message, IReadOnlyList? args = null, Exception? innerException = null) + : base(message, innerException) + { + ReasonKey = reasonKey; + Args = args ?? []; + } + + /// Localisation key of the reason (e.g. ). + public string ReasonKey { get; } + + public IReadOnlyList Args { get; } +} diff --git a/src/Titano.Core/Render/RenderPipeline.cs b/src/Titano.Core/Render/RenderPipeline.cs new file mode 100644 index 00000000..670c0ea8 --- /dev/null +++ b/src/Titano.Core/Render/RenderPipeline.cs @@ -0,0 +1,461 @@ +using System.Diagnostics; +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Render; + +/// +/// Renders sequences (BRIEF §11). For every planned output frame: source frames come from the +/// at the working size; per-frame exposure corrections (deflicker, holy grail, white +/// balance, regions) are applied; stabilisation, virtual camera and crop are resampled once to the output size; +/// fractional positions are synthesised from the bidirectional flow; motion blur follows the flow with shutter-angle +/// composition; stacking (median, mean, star trails) and the highlight knee come last, then the encoder. Encoding of a +/// frame overlaps the processing of the next. Cancellation and failures leave no output behind (sessions delete their +/// partial files on dispose) and every background task is awaited, so exceptions surface exactly once. +/// +public sealed class RenderPipeline(IReadOnlyList encoders, EncoderHost host = EncoderHost.Client) +{ + internal const string LogCategory = "Render"; + + /// Encoder providers in priority order (client: Media Foundation, then managed; server: managed). + public IReadOnlyList Encoders { get; } = encoders ?? throw new ArgumentNullException(nameof(encoders)); + + public EncoderHost Host { get; } = host; + + /// Geometry, encoder and plan of a target without rendering (Export tab, estimates). + public RenderSetup Setup(RenderInput input, RenderTarget target, RenderOptions? options = null, RenderCorrections? corrections = null) => + RenderSetup.Create(input, target, Encoders, Host, options, corrections); + + /// Prepares the sequence and renders one target. + public async Task RenderAsync(RenderInput input, RenderTarget target, RenderOptions? options = null, IProgress? progress = null, + CancellationToken cancellationToken = default) + { + var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false); + return await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false); + } + + /// Renders one target with corrections prepared earlier (shared by a batch). + /// No encoder can produce the target, or every frame is excluded. + public async Task RenderAsync(RenderInput input, RenderCorrections corrections, RenderTarget target, RenderOptions? options = null, + IProgress? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(corrections); + ArgumentNullException.ThrowIfNull(target); + options ??= RenderOptions.Default; + if (corrections.FrameCount != input.Source.FrameCount) throw new ArgumentException("The corrections belong to another sequence.", nameof(corrections)); + await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + cancellationToken.ThrowIfCancellationRequested(); + + var setup = Setup(input, target, options, corrections); + if (!setup.Encoder.IsReady) + { + var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString()); + throw new RenderException(notice.Key, $"No encoder can produce {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args); + } + if (setup.Plan.Frames.Count == 0) throw new RenderException("Render.Error.NoFrames", "Every frame is excluded."); + using var run = new RenderRun(input, corrections, setup, options, progress); + return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Renders several targets of one sequence one after the other, preparing the sequence once. A failing target is + /// reported and the batch continues; cancellation stops the batch. + /// + public async Task> RenderBatchAsync(RenderInput input, IReadOnlyList targets, RenderOptions? options = null, + IProgress? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(targets); + var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false); + var results = new List(targets.Count); + foreach (var target in targets) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + results.Add(new BatchItemResult(target, await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false), null)); + } + catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested)) + { + Log.Warning(LogCategory, $"Batch target {target.OutputPath} failed", ex); + results.Add(new BatchItemResult(target, null, ex)); + } + } + return results; + } +} + +/// State of one render: caches, flow, stacking, the encoder session and the encode in flight. +internal sealed class RenderRun : IDisposable +{ + /// Largest speed (source frames per output period) that scales motion blur; faster plans blur no further. + private const double MaxBlurSpeed = 4; + + private readonly RenderInput _input; + private readonly RenderCorrections _corrections; + private readonly RenderSetup _setup; + private readonly RenderOptions _options; + private readonly IProgress? _progress; + private readonly RenderPlan _plan; + private readonly RenderGeometry _geometry; + private readonly PreparedFrameCache _prepared; + private readonly FlowCache _flows = new(2); + private readonly MotionBlurRenderer _blur = new(); + private readonly List _warnings = []; + private readonly Stopwatch _clock = new(); + private readonly int _workingEdge; + private readonly float? _knee; + private readonly double _targetShutter; + private readonly FlowQuality _flowQuality; + private OpticalFlowEngine? _flowEngine; + private RegionMask? _mask; + private IVideoEncoderSession? _session; + private Task? _encoding; + private int _done; + + public RenderRun(RenderInput input, RenderCorrections corrections, RenderSetup setup, RenderOptions options, IProgress? progress) + { + _input = input; + _corrections = corrections; + _setup = setup; + _options = options; + _progress = progress; + _plan = setup.Plan; + _geometry = setup.Geometry; + _prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames)); + _workingEdge = _geometry.WorkingLongEdge; + var exposure = input.Project.Exposure; + if (exposure.HighlightKnee is { } knee) + { + if (knee is > 0 and < 1) _knee = (float)knee; + else _warnings.Add(new RenderWarning("Render.Warning.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture))); + } + var motion = input.Project.Motion; + _targetShutter = double.Clamp(ProjectValues.Get(motion.TargetShutterAngle, 180.0), 0, 360); + _flowQuality = ProjectValues.Get(motion.FlowQuality, FlowQualitySetting.Balanced) switch + { + FlowQualitySetting.Draft => FlowQuality.Draft, + FlowQualitySetting.Best => FlowQuality.Best, + _ => FlowQuality.Balanced, + }; + } + + public async Task ExecuteAsync(CancellationToken cancellationToken) + { + var settings = _setup.Encoder.Settings; + _clock.Start(); + Log.Info(RenderPipeline.LogCategory, $"Rendering {_plan.Frames.Count} frames ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}"); + var session = _session = _setup.Encoder.Open(); + try + { + await RenderFramesAsync(cancellationToken).ConfigureAwait(false); + await FlushEncodingAsync().ConfigureAwait(false); + _progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _plan.Frames.Count, Fps(), _clock.Elapsed, TimeSpan.Zero)); + session.Complete(); + } + catch + { + await ObserveEncodingAsync().ConfigureAwait(false); + throw; + } + finally + { + session.Dispose(); + } + _clock.Stop(); + var warnings = new List(_setup.Warnings); + warnings.AddRange(_corrections.Report.Warnings); + warnings.AddRange(_warnings); + var result = new RenderResult + { + OutputPath = settings.OutputPath, + PresetId = _setup.Target.Export.PresetId, + Codec = settings.Codec, + Width = settings.Width, + Height = settings.Height, + FrameRate = settings.FrameRate, + DurationSeconds = _plan.DurationSeconds, + FrameCount = _plan.Frames.Count, + Bytes = RenderResult.SizeOf(settings.OutputPath), + EncoderName = session.EncoderName, + Hardware = session.IsHardware, + Elapsed = _clock.Elapsed, + Warnings = warnings, + }; + Log.Info(RenderPipeline.LogCategory, $"Rendered {result.FrameCount} frames in {result.Elapsed.TotalSeconds:F1} s with {result.EncoderName}: {result.Bytes} bytes"); + return result; + } + + public void Dispose() + { + _prepared.Dispose(); + _flows.Dispose(); + _flowEngine?.Dispose(); + } + + private async Task RenderFramesAsync(CancellationToken cancellationToken) + { + var stack = _input.Project.Stack; + switch (stack.Mode) + { + case StackSetting.Median or StackSetting.Mean: + await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false); + break; + case StackSetting.StarTrails: + using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity))) + { + foreach (var planned in _plan.Frames) + { + cancellationToken.ThrowIfCancellationRequested(); + using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) trails.Add(frame); + await EmitAsync(trails.Result!.Clone(), planned.Duration90k).ConfigureAwait(false); + } + } + break; + default: + foreach (var planned in _plan.Frames) + { + cancellationToken.ThrowIfCancellationRequested(); + var frame = await RenderFrameAsync(planned, _setup.MotionBlur, cancellationToken).ConfigureAwait(false); + await EmitAsync(frame, planned.Duration90k).ConfigureAwait(false); + } + break; + } + } + + /// Centred median/mean window: output k is emitted once frame k + half has been pushed (the tail reuses the + /// last full window). + private async Task RenderWindowStackAsync(StackSettings stack, CancellationToken cancellationToken) + { + var window = int.Max(1, stack.Length); + var half = (window - 1) / 2; + using var stacker = new TemporalStacker(window, stack.Mode == StackSetting.Median ? StackMode.Median : StackMode.Mean); + var pending = new Queue(); + foreach (var planned in _plan.Frames) + { + cancellationToken.ThrowIfCancellationRequested(); + using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame); + pending.Enqueue(planned); + if (pending.Count > half) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false); + } + while (pending.Count > 0) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false); + } + + private async Task EmitStackAsync(TemporalStacker stacker, PlannedFrame planned, CancellationToken cancellationToken) + { + var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false); + try + { + stacker.Render(output, cancellationToken); + } + catch + { + output.Dispose(); + throw; + } + await EmitAsync(output, planned.Duration90k).ConfigureAwait(false); + } + + /// The picture of one planned frame at the output size (a new buffer owned by the caller). + private async Task RenderFrameAsync(PlannedFrame planned, bool blur, CancellationToken cancellationToken) + { + if (planned.Fraction == 0) + { + var frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false); + if (blur && BlurPair(planned.From) is { } pair && BlurFraction(pair.From, pair.To, planned.Speed) is var fraction and > 0) + { + var flows = await FlowAsync(pair.From, pair.To, needBackward: false, cancellationToken).ConfigureAwait(false); + frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false); + return Blurred(frame, flows.Forward, fraction, cancellationToken); + } + return frame.Clone(); + } + + var pairFlows = await FlowAsync(planned.From, planned.To, needBackward: true, cancellationToken).ConfigureAwait(false); + var a = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false); + var b = await PreparedAsync(planned.To, cancellationToken).ConfigureAwait(false); + var synthesised = new ImageBuffer(a.Width, a.Height, a.Channels, clear: false); + try + { + FrameInterpolator.Synthesize(a, b, pairFlows.Forward, pairFlows.Backward!, planned.Fraction, synthesised, cancellationToken: cancellationToken); + var fraction = blur ? BlurFraction(planned.From, planned.To, planned.Speed) : 0; + if (fraction <= 0) return synthesised; + using (synthesised) return Blurred(synthesised, pairFlows.Forward, fraction, cancellationToken); + } + catch + { + synthesised.Dispose(); + throw; + } + } + + private ImageBuffer Blurred(ImageBuffer source, MotionField flow, double fraction, CancellationToken cancellationToken) + { + var output = new ImageBuffer(source.Width, source.Height, source.Channels, clear: false); + try + { + _blur.Render(source, flow, fraction, output, cancellationToken); + return output; + } + catch + { + output.Dispose(); + throw; + } + } + + /// Continuous neighbours whose flow describes the motion at . + private (int From, int To)? BlurPair(int index) + { + var next = _plan.NextContinuous(index); + if (next >= 0) return (index, next); + var previous = _plan.PreviousContinuous(index); + return previous >= 0 ? (previous, index) : null; + } + + /// + /// Fraction of the → flow to smear: the target shutter is relative to the + /// output period, which spans source intervals, and the camera's own exposure already + /// blurred of one interval (√(target² − real²) composition, §11.1). + /// + private double BlurFraction(int from, int to, double speed) + { + var steps = to - from; + if (steps <= 0) return 0; + var real = 0.0; + var info = _input.Frames[from]; + if (info.ExposureTime is > 0 and var exposure && info.CapturedAt is { } t0 && _input.Frames[to].CapturedAt is { } t1 && t1 > t0) + real = double.Min(360, ShutterAngle.FromExposure(exposure, (t1 - t0).TotalSeconds / steps)); + return ShutterAngle.BlurFraction(_targetShutter * double.Clamp(double.Abs(speed), 0, MaxBlurSpeed), real) / steps; + } + + private async Task FlowAsync(int from, int to, bool needBackward, CancellationToken cancellationToken) + { + if (_flows.TryGet(from, to, needBackward, out var cached)) return cached; + var a = await PreparedAsync(from, cancellationToken).ConfigureAwait(false); + var b = await PreparedAsync(to, cancellationToken).ConfigureAwait(false); + _flowEngine ??= new OpticalFlowEngine(_flowQuality); + FlowPair flows; + if (needBackward) + { + var (forward, backward) = _flowEngine.ComputeBidirectional(a, b, cancellationToken); + flows = new FlowPair(forward, backward); + } + else + { + flows = new FlowPair(_flowEngine.Compute(a, b, cancellationToken), null); + } + _flows.Add(from, to, flows); + return flows; + } + + /// Source frame decoded, exposure-corrected and warped to the output size (cached). + private async Task PreparedAsync(int index, CancellationToken cancellationToken) + { + if (_prepared.TryGet(index, out var cached)) return cached; + var raw = await _input.Source.GetFrameAsync(index, _workingEdge, DecodePurpose.Render, cancellationToken).ConfigureAwait(false); + ImageBuffer prepared; + try + { + raw = Rgb(raw); + ApplyExposure(raw, index); + var settings = _geometry.For(raw.Width, raw.Height, index, _corrections.StabilizationAt(index, raw.Width, raw.Height)); + prepared = GeometryStage.Apply(raw, settings, cancellationToken); + } + finally + { + raw.Dispose(); + } + _prepared.Add(index, prepared); + return prepared; + } + + /// Gray sources become RGB and alpha is dropped, so every stage and encoder sees three channels. + private static ImageBuffer Rgb(ImageBuffer frame) + { + if (frame.Channels == 3) return frame; + using (frame) + { + if (frame.Channels == 1) return PixelConvert.GrayToRgb(frame); + var rgb = new ImageBuffer(frame.Width, frame.Height, 3, clear: false); + frame.Data[..(3 * frame.PlaneLength)].CopyTo(rgb.Data); + return rgb; + } + } + + private void ApplyExposure(ImageBuffer frame, int index) + { + var gains = _corrections.WhiteBalance?[index]; + if (_corrections is { Regions: { } mask, SkyEv: { } sky, LandEv: { } land }) + { + if (_mask is null || _mask.Width != frame.Width || _mask.Height != frame.Height) _mask = mask.Resample(frame.Width, frame.Height); + ExposureProcessor.ApplyRegion(frame, _mask.Sky, sky[index], land[index], gains); + return; + } + var ev = _corrections.ExposureEv[index]; + if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains); + } + + /// Applies the knee and hands the frame to the encoder once the previous frame is encoded; owns . + private async Task EmitAsync(ImageBuffer frame, long duration90k) + { + ImageBuffer? preview = null; + try + { + await FlushEncodingAsync().ConfigureAwait(false); + if (_knee is { } knee) ExposureProcessor.Apply(frame, 0, null, knee); + _done++; + if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge); + } + catch + { + frame.Dispose(); + throw; + } + var session = _session!; + _encoding = Task.Run(() => + { + using (frame) session.WriteFrame(frame, duration90k); + }, CancellationToken.None); + if (_progress is not null) + { + var fps = Fps(); + _progress.Report(new RenderProgress(RenderStage.Rendering, _done, _plan.Frames.Count, fps, _clock.Elapsed, + fps > 0 ? TimeSpan.FromSeconds((_plan.Frames.Count - _done) / fps) : null, preview)); + } + else + { + preview?.Dispose(); + } + } + + private double Fps() => _done / double.Max(_clock.Elapsed.TotalSeconds, 1e-6); + + /// Waits for the encode in flight; its failure propagates here (once). + private async Task FlushEncodingAsync() + { + var encoding = _encoding; + _encoding = null; + if (encoding is not null) await encoding.ConfigureAwait(false); + } + + /// After a failure: waits for the encode in flight and logs (never throws) a second error. + private async Task ObserveEncodingAsync() + { + try + { + await FlushEncodingAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + Log.Warning(RenderPipeline.LogCategory, "The encoder also failed while the render was stopping", ex); + } + } +} diff --git a/src/Titano.Core/Render/RenderPlan.cs b/src/Titano.Core/Render/RenderPlan.cs index b8e8cffb..8f83ed7f 100644 --- a/src/Titano.Core/Render/RenderPlan.cs +++ b/src/Titano.Core/Render/RenderPlan.cs @@ -204,7 +204,7 @@ public sealed class RenderPlan options ??= RenderPlanOptions.Default; var n = captureTimes.Count; var timing = project.Timing; - var mode = timing.Mode.Resolve(TimingMode.Constant); + var mode = ProjectValues.Get(timing.Mode, TimingMode.Constant); var playback = FrameRateText.TryParse(timing.FrameRate.Resolve(string.Empty), out var rate) ? rate.Value : frameRate.Value; var warnings = new List(); diff --git a/src/Titano.Core/Render/RenderPreparation.cs b/src/Titano.Core/Render/RenderPreparation.cs new file mode 100644 index 00000000..1c75db82 --- /dev/null +++ b/src/Titano.Core/Render/RenderPreparation.cs @@ -0,0 +1,445 @@ +using System.Diagnostics; +using System.Globalization; +using Titano.Core.Analysis; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; + +namespace Titano.Core.Render; + +/// Diagnostics of for the editor's measuring tools and the render log. +public sealed record RenderPreparationReport +{ + /// Frames decoded by the preparation pass (0 when cached analysis covered everything needed). + public int MeasuredFrames { get; init; } + + public DeflickerDiagnostics? Deflicker { get; init; } + + /// Holy-grail transitions (received and ignored steps). + public IReadOnlyList Transitions { get; init; } = []; + + /// Largest frame-to-frame change of the holy-grail target, in EV. + public double? MaxTargetStepEv { get; init; } + + public double? ShakeRms { get; init; } + + public RegionMethod? RegionMethod { get; init; } + + public IReadOnlyList Warnings { get; init; } = []; +} + +/// Per-source-frame corrections computed once per render (every array has one entry per source frame). +public sealed record RenderCorrections +{ + public required int FrameCount { get; init; } + + /// Measured log2 luminance (NaN where not measured): the amber curve of the Exposure chart. + public required double[] MeasuredLogLuminance { get; init; } + + /// Global exposure correction in EV, including the project's exposure offset. + public required double[] ExposureEv { get; init; } + + /// White-balance gains; null when smoothing is off. + public ChannelGains[]? WhiteBalance { get; init; } + + /// Sky/land mask; when set, and replace . + public RegionMask? Regions { get; init; } + + public double[]? SkyEv { get; init; } + public double[]? LandEv { get; init; } + + /// Stabiliser corrections (source → stabilised) in pixels of a -wide frame. + public Affine2D[]? Stabilization { get; init; } + + public int StabilizationWidth { get; init; } + public int StabilizationHeight { get; init; } + + /// Zoom applied about the centre so stabilisation borders stay outside the picture (1 = none). + public double StabilizationZoom { get; init; } = 1; + + public RenderPreparationReport Report { get; init; } = new(); + + /// Target log2 luminance (measured + correction): the accent curve of the Exposure chart. + public double[] TargetLogLuminance() + { + var target = new double[FrameCount]; + for (var i = 0; i < FrameCount; i++) target[i] = MeasuredLogLuminance[i] + ExposureEv[i]; + return target; + } + + /// The stabiliser correction of frame for a frame of ×. + public Affine2D StabilizationAt(int index, int width, int height) + { + if (Stabilization is null) return Affine2D.Identity; + var c = Stabilization[index]; + if (c.IsIdentity() || (width == StabilizationWidth && height == StabilizationHeight)) return c; + // Pixel-centre scaling between the two frame sizes: x' = (x + ½)·s − ½. + double sx = (double)width / StabilizationWidth, sy = (double)height / StabilizationHeight; + var toFrame = new Affine2D(sx, 0, 0, sy, (sx - 1) / 2, (sy - 1) / 2); + return toFrame * c * toFrame.Invert(); + } +} + +/// +/// The pass over the sequence that a render needs before its first frame (BRIEF §11.1–§11.2): luminance, colour and +/// region series for deflicker / holy grail / white balance / region deflicker, and the stabilisation path. Values the +/// cached provides are reused; the rest is measured on frames decoded at +/// one at a time (memory does not grow with the sequence). +/// +/// Modules switch on only when their setting resolves to true; Auto without advice changes nothing. +/// Deflicker keeps metadata exposure steps (as intentional offsets); holy grail turns the received steps into +/// ramps (alone, or on top of deflicker); region deflicker gives sky and land their own curves. +/// Stabilisation analyses the included frames only and zooms in by 1 / crop scale (at most 1 / 0.75) to hide borders. +/// +/// +public static class RenderPreparation +{ + /// Smallest stabilisation crop scale compensated by zooming; below it borders may show. + public const double MinimumCropScale = 0.75; + + /// Region masks below this confidence are not used when the region mode is Auto. + public const double MinimumRegionConfidence = 0.3; + + public static async Task PrepareAsync(RenderInput input, RenderOptions? options = null, IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + options ??= RenderOptions.Default; + await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + var n = input.Source.FrameCount; + if (input.Frames.Count != n) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input)); + var exposure = input.Project.Exposure; + var motion = input.Project.Motion; + var cached = input.Analysis; + var warnings = new List(); + var included = Included(input.Project.ExcludedFrames, n); + + var deflicker = ProjectValues.Get(exposure.Deflicker, false); + var holyGrail = ProjectValues.Get(exposure.HolyGrail, false); + var regionMode = deflicker ? ProjectValues.Get(exposure.Regions, RegionMode.Off) : RegionMode.Off; + var whiteBalance = ProjectValues.Get(exposure.WhiteBalanceSmoothing, false); + var stabilize = ProjectValues.Get(motion.Stabilize, false); + var smoothing = ProjectValues.Get(motion.StabilizeSmoothing, new StabilizerOptions().SmoothingSigma); + + var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, n) : null; + var measureLuminance = (deflicker || holyGrail) && luminance is null; + double[]? red = null, green = null, blue = null; + if (whiteBalance && Valid(cached?.MeanRed, n) is { } r && Valid(cached?.MeanGreen, n) is { } g && Valid(cached?.MeanBlue, n) is { } b) + (red, green, blue) = (r, g, b); + var measureColour = whiteBalance && red is null; + RegionMask? mask = null; + double[]? sky = null, land = null; + if (regionMode != RegionMode.Off && cached?.Regions is { } m && Valid(cached.SkyLogLuminance, n) is { } s && Valid(cached.LandLogLuminance, n) is { } l) + (mask, sky, land) = (m, s, l); + var stabilization = stabilize ? CachedStabilization(cached, n, smoothing) : null; + var measureStabilization = stabilize && stabilization is null; + + if (regionMode != RegionMode.Off && mask is null && included.Count > 0) + { + mask = await SegmentAsync(input.Source, included, regionMode, options.AnalysisLongEdge, cancellationToken).ConfigureAwait(false); + if (mask is null) warnings.Add(new RenderWarning("Render.Warning.RegionsUnavailable")); + else if (regionMode == RegionMode.Auto && mask.Confidence < MinimumRegionConfidence) + { + warnings.Add(new RenderWarning("Render.Warning.RegionsUnreliable", mask.Confidence.ToString("0.00", CultureInfo.InvariantCulture))); + mask = null; + } + } + var measureRegions = mask is not null && sky is null; + + var pass = new MeasurementPass(n, measureLuminance, measureColour, measureRegions ? mask : null, measureStabilization, smoothing); + if (pass.Needed) + { + await pass.RunAsync(input.Source, included, options.AnalysisLongEdge, progress, cancellationToken).ConfigureAwait(false); + luminance ??= pass.Luminance; + red ??= pass.Red; + green ??= pass.Green; + blue ??= pass.Blue; + sky ??= pass.Sky; + land ??= pass.Land; + if (measureStabilization) + { + stabilization = pass.SolveStabilization(included, n); + if (stabilization is null) warnings.Add(new RenderWarning("Render.Warning.StabilizationUnavailable")); + } + } + + return Combine(input, luminance, red, green, blue, mask, sky, land, stabilization, deflicker, holyGrail, pass.MeasuredFrames, warnings); + } + + private static RenderCorrections Combine(RenderInput input, double[]? luminance, double[]? red, double[]? green, double[]? blue, RegionMask? mask, + double[]? sky, double[]? land, StabilizationData? stabilization, bool deflicker, bool holyGrail, int measured, List warnings) + { + var n = input.Source.FrameCount; + var exposure = input.Project.Exposure; + var ev = new double[n]; + double[]? skyEv = null, landEv = null; + DeflickerDiagnostics? diagnostics = null; + HolyGrailResult? hg = null; + if (luminance is not null) + { + var options = new DeflickerOptions + { + Window = int.Max(3, ProjectValues.Get(exposure.DeflickerWindow, 0) is var w and > 0 ? w : RecommendedWindow(luminance)), + Strength = double.Clamp(ProjectValues.Get(exposure.DeflickerStrength, 1.0), 0, 1), + }; + var evs = new double?[n]; + for (var i = 0; i < n; i++) evs[i] = input.Frames[i].ExposureValue; + if (holyGrail) + { + var transition = ProjectValues.Get(exposure.TransitionLength, 0); + hg = HolyGrailEngine.Compute(luminance, evs, new HolyGrailOptions { TransitionFrames = transition > 0 ? transition : null, Deflicker = options }); + } + var offsets = hg?.StepOffsets ?? DeflickerEngine.OffsetsFromExposure(evs); + if (deflicker && hg is not null) + { + Array.Copy(hg.CorrectionEv, ev, n); + diagnostics = hg.Deflicker.Diagnostics; + } + else if (deflicker) + { + var result = DeflickerEngine.Compute(luminance, options, offsets); + Array.Copy(result.CorrectionEv, ev, n); + diagnostics = result.Diagnostics; + } + else if (hg is not null) + { + for (var i = 0; i < n; i++) ev[i] = hg.SmoothedOffsets[i] - hg.StepOffsets[i]; + } + if (mask is not null && sky is not null && land is not null) + { + var regions = RegionDeflicker.Compute(sky, land, options, offsets); + skyEv = new double[n]; + landEv = new double[n]; + for (var i = 0; i < n; i++) + { + var ramp = hg is null ? 0 : hg.SmoothedOffsets[i] - hg.StepOffsets[i]; + skyEv[i] = regions.Sky.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv; + landEv[i] = regions.Land.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv; + } + } + } + for (var i = 0; i < n; i++) ev[i] += exposure.ExposureOffsetEv; + + ChannelGains[]? gains = red is not null && green is not null && blue is not null ? WhiteBalanceSmoother.Smooth(red, green, blue).Gains : null; + var zoom = 1.0; + if (stabilization is not null) + { + zoom = 1 / double.Max(stabilization.CropScale, MinimumCropScale); + if (stabilization.CropScale < MinimumCropScale) + warnings.Add(new RenderWarning("Render.Warning.StabilizationBorders", stabilization.CropScale.ToString("0.00", CultureInfo.InvariantCulture))); + } + var measuredLuminance = luminance ?? NaNs(n); + return new RenderCorrections + { + FrameCount = n, + MeasuredLogLuminance = measuredLuminance, + ExposureEv = ev, + WhiteBalance = gains, + Regions = skyEv is null ? null : mask, + SkyEv = skyEv, + LandEv = landEv, + Stabilization = stabilization?.Corrections, + StabilizationWidth = stabilization?.Width ?? 0, + StabilizationHeight = stabilization?.Height ?? 0, + StabilizationZoom = zoom, + Report = new RenderPreparationReport + { + MeasuredFrames = measured, + Deflicker = diagnostics, + Transitions = hg?.Transitions ?? [], + MaxTargetStepEv = hg?.MaxFrameStepEv, + ShakeRms = stabilization?.ShakeRms, + RegionMethod = skyEv is null ? null : mask!.Method, + Warnings = warnings, + }, + }; + } + + /// Corrections for every source frame (identity for excluded ones) with the frame size they are measured in. + private sealed record StabilizationData(Affine2D[] Corrections, int Width, int Height, double CropScale, double ShakeRms); + + private static StabilizationData? CachedStabilization(PrecomputedAnalysis? cached, int n, double smoothing) + { + if (cached?.Stabilization is not { } result || result.Corrections.Count != n || cached.StabilizationWidth <= 0 || cached.StabilizationHeight <= 0 + || double.Abs(cached.StabilizationSmoothing - smoothing) > 1e-9) return null; + return new StabilizationData([.. result.Corrections], cached.StabilizationWidth, cached.StabilizationHeight, result.CropScale, result.ShakeRms); + } + + private static int RecommendedWindow(double[] luminance) + { + var finite = luminance.Where(double.IsFinite).ToArray(); + return finite.Length >= 16 ? FlickerSpectrum.Analyze(finite).RecommendedWindow : DeflickerOptions.Default.Window; + } + + private static List Included(IReadOnlyList excluded, int n) + { + var skip = new bool[n]; + foreach (var i in excluded) + { + if ((uint)i < (uint)n) skip[i] = true; + } + var result = new List(n); + for (var i = 0; i < n; i++) + { + if (!skip[i]) result.Add(i); + } + return result; + } + + private static double[]? Valid(double[]? values, int n) => values is not null && values.Length == n ? values : null; + + private static double[] NaNs(int n) + { + var values = new double[n]; + Array.Fill(values, double.NaN); + return values; + } + + private static async Task SegmentAsync(IRenderFrameSource source, List included, RegionMode mode, int longEdge, CancellationToken cancellationToken) + { + var options = new RegionSegmenterOptions + { + // Horizon mode accepts any detected horizon; Luminance mode lets the horizon win only when it is more confident. + MinimumHorizonConfidence = mode switch { RegionMode.Horizon => 0, RegionMode.Luminance => 2, _ => RegionSegmenterOptions.Default.MinimumHorizonConfidence }, + }; + var count = int.Min(options.MaxFrames, included.Count); + var frames = new List(count); + try + { + for (var k = 0; k < count; k++) + { + var index = included[(int)((long)k * (included.Count - 1) / int.Max(1, count - 1))]; + var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false); + frames.Add(frames.Count == 0 ? frame : Conform(frame, frames[0].Width, frames[0].Height)); + } + return frames[0].Height < 8 ? null : RegionSegmenter.Segment(frames, options); + } + finally + { + foreach (var f in frames) f.Dispose(); + } + } + + /// Resizes to the given size (disposing it) when a source returns frames of varying size. + internal static ImageBuffer Conform(ImageBuffer frame, int width, int height) + { + if (frame.Width == width && frame.Height == height) return frame; + try + { + return Resampler.Resize(frame, width, height); + } + finally + { + frame.Dispose(); + } + } + + /// One sequential pass that measures whatever the cache did not provide. + private sealed class MeasurementPass(int n, bool luminance, bool colour, RegionMask? regions, bool stabilization, double smoothing) + { + public bool Needed => luminance || colour || regions is not null || stabilization; + public int MeasuredFrames { get; private set; } + public double[]? Luminance { get; } = luminance ? NaNs(n) : null; + public double[]? Red { get; } = colour ? NaNs(n) : null; + public double[]? Green { get; } = colour ? NaNs(n) : null; + public double[]? Blue { get; } = colour ? NaNs(n) : null; + public double[]? Sky { get; } = regions is not null ? NaNs(n) : null; + public double[]? Land { get; } = regions is not null ? NaNs(n) : null; + private Stabilizer? _stabilizer; + + public async Task RunAsync(IRenderFrameSource source, List included, int longEdge, IProgress? progress, CancellationToken cancellationToken) + { + var clock = Stopwatch.StartNew(); + RegionMask? fitted = null; + var stabilize = stabilization; + try + { + foreach (var index in included) + { + cancellationToken.ThrowIfCancellationRequested(); + var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false); + using (frame) + { + if (Luminance is not null) Luminance[index] = FrameStatistics.MeasureLogLuminance(frame); + if (Red is not null) (Red[index], Green![index], Blue![index]) = Means(frame); + if (regions is not null && Sky is not null) + { + if (fitted is null || fitted.Width != frame.Width || fitted.Height != frame.Height) fitted = regions.Resample(frame.Width, frame.Height); + (Sky[index], Land![index]) = RegionDeflicker.Measure(frame, fitted); + } + if (stabilize) stabilize = AddToStabilizer(frame); + } + MeasuredFrames++; + if (progress is not null) + { + var elapsed = clock.Elapsed; + var fps = MeasuredFrames / double.Max(elapsed.TotalSeconds, 1e-6); + progress.Report(new RenderProgress(RenderStage.Preparing, MeasuredFrames, included.Count, fps, elapsed, + TimeSpan.FromSeconds((included.Count - MeasuredFrames) / fps))); + } + } + } + catch + { + _stabilizer?.Dispose(); + _stabilizer = null; + throw; + } + if (!stabilize) + { + _stabilizer?.Dispose(); + _stabilizer = null; + } + } + + /// False when the frames are too small to stabilise. + private bool AddToStabilizer(ImageBuffer frame) + { + if (_stabilizer is null) + { + if (frame.Width < 16 || frame.Height < 16) return false; + _stabilizer = new Stabilizer(frame.Width, frame.Height, new StabilizerOptions { SmoothingSigma = smoothing }); + } + if (frame.Width == _stabilizer.Width && frame.Height == _stabilizer.Height) + { + _stabilizer.AddFrame(frame); + return true; + } + using var resized = Resampler.Resize(frame, _stabilizer.Width, _stabilizer.Height); + _stabilizer.AddFrame(resized); + return true; + } + + public StabilizationData? SolveStabilization(List included, int frameCount) + { + var stabilizer = _stabilizer; + _stabilizer = null; + if (stabilizer is null) return null; + using (stabilizer) + { + if (stabilizer.FrameCount == 0) return null; + var result = stabilizer.Solve(); + var corrections = new Affine2D[frameCount]; + Array.Fill(corrections, Affine2D.Identity); + for (var k = 0; k < included.Count; k++) corrections[included[k]] = result.Corrections[k]; + return new StabilizationData(corrections, stabilizer.Width, stabilizer.Height, result.CropScale, result.ShakeRms); + } + } + + private static (double R, double G, double B) Means(ImageBuffer image) + { + var count = image.PlaneLength; + var r = Sum(image.Plane(0)) / count; + if (image.Channels < 3) return (r, r, r); + return (r, Sum(image.Plane(1)) / count, Sum(image.Plane(2)) / count); + } + + private static double Sum(ReadOnlySpan values) + { + double sum = 0; + foreach (var v in values) sum += v; + return sum; + } + } +} diff --git a/src/Titano.Core/Render/RenderResult.cs b/src/Titano.Core/Render/RenderResult.cs new file mode 100644 index 00000000..cd244ff3 --- /dev/null +++ b/src/Titano.Core/Render/RenderResult.cs @@ -0,0 +1,71 @@ +using Titano.Core.Export; +using Titano.Core.Video; + +namespace Titano.Core.Render; + +/// A finished render, for the render history and the database (). +public sealed record RenderResult +{ + /// The output file, or folder for image sequences. + public required string OutputPath { get; init; } + + /// Effective preset id (or ). + public required string PresetId { get; init; } + + public required VideoCodec Codec { get; init; } + public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec); + public required int Width { get; init; } + public required int Height { get; init; } + public required Rational FrameRate { get; init; } + public required double DurationSeconds { get; init; } + + /// Output pictures rendered (held frames count once). + public required int FrameCount { get; init; } + + /// Size of the file, or of every file of a sequence. + public required long Bytes { get; init; } + + public required string EncoderName { get; init; } + public required bool Hardware { get; init; } + public required TimeSpan Elapsed { get; init; } + + /// Plan, geometry, encoder and preparation remarks. + public IReadOnlyList Warnings { get; init; } = []; + + /// The render-history entity. + /// Display name of the preset at render time. + /// The project settings used (). + /// Client or render-node name. + public Model.Render ToEntity(Guid sequenceId, string presetName, string? settingsJson, string? producedBy) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = sequenceId, + PresetName = presetName, + SettingsJson = settingsJson, + OutputPath = OutputPath, + Codec = Codec.ToString(), + Width = Width, + Height = Height, + Fps = FrameRate.Value, + DurationSeconds = DurationSeconds, + Bytes = Bytes, + Created = DateTimeOffset.UtcNow, + ProducedBy = producedBy, + }; + + /// Bytes of a file, or the total of the files in a folder. + internal static long SizeOf(string path) + { + if (File.Exists(path)) return new FileInfo(path).Length; + if (!Directory.Exists(path)) return 0; + long total = 0; + foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories)) total += file.Length; + return total; + } +} + +/// Outcome of one target of : a result or the failure that stopped it. +public sealed record BatchItemResult(RenderTarget Target, RenderResult? Result, Exception? Error) +{ + public bool Succeeded => Result is not null; +} diff --git a/src/Titano.Core/Render/RenderSetup.cs b/src/Titano.Core/Render/RenderSetup.cs new file mode 100644 index 00000000..cd7ae688 --- /dev/null +++ b/src/Titano.Core/Render/RenderSetup.cs @@ -0,0 +1,82 @@ +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; + +namespace Titano.Core.Render; + +/// +/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments) and plan. +/// The Export tab uses it for the output size, encoder notices, plan chart and estimates. +/// +public sealed record RenderSetup +{ + public required RenderTarget Target { get; init; } + public required RenderGeometry Geometry { get; init; } + public required EncoderSelection Encoder { get; init; } + public required RenderPlan Plan { get; init; } + + /// Synthetic motion blur applies (it is off while stacking). + public bool MotionBlur { get; init; } + + /// The preparation pass decodes frames (no corrections were supplied and a module needs measurements). + public bool NeedsPreparation { get; init; } + + /// Geometry, plan and encoder remarks. + public IReadOnlyList Warnings { get; init; } = []; + + /// Decides geometry, encoder and plan for one target. + /// Prepared corrections when available (their stabilisation zoom affects the decode size). + public static RenderSetup Create(RenderInput input, RenderTarget target, IReadOnlyList encoders, EncoderHost host, + RenderOptions? options = null, RenderCorrections? corrections = null) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(encoders); + options ??= RenderOptions.Default; + var project = input.Project; + var geometry = RenderGeometry.Create(project.Camera, target.Export, input.Source.Width, input.Source.Height, + corrections?.StabilizationZoom ?? 1, options.MaxWorkingLongEdge); + var selection = EncoderSelector.Select(target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight), encoders, host); + geometry = geometry.WithOutputSize(selection.Settings.Width, selection.Settings.Height); + var times = new DateTime?[input.Frames.Count]; + for (var i = 0; i < times.Length; i++) times[i] = input.Frames[i].CapturedAt; + var plan = RenderPlan.Build(times, project, selection.Settings.FrameRate, options.Plan); + + var warnings = new List(geometry.Warnings); + warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k))); + warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args))); + var stacking = project.Stack.Mode != StackSetting.None; + var blur = ProjectValues.Get(project.Motion.MotionBlur, false); + if (blur && stacking) warnings.Add(new RenderWarning("Render.Warning.BlurOffWhileStacking")); + var exposure = project.Exposure; + var measuring = ProjectValues.Get(exposure.Deflicker, false) || ProjectValues.Get(exposure.HolyGrail, false) + || ProjectValues.Get(exposure.WhiteBalanceSmoothing, false) || ProjectValues.Get(project.Motion.Stabilize, false); + return new RenderSetup + { + Target = target, + Geometry = geometry, + Encoder = selection, + Plan = plan, + MotionBlur = blur && !stacking, + NeedsPreparation = corrections is null && measuring, + Warnings = warnings, + }; + } + + /// The render's workload in the units of . + public ExportWorkload Workload() + { + var edge = Geometry.WorkingLongEdge; + var shortEdge = (long)double.Round(edge * (double)int.Min(Geometry.SourceWidth, Geometry.SourceHeight) / int.Max(Geometry.SourceWidth, Geometry.SourceHeight)); + var flowFrames = MotionBlur ? Plan.Frames.Count : Plan.Statistics.InterpolatedFrames; + return new ExportWorkload(Plan.Frames.Count, Plan.SlotCount, Plan.DurationSeconds, Geometry.OutputWidth, Geometry.OutputHeight, edge * shortEdge, + flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false); + } + + /// Size and time estimates for the values the encoder will actually use. + public ExportEstimate Estimate(ThroughputModel? model = null) + { + var s = Encoder.Settings; + return ExportEstimator.Estimate(Target.Export with { Codec = s.Codec, BitRate = s.BitRate, BitDepth = s.BitDepth, Quality = s.Quality }, Workload(), model); + } +} diff --git a/tests/Titano.Core.Tests/Render/RenderFixture.cs b/tests/Titano.Core.Tests/Render/RenderFixture.cs new file mode 100644 index 00000000..17c77d8c --- /dev/null +++ b/tests/Titano.Core.Tests/Render/RenderFixture.cs @@ -0,0 +1,83 @@ +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Render.Diagnostics; +using Titano.Core.Video; +using Titano.Core.Video.Managed; + +namespace Titano.Core.Tests.Render; + +/// Small synthetic renders shared by the render tests. +internal static class RenderFixture +{ + /// No module and no knee: the output equals the source. + public static ProjectSettings Plain { get; } = new() { Exposure = new ExposureSettings { HighlightKnee = null } }; + + public static SyntheticFrameSource Source(int frames = 12, double flickerEv = 0, Func? motion = null, int width = 96, int height = 64, + Func? configure = null) + { + var options = new SyntheticSequenceOptions + { + Width = width, + Height = height, + FrameCount = frames, + StartEv = 0, + EndEv = 1, + FlickerEv = flickerEv, + Seed = 5, + }; + return new SyntheticFrameSource(SyntheticSequence.Create(configure is null ? options : configure(options)), motion); + } + + /// Renders into a capturing encoder (PNG-sequence capability) and returns the captured frames. + public static async Task<(CapturedEncode Encode, RenderResult Result)> CaptureAsync(RenderInput input, ResolvedExport? export = null, RenderOptions? options = null, + CancellationToken cancellationToken = default) + { + var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true)); + var target = new RenderTarget(export ?? Preset("png-sequence"), Path.Combine(Path.GetTempPath(), "titano-capture-" + Guid.NewGuid().ToString("N"))); + var result = await Pipeline(capture).RenderAsync(input, target, options, cancellationToken: cancellationToken); + return (capture.Encodes.Single(), result); + } + + public static RenderInput Input(SyntheticFrameSource source, ProjectSettings? project = null) => + new() { Source = source, Frames = source.Metadata(), Project = project ?? Plain }; + + /// A built-in preset's values at an explicit size (0×0 = source size). + public static ResolvedExport Preset(string presetId, int width = 96, int height = 64) => + ExportResolver.FromPreset(ExportPresets.Find(presetId)!) with { Width = width, Height = height }; + + public static RenderTarget Target(string folder, ResolvedExport export, string name = "out") => + new(export, Path.Combine(folder, name + (export.Container == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(export.Codec)))); + + public static RenderPipeline Pipeline(params IVideoEncoderProvider[] extra) => + new([.. extra, new ManagedEncoderProvider()]); + + /// Peak signal-to-noise ratio of the 8-bit sRGB encodings. + public static double Psnr(ImageBuffer expected, ImageBuffer actual) + { + var a = PixelConvert.ToInterleaved8(expected, 3); + var b = PixelConvert.ToInterleaved8(actual, 3); + double sum = 0; + for (var i = 0; i < a.Length; i++) sum += (a[i] - b[i]) * (a[i] - b[i]); + return sum == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255 / (sum / a.Length)); + } + + /// Synchronous progress sink (Progress<T> would post to the thread pool). + public sealed class Sink(Action report) : IProgress + { + public void Report(T value) => report(value); + } + + /// Throws an for one frame, as an unreadable file would. + public sealed class FailingSource(IRenderFrameSource inner, int failAt) : IRenderFrameSource + { + public int FrameCount => inner.FrameCount; + public int Width => inner.Width; + public int Height => inner.Height; + + public ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) => + index == failAt ? throw new IOException($"frame {index} is unreadable") : inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken); + } +} diff --git a/tests/Titano.Core.Tests/Render/RenderIsolationTests.cs b/tests/Titano.Core.Tests/Render/RenderIsolationTests.cs new file mode 100644 index 00000000..50456937 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/RenderIsolationTests.cs @@ -0,0 +1,69 @@ +using Titano.Core.Render; +using Titano.Core.Video; +using Titano.Testing; +using static Titano.Core.Tests.Render.RenderFixture; + +namespace Titano.Core.Tests.Render; + +/// Process-wide observations (unobserved task exceptions, managed heap) that must not overlap other tests. +[Serial] +public sealed class RenderIsolationTests +{ + private readonly TestContext _context; + + public RenderIsolationTests(TestContext context) => _context = context; + + [Test] + public async Task FailuresLeaveNoUnobservedTaskExceptions() + { + var unobserved = 0; + void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved); + TaskScheduler.UnobservedTaskException += Handler; + try + { + var dir = _context.CreateTempDirectory(); + var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true)) + { + FailAt = (2, new InvalidDataException("encoder broke")), + }; + for (var i = 0; i < 3; i++) + { + await Assert.ThrowsAsync(() => Pipeline(capture).RenderAsync(Input(Source()), Target(dir, Preset("png-sequence")))); + var input = Input(Source()) with { Source = new FailingSource(Source(), failAt: 3 + i) }; + await Assert.ThrowsAsync(() => Pipeline().RenderAsync(input, Target(dir, Preset("gif-preview")))); + } + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + Assert.Equal(0, unobserved); + Assert.Empty(Directory.GetFileSystemEntries(dir)); + } + finally + { + TaskScheduler.UnobservedTaskException -= Handler; + } + } + + /// BRIEF §20.4: peak memory does not depend on the sequence length (live managed heap sampled while rendering). + [Test] + public async Task MemoryDoesNotGrowWithSequenceLength() + { + async Task PeakAsync(int frames) + { + var dir = _context.CreateTempDirectory(); + long peak = 0; + var progress = new Sink(p => + { + if (p.Stage == RenderStage.Rendering && p.Done % 8 == 0) peak = Math.Max(peak, GC.GetTotalMemory(forceFullCollection: true)); + }); + var project = Plain with { Exposure = new Titano.Core.Project.ExposureSettings { Deflicker = new Titano.Core.Project.Auto().WithManual(true) } }; + await Pipeline().RenderAsync(Input(Source(frames), project), Target(dir, Preset("mjpeg-avi")), progress: progress, cancellationToken: _context.Cancellation); + return peak; + } + await PeakAsync(16); + var shortPeak = await PeakAsync(48); + var longPeak = await PeakAsync(192); + _context.Log($"peak live heap: 48 frames {shortPeak / 1024} KiB, 192 frames {longPeak / 1024} KiB"); + Assert.Less(longPeak - shortPeak, 2 << 20); + } +} diff --git a/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs b/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs new file mode 100644 index 00000000..a9ff53d6 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs @@ -0,0 +1,208 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Render.Diagnostics; +using Titano.Core.Video; +using Titano.Core.Video.Managed; +using Titano.Testing; +using static Titano.Core.Tests.Render.RenderFixture; + +namespace Titano.Core.Tests.Render; + +public sealed class RenderPipelineTests +{ + private readonly TestContext _context; + + public RenderPipelineTests(TestContext context) => _context = context; + + [Theory] + [Case("mjpeg-avi", 8)] + [Case("jpeg-sequence", 8)] + [Case("png-sequence", 8)] + [Case("png-sequence", 16)] + [Case("tiff16-sequence", 16)] + [Case("dng-sequence", 16)] + [Case("gif-preview", 8)] + [Case("apng", 8)] + public async Task RendersEveryManagedFormat(string presetId, int bitDepth) + { + var dir = _context.CreateTempDirectory(); + var source = Source(); + var export = Preset(presetId) with { BitDepth = bitDepth }; + var target = Target(dir, export); + var result = await Pipeline().RenderAsync(Input(source), target, cancellationToken: _context.Cancellation); + + Assert.Equal(target.OutputPath, result.OutputPath); + Assert.SequenceEqual(new[] { Path.GetFileName(target.OutputPath) }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName)); + Assert.Equal((96, 64), (result.Width, result.Height)); + Assert.Equal(12, result.FrameCount); + Assert.Equal(RenderResultBytes(target.OutputPath), result.Bytes); + Assert.False(result.Hardware); + Assert.Approximately(12 / export.FrameRate.Value, result.DurationSeconds, 1e-4); + + using var expected = source.Sequence.Render(5); + using var decoded = DecodeFrame(export.Codec, target.OutputPath, 5, out var count); + Assert.Equal(12, count); + var psnr = Psnr(expected, decoded); + _context.Log($"{presetId} {bitDepth}-bit: {result.Bytes} bytes, PSNR {psnr:F1} dB"); + Assert.Greater(psnr, export.Codec switch { VideoCodec.Gif => 25, VideoCodec.Mjpeg or VideoCodec.JpegSequence => 35, _ => 60 }); + } + + [Test] + public async Task LosslessOutputsAreByteIdenticalAcrossRuns() + { + var dir = _context.CreateTempDirectory(); + var project = Plain with + { + Exposure = new ExposureSettings { Deflicker = new Auto().WithManual(true), HighlightKnee = 0.9 }, + Timing = new TimingSettings { Mode = new Auto().WithManual(TimingMode.Interpolated), FrameRate = new Auto().WithManual("15") }, + }; + var first = await Pipeline().RenderAsync(Input(Source(flickerEv: 0.2), project), Target(dir, Preset("png-sequence"), "a"), cancellationToken: _context.Cancellation); + var second = await Pipeline().RenderAsync(Input(Source(flickerEv: 0.2), project), Target(dir, Preset("png-sequence"), "b"), cancellationToken: _context.Cancellation); + var a = Directory.GetFiles(first.OutputPath).Order(StringComparer.Ordinal).ToArray(); + var b = Directory.GetFiles(second.OutputPath).Order(StringComparer.Ordinal).ToArray(); + Assert.Equal(a.Length, b.Length); + Assert.Greater(first.FrameCount, 12); + for (var i = 0; i < a.Length; i++) Assert.BytesEqual(File.ReadAllBytes(a[i]), File.ReadAllBytes(b[i])); + + var apngA = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, Preset("apng"), "c"), cancellationToken: _context.Cancellation); + var apngB = await Pipeline().RenderAsync(Input(Source(), project), Target(dir, Preset("apng"), "d"), cancellationToken: _context.Cancellation); + Assert.BytesEqual(File.ReadAllBytes(apngA.OutputPath), File.ReadAllBytes(apngB.OutputPath)); + } + + [Theory] + [Case("mjpeg-avi")] + [Case("png-sequence")] + [Case("gif-preview")] + public async Task CancellationLeavesNoOutput(string presetId) + { + var dir = _context.CreateTempDirectory(); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_context.Cancellation); + var progress = new Sink(p => + { + if (p.Stage == RenderStage.Rendering && p.Done == 5) cts.Cancel(); + }); + await Assert.ThrowsAsync(() => Pipeline().RenderAsync(Input(Source(24)), Target(dir, Preset(presetId)), progress: progress, cancellationToken: cts.Token)); + Assert.Empty(Directory.GetFileSystemEntries(dir)); + } + + [Test] + public async Task SourceFailurePropagatesOnceAndLeavesNoOutput() + { + var dir = _context.CreateTempDirectory(); + var input = Input(Source()) with { Source = new FailingSource(Source(), failAt: 7) }; + var error = await Assert.ThrowsAsync(() => Pipeline().RenderAsync(input, Target(dir, Preset("mjpeg-avi")))); + Assert.Equal("frame 7 is unreadable", error.Message); + Assert.Empty(Directory.GetFileSystemEntries(dir)); + } + + [Test] + public async Task EncoderFailurePropagatesAndDisposesTheSession() + { + var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true)) + { + FailAt = (4, new InvalidDataException("encoder broke")), + }; + var error = await Assert.ThrowsAsync(() => Pipeline(capture).RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("png-sequence")))); + Assert.Equal("encoder broke", error.Message); + var encode = capture.Encodes.Single(); + Assert.True(encode.Disposed); + Assert.False(encode.Completed); + Assert.Equal(4, encode.Frames.Count); + } + + [Test] + public async Task ProgressReportsEveryFrameAndPreviews() + { + var reports = new List(); + var options = new RenderOptions { PreviewInterval = 5, PreviewLongEdge = 32 }; + var project = Plain with { Exposure = new ExposureSettings { Deflicker = new Auto().WithManual(true), HighlightKnee = null } }; + await Pipeline().RenderAsync(Input(Source(), project), Target(_context.CreateTempDirectory(), Preset("jpeg-sequence")), options, + new Sink(reports.Add), _context.Cancellation); + var preparing = reports.Where(r => r.Stage == RenderStage.Preparing).ToList(); + var rendering = reports.Where(r => r.Stage == RenderStage.Rendering).ToList(); + Assert.Equal(12, preparing.Count); + Assert.SequenceEqual(Enumerable.Range(1, 12), rendering.Select(r => r.Done)); + Assert.True(rendering.All(r => r.Total == 12 && r.FramesPerSecond > 0 && r.Remaining >= TimeSpan.Zero)); + Assert.SequenceEqual(new[] { 1, 6, 11 }, rendering.Where(r => r.Preview is not null).Select(r => r.Done)); + Assert.Equal(32, rendering[0].Preview!.Width); + Assert.Equal(RenderStage.Finishing, reports[^1].Stage); + foreach (var r in rendering) r.Preview?.Dispose(); + } + + [Test] + public async Task BatchRendersEachTargetAndReportsFailures() + { + var dir = _context.CreateTempDirectory(); + var server = new RenderPipeline([new ManagedEncoderProvider()], EncoderHost.Server); + var targets = new[] + { + Target(dir, Preset("png-sequence"), "png"), + Target(dir, Preset("1080p-h264"), "h264"), + Target(dir, Preset("gif-preview"), "gif"), + }; + var results = await server.RenderBatchAsync(Input(Source()), targets, cancellationToken: _context.Cancellation); + Assert.Equal(3, results.Count); + Assert.True(results[0].Succeeded && results[2].Succeeded); + var error = Assert.NotNull(results[1].Error as RenderException); + Assert.Equal(EncoderNotices.NeedsRenderNode, error.ReasonKey); + Assert.SequenceEqual(new[] { "gif.gif", "png" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + } + + [Test] + public async Task EverythingExcludedIsARenderError() + { + var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 12)] }; + var error = await Assert.ThrowsAsync(() => Pipeline().RenderAsync(Input(Source(), project), Target(_context.CreateTempDirectory(), Preset("png-sequence")))); + Assert.Equal("Render.Error.NoFrames", error.ReasonKey); + } + + [Test] + public async Task ResultBecomesARenderHistoryEntity() + { + var result = await Pipeline().RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("apng")), cancellationToken: _context.Cancellation); + var sequence = Guid.CreateVersion7(); + var entity = result.ToEntity(sequence, "APNG", "{}", "test"); + Assert.Equal(sequence, entity.SequenceId); + Assert.Equal(result.OutputPath, entity.OutputPath); + Assert.Equal("Apng", entity.Codec); + Assert.Equal(result.Bytes, entity.Bytes); + Assert.Approximately(15, entity.Fps, 1e-12); + Assert.Equal("Managed APNG", result.EncoderName); + } + + private static long RenderResultBytes(string path) => File.Exists(path) + ? new FileInfo(path).Length + : new DirectoryInfo(path).EnumerateFiles().Sum(f => f.Length); + + /// Decodes output picture and counts the pictures of the output. + private static ImageBuffer DecodeFrame(VideoCodec codec, string path, int index, out int count) + { + switch (codec) + { + case VideoCodec.Mjpeg: + var avi = AviReader.Read(File.ReadAllBytes(path)); + count = avi.Frames.Count; + return JpegDecoder.DecodeToLinear(avi.Frames[index]); + case VideoCodec.Gif or VideoCodec.Apng: + var bytes = File.ReadAllBytes(path); + var animation = codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes); + count = animation.Frames.Count; + return animation.ToLinear(index); + default: + var files = Directory.GetFiles(path).Order(StringComparer.Ordinal).ToArray(); + count = files.Length; + var data = File.ReadAllBytes(files[index]); + return codec switch + { + VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(data), + VideoCodec.PngSequence => PngDecoder.DecodeToLinear(data), + _ => TiffImageReader.Decode(data), + }; + } + } +} diff --git a/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs new file mode 100644 index 00000000..c7f223b7 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs @@ -0,0 +1,351 @@ +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Render.Diagnostics; +using Titano.Testing; +using static Titano.Core.Tests.Render.RenderFixture; + +namespace Titano.Core.Tests.Render; + +public sealed class RenderProcessingTests +{ + private readonly TestContext _context; + + public RenderProcessingTests(TestContext context) => _context = context; + + private static ProjectSettings With(ExposureSettings? exposure = null, MotionSettings? motion = null, CameraSettings? camera = null, StackSettings? stack = null, + TimingSettings? timing = null) => Plain with + { + Exposure = exposure ?? Plain.Exposure, + Motion = motion ?? new MotionSettings(), + Camera = camera ?? new CameraSettings(), + Stack = stack ?? new StackSettings(), + Timing = timing ?? new TimingSettings(), + }; + + private static Auto On(T value) => new Auto().WithManual(value); + + private static double[] LogLuminance(IEnumerable frames) => [.. frames.Select(f => FrameStatistics.MeasureLogLuminance(f))]; + + private static double Rms(IEnumerable values) + { + var v = values.ToArray(); + var mean = v.Average(); + return Math.Sqrt(v.Sum(x => (x - mean) * (x - mean)) / v.Length); + } + + /// The §20.4 deflicker gate measured on rendered frames (same recipe as the analysis gate). + [Test] + public async Task DeflickerRemovesFlickerAndKeepsTheRamp() + { + var source = Source(200, configure: o => o with { Seed = 3, StartEv = -2, EndEv = 1, FlickerEv = 0.1 }); + var project = With(new ExposureSettings { Deflicker = On(true), DeflickerWindow = On(21), HighlightKnee = null }); + var (encode, _) = await CaptureAsync(Input(source, project), cancellationToken: _context.Cancellation); + var truth = source.Sequence.SceneEv; + var measured = Analysis.AnalysisFixtures.MeasureSeries(source.Sequence); + var output = LogLuminance(encode.Frames); + var before = Analysis.AnalysisFixtures.FrameToFrameResidualRms(measured, truth); + var after = Analysis.AnalysisFixtures.FrameToFrameResidualRms(output, truth); + var rampError = Analysis.AnalysisFixtures.MaxDeviation(output, truth); + _context.Log($"flicker {before:F4} → {after:F4} EV ({1 - after / before:P0}); max ramp deviation {rampError:F4} EV"); + Assert.GreaterOrEqual(1 - after / before, 0.6); + Assert.LessOrEqual(rampError, 0.05); + } + + [Test] + public async Task HolyGrailTurnsExposureStepsIntoRamps() + { + var source = Source(80, configure: o => o with { ExposureSteps = [new SyntheticExposureStep(40, 1.0)], StartEv = 0, EndEv = 0 }); + var project = With(new ExposureSettings { HolyGrail = On(true), Deflicker = On(true), HighlightKnee = null }); + var (encode, _) = await CaptureAsync(Input(source, project), cancellationToken: _context.Cancellation); + var output = LogLuminance(encode.Frames); + var steps = output.Zip(output.Skip(1), (a, b) => Math.Abs(b - a)).ToArray(); + _context.Log($"largest output step {steps.Max():F3} EV"); + Assert.LessOrEqual(steps.Max(), 0.3 + 0.02); + Assert.Approximately(-1.0, output[^1] - output[0], 0.1, "the step is kept, only spread out"); + } + + [Test] + public async Task WhiteBalanceSmoothingRemovesColourJitter() + { + var source = Source(48, configure: o => o with { WhiteBalanceJitter = 0.1 }); + var (encode, _) = await CaptureAsync(Input(source, With(new ExposureSettings { WhiteBalanceSmoothing = On(true), HighlightKnee = null })), cancellationToken: _context.Cancellation); + double Ratio(ImageBuffer f) + { + var stats = FrameStatistics.Measure(f); + return Math.Log2(stats.MeanRed / stats.MeanGreen); + } + var before = Enumerable.Range(0, 48).Select(i => + { + using var f = source.Sequence.Render(i); + return Ratio(f); + }).ToArray(); + var after = encode.Frames.Select(Ratio).ToArray(); + double Jitter(double[] r) => Rms(r.Zip(r.Skip(1), (a, b) => b - a)); + _context.Log($"R/G jitter {Jitter(before):F4} → {Jitter(after):F4}"); + Assert.Less(Jitter(after), 0.3 * Jitter(before)); + } + + [Test] + public async Task RegionDeflickerCorrectsSkyAndLandSeparately() + { + var source = Source(48, configure: o => o with { SkyFlickerEv = 0.3, LandFlickerEv = 0.3, StartEv = 0, EndEv = 0 }); + var landMask = new float[96 * 64]; + for (var y = 0; y < 64; y++) + { + for (var x = 0; x < 96; x++) landMask[y * 96 + x] = source.Sequence.IsSky(x, y) ? 0 : 1; + } + double LandResidual(List frames) => Rms(frames.Select(f => FrameStatistics.MeasureLogLuminance(f, landMask))); + var global = await CaptureAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), HighlightKnee = null })), cancellationToken: _context.Cancellation); + var regions = await CaptureAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), Regions = On(RegionMode.Horizon), HighlightKnee = null })), + cancellationToken: _context.Cancellation); + var g = LandResidual(global.Encode.Frames); + var r = LandResidual(regions.Encode.Frames); + _context.Log($"land residual global {g:F3} EV, regions {r:F3} EV"); + Assert.Less(r, 0.5 * g); + var prepared = await RenderPreparation.PrepareAsync(Input(source, With(new ExposureSettings { Deflicker = On(true), Regions = On(RegionMode.Horizon) })), + cancellationToken: _context.Cancellation); + Assert.Equal(RegionMethod.Horizon, prepared.Report.RegionMethod); + Assert.NotNull(prepared.SkyEv); + } + + [Test] + public async Task ExportAspectCropsTheCentreAndCameraCropMovesIt() + { + var source = Source(4); + using var reference = source.Sequence.Render(2); + var (square, _) = await CaptureAsync(Input(source), Preset("png-sequence", 64, 64), cancellationToken: _context.Cancellation); + using (var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(16, 0, 64, 64), OutputWidth = 64, OutputHeight = 64 })) + Assert.Greater(Psnr(expected, square.Frames[2]), 60); + + var quarter = With(camera: new CameraSettings { Crop = [0.5, 0.5, 0.5, 0.5] }); + var (corner, result) = await CaptureAsync(Input(source, quarter), Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation); + Assert.Equal((48, 32), (result.Width, result.Height)); + using (var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(48, 32, 48, 32) })) + Assert.Greater(Psnr(expected, corner.Frames[2]), 60); + } + + [Test] + public async Task VirtualCameraZoomsAndTheDecodeSizeFollowsTheNeed() + { + var plain = Source(4, width: 480, height: 320); + await CaptureAsync(Input(plain), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation); + Assert.Equal(96, plain.LargestRenderRequest); + + var zoomed = Source(4, width: 480, height: 320); + var camera = With(camera: new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 2, 0), new CameraKey(3, 0.5, 0.5, 2, 0)] }); + var (encode, _) = await CaptureAsync(Input(zoomed, camera), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation); + Assert.Equal(192, zoomed.LargestRenderRequest); + using var full = zoomed.Sequence.Render(1); + using var expected = GeometryStage.Apply(full, new GeometrySettings { Crop = new RectD(120, 80, 240, 160), OutputWidth = 96, OutputHeight = 64 }); + var psnr = Psnr(expected, encode.Frames[1]); + _context.Log($"zoom ×2 vs direct crop: {psnr:F1} dB"); + Assert.Greater(psnr, 28); + } + + [Test] + public async Task ExposureOffsetAndKneeAreApplied() + { + var source = Source(3, configure: o => o with { StartEv = 2, EndEv = 2 }); + var (raw, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation); + var (brighter, _) = await CaptureAsync(Input(source, With(new ExposureSettings { ExposureOffsetEv = 1, HighlightKnee = null })), cancellationToken: _context.Cancellation); + for (var i = 0; i < raw.Frames[0].Data.Length; i += 13) Assert.Approximately(2 * raw.Frames[0].Data[i], brighter.Frames[0].Data[i], 1e-5); + Assert.Greater(raw.Frames[0].Data.ToArray().Max(), 1f); + + var (kneed, _) = await CaptureAsync(Input(source, With(new ExposureSettings { HighlightKnee = 0.8 })), cancellationToken: _context.Cancellation); + Assert.Less(kneed.Frames[0].Data.ToArray().Max(), 1f); + for (var i = 0; i < raw.Frames[0].Data.Length; i += 13) + { + if (raw.Frames[0].Data[i] < 0.5f) Assert.Approximately(raw.Frames[0].Data[i], kneed.Frames[0].Data[i], 1e-6); + } + } + + [Test] + public async Task InterpolatedFramesFollowTheMotion() + { + Func pan = i => (2.0 * i, 0); + var source = Source(6, motion: pan, configure: o => o with { StartEv = 0, EndEv = 0 }); + var timing = new TimingSettings { Mode = On(TimingMode.Interpolated), FrameRate = new Auto().WithManual("15") }; + var export = Preset("png-sequence") with { FrameRate = new Titano.Core.Video.Rational(30, 1) }; + var (encode, result) = await CaptureAsync(Input(source, With(timing: timing)), export, cancellationToken: _context.Cancellation); + Assert.Equal(11, result.FrameCount); + Assert.Equal(12, encode.Durations.Sum() / 3000); + var truth = Source(6, motion: i => (2.0 * i + 1, 0), configure: o => o with { StartEv = 0, EndEv = 0 }); + using var shifted = await truth.GetFrameAsync(2, 0, DecodePurpose.Render, _context.Cancellation); + double Interior(ImageBuffer a, ImageBuffer b) + { + using var ca = GeometryStage.Apply(a, new GeometrySettings { Crop = new RectD(12, 4, 72, 56) }); + using var cb = GeometryStage.Apply(b, new GeometrySettings { Crop = new RectD(12, 4, 72, 56) }); + return Psnr(ca, cb); + } + var synthesised = Interior(shifted, encode.Frames[5]); + var nearest = Interior(shifted, encode.Frames[4]); + _context.Log($"synthesised frame {synthesised:F1} dB vs nearest whole frame {nearest:F1} dB"); + Assert.Greater(synthesised, 30); + Assert.Greater(synthesised, nearest + 5); + } + + [Test] + public async Task MotionBlurSmearsAlongTheMotionOnly() + { + var blur = new MotionSettings { MotionBlur = On(true), TargetShutterAngle = On(360.0) }; + var moving = Source(6, motion: i => (3.0 * i, 0), configure: o => o with { StartEv = 0, EndEv = 0 }); + var sharp = await CaptureAsync(Input(moving), cancellationToken: _context.Cancellation); + var blurred = await CaptureAsync(Input(moving, With(motion: blur)), cancellationToken: _context.Cancellation); + double Gradient(ImageBuffer f, int dx, int dy) + { + double sum = 0; + var g = f.Plane(1); + for (var y = 8; y < f.Height - 8; y++) + { + for (var x = 8; x < f.Width - 8; x++) sum += Math.Abs(g[y * f.Width + x] - g[(y + dy) * f.Width + x + dx]); + } + return sum; + } + var horizontal = Gradient(blurred.Encode.Frames[3], 1, 0) / Gradient(sharp.Encode.Frames[3], 1, 0); + var vertical = Gradient(blurred.Encode.Frames[3], 0, 1) / Gradient(sharp.Encode.Frames[3], 0, 1); + _context.Log($"gradient ratios: horizontal {horizontal:F3}, vertical {vertical:F3}"); + Assert.Less(horizontal, 0.75); + Assert.Greater(vertical, horizontal + 0.1); + + var still = Source(6, configure: o => o with { StartEv = 0, EndEv = 0 }); + var a = await CaptureAsync(Input(still), cancellationToken: _context.Cancellation); + var b = await CaptureAsync(Input(still, With(motion: blur)), cancellationToken: _context.Cancellation); + Assert.Greater(Psnr(a.Encode.Frames[3], b.Encode.Frames[3]), 40); + } + + [Test] + public async Task StabilisationRemovesShake() + { + var random = new Random(11); + var shake = Enumerable.Range(0, 24).Select(_ => (X: random.NextDouble() * 6 - 3, Y: random.NextDouble() * 6 - 3)).ToArray(); + var source = new PatternFrameSource(320, 192, 24, i => shake[i]); + var project = With(motion: new MotionSettings { Stabilize = On(true), StabilizeSmoothing = On(12.0) }); + var input = new RenderInput { Source = source, Frames = source.Metadata(), Project = project }; + + static double Steps(IReadOnlyList<(double X, double Y)> p) => + Math.Sqrt(Enumerable.Range(1, p.Count - 1).Average(k => Math.Pow(p[k].X - p[k - 1].X, 2) + Math.Pow(p[k].Y - p[k - 1].Y, 2))); + var prepared = await RenderPreparation.PrepareAsync(input, cancellationToken: _context.Cancellation); + var residual = Enumerable.Range(0, 24).Select(k => + { + var (x, y) = prepared.Stabilization![k].Apply(159.5, 95.5); + return (shake[k].X + x - 159.5, shake[k].Y + y - 95.5); + }).ToArray(); + _context.Log($"camera path steps {Steps(shake):F2} px → {Steps(residual):F3} px after correction; zoom {prepared.StabilizationZoom:F3}"); + Assert.Less(Steps(residual), 0.1 * Steps(shake)); + Assert.InRange(prepared.StabilizationZoom, 1.01, 1.2); + + var (encode, result) = await CaptureAsync(input, Preset("png-sequence", 0, 0), cancellationToken: _context.Cancellation); + Assert.Equal((320, 192), (result.Width, result.Height)); + using var stabilizer = new Stabilizer(320, 192); + var output = encode.Frames.Select(f => stabilizer.AddFrame(f).Transform).Skip(1).ToArray(); + var after = Math.Sqrt(output.Average(m => m.Tx * m.Tx + m.Ty * m.Ty)); + _context.Log($"rendered frame-to-frame shift {after:F3} px"); + Assert.Less(after, 0.1 * Steps(shake) * prepared.StabilizationZoom); + } + + [Test] + public async Task MedianStackRemovesTransientsAndStarTrailsNeverDarken() + { + var source = Source(9, configure: o => o with { StartEv = 0, EndEv = 0 }); + var input = Input(source, With(stack: new StackSettings { Mode = StackSetting.Median, Length = 5 })) with { Source = new TransientSource(source, 4) }; + var (median, _) = await CaptureAsync(input, cancellationToken: _context.Cancellation); + Assert.Equal(9, median.Frames.Count); + using var clean = source.Sequence.Render(4); + Assert.Greater(Psnr(clean, median.Frames[4]), 45); + + var stars = Source(12, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 }); + var (trails, _) = await CaptureAsync(Input(stars, With(stack: new StackSettings { Mode = StackSetting.StarTrails, Length = 0 })), cancellationToken: _context.Cancellation); + var luminance = LogLuminance(trails.Frames); + Assert.Monotonic(luminance); + for (var k = 1; k < trails.Frames.Count; k++) + { + var previous = trails.Frames[k - 1].Data; + var current = trails.Frames[k].Data; + for (var i = 0; i < current.Length; i++) Assert.True(current[i] >= previous[i] - 1e-6f, $"pixel {i} darkened at frame {k}"); + } + } + + [Test] + public async Task PrecomputedAnalysisSkipsTheMeasuringPass() + { + var source = Source(30, flickerEv: 0.2); + var project = With(new ExposureSettings { Deflicker = On(true), HighlightKnee = null }); + var measured = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: _context.Cancellation); + Assert.Equal(30, measured.Report.MeasuredFrames); + var cached = new PrecomputedAnalysis { LogLuminance = measured.MeasuredLogLuminance }; + var decodes = source.Decodes; + var reused = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = cached }, cancellationToken: _context.Cancellation); + Assert.Equal(0, reused.Report.MeasuredFrames); + Assert.Equal(decodes, source.Decodes); + Assert.SequenceEqual(measured.ExposureEv, reused.ExposureEv); + + var wrongLength = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = new PrecomputedAnalysis { LogLuminance = new double[3] } }, + cancellationToken: _context.Cancellation); + Assert.Equal(30, wrongLength.Report.MeasuredFrames); + Assert.SequenceEqual(measured.ExposureEv, wrongLength.ExposureEv); + + var nothing = await RenderPreparation.PrepareAsync(Input(source), cancellationToken: _context.Cancellation); + Assert.Equal(0, nothing.Report.MeasuredFrames); + Assert.True(nothing.ExposureEv.All(e => e == 0)); + } + + [Test] + public async Task HeldFramesKeepTheirDurationOnConstantRateOutputs() + { + var source = Source(10, configure: o => o with { TimeShifts = [new SyntheticTimeShift(5, 20)] }); + var project = With(timing: new TimingSettings { Mode = On(TimingMode.Adaptive) }); + var export = Preset("mjpeg-avi"); + var dir = _context.CreateTempDirectory(); + var result = await Pipeline().RenderAsync(Input(source, project), Target(dir, export), cancellationToken: _context.Cancellation); + var avi = AviReader.Read(File.ReadAllBytes(result.OutputPath)); + Assert.Equal(10, result.FrameCount); + Assert.Equal(12, avi.Frames.Count); // frame 4 lasts three periods (30 s ÷ 10 s) + Assert.Approximately(12 / 25.0, result.DurationSeconds, 1e-9); + } + + [Test] + public void SetupReportsGeometryEncoderPlanAndEstimates() + { + var source = Source(48, width: 480, height: 320); + var input = Input(source, With(new ExposureSettings { Deflicker = On(true) }, motion: new MotionSettings { MotionBlur = On(true) })); + var setup = Pipeline().Setup(input, Target("/exports", Preset("gif-preview", 480, 270))); + Assert.True(setup.Encoder.IsReady); + Assert.Equal((480, 270), (setup.Geometry.OutputWidth, setup.Geometry.OutputHeight)); + Assert.Equal(48, setup.Plan.Frames.Count); + Assert.True(setup.NeedsPreparation); + var workload = setup.Workload(); + Assert.Equal(48, workload.FlowFrames); + Assert.Equal(48, workload.AnalysisFrames); + Assert.Equal(480L * 320, workload.WorkingPixels); + var estimate = setup.Estimate(); + Assert.Greater(estimate.Bytes, 0); + Assert.Greater(estimate.Time.TotalSeconds, 0); + } + + /// Adds a bright square to one frame (a passing aircraft light). + private sealed class TransientSource(IRenderFrameSource inner, int frame) : IRenderFrameSource + { + public int FrameCount => inner.FrameCount; + public int Width => inner.Width; + public int Height => inner.Height; + + public async ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + var image = await inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken); + if (index != frame) return image; + for (var c = 0; c < 3; c++) + { + for (var y = 20; y < 30; y++) + { + for (var x = 40; x < 50; x++) image[c, x, y] = 1; + } + } + return image; + } + } +} From ea3de59c7249906da7becfecc66a2e0267170de7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:09:30 +0000 Subject: [PATCH 143/188] test(ui): host smoke-test visuals under a parent so their styles apply WPF fetches implicit and theme styles only once an element is initialized (EndInit, a visual parent, or a window root). The smoke tests measured bare elements created in code, so templated controls had no template: zero-size cards, no wrap panel in the card list, an empty preview. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Visuals/VisualsSmokeTests.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/Titano.App.Tests/Visuals/VisualsSmokeTests.cs b/tests/Titano.App.Tests/Visuals/VisualsSmokeTests.cs index 65e1a41f..408c2020 100644 --- a/tests/Titano.App.Tests/Visuals/VisualsSmokeTests.cs +++ b/tests/Titano.App.Tests/Visuals/VisualsSmokeTests.cs @@ -48,6 +48,7 @@ public sealed class VisualsSmokeTests public void CardFitsTheDefaultGridSlot() => WpfHost.Run(() => { var card = SampleCard(); + Host(card); card.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Assert.Approximately(236, card.DesiredSize.Width, 0.5); Assert.LessOrEqual(card.DesiredSize.Height, (double)VirtualizingWrapPanel.ItemHeightProperty.DefaultMetadata.DefaultValue + 0.5); @@ -236,14 +237,22 @@ public sealed class VisualsSmokeTests private static RenderTargetBitmap Render(FrameworkElement element, double width, double height) { - element.Measure(new Size(width, height)); - element.Arrange(new Rect(0, 0, width, height)); - element.UpdateLayout(); + var host = Host(element); + host.Measure(new Size(width, height)); + host.Arrange(new Rect(0, 0, width, height)); + host.UpdateLayout(); var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32); - bitmap.Render(element); + bitmap.Render(host); return bitmap; } + /// + /// Gives the element a visual parent, as in a real window: WPF fetches implicit and theme styles (and with them + /// templates) only once an element is initialized, which a bare element created in code never is. + /// + private static Border Host(FrameworkElement element) => + element.Parent as Border ?? new Border { Child = element }; + private static int Painted(BitmapSource bitmap) { var stride = bitmap.PixelWidth * 4; From 7e157cbf72f80185701ca1a23ccac624c361c78f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:13:18 +0000 Subject: [PATCH 144/188] feat(raw): native CR2, NEF, ARW, PEF and RAF decoders Each container reader builds a RawFrame for the shared pipeline: CR2 sliced lossless JPEG with SensorInfo crop, masked-column black and ColorData WB; NEF uncompressed and Nikon Huffman (lossy type 1, lossless, lossy type 2 incl. split); ARW uncompressed and ARW2 cRAW with tone curve; PEF uncompressed and Pentax Huffman; RAF uncompressed Bayer and X-Trans with FujiIFD. Colour comes from a dcraw adobe_coeff matrix table; bodies without an entry are reported unsupported so the caller uses the embedded preview. Native RAWs detect the sensor's saturation level for clipping only, never rescaling per frame. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Dng/DngReader.cs | 11 + src/Titano.Core/Codecs/Raw/ArwReader.cs | 136 +++++ src/Titano.Core/Codecs/Raw/CameraMatrices.cs | 114 ++++ src/Titano.Core/Codecs/Raw/Cr2Reader.cs | 161 ++++++ src/Titano.Core/Codecs/Raw/NativeRaw.cs | 251 +++++++++ src/Titano.Core/Codecs/Raw/NefReader.cs | 231 +++++++++ src/Titano.Core/Codecs/Raw/PefReader.cs | 149 ++++++ src/Titano.Core/Codecs/Raw/RafReader.cs | 114 ++++ src/Titano.Core/Codecs/Raw/RawDecoder.cs | 11 +- src/Titano.Core/Codecs/Raw/RawDeveloper.cs | 54 +- src/Titano.Core/Codecs/Raw/RawFrame.cs | 6 +- tests/Titano.Core.Tests/Raw/NativeRawTests.cs | 183 +++++++ .../Titano.Core.Tests/Raw/NativeRawWriters.cs | 485 ++++++++++++++++++ tests/Titano.Core.Tests/Raw/RawFuzzTests.cs | 92 ++++ 14 files changed, 1974 insertions(+), 24 deletions(-) create mode 100644 src/Titano.Core/Codecs/Raw/ArwReader.cs create mode 100644 src/Titano.Core/Codecs/Raw/CameraMatrices.cs create mode 100644 src/Titano.Core/Codecs/Raw/Cr2Reader.cs create mode 100644 src/Titano.Core/Codecs/Raw/NativeRaw.cs create mode 100644 src/Titano.Core/Codecs/Raw/NefReader.cs create mode 100644 src/Titano.Core/Codecs/Raw/PefReader.cs create mode 100644 src/Titano.Core/Codecs/Raw/RafReader.cs create mode 100644 tests/Titano.Core.Tests/Raw/NativeRawTests.cs create mode 100644 tests/Titano.Core.Tests/Raw/NativeRawWriters.cs create mode 100644 tests/Titano.Core.Tests/Raw/RawFuzzTests.cs diff --git a/src/Titano.Core/Codecs/Dng/DngReader.cs b/src/Titano.Core/Codecs/Dng/DngReader.cs index 786793d5..a56db315 100644 --- a/src/Titano.Core/Codecs/Dng/DngReader.cs +++ b/src/Titano.Core/Codecs/Dng/DngReader.cs @@ -37,6 +37,7 @@ internal static class DngReader var photometric = r.GetUInt(raw, TiffTags.PhotometricInterpretation); var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1; if (compression is not (1 or 7 or 8 or 34892)) throw new InvalidDataException($"DNG: compression {compression} is not supported"); + if (compression is 1 or 7) RequirePayload(r, raw, (long)width * height * spp); var floating = (r.GetUInt(raw, TiffTags.SampleFormat) ?? 1) == 3; var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 16); @@ -86,6 +87,16 @@ internal static class DngReader return frame; } + /// Uncompressed and lossless-JPEG data hold at least one bit per sample; checked before the raster is allocated + /// so a corrupted size cannot trigger a huge allocation. + private static void RequirePayload(TiffReader r, Ifd raw, long samples) + { + var counts = r.GetUInts(raw, raw.Has(TiffTags.TileByteCounts) ? TiffTags.TileByteCounts : TiffTags.StripByteCounts); + long total = 0; + foreach (var c in counts ?? []) total += c; + if (total * 8 < samples) throw new InvalidDataException("DNG: image data too short for the raster"); + } + /// First IFD with NewSubfileType 0 and a CFA/LinearRaw photometric: IFD0, its SubIFDs (two levels), the chain. private static Ifd? FindRawIfd(TiffReader r, IReadOnlyList chain) { diff --git a/src/Titano.Core/Codecs/Raw/ArwReader.cs b/src/Titano.Core/Codecs/Raw/ArwReader.cs new file mode 100644 index 00000000..f055db04 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/ArwReader.cs @@ -0,0 +1,136 @@ +using System.Buffers.Binary; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Sony ARW: the CFA SubIFD holds uncompressed 16-bit words (or packed samples) or ARW2 "cRAW" (Compression 32767 with +/// one byte per pixel): 16-pixel blocks of one colour storing an 11-bit maximum and minimum with their positions and +/// fourteen 7-bit deltas scaled by a shift, expanded through the tone curve of tag 0x7010 (dcraw +/// sony_arw2_load_raw). Black and white come from tags 0x7310/0x787F when present (14-bit scale), otherwise +/// 512 and the curve's top (cRAW) or 16383. As-shot white balance sits in the encrypted SR2 block, which is not read: ARW files develop with daylight +/// balance. ARW1 (DSLR-A100) and the lossless ARW 5.0 codec are not supported. +/// +internal static class ArwReader +{ + private const uint CompressionSony = 32767; + private const ushort ToneCurveTag = 0x7010; + private const ushort BlackLevelTag = 0x7310; + private const ushort WhiteLevelTag = 0x787F; + + public static RawFrame Read(Stream stream) + { + var r = TiffReader.Open(stream) ?? throw new InvalidDataException("ARW: missing TIFF header"); + var chain = r.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("ARW: no image directory"); + var ifd0 = chain[0]; + var raw = NefReader.FindCfa(r, ifd0) ?? throw new InvalidDataException("ARW: CFA image missing"); + var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0); + var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0); + var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1; + var (offset, length) = NefReader.Strip(r, raw); + var warnings = new List(); + var cfa = NativeRaw.TiffEpCfa(r, raw); + if (cfa is null) + { + cfa = CfaPattern.Bayer("RGGB"); + warnings.Add("ARW: CFA pattern missing; RGGB assumed"); + } + if (!cfa.IsBayer) throw new InvalidDataException("ARW: only Bayer sensors are supported"); + + RawLoader loader; + double black, white; + if (compression == CompressionSony && length == (long)width * height) + { + if (width < 32 || width % 32 != 0) throw new InvalidDataException("ARW: cRAW width must be a multiple of 32"); + var curve = ToneCurve(r, raw, ifd0); + loader = new Arw2Loader(offset, width, height, curve); + // Sensor saturation is the largest 11-bit code through the curve. + (black, white) = (512, curve[0x7FF << 1]); + } + else if (length >= (long)width * height * 2) + { + loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: r.LittleEndian); + (black, white) = (512, 16383); + } + else if (compression == 1 && bits is 12 or 14 && length >= ((long)width * bits + 7) / 8 * height) + { + loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false); + (black, white) = (128 << (bits - 12), (1 << bits) - 1); + } + else + { + throw new InvalidDataException($"ARW: compression {compression} with {length} bytes is not supported"); + } + + var blackLevel = IfdValue.UInts(r, raw, BlackLevelTag) is { Length: 4 } b + ? NativeRaw.Black2x2(cfa, [b[0], b[1], b[2], b[3]]) + : NativeRaw.Black(black); + if (IfdValue.UInts(r, raw, WhiteLevelTag) is { Length: > 0 } w) white = w.Max(); + return NativeRaw.Frame("managed-arw", width, height, cfa, new RawRect(0, 0, width, height), blackLevel, white, null, + (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings); + } + + /// Tone curve from the four breakpoints of tag 0x7010: slopes 1, 2, 4, 8, 16 between 0, the breakpoints and 4095. + private static ushort[] ToneCurve(TiffReader r, Ifd raw, Ifd ifd0) + { + Span knots = [0, 0, 0, 0, 0, 4095]; + if ((IfdValue.UInts(r, raw, ToneCurveTag) ?? IfdValue.UInts(r, ifd0, ToneCurveTag)) is { Length: >= 4 } t) + { + for (var i = 0; i < 4; i++) knots[i + 1] = (int)(t[i] >> 2 & 0xFFF); + } + var curve = new ushort[0x1000]; + for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i; + for (var i = 0; i < 5; i++) + { + for (var j = knots[i] + 1; j <= knots[i + 1] && j < curve.Length; j++) curve[j] = (ushort)(curve[j - 1] + (1 << i)); + } + return curve; + } + + private sealed class Arw2Loader(long offset, int width, int height, ushort[] curve) : RawLoader + { + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var data = NativeRaw.ReadPayload(stream, offset, (long)width * height); + var samples = new ushort[width * height]; + Parallel.For(0, height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, row => + { + // One spare byte: the last delta of a block is read as a 16-bit word that reaches one byte past it. + Span line = stackalloc byte[width + 2]; + line.Clear(); + data.AsSpan(row * width, width).CopyTo(line); + Span pix = stackalloc int[16]; + var dst = samples.AsSpan(row * width, width); + var dp = 0; + for (var col = 0; col < width - 30; dp += 16) + { + var val = BinaryPrimitives.ReadUInt32LittleEndian(line[dp..]); + int max = (int)(val & 0x7FF), min = (int)(val >> 11 & 0x7FF), imax = (int)(val >> 22 & 0xF), imin = (int)(val >> 26 & 0xF); + var sh = 0; + while (sh < 4 && 0x80 << sh <= max - min) sh++; + var bit = 30; + for (var i = 0; i < 16; i++) + { + if (i == imax) + { + pix[i] = max; + } + else if (i == imin) + { + pix[i] = min; + } + else + { + pix[i] = int.Min(((BinaryPrimitives.ReadUInt16LittleEndian(line[(dp + (bit >> 3))..]) >> (bit & 7) & 0x7F) << sh) + min, 0x7FF); + bit += 7; + } + } + for (var i = 0; i < 16; i++, col += 2) dst[col] = curve[pix[i] << 1]; + col -= (col & 1) != 0 ? 1 : 31; + } + }); + return new RawSamples(width, height, 1, samples, null); + } + } +} diff --git a/src/Titano.Core/Codecs/Raw/CameraMatrices.cs b/src/Titano.Core/Codecs/Raw/CameraMatrices.cs new file mode 100644 index 00000000..bc1967f1 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/CameraMatrices.cs @@ -0,0 +1,114 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Camera colour matrices (XYZ → camera, D65 calibration, values × 10 000) for bodies whose native RAW files Titano +/// develops, keyed by the normalised "Brand Model" name. The numbers are the public adobe_coeff table of Dave Coffin's +/// dcraw (public-domain origin, also carried by LibRaw), which reproduces the ColorMatrix2 values Adobe DNG Converter +/// writes for these cameras; they are data, not code. A body missing here is decoded through its embedded preview. +/// +internal static class CameraMatrices +{ + private static readonly Dictionary Table = Build(); + + /// Matrix for a normalised camera name (see ), or null. + public static Matrix3? Find(string? cameraName) + { + if (cameraName is null || !Table.TryGetValue(cameraName, out var m)) return null; + return new Matrix3(m[0] / 1e4, m[1] / 1e4, m[2] / 1e4, m[3] / 1e4, m[4] / 1e4, m[5] / 1e4, m[6] / 1e4, m[7] / 1e4, m[8] / 1e4); + } + + /// Normalised names with an entry (for diagnostics and tests). + public static IEnumerable Names => Table.Keys; + + private static Dictionary Build() + { + var t = new Dictionary(StringComparer.OrdinalIgnoreCase); + void Add(short[] m, params string[] names) + { + foreach (var n in names) t[n] = m; + } + + // Canon (CR2). + Add([6347, -479, -972, -8297, 15954, 2480, -1968, 2131, 7649], "Canon EOS 5D"); + Add([4716, 603, -830, -7798, 15474, 2480, -1496, 1937, 6651], "Canon EOS 5D Mark II"); + Add([6722, -635, -963, -4287, 12460, 2028, -908, 2162, 5668], "Canon EOS 5D Mark III"); + Add([6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348], "Canon EOS 5D Mark IV"); + Add([6250, -711, -808, -5153, 12794, 2636, -1249, 2198, 5610], "Canon EOS 5DS", "Canon EOS 5DS R"); + Add([7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758], "Canon EOS 6D", "Canon EOS 70D"); + Add([6875, -970, -932, -4691, 12459, 2501, -874, 1953, 5809], "Canon EOS 6D Mark II"); + Add([6844, -996, -856, -3876, 11761, 2396, -593, 1772, 6198], "Canon EOS 7D"); + Add([7268, -1082, -969, -4186, 11839, 2663, -825, 2029, 5839], "Canon EOS 7D Mark II"); + Add([6071, -747, -856, -7653, 15365, 2441, -2025, 2553, 7315], "Canon EOS 40D"); + Add([4920, 616, -593, -6493, 13964, 2784, -1774, 3178, 7005], "Canon EOS 50D"); + Add([6719, -994, -925, -4408, 12426, 2211, -887, 2129, 6051], "Canon EOS 60D"); + Add([7457, -671, -937, -4849, 12495, 2643, -1213, 2354, 5492], "Canon EOS 80D"); + Add([6941, -1164, -857, -3825, 11597, 2534, -416, 1540, 6039], "Canon EOS 550D", "Canon EOS Rebel T2i", "Canon EOS Kiss X4"); + Add([6461, -907, -882, -4300, 12184, 2378, -819, 1944, 5931], "Canon EOS 600D", "Canon EOS Rebel T3i", "Canon EOS Kiss X5", + "Canon EOS 1200D", "Canon EOS Rebel T5", "Canon EOS Kiss X70"); + Add([6602, -841, -939, -4472, 12458, 2247, -975, 2039, 6148], "Canon EOS 650D", "Canon EOS Rebel T4i", "Canon EOS Kiss X6i", + "Canon EOS 700D", "Canon EOS Rebel T5i", "Canon EOS Kiss X7i", "Canon EOS 100D", "Canon EOS Rebel SL1", "Canon EOS Kiss X7", "Canon EOS M"); + Add([6362, -823, -847, -4426, 12109, 2616, -743, 1857, 5635], "Canon EOS 750D", "Canon EOS Rebel T6i", "Canon EOS Kiss X8i", + "Canon EOS 760D", "Canon EOS Rebel T6s", "Canon EOS 8000D"); + Add([7377, -742, -998, -4235, 11981, 2549, -673, 1918, 5538], "Canon EOS 77D", "Canon EOS 9000D", "Canon EOS 800D", "Canon EOS Rebel T7i", "Canon EOS Kiss X9i"); + Add([6847, -614, -1014, -4669, 12737, 2139, -1197, 2488, 6846], "Canon EOS-1D X"); + Add([7596, -978, -967, -4808, 12571, 2503, -1398, 2567, 5752], "Canon EOS-1D X Mark II"); + + // Nikon (NEF). + Add([7309, -1403, -519, -8474, 16008, 2622, -2434, 2826, 8064], "Nikon D90"); + Add([9030, -1992, -715, -8465, 16302, 2255, -2689, 3217, 8069], "Nikon D300", "Nikon D300S"); + Add([8139, -2171, -663, -8747, 16541, 2295, -1925, 2008, 8093], "Nikon D3", "Nikon D700"); + Add([8828, -2406, -694, -4874, 12603, 2541, -660, 1509, 7587], "Nikon D3S"); + Add([7171, -1986, -648, -8085, 15555, 2718, -2170, 2512, 7457], "Nikon D3X"); + Add([8598, -2848, -857, -5618, 13606, 2195, -1002, 1773, 7137], "Nikon D4", "Nikon Df"); + Add([9200, -3522, -992, -5755, 13803, 2117, -753, 1486, 6338], "Nikon D5"); + Add([7911, -2167, -813, -5327, 13150, 2408, -1288, 2483, 7968], "Nikon D3100"); + Add([7013, -1408, -635, -5268, 12902, 2640, -1470, 2801, 7379], "Nikon D3200"); + Add([6988, -1384, -714, -5631, 13410, 2447, -1485, 2204, 7318], "Nikon D3300", "Nikon D3400", "Nikon D5300"); + Add([8198, -2239, -724, -4871, 12389, 2798, -1043, 2050, 7181], "Nikon D5100", "Nikon D7000"); + Add([8322, -3112, -1047, -6367, 14342, 2179, -988, 1638, 6394], "Nikon D5200", "Nikon D7100", "Nikon D7200"); + Add([8821, -2938, -785, -4178, 12142, 2287, -824, 1651, 6860], "Nikon D5500", "Nikon D5600"); + Add([8813, -3210, -1036, -4703, 12868, 2021, -1054, 1940, 6129], "Nikon D500", "Nikon D7500"); + Add([8178, -2245, -609, -4857, 12394, 2776, -1207, 2086, 7298], "Nikon D600", "Nikon D610"); + Add([9020, -2890, -715, -4535, 12436, 2348, -934, 1919, 7086], "Nikon D750"); + Add([7866, -2108, -555, -4869, 12483, 2681, -1176, 2069, 7501], "Nikon D800", "Nikon D800E"); + Add([9369, -3195, -791, -4488, 12430, 2301, -893, 1796, 6872], "Nikon D810"); + Add([10405, -3755, -1270, -5461, 13787, 1793, -1040, 2015, 6785], "Nikon D850", "Nikon Z 7"); + Add([8210, -2534, -683, -5355, 13338, 2212, -1143, 1929, 6464], "Nikon Z 6"); + + // Sony (ARW). + Add([5271, -712, -347, -6153, 13653, 2763, -1601, 2366, 7242], "Sony ILCE-7", "Sony ILCE-7M2"); + Add([7374, -2389, -551, -5435, 13162, 2519, -1006, 1795, 6552], "Sony ILCE-7M3"); + Add([4913, -541, -202, -6130, 13513, 2906, -1564, 2151, 7183], "Sony ILCE-7R"); + Add([6629, -1900, -483, -4618, 12349, 2550, -622, 1381, 6514], "Sony ILCE-7RM2"); + Add([6640, -1847, -503, -5238, 13010, 2474, -993, 1673, 6527], "Sony ILCE-7RM3"); + Add([5838, -1430, -246, -3497, 11477, 2297, -748, 1885, 5778], "Sony ILCE-7S", "Sony ILCE-7SM2"); + Add([5991, -1456, -455, -4764, 12135, 2980, -707, 1425, 6701], "Sony ILCE-6000", "Sony ILCE-5100", "Sony SLT-A57"); + Add([5973, -1695, -419, -3826, 11797, 2293, -639, 1398, 5789], "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-6400"); + Add([5491, -1192, -363, -4951, 12342, 2948, -911, 1722, 7192], "Sony NEX-7", "Sony SLT-A65", "Sony SLT-A77"); + Add([8651, -2754, -1057, -3464, 12207, 1373, -568, 1398, 4434], "Sony DSC-RX100"); + Add([6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181], "Sony DSC-RX100M2"); + + // Pentax (PEF). + Add([9566, -2863, -803, -7170, 15172, 2112, -818, 803, 9705], "Pentax K10D"); + Add([9427, -2714, -868, -7493, 16092, 1373, -2199, 3264, 7180], "Pentax K20D"); + Add([9142, -2947, -678, -8648, 16967, 1663, -2224, 2898, 8615], "Pentax K-7"); + Add([8713, -2833, -743, -4342, 11900, 2772, -722, 1543, 6247], "Pentax K-5"); + Add([8170, -2725, -639, -4440, 12017, 2744, -771, 1465, 6599], "Pentax K-5 II", "Pentax K-5 II s"); + Add([8843, -2837, -625, -5025, 12644, 2668, -411, 1234, 7410], "Pentax K-x"); + Add([9895, -3077, -850, -5304, 13035, 2521, -883, 1768, 6936], "Pentax K-r"); + Add([8710, -2632, -1167, -3995, 12301, 1881, -981, 1719, 6535], "Pentax K-30"); + Add([7415, -2052, -721, -5186, 12788, 2682, -1446, 2157, 6773], "Pentax K-3"); + Add([8596, -2981, -639, -4202, 12046, 2431, -685, 1424, 6122], "Pentax K-1"); + + // Fujifilm (RAF). + Add([10413, -3996, -993, -3721, 11640, 2361, -733, 1540, 6011], "Fujifilm X-E1", "Fujifilm X-Pro1", "Fujifilm X-M1"); + Add([10592, -4262, -1008, -3514, 11355, 2465, -870, 2025, 6386], "Fujifilm X100S", "Fujifilm X20"); + Add([8458, -2451, -855, -4597, 12447, 2407, -1475, 2482, 6526], "Fujifilm X-T1", "Fujifilm X-E2", "Fujifilm X-T10", "Fujifilm X100T", "Fujifilm X30"); + Add([11434, -4948, -1210, -3746, 12042, 1903, -666, 1479, 5235], "Fujifilm X-T2", "Fujifilm X-Pro2", "Fujifilm X-T20", "Fujifilm X100F", "Fujifilm X-E3"); + Add([13426, -6334, -1177, -4244, 12136, 2371, -580, 1303, 5980], "Fujifilm X-T3", "Fujifilm X-T30"); + Add([11086, -4555, -839, -3512, 11310, 2517, -815, 1341, 5940], "Fujifilm X-A1"); + return t; + } +} diff --git a/src/Titano.Core/Codecs/Raw/Cr2Reader.cs b/src/Titano.Core/Codecs/Raw/Cr2Reader.cs new file mode 100644 index 00000000..25684416 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/Cr2Reader.cs @@ -0,0 +1,161 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Canon CR2: the fourth IFD holds one lossless-JPEG (SOF3) strip whose samples are laid out in vertical slices +/// (tag 0xC640 cr2_slice = count, slice width, last slice width; dcraw lossless_jpeg_load_raw). The MakerNote +/// supplies SensorInfo (0x00E0: sensor borders, i.e. the active area) and ColorData (0x4001: as-shot RGGB levels at a +/// version-dependent offset). Black is measured on the masked left columns. sRAW/mRAW (subsampled YCbCr) is not +/// supported and falls back to the preview. +/// +internal static class Cr2Reader +{ + private const ushort SliceTag = 0xC640; + private const ushort SensorInfoTag = 0x00E0; + private const ushort ColorDataTag = 0x4001; + private const int RawIfdIndex = 3; + private const int HeaderProbeBytes = 64 * 1024; + + public static RawFrame Read(Stream stream) + { + var r = TiffReader.Open(stream) ?? throw new InvalidDataException("CR2: missing TIFF header"); + var chain = r.ReadChain(); + if (chain.Count <= RawIfdIndex) throw new InvalidDataException("CR2: raw IFD missing"); + var ifd0 = chain[0]; + var raw = chain[RawIfdIndex]; + var offset = r.GetUInt(raw, TiffTags.StripOffsets) ?? throw new InvalidDataException("CR2: raw strip missing"); + var length = r.GetUInt(raw, TiffTags.StripByteCounts) ?? throw new InvalidDataException("CR2: raw strip length missing"); + if (offset + (long)length > stream.Length || length < 16) throw new InvalidDataException("CR2: raw strip outside the file"); + + var head = NativeRaw.ReadPayload(stream, offset, long.Min(length, HeaderProbeBytes)); + JpegInfo info; + try + { + info = JpegDecoder.ReadInfo(head); + } + catch (InvalidDataException ex) + { + throw new InvalidDataException("CR2: raw strip is not a JPEG: " + ex.Message); + } + if (info.Process != JpegProcess.Lossless) throw new InvalidDataException("CR2: raw strip is not lossless JPEG"); + if (info.Sampling.Any(s => s != (1, 1))) throw new InvalidDataException("CR2: sRAW/mRAW is not supported"); + var rawWidth = (long)info.Width * info.Components; + var slices = IfdValue.UInts(r, raw, SliceTag); + if (slices is [var count, var sliceWidth, var lastWidth, ..] && count + sliceWidth + lastWidth > 0) + { + if (count * (long)sliceWidth + lastWidth != rawWidth || lastWidth == 0 || count > 0 && sliceWidth == 0) + throw new InvalidDataException("CR2: slice layout does not match the JPEG frame"); + } + else + { + slices = null; + } + var (width, height) = NativeRaw.Size(rawWidth, info.Height); + NativeRaw.RequireBits(length, (long)width * height); + + var make = r.GetString(ifd0, TiffTags.Make); + var model = r.GetString(ifd0, TiffTags.Model); + var warnings = new List(); + var makerNote = MakerNote(r, ifd0); + var active = new RawRect(0, 0, width, height); + if (makerNote is not null && IfdValue.UInts(r, makerNote, SensorInfoTag) is { Length: >= 9 } sensor) + { + // SensorInfo borders are inclusive pixel indices. + var area = new RawRect((int)sensor[5], (int)sensor[6], (int)sensor[7] + 1, (int)sensor[8] + 1).Intersect(active); + if (!area.IsEmpty && sensor[7] > sensor[5] && sensor[8] > sensor[6]) active = area; + else warnings.Add("CR2: SensorInfo borders ignored"); + } + else + { + warnings.Add("CR2: SensorInfo missing; full raster used"); + } + var cfa = CfaPattern.Bayer("RGGB").Shift(active.Left, active.Top); + var white = (1 << info.Precision) - 1; + var loader = new Cr2Loader(offset, length, width, height, slices, active); + return NativeRaw.Frame("managed-cr2", width, height, cfa, active, NativeRaw.Black(0), white, + Multipliers(r, makerNote), (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), make, model, loader, warnings); + } + + /// Canon MakerNote: a plain IFD inside the Exif IFD, offsets relative to the TIFF header. + private static Ifd? MakerNote(TiffReader r, Ifd ifd0) + { + if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var note) || note.IsInline) return null; + return r.ReadIfd(note.ValueOffset); + } + + /// As-shot RGGB levels from ColorData; the offset (in 16-bit words) depends on the record's length (dcraw). + private static Vector3D? Multipliers(TiffReader r, Ifd? makerNote) + { + if (makerNote is null || !makerNote.Entries.TryGetValue(ColorDataTag, out var e) || e.Count <= 500 || e.Count > 8192) return null; + var data = r.GetUInts(e); + if (data is null) return null; + var at = data.Length switch { 582 => 25, 653 => 34, 5120 => 71, _ => 63 }; + if (at + 4 > data.Length) return null; + double red = data[at], green = (data[at + 1] + data[at + 2]) / 2.0, blue = data[at + 3]; + return red > 0 && green > 0 && blue > 0 ? new Vector3D(red / green, 1, blue / green) : null; + } + + /// Decodes the strip, places samples by slice, and measures black on the masked columns left of the active area. + private sealed class Cr2Loader(long offset, long length, int width, int height, uint[]? slices, RawRect active) : RawLoader + { + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var data = NativeRaw.ReadPayload(stream, offset, length); + var jpeg = JpegLosslessDecoder.Decode(data); + var src = jpeg.Samples; + if ((long)jpeg.Width * jpeg.Components != width || jpeg.Height != height) throw new InvalidDataException("CR2: JPEG frame changed size"); + cancellationToken.ThrowIfCancellationRequested(); + ushort[] samples; + if (slices is null) + { + samples = src; + } + else + { + samples = new ushort[src.Length]; + int count = (int)slices[0], sliceWidth = (int)slices[1], lastWidth = (int)slices[2]; + var perSlice = (long)sliceWidth * height; + Parallel.For(0, count + 1, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, s => + { + var w = s < count ? sliceWidth : lastWidth; + var start = s * perSlice; + for (var row = 0; row < height; row++) + { + src.AsSpan((int)(start + (long)row * w), w).CopyTo(samples.AsSpan(row * width + s * sliceWidth, w)); + } + }); + } + var result = new RawSamples(width, height, 1, samples, null); + result.MeasuredBlack = MaskedBlack(samples, result.Warnings); + return result; + } + + /// Per-CFA-colour mean of the masked columns (4 px away from both edges of the mask). + private RawBlackLevel MaskedBlack(ushort[] samples, List warnings) + { + if (active.Left < 12) + { + warnings.Add("CR2: no masked columns; black level 0 assumed"); + return NativeRaw.Black(0); + } + Span sum = stackalloc double[4]; + Span n = stackalloc long[4]; + for (var y = active.Top; y < active.Bottom; y++) + { + for (var x = 4; x < active.Left - 4; x++) + { + // Cell index relative to the active area's CFA phase. + var cell = ((y - active.Top) & 1) * 2 + ((x - active.Left) & 1); + sum[cell] += samples[y * width + x]; + n[cell]++; + } + } + var values = new float[4]; + for (var i = 0; i < 4; i++) values[i] = n[i] > 0 ? (float)(sum[i] / n[i]) : 0f; + return new RawBlackLevel(2, 2, values, null, null); + } + } +} diff --git a/src/Titano.Core/Codecs/Raw/NativeRaw.cs b/src/Titano.Core/Codecs/Raw/NativeRaw.cs new file mode 100644 index 00000000..342d110b --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/NativeRaw.cs @@ -0,0 +1,251 @@ +using Titano.Core.Codecs.Dng; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// Shared pieces of the native (non-DNG) RAW readers: camera naming, frame construction, MakerNote access and +/// bounded payload reads. +internal static class NativeRaw +{ + /// Largest raw raster accepted (256 megapixels). + public const long MaxPixels = 1L << 28; + + /// "Brand Model" as keyed in : "NIKON CORPORATION" + "NIKON D850" → "Nikon D850". + public static string? CameraName(string? make, string? model) + { + if (string.IsNullOrWhiteSpace(model)) return null; + var m = make?.Trim() ?? string.Empty; + string brand; + if (m.StartsWith("Canon", StringComparison.OrdinalIgnoreCase)) brand = "Canon"; + else if (m.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase)) brand = "Nikon"; + else if (m.StartsWith("SONY", StringComparison.OrdinalIgnoreCase)) brand = "Sony"; + else if (m.StartsWith("PENTAX", StringComparison.OrdinalIgnoreCase) || m.StartsWith("RICOH", StringComparison.OrdinalIgnoreCase) || m.StartsWith("ASAHI", StringComparison.OrdinalIgnoreCase)) brand = "Pentax"; + else if (m.StartsWith("FUJIFILM", StringComparison.OrdinalIgnoreCase)) brand = "Fujifilm"; + else brand = m.Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty; + var words = model.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); + if (words.Count > 1 && (words[0].Equals(brand, StringComparison.OrdinalIgnoreCase) || words[0].Equals("PENTAX", StringComparison.OrdinalIgnoreCase))) + words.RemoveAt(0); + return words.Count == 0 ? null : $"{brand} {string.Join(' ', words)}"; + } + + /// Builds the frame of a native RAW developed with a tabulated D65 matrix. + /// As-shot white-balance multipliers (R, G, B); null falls back to daylight. + /// The body has no colour matrix (the caller falls back to the preview). + public static RawFrame Frame(string decoder, int width, int height, CfaPattern cfa, RawRect active, RawBlackLevel black, double white, + Vector3D? multipliers, int orientation, string? make, string? model, RawLoader loader, IEnumerable warnings) + { + var name = CameraName(make, model); + var matrix = CameraMatrices.Find(name) ?? throw new InvalidDataException($"RAW: no colour matrix for {name ?? "unknown camera"}"); + if (active.IsEmpty || active.Left < 0 || active.Top < 0 || active.Right > width || active.Bottom > height) + throw new InvalidDataException("RAW: sensor area outside the raster"); + Vector3D? neutral = multipliers is { } m && m.X > 0 && m.Y > 0 && m.Z > 0 && double.IsFinite(m.X + m.Y + m.Z) + ? new Vector3D(1 / m.X, 1 / m.Y, 1 / m.Z) + : null; + var frame = new RawFrame + { + Decoder = decoder, + Width = width, + Height = height, + Cfa = cfa, + ActiveArea = active, + Black = black, + White = [white], + DetectSaturation = true, + Color = new DngColorProfile + { + ColorMatrix1 = matrix, + CalibrationIlluminant1 = 21, + AsShotNeutral = neutral, + AsShotWhite = neutral is null ? Chromaticity.D65 : null, + }, + Orientation = orientation is >= 1 and <= 8 ? orientation : 1, + Make = make, + Model = model, + Loader = loader, + }; + frame.Warnings.AddRange(warnings); + if (neutral is null) frame.Warnings.Add("RAW: as-shot white balance unavailable; daylight assumed"); + return frame; + } + + /// Validated raster size. + public static (int Width, int Height) Size(long width, long height) + { + if (width <= 0 || height <= 0 || width * height > MaxPixels) throw new InvalidDataException($"RAW: unsupported raster size {width}x{height}"); + return ((int)width, (int)height); + } + + /// Rejects entropy-coded payloads too short to hold one bit per sample, before the raster is allocated (a + /// corrupted size must not trigger a huge allocation). + public static void RequireBits(long payloadBytes, long samples) + { + if (payloadBytes * 8 < samples) throw new InvalidDataException("RAW: compressed data too short for the raster"); + } + + /// Uniform black level for every CFA cell. + public static RawBlackLevel Black(double value) => new(1, 1, [(float)value], null, null); + + /// Black level of a 2×2 CFA from values in R, G1, G2, B order, re-anchored at the active area. + public static RawBlackLevel Black2x2(CfaPattern cfa, ReadOnlySpan rggb) + { + var values = new float[4]; + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 2; x++) + { + var c = cfa.ColorAt(x, y); + // The second green of a 2×2 cell is the one sharing a row with blue. + var index = c == 0 ? 0 : c == 2 ? 3 : cfa.ColorAt(x ^ 1, y) == 0 ? 1 : 2; + values[y * 2 + x] = (float)rggb[index]; + } + } + return new RawBlackLevel(2, 2, values, null, null); + } + + /// Exif IFD of IFD0, or null. + public static Ifd? ExifIfd(TiffReader r, Ifd ifd0) => r.GetUInt(ifd0, TiffTags.ExifIfd) is { } offset and > 0 ? r.ReadIfd(offset) : null; + + /// Reads bytes at an absolute position (bounded by the stream). + public static byte[] ReadPayload(Stream stream, long position, long length) + { + if (position < 0 || length <= 0 || length > int.MaxValue || position > stream.Length - length) + throw new InvalidDataException("RAW: image data outside the file"); + var data = new byte[length]; + stream.Position = position; + stream.ReadExactly(data); + return data; + } + + /// CFA pattern from TIFF/EP CFARepeatPatternDim/CFAPattern tags (as written in NEF/ARW/PEF raw IFDs), or null. + public static CfaPattern? TiffEpCfa(TiffReader r, Ifd ifd) + { + if (IfdValue.UInts(r, ifd, TiffTags.CfaPattern) is not { } pattern) return null; + var dim = IfdValue.UInts(r, ifd, TiffTags.CfaRepeatPatternDim) ?? [2, 2]; + if (dim.Length < 2 || dim[0] is < 1 or > CfaPattern.MaxSize || dim[1] is < 1 or > CfaPattern.MaxSize || pattern.Length < dim[0] * dim[1]) return null; + var colors = new byte[dim[0] * dim[1]]; + for (var i = 0; i < colors.Length; i++) + { + if (pattern[i] > 2) return null; + colors[i] = (byte)pattern[i]; + } + try + { + return new CfaPattern((int)dim[1], (int)dim[0], colors); + } + catch (InvalidDataException) + { + return null; + } + } +} + +/// Uncompressed raw payloads: 16-bit words (either byte order) or MSB-first packed samples (TIFF convention). +internal sealed class PlainRawLoader(long offset, long length, int width, int height, int bits, bool words, bool littleEndian) : RawLoader +{ + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var rowBytes = words ? width * 2L : (width * (long)bits + 7) / 8; + if (rowBytes * height > length) throw new InvalidDataException("RAW: image data truncated"); + var data = NativeRaw.ReadPayload(stream, offset, rowBytes * height); + var samples = new ushort[width * height]; + var mask = (1 << bits) - 1; + Parallel.For(0, height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, y => + { + var row = data.AsSpan((int)(y * rowBytes), (int)rowBytes); + var dst = samples.AsSpan(y * width, width); + if (words) + { + for (var x = 0; x < width; x++) + dst[x] = (ushort)((littleEndian ? row[2 * x] | row[2 * x + 1] << 8 : row[2 * x] << 8 | row[2 * x + 1]) & mask); + return; + } + long bit = 0; + for (var x = 0; x < width; x++, bit += bits) + { + var b = (int)(bit >> 3); + // Up to 16 bits spanning at most three bytes. + var window = row[b] << 16 | (b + 1 < row.Length ? row[b + 1] << 8 : 0) | (b + 2 < row.Length ? row[b + 2] : 0); + dst[x] = (ushort)(window >> (24 - (int)(bit & 7) - bits) & mask); + } + }); + return new RawSamples(width, height, 1, samples, null); + } +} + +/// MSB-first bit reader without byte stuffing (Nikon and Pentax Huffman streams). Reading past the end yields +/// zero bits and sets . +internal ref struct MsbBitReader(ReadOnlySpan data) +{ + private readonly ReadOnlySpan _data = data; + private int _pos; + private ulong _buffer; + private int _bits; + + public readonly bool Overrun => _pos > _data.Length + 8; + + /// Next bits (n ≤ 32) without consuming them. + public uint Peek(int n) + { + if (n == 0) return 0; + while (_bits < n) + { + _buffer = _buffer << 8 | (_pos < _data.Length ? _data[_pos] : 0u); + _pos++; + _bits += 8; + } + return (uint)(_buffer >> (_bits - n)) & (uint)((1UL << n) - 1); + } + + public void Skip(int n) => _bits -= n; + + public uint Read(int n) + { + var v = Peek(n); + _bits -= n; + return v; + } +} + +/// Huffman lookup in dcraw's make_decoder layout: code-length counts for lengths 1–16 followed by symbols, +/// codes assigned canonically; each table entry is (length << 8 | symbol) indexed by the next bits. +internal sealed class HuffmanTable +{ + private readonly ushort[] _lut; + + public HuffmanTable(ReadOnlySpan countsAndSymbols) + { + var bits = 16; + while (bits > 0 && countsAndSymbols[bits - 1] == 0) bits--; + if (bits == 0) throw new InvalidDataException("RAW: empty Huffman table"); + Bits = bits; + _lut = new ushort[1 << bits]; + var h = 0; + var symbol = 16; + for (var len = 1; len <= bits; len++) + { + for (var i = 0; i < countsAndSymbols[len - 1]; i++, symbol++) + { + var value = symbol < countsAndSymbols.Length ? countsAndSymbols[symbol] : (byte)0; + for (var j = 0; j < 1 << (bits - len) && h < _lut.Length; j++) _lut[h++] = (ushort)(len << 8 | value); + } + } + } + + /// Wraps a prebuilt lookup (Pentax tables). + public HuffmanTable(ushort[] lut, int bits) + { + _lut = lut; + Bits = bits; + } + + public int Bits { get; } + + /// Decodes one symbol. + public int Decode(ref MsbBitReader reader) + { + var entry = _lut[reader.Peek(Bits)]; + reader.Skip(entry >> 8); + return entry & 0xFF; + } +} diff --git a/src/Titano.Core/Codecs/Raw/NefReader.cs b/src/Titano.Core/Codecs/Raw/NefReader.cs new file mode 100644 index 00000000..e42d8fc5 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/NefReader.cs @@ -0,0 +1,231 @@ +using System.Buffers.Binary; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Nikon NEF: the CFA SubIFD is uncompressed (16-bit words or MSB-packed samples) or Nikon-compressed (Compression +/// 34713): lossy type 1, lossless and lossy type 2 including the "after split" variant, decoded as dcraw's +/// nikon_load_raw does from the MakerNote decode info (0x0096: version, vertical predictors, tone curve, split row) +/// with Nikon's six Huffman trees and two-column horizontal prediction. White balance comes from MakerNote 0x000C, black +/// from 0x003D. Packed 12-bit "uncompressed" variants, YUV NEFs and the high-efficiency (TicoRAW) codec are not supported +/// and fall back to the preview. +/// +internal static class NefReader +{ + private const ushort WbLevelsTag = 0x000C; + private const ushort BlackLevelTag = 0x003D; + private const ushort DecodeInfoTag = 0x0096; + private const uint CompressionNikon = 34713; + + /// Nikon Huffman trees (dcraw nikon_tree): 16 code-length counts, then the symbols (len | shift << 4). + internal static readonly byte[][] Trees = + [ + [0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12, 0, 0, 0], + [0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12, 0, 0], + [0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12, 0, 0, 0], + [0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14, 0], + [0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14, 0], + [0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14, 0], + ]; + + public static RawFrame Read(Stream stream) + { + var r = TiffReader.Open(stream) ?? throw new InvalidDataException("NEF: missing TIFF header"); + var chain = r.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("NEF: no image directory"); + var ifd0 = chain[0]; + var raw = FindCfa(r, ifd0) ?? throw new InvalidDataException("NEF: CFA image missing"); + var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0); + var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0); + if (bits is not (12 or 14)) throw new InvalidDataException($"NEF: {bits}-bit data is not supported"); + var (offset, length) = Strip(r, raw); + var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1; + var note = MakerNote(stream, r, ifd0); + var warnings = new List(); + var cfa = NativeRaw.TiffEpCfa(r, raw); + if (cfa is null) + { + cfa = CfaPattern.Bayer("RGGB"); + warnings.Add("NEF: CFA pattern missing; RGGB assumed"); + } + if (!cfa.IsBayer) throw new InvalidDataException("NEF: only Bayer sensors are supported"); + + RawLoader loader; + double white = (1 << bits) - 1; + if (compression == CompressionNikon && length != (long)width * height * 2) + { + if (note is not { } mn || !mn.Ifd.Entries.TryGetValue(DecodeInfoTag, out var meta) || mn.Reader.ReadBytes(meta) is not { } info) + throw new InvalidDataException("NEF: compressed data without decode information"); + NativeRaw.RequireBits(length, (long)width * height); + var decode = DecodeInfo.Parse(info, mn.Reader.LittleEndian, bits); + white = decode.White; + loader = new NikonHuffmanLoader(offset, length, width, height, decode); + } + else if (compression is CompressionNikon or 1 && length >= (long)width * height * 2) + { + // Nikon writes unpacked "compressed" data big-endian; plain uncompressed follows the TIFF byte order. + loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: compression == 1 && r.LittleEndian); + } + else if (compression == 1 && length >= ((long)width * bits + 7) / 8 * height) + { + loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false); + } + else + { + throw new InvalidDataException($"NEF: compression {compression} with {length} bytes is not supported"); + } + + var black = NativeRaw.Black(0); + if (note is { } n && IfdValue.UInts(n.Reader, n.Ifd, BlackLevelTag) is { Length: 4 } b) + { + // Stored on a 14-bit scale whatever the bit depth. + black = NativeRaw.Black2x2(cfa, [b[0] >> (14 - bits), b[1] >> (14 - bits), b[2] >> (14 - bits), b[3] >> (14 - bits)]); + } + Vector3D? multipliers = note is { } w && IfdValue.Doubles(w.Reader, w.Ifd, WbLevelsTag, 2) is [var red, var blue, ..] ? new Vector3D(red, 1, blue) : null; + return NativeRaw.Frame("managed-nef", width, height, cfa, new RawRect(0, 0, width, height), black, white, multipliers, + (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings); + } + + /// The full-resolution CFA IFD: IFD0 or one of its SubIFDs. + internal static Ifd? FindCfa(TiffReader r, Ifd ifd0) + { + bool IsRaw(Ifd ifd) => (r.GetUInt(ifd, TiffTags.NewSubfileType) ?? 0) == 0 && r.GetUInt(ifd, TiffTags.PhotometricInterpretation) == 32803; + if (IsRaw(ifd0)) return ifd0; + if (!ifd0.Entries.TryGetValue(TiffTags.SubIfds, out var sub) || sub.Count > 16) return null; + foreach (var offset in r.GetUInts(sub) ?? []) + { + if (r.ReadIfd(offset) is { } child && IsRaw(child)) return child; + } + return null; + } + + /// Absolute position and length of the image data (several strips must be contiguous). + internal static (long Offset, long Length) Strip(TiffReader r, Ifd ifd) + { + var offsets = IfdValue.UInts(r, ifd, TiffTags.StripOffsets) ?? r.GetUInts(ifd, TiffTags.StripOffsets); + var counts = IfdValue.UInts(r, ifd, TiffTags.StripByteCounts) ?? r.GetUInts(ifd, TiffTags.StripByteCounts); + if (offsets is not { Length: > 0 } || counts is null || counts.Length < offsets.Length) throw new InvalidDataException("RAW: strip offsets missing"); + long length = 0; + for (var i = 0; i < offsets.Length; i++) + { + if (offsets[i] != offsets[0] + length) throw new InvalidDataException("RAW: non-contiguous strips are not supported"); + length += counts[i]; + } + var offset = r.Base + offsets[0]; + if (offset + length > r.StreamLength) throw new InvalidDataException("RAW: image data outside the file"); + return (offset, length); + } + + /// Nikon type-3 MakerNote: "Nikon\0", version, then an embedded TIFF header 10 bytes in. + private static (TiffReader Reader, Ifd Ifd)? MakerNote(Stream stream, TiffReader r, Ifd ifd0) + { + if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var e) || e.IsInline || e.Count < 18) return null; + var start = e.ValuePosition(r.Base); + var head = r.ReadRelative(start - r.Base, 6); + if (head is null || !head.AsSpan().SequenceEqual("Nikon\0"u8)) return null; + var reader = TiffReader.Open(stream, start + 10); + return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? (reader, ifd) : null; + } + + /// Parsed MakerNote 0x0096: Huffman tree, initial vertical predictors, tone curve and split row. + internal sealed record DecodeInfo(int Tree, ushort[] Predictors, ushort[] Curve, int Split, double White) + { + public static DecodeInfo Parse(byte[] meta, bool littleEndian, int bits) + { + if (meta.Length < 12) throw new InvalidDataException("NEF: decode information truncated"); + var pos = 0; + ushort U16() + { + if (pos + 2 > meta.Length) throw new InvalidDataException("NEF: decode information truncated"); + var v = littleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(meta.AsSpan(pos)) : BinaryPrimitives.ReadUInt16BigEndian(meta.AsSpan(pos)); + pos += 2; + return v; + } + int ver0 = meta[0], ver1 = meta[1]; + pos = ver0 == 0x49 || ver1 == 0x58 ? 2 + 2110 : 2; + var tree = (ver0 == 0x46 ? 2 : 0) + (bits == 14 ? 3 : 0); + ushort[] predictors = [U16(), U16(), U16(), U16()]; + var max = 1 << bits & 0x7FFF; + var curve = new ushort[0x10000]; + for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i; + var size = U16(); + var step = size > 1 ? max / (size - 1) : 0; + var split = 0; + var top = max; + if (ver0 == 0x44 && ver1 == 0x20 && step > 0) + { + // Lossy type 2: curve sampled every 'step' codes, linearly interpolated; split row at offset 562. + for (var i = 0; i < size; i++) curve[int.Min(i * step, curve.Length - 1)] = U16(); + for (var i = 0; i < max; i++) + { + var k = i % step; + var a = i - k; + curve[i] = (ushort)((curve[a] * (step - k) + curve[int.Min(a + step, curve.Length - 1)] * k) / step); + } + if (meta.Length >= 564) + { + pos = 562; + split = U16(); + } + } + else if (ver0 != 0x46 && size <= 0x4001) + { + // Lossy type 1: the curve is stored in full. + for (var i = 0; i < size; i++) curve[i] = U16(); + top = size; + } + double white = 0; + for (var i = 0; i < int.Max(top, 1); i++) white = double.Max(white, curve[i]); + return new DecodeInfo(tree, predictors, curve, split, white); + } + } + + /// dcraw nikon_load_raw. + private sealed class NikonHuffmanLoader(long offset, long length, int width, int height, DecodeInfo info) : RawLoader + { + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var data = NativeRaw.ReadPayload(stream, offset, length); + var samples = new ushort[width * height]; + var huff = new HuffmanTable(Trees[info.Tree]); + var reader = new MsbBitReader(data); + Span vpred = stackalloc ushort[4]; + info.Predictors.CopyTo(vpred); + Span hpred = stackalloc ushort[2]; + var curve = info.Curve; + for (var row = 0; row < height; row++) + { + if (info.Split > 0 && row == info.Split && info.Tree + 1 < Trees.Length) huff = new HuffmanTable(Trees[info.Tree + 1]); + if ((row & 63) == 0) cancellationToken.ThrowIfCancellationRequested(); + var dst = samples.AsSpan(row * width, width); + for (var col = 0; col < width; col++) + { + var symbol = huff.Decode(ref reader); + int len = symbol & 15, shl = symbol >> 4; + var diff = 0; + if (len > 0) + { + diff = (int)(((reader.Read(int.Max(len - shl, 0)) << 1) + 1) << shl >> 1); + if ((diff & 1 << (len - 1)) == 0) diff -= (1 << len) - (shl == 0 ? 1 : 0); + } + ushort predicted; + if (col < 2) + { + ref var v = ref vpred[(row & 1) * 2 + col]; + v = (ushort)(v + diff); + predicted = hpred[col] = v; + } + else + { + predicted = hpred[col & 1] = (ushort)(hpred[col & 1] + diff); + } + dst[col] = curve[int.Clamp((short)predicted, 0, 0x3FFF)]; + } + if (reader.Overrun) throw new InvalidDataException($"NEF: compressed data ends at row {row}"); + } + return new RawSamples(width, height, 1, samples, null); + } + } +} diff --git a/src/Titano.Core/Codecs/Raw/PefReader.cs b/src/Titano.Core/Codecs/Raw/PefReader.cs new file mode 100644 index 00000000..7c8f73b2 --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/PefReader.cs @@ -0,0 +1,149 @@ +using System.Buffers.Binary; +using Titano.Core.Mathematics; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Pentax PEF: the CFA image in IFD0 is uncompressed or Pentax-Huffman coded (Compression 65535): a code table from +/// MakerNote 0x0220 (code values left-aligned in 12 bits and their lengths, dcraw pentax_load_raw), JPEG-style +/// difference magnitudes, and two-column horizontal prediction seeded per row parity. Black (0x0200) and as-shot RGGB +/// levels (0x0201) come from the "AOC" MakerNote, whose offsets are relative to the TIFF header. +/// +internal static class PefReader +{ + private const uint CompressionPentax = 65535; + private const ushort BlackPointTag = 0x0200; + private const ushort WhiteBalanceTag = 0x0201; + private const ushort HuffmanTag = 0x0220; + + public static RawFrame Read(Stream stream) + { + var r = TiffReader.Open(stream) ?? throw new InvalidDataException("PEF: missing TIFF header"); + var chain = r.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("PEF: no image directory"); + var ifd0 = chain[0]; + var raw = NefReader.FindCfa(r, ifd0) ?? throw new InvalidDataException("PEF: CFA image missing"); + var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0); + var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0); + if (bits is not (12 or 14)) throw new InvalidDataException($"PEF: {bits}-bit data is not supported"); + var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1; + var (offset, length) = NefReader.Strip(r, raw); + var note = MakerNote(stream, r, ifd0); + var warnings = new List(); + var cfa = NativeRaw.TiffEpCfa(r, raw); + if (cfa is null) + { + cfa = CfaPattern.Bayer("RGGB"); + warnings.Add("PEF: CFA pattern missing; RGGB assumed"); + } + if (!cfa.IsBayer) throw new InvalidDataException("PEF: only Bayer sensors are supported"); + + RawLoader loader; + if (compression == CompressionPentax) + { + if (note is not { } mn || !mn.Ifd.Entries.TryGetValue(HuffmanTag, out var e) || mn.Reader.ReadBytes(e) is not { } table) + throw new InvalidDataException("PEF: Huffman table missing"); + NativeRaw.RequireBits(length, (long)width * height); + loader = new PentaxLoader(offset, length, width, height, bits, Table(table, mn.Reader.LittleEndian)); + } + else if (compression == 1 && length >= (long)width * height * 2) + { + loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: r.LittleEndian); + } + else if (compression == 1 && length >= ((long)width * bits + 7) / 8 * height) + { + loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false); + } + else + { + throw new InvalidDataException($"PEF: compression {compression} is not supported"); + } + + var black = note is { } n && IfdValue.UInts(n.Reader, n.Ifd, BlackPointTag) is { Length: 4 } b + ? NativeRaw.Black2x2(cfa, [b[0], b[1], b[2], b[3]]) + : NativeRaw.Black(0); + Vector3D? multipliers = note is { } w && IfdValue.UInts(w.Reader, w.Ifd, WhiteBalanceTag) is { Length: 4 } wb && wb[1] + wb[2] > 0 + ? new Vector3D(wb[0] * 2.0 / (wb[1] + wb[2]), 1, wb[3] * 2.0 / (wb[1] + wb[2])) + : null; + return NativeRaw.Frame("managed-pef", width, height, cfa, new RawRect(0, 0, width, height), black, (1 << bits) - 1, multipliers, + (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings); + } + + /// "AOC\0" + byte order ("MM"/"II", else the file's) + IFD; offsets relative to the file's TIFF header. + private static (TiffReader Reader, Ifd Ifd)? MakerNote(Stream stream, TiffReader r, Ifd ifd0) + { + if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var e) || e.IsInline || e.Count < 8) return null; + var start = e.ValuePosition(r.Base); + var head = r.ReadRelative(start - r.Base, 6); + if (head is null || !head.AsSpan(0, 4).SequenceEqual("AOC\0"u8)) return null; + var littleEndian = head[4] == 'I' && head[5] == 'I' || !(head[4] == 'M' && head[5] == 'M') && r.LittleEndian; + var reader = TiffReader.ForEmbedded(stream, r.Base, littleEndian); + return reader.ReadIfd((uint)(start + 6 - r.Base)) is { } ifd ? (reader, ifd) : null; + } + + /// 12-bit lookup from MakerNote 0x0220: a code count, 12 skipped bytes, left-aligned code values (16-bit) and + /// code lengths (8-bit); every 12-bit prefix of a code maps to (length, difference magnitude). + internal static HuffmanTable Table(byte[] table, bool littleEndian) + { + if (table.Length < 14) throw new InvalidDataException("PEF: Huffman table truncated"); + ushort U16(int at) => littleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(table.AsSpan(at)) : BinaryPrimitives.ReadUInt16BigEndian(table.AsSpan(at)); + var depth = (U16(0) + 12) & 15; + if (table.Length < 14 + depth * 3) throw new InvalidDataException("PEF: Huffman table truncated"); + var lut = new ushort[4096]; + for (var c = 0; c < depth; c++) + { + int code = U16(14 + 2 * c), len = table[14 + 2 * depth + c]; + if (code > 4095 || len > 12) continue; + var end = (code + (4096 >> len) - 1) & 4095; + for (var i = code; i <= end; i++) lut[i] = (ushort)(len << 8 | c); + } + return new HuffmanTable(lut, 12); + } + + private sealed class PentaxLoader(long offset, long length, int width, int height, int bits, HuffmanTable huff) : RawLoader + { + public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) + { + var data = NativeRaw.ReadPayload(stream, offset, length); + var samples = new ushort[width * height]; + var reader = new MsbBitReader(data); + Span vpred = stackalloc int[4]; + Span hpred = stackalloc int[2]; + var limit = (1 << bits) - 1; + var outOfRange = false; + for (var row = 0; row < height; row++) + { + if ((row & 63) == 0) cancellationToken.ThrowIfCancellationRequested(); + var dst = samples.AsSpan(row * width, width); + for (var col = 0; col < width; col++) + { + var len = huff.Decode(ref reader); + var diff = 0; + if (len == 16) + { + diff = -32768; + } + else if (len > 0) + { + diff = (int)reader.Read(len); + if ((diff & 1 << (len - 1)) == 0) diff -= (1 << len) - 1; + } + int value; + if (col < 2) value = hpred[col] = vpred[(row & 1) * 2 + col] += diff; + else value = hpred[col & 1] += diff; + if ((uint)value > (uint)limit) + { + outOfRange = true; + value = int.Clamp(value, 0, limit); + } + dst[col] = (ushort)value; + } + if (reader.Overrun) throw new InvalidDataException($"PEF: compressed data ends at row {row}"); + } + var result = new RawSamples(width, height, 1, samples, null); + if (outOfRange) result.Warnings.Add("PEF: predicted values outside the bit depth were clamped"); + return result; + } + } +} diff --git a/src/Titano.Core/Codecs/Raw/RafReader.cs b/src/Titano.Core/Codecs/Raw/RafReader.cs new file mode 100644 index 00000000..2219b7ee --- /dev/null +++ b/src/Titano.Core/Codecs/Raw/RafReader.cs @@ -0,0 +1,114 @@ +using System.Buffers.Binary; +using Titano.Core.Mathematics; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Raw; + +/// +/// Fujifilm RAF, uncompressed: the header's CFA offset (0x64) points to a big-endian TIFF block whose FujiIFD (0xF000) +/// gives the raster size (0xF001/0xF002), bit depth (0xF003), the data offset relative to that block (0xF007), its length +/// (0xF008) and black levels (0xF00A); the RAF directory supplies the crop (0x0110 top-left, 0x0111 size), the 6×6 +/// colour layout (0x0131, stored reversed, anchored at the raster origin; Bayer bodies describe their 2×2 pattern the same +/// way) and the as-shot GRGB levels (0x2FF0). Samples are 16-bit words in the block's byte order. Compressed RAFs and +/// SuperCCD (45°) layouts are not supported and fall back to the preview. +/// +internal static class RafReader +{ + private const int HeaderLength = 0x6C; + private const int MaxDirectoryBytes = 1 << 20; + private const ushort FullSizeRecord = 0x0100, CropTopLeftRecord = 0x0110, CropSizeRecord = 0x0111; + private const ushort LayoutRecord = 0x0130, CfaRecord = 0x0131, WhiteBalanceRecord = 0x2FF0; + private const ushort FujiIfdTag = 0xF000, WidthTag = 0xF001, HeightTag = 0xF002, BitsTag = 0xF003; + private const ushort OffsetTag = 0xF007, LengthTag = 0xF008, BlackTag = 0xF00A; + + public static RawFrame Read(Stream stream) + { + var header = new byte[HeaderLength]; + stream.Position = 0; + if (stream.ReadAtLeast(header, HeaderLength, throwOnEndOfStream: false) < HeaderLength || !header.AsSpan().StartsWith("FUJIFILMCCD-RAW "u8)) + throw new InvalidDataException("RAF: header missing"); + var records = Directory(stream, BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x5C)), BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x60))); + if (records.TryGetValue(LayoutRecord, out var layout) && layout.Length >= 2 && (layout[1] & 8) == 0) + throw new InvalidDataException("RAF: SuperCCD layouts are not supported"); + if (!records.TryGetValue(CfaRecord, out var pattern) || pattern.Length < 36) throw new InvalidDataException("RAF: colour layout record missing"); + + var blockBase = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x64)); + var r = TiffReader.Open(stream, blockBase) ?? throw new InvalidDataException("RAF: raw block is not TIFF-structured"); + var fuji = r.ReadIfd(r.FirstIfdOffset) is { } top && r.GetUInt(top, FujiIfdTag) is { } sub ? r.ReadIfd(sub) : null; + if (fuji is null) throw new InvalidDataException("RAF: FujiIFD missing"); + var (width, height) = NativeRaw.Size(r.GetUInt(fuji, WidthTag) ?? 0, r.GetUInt(fuji, HeightTag) ?? 0); + var bits = (int)(r.GetUInt(fuji, BitsTag) ?? 0); + if (bits is < 12 or > 16) throw new InvalidDataException($"RAF: {bits}-bit data is not supported"); + var offset = blockBase + (long)(r.GetUInt(fuji, OffsetTag) ?? 0); + var length = (long)(r.GetUInt(fuji, LengthTag) ?? 0); + if (length < (long)width * height * 2) throw new InvalidDataException("RAF: compressed RAF is not supported"); + + var warnings = new List(); + var active = new RawRect(0, 0, width, height); + if (records.TryGetValue(CropTopLeftRecord, out var tl) && tl.Length >= 4 && records.TryGetValue(CropSizeRecord, out var size) && size.Length >= 4) + { + int top0 = BinaryPrimitives.ReadUInt16BigEndian(tl), left0 = BinaryPrimitives.ReadUInt16BigEndian(tl.AsSpan(2)); + int h = BinaryPrimitives.ReadUInt16BigEndian(size), w = BinaryPrimitives.ReadUInt16BigEndian(size.AsSpan(2)); + var crop = new RawRect(left0, top0, left0 + w, top0 + h).Intersect(active); + if (!crop.IsEmpty) active = crop; + } + var colors = new byte[36]; + for (var i = 0; i < 36; i++) colors[35 - i] = (byte)(pattern[i] & 3); + var cfa = new CfaPattern(6, 6, colors).Shift(active.Left, active.Top); + + var black = NativeRaw.Black(1024 >> (14 - int.Min(bits, 14))); + if (fuji.Entries.TryGetValue(BlackTag, out var be) && be.Count is > 0 and <= 64 && r.GetUInts(be) is { } levels) + { + if (levels.Length >= 36) + { + // A 6×6 grid anchored at the raster origin, re-anchored at the active area. + var grid = new float[36]; + for (var y = 0; y < 6; y++) + { + for (var x = 0; x < 6; x++) grid[y * 6 + x] = levels[(y + active.Top) % 6 * 6 + (x + active.Left) % 6]; + } + black = new RawBlackLevel(6, 6, grid, null, null); + } + else + { + black = NativeRaw.Black(levels.Average(v => (double)v)); + } + } + else + { + warnings.Add("RAF: black level missing; default used"); + } + + Vector3D? multipliers = null; + if (records.TryGetValue(WhiteBalanceRecord, out var wb) && wb.Length >= 8) + { + double g = BinaryPrimitives.ReadUInt16BigEndian(wb), red = BinaryPrimitives.ReadUInt16BigEndian(wb.AsSpan(2)), blue = BinaryPrimitives.ReadUInt16BigEndian(wb.AsSpan(6)); + if (g > 0) multipliers = new Vector3D(red / g, 1, blue / g); + } + var metadata = MetadataReader.Read(stream, "frame.raf"); + var loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: r.LittleEndian); + return NativeRaw.Frame("managed-raf", width, height, cfa, active, black, (1 << bits) - 1, multipliers, metadata.Orientation, + metadata.Make ?? "FUJIFILM", metadata.Model, loader, warnings); + } + + /// RAF directory: u32 record count, then (u16 tag, u16 size, data) records, big-endian. + private static Dictionary Directory(Stream stream, uint offset, uint length) + { + var result = new Dictionary(); + if (offset < HeaderLength || length < 4 || length > MaxDirectoryBytes || offset > stream.Length - length) throw new InvalidDataException("RAF: directory missing"); + var data = NativeRaw.ReadPayload(stream, offset, length); + var count = BinaryPrimitives.ReadUInt32BigEndian(data); + var pos = 4; + for (var i = 0; i < count && pos + 4 <= data.Length; i++) + { + var tag = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(pos)); + var size = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(pos + 2)); + pos += 4; + if (pos + size > data.Length) break; + result.TryAdd(tag, data.AsSpan(pos, size).ToArray()); + pos += size; + } + return result; + } +} diff --git a/src/Titano.Core/Codecs/Raw/RawDecoder.cs b/src/Titano.Core/Codecs/Raw/RawDecoder.cs index 9e1dff47..51094fb1 100644 --- a/src/Titano.Core/Codecs/Raw/RawDecoder.cs +++ b/src/Titano.Core/Codecs/Raw/RawDecoder.cs @@ -58,15 +58,15 @@ public sealed class RawDecodeResult(ImageBuffer image, RawImageInfo info, IReadO } /// -/// Managed RAW decoding (BRIEF §8.2): DNG (CFA and LinearRaw) through , -/// developed by the shared pipeline. Bodies or encodings +/// Managed RAW decoding (BRIEF §8.2): DNG (CFA and LinearRaw) through , and the native containers +/// Canon CR2, Nikon NEF, Sony ARW, Pentax PEF and Fujifilm RAF, all developed by the same pipeline. Bodies or encodings /// without support are reported by so callers can fall back to the embedded preview. /// public static class RawDecoder { /// Formats with a managed decoder (individual files may still be unsupported). public static IReadOnlyList Formats { get; } = - [ImageFileFormat.Dng]; + [ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Arw, ImageFileFormat.Pef, ImageFileFormat.Raf]; /// Parses the container and decides whether it can be developed natively; never reads the pixel payload. public static RawProbe Probe(Stream stream, string? fileName = null) @@ -112,6 +112,11 @@ public static class RawDecoder var frame = format switch { ImageFileFormat.Dng => DngReader.Read(stream), + ImageFileFormat.Cr2 => Cr2Reader.Read(stream), + ImageFileFormat.Nef => NefReader.Read(stream), + ImageFileFormat.Arw => ArwReader.Read(stream), + ImageFileFormat.Pef => PefReader.Read(stream), + ImageFileFormat.Raf => RafReader.Read(stream), _ => throw new InvalidDataException($"RAW: no managed decoder for {format}"), }; return (format, frame); diff --git a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs index 94e0253d..fcd185a1 100644 --- a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs +++ b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs @@ -17,8 +17,11 @@ internal static class RawDeveloper /// Normalised level at or above which a sample counts as clipped. private const float ClipThreshold = 0.999f; - /// LibRaw's adjust_maximum_thr: the data maximum replaces the nominal white level above this fraction of it. - private const double AdjustMaximumThreshold = 0.75; + /// A pile-up of samples at the data maximum counts as sensor saturation only above this fraction of the white level. + private const double SaturationFloor = 0.75; + + /// Samples that must sit at the data maximum for it to count as saturation rather than the brightest detail. + private const int SaturationPileUp = 16; public static ImageBuffer Develop(RawFrame frame, RawSamples samples, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) { @@ -28,8 +31,8 @@ internal static class RawDeveloper var spp = frame.SamplesPerPixel; var active = frame.ActiveArea; var black = samples.MeasuredBlack ?? frame.Black; - var white = (double[])frame.White.Clone(); - if (frame.AdjustWhiteToData) AdjustWhite(samples, active, white, warnings); + var white = frame.White; + var saturation = frame.DetectSaturation && frame.Linearization is null && spp == 1 ? Saturation(samples, active, black, white[0]) : 1f; var list1 = DngOpcodes.Parse(frame.OpcodeList1, 1, warnings); ImageBuffer? stage1 = null; @@ -50,7 +53,7 @@ internal static class RawDeveloper byte[]? clip; try { - (linear, clip) = Linearize(frame, samples, stage1, black, white, dop, cancellationToken); + (linear, clip) = Linearize(frame, samples, stage1, black, white, saturation * ClipThreshold, dop, cancellationToken); } finally { @@ -63,7 +66,7 @@ internal static class RawDeveloper DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList2, 2, warnings), stage, warnings, cancellationToken); return frame.Cfa is null && spp == 1 ? DevelopMonochrome(frame, stage, options, warnings, cancellationToken) - : DevelopColour(frame, stage, options, warnings, cancellationToken); + : DevelopColour(frame, stage, saturation, options, warnings, cancellationToken); } finally { @@ -71,7 +74,7 @@ internal static class RawDeveloper } } - private static ImageBuffer DevelopColour(RawFrame frame, OpcodeImage stage, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) + private static ImageBuffer DevelopColour(RawFrame frame, OpcodeImage stage, float saturation, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) { var dop = options.MaxDegreeOfParallelism; var colour = frame.Color.Solve(warnings); @@ -109,7 +112,7 @@ internal static class RawDeveloper var image = new OpcodeImage(rgb, stage.Left, stage.Top, step, null); try { - if (bits is not null) HighlightReconstruction.Apply(rgb, bits, wb, dop, cancellationToken); + if (bits is not null) HighlightReconstruction.Apply(rgb, bits, [wb[0] * saturation, wb[1] * saturation, wb[2] * saturation], dop, cancellationToken); var list3 = DngOpcodes.Parse(frame.OpcodeList3, 3, warnings); if (list3.Count > 0) { @@ -190,7 +193,7 @@ internal static class RawDeveloper /// Linear reference values over the active area plus a clip map (bit = CFA colour or sample plane), or null /// when nothing clipped. - private static (ImageBuffer Image, byte[]? Clip) Linearize(RawFrame frame, RawSamples samples, ImageBuffer? stage1, RawBlackLevel black, double[] white, int dop, CancellationToken cancellationToken) + private static (ImageBuffer Image, byte[]? Clip) Linearize(RawFrame frame, RawSamples samples, ImageBuffer? stage1, RawBlackLevel black, double[] white, float clipLevel, int dop, CancellationToken cancellationToken) { var active = frame.ActiveArea; int w = active.Width, h = active.Height, spp = frame.SamplesPerPixel; @@ -227,7 +230,7 @@ internal static class RawDeveloper + (black.DeltaH is { } dh && x < dh.Length ? dh[x] : 0f); var value = (v - b) * scale[s]; row[x] = value; - if (value >= ClipThreshold) + if (value >= clipLevel) { clip[y * w + x] |= (byte)(1 << (cfa is null ? s : cfa.ColorAt(x, y))); rowClip = 1; @@ -239,19 +242,34 @@ internal static class RawDeveloper return (image, anyClip != 0 ? clip : null); } - private static void AdjustWhite(RawSamples samples, RawRect active, double[] white, ICollection warnings) + /// Normalised saturation level of a native RAW: the data maximum when at least + /// samples reach it and it lies between and 1 of the white level, else 1. It only moves + /// the clip threshold; scaling stays tied to the white level so brightness never depends on frame content. + private static float Saturation(RawSamples samples, RawRect active, RawBlackLevel black, double white) { var max = 0f; + var count = 0; for (var y = active.Top; y < active.Bottom; y++) { - var o = (long)y * samples.Width * samples.SamplesPerPixel; - for (var x = active.Left * samples.SamplesPerPixel; x < active.Right * samples.SamplesPerPixel; x++) max = float.Max(max, samples[o + x]); + var o = (long)y * samples.Width; + for (var x = active.Left; x < active.Right; x++) + { + var v = samples[o + x]; + if (v > max + 1) + { + max = v; + count = 1; + } + else if (v >= max - 1) + { + count++; + max = float.Max(max, v); + } + } } - for (var s = 0; s < white.Length; s++) - { - if (max > 0 && max < white[s] && max > white[s] * AdjustMaximumThreshold) white[s] = max; - } - if (max > white.Max()) warnings.Add($"RAW: samples exceed the white level ({max} > {white.Max()})"); + if (count < SaturationPileUp || max >= white || max < white * SaturationFloor) return 1f; + var floor = black.Max(0, 1); + return (float)double.Clamp((max - 1 - floor) / (white - floor), 0.5, 1); } private static void ScaleMosaic(ImageBuffer mosaic, CfaPattern cfa, float[] wb, int dop, CancellationToken cancellationToken) diff --git a/src/Titano.Core/Codecs/Raw/RawFrame.cs b/src/Titano.Core/Codecs/Raw/RawFrame.cs index 9d5e940b..3fc24b4d 100644 --- a/src/Titano.Core/Codecs/Raw/RawFrame.cs +++ b/src/Titano.Core/Codecs/Raw/RawFrame.cs @@ -112,9 +112,9 @@ internal sealed class RawFrame /// White level per sample plane, in linearised units. public required double[] White { get; init; } - /// Lower the white level to the data maximum when that exceeds 75 % of it (LibRaw adjust_maximum_thr): native - /// RAWs state a nominal bit-depth maximum while sensors saturate earlier. - public bool AdjustWhiteToData { get; init; } + /// Find the clip threshold in the data: native RAWs state a nominal bit-depth maximum while sensors saturate + /// earlier. Only clip detection uses it; the white level keeps scaling every frame the same (no flicker). + public bool DetectSaturation { get; init; } public required DngColorProfile Color { get; init; } public byte[]? OpcodeList1 { get; init; } diff --git a/tests/Titano.Core.Tests/Raw/NativeRawTests.cs b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs new file mode 100644 index 00000000..6166181a --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs @@ -0,0 +1,183 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Testing; +using static Titano.Core.Tests.Raw.NativeRawWriters; + +namespace Titano.Core.Tests.Raw; + +/// Native RAW decoders on synthetic files written in each container's layout: the decoded image must match the +/// scene the sensor data was generated from (camera matrix, as-shot white balance, black/white levels, crop). +public sealed class NativeRawTests(TestContext context) +{ + private const int W = 96, H = 64; + + private RawDecodeResult Decode(byte[] file, string name, RawDecodeOptions? options = null) + { + var result = RawDecoder.Decode(new MemoryStream(file), name, options); + context.Log($"{name}: {result.Info} warnings: {string.Join("; ", result.Warnings)}"); + return result; + } + + private static void AssertScene(ImageBuffer scene, ImageBuffer image, double minimum, TestContext context) + { + Assert.Equal(scene.Width, image.Width); + Assert.Equal(scene.Height, image.Height); + var psnr = SyntheticRaw.Psnr(scene, image, 4); + context.Log($"PSNR {psnr:F1} dB"); + Assert.GreaterOrEqual(psnr, minimum); + } + + [Test] + public void Cr2SlicedLosslessJpegWithMaskedBlack() + { + using var scene = SyntheticRaw.Smooth(W, H); + // 24 masked columns left and 4 rows on top; Canon's CFA is RGGB at the raster origin. + var active = new RawRect(24, 4, 24 + W, 4 + H); + var sensor = Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383); + using var result = Decode(Cr2(sensor, active), "IMG_0001.CR2"); + Assert.Equal("managed-cr2", result.Info.Decoder); + Assert.Equal("RGGB", result.Info.Layout); + AssertScene(scene, result.Image, 38, context); + } + + [Theory] + [Case(NefEncoding.Lossless, 14)] + [Case(NefEncoding.Lossless, 12)] + [Case(NefEncoding.Unpacked, 14)] + [Case(NefEncoding.Packed, 12)] + public void NefEncodings(NefEncoding encoding, int bits) + { + using var scene = SyntheticRaw.Smooth(W, H); + var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600 >> (14 - bits), (1 << bits) - 1); + using var result = Decode(Nef(sensor, bits, encoding), "DSC_0001.NEF"); + Assert.Equal("managed-nef", result.Info.Decoder); + AssertScene(scene, result.Image, 38, context); + } + + [Theory] + [Case(NefEncoding.LossyType1, 12, 0)] + [Case(NefEncoding.LossyType2, 14, 0)] + [Case(NefEncoding.LossyType2, 14, 40)] + public void NefLossyCurves(NefEncoding encoding, int bits, int split) + { + // A square-law curve: dense codes in the shadows, coarse in the highlights. + var size = encoding == NefEncoding.LossyType1 ? 683 : 1 << bits; + var curve = Enumerable.Range(0, size).Select(i => (ushort)double.Round(((1 << bits) - 1) * (i / (double)(size - 1)) * (i / (double)(size - 1)))).ToArray(); + var white = encoding == NefEncoding.LossyType1 ? curve[^1] : InterpolatedCurve(curve, bits).Max(); + // After the split row the tree has no unshifted codes for 9–12-bit differences: keep that scene gentle. + using var scene = split > 0 ? Gentle() : SyntheticRaw.Smooth(W, H); + var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600 >> (14 - bits), white); + using var result = Decode(Nef(sensor, bits, encoding, curve: curve, split: split), "DSC_0002.NEF"); + AssertScene(scene, result.Image, 36, context); + } + + [Theory] + [Case(true)] + [Case(false)] + public void ArwCompressedAndUncompressed(bool compressed) + { + ushort[] knots = [8000, 10400, 12900, 14100]; + var curve = ToneCurve(knots); + double white = compressed ? curve[0x7FF << 1] : 16383; + using var scene = SyntheticRaw.Smooth(W, H); + var sensor = Sensor(scene, "Sony ILCE-7M3", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 512, white); + using var result = Decode(Arw(sensor, knots, compressed), "DSC00001.ARW"); + Assert.Equal("managed-arw", result.Info.Decoder); + Assert.Contains(result.Warnings, w => w.Contains("daylight")); + AssertScene(scene, result.Image, compressed ? 36 : 38, context); + } + + [Theory] + [Case(true)] + [Case(false)] + public void PefHuffmanAndUncompressed(bool compressed) + { + using var scene = SyntheticRaw.Smooth(W, H); + var sensor = Sensor(scene, "Pentax K-1", CfaPattern.Bayer("BGGR"), W, H, 0, 0, 512, 16383); + using var result = Decode(Pef(sensor, 14, compressed), "IMGP0001.PEF"); + Assert.Equal("managed-pef", result.Info.Decoder); + Assert.Equal("BGGR", result.Info.Layout); + AssertScene(scene, result.Image, 38, context); + } + + [Theory] + [Case(true)] + [Case(false)] + public void RafXTransAndBayerLayouts(bool xtrans) + { + using var scene = SyntheticRaw.Smooth(W, H); + var rasterCfa = xtrans ? DemosaicTests.XTrans : CfaPattern.Bayer("GRBG"); + // Crop starts at an odd offset so the pattern must be re-anchored. + var crop = new RawRect(5, 3, 5 + W, 3 + H); + var sensor = Sensor(scene, "Fujifilm X-T2", rasterCfa, W + 8, H + 6, crop.Left, crop.Top, 1024, 16383); + using var result = Decode(Raf(sensor, Expand(rasterCfa), crop, orientation: 1), "DSCF0001.RAF"); + Assert.Equal("managed-raf", result.Info.Decoder); + Assert.Equal("X-T2", result.Info.Model); + AssertScene(scene, result.Image, xtrans ? 34 : 38, context); + using var binned = Decode(Raf(sensor, Expand(rasterCfa), crop), "DSCF0001.RAF", new RawDecodeOptions { Binning = true }); + Assert.Equal(W / (xtrans ? 3 : 2), binned.Image.Width); + } + + [Test] + public void OrientationComesFromTheContainer() + { + using var scene = SyntheticRaw.Smooth(W, H); + var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383); + using var result = Decode(Nef(sensor, 14, NefEncoding.Lossless, orientation: 8), "DSC_0003.NEF"); + Assert.Equal(H, result.Image.Width); + Assert.Equal(W, result.Image.Height); + Assert.Equal(H, result.Info.Width); + } + + [Test] + public void UnknownBodyIsUnsupported() + { + using var scene = SyntheticRaw.Smooth(W, H); + var active = new RawRect(24, 4, 24 + W, 4 + H); + var sensor = Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383); + var probe = RawDecoder.Probe(new MemoryStream(Cr2(sensor, active, model: "Canon EOS R99")), "x.cr2"); + Assert.False(probe.IsSupported); + Assert.Contains("no colour matrix", probe.Reason); + Assert.Throws(() => RawDecoder.Decode(new MemoryStream(Cr2(sensor, active, model: "Canon EOS R99")), "x.cr2")); + } + + [Test] + public void CameraNamesNormalise() + { + Assert.Equal("Nikon D850", NativeRaw.CameraName("NIKON CORPORATION", "NIKON D850")); + Assert.Equal("Canon EOS 5D Mark III", NativeRaw.CameraName("Canon", "Canon EOS 5D Mark III")); + Assert.Equal("Sony ILCE-7M3", NativeRaw.CameraName("SONY", "ILCE-7M3")); + Assert.Equal("Pentax K-1", NativeRaw.CameraName("RICOH IMAGING COMPANY, LTD.", "PENTAX K-1")); + Assert.Equal("Fujifilm X-T2", NativeRaw.CameraName("FUJIFILM", "X-T2")); + // Every tabulated matrix maps D65 to a positive camera neutral with green the strongest channel. + foreach (var name in CameraMatrices.Names) + { + var m = CameraMatrices.Find(name)!.Value; + var n = m * Titano.Core.Mathematics.Chromaticity.D65.ToXyz(); + Assert.True(n.X > 0 && n.Z > 0 && n.Y > n.X && n.Y > n.Z, name); + } + } + + private static ImageBuffer Gentle() + { + var scene = new ImageBuffer(W, H); + for (var y = 0; y < H; y++) + { + for (var x = 0; x < W; x++) + { + scene[0, x, y] = 0.3f + 0.03f * x / W; + scene[1, x, y] = 0.32f + 0.02f * y / H; + scene[2, x, y] = 0.25f + 0.01f * (x + y) / (W + H); + } + } + return scene; + } + + /// The pattern written into the RAF layout record, expanded to 6×6. + private static CfaPattern Expand(CfaPattern cfa) + { + var colors = new byte[36]; + for (var i = 0; i < 36; i++) colors[i] = (byte)cfa.ColorAt(i % 6, i / 6); + return new CfaPattern(6, 6, colors); + } +} diff --git a/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs b/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs new file mode 100644 index 00000000..9fa3bce0 --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs @@ -0,0 +1,485 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Core.Mathematics; +using Titano.Core.Metadata; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Tests.Metadata.Builders; + +namespace Titano.Core.Tests.Raw; + +/// Payload encodings of the synthetic NEF writer. +public enum NefEncoding +{ + Lossless, + LossyType1, + LossyType2, + Unpacked, + Packed, +} + +/// A synthetic sensor readout: stored samples of a scene through a camera model, plus the as-shot neutral. +internal sealed record SensorData(ushort[] Samples, int Width, int Height, Vector3D Neutral); + +/// +/// Test-side writers for native RAW containers. Each follows the layout its reader documents (and dcraw/LibRaw decode): +/// CR2 sliced lossless JPEG with Canon MakerNote, NEF Nikon Huffman with type-3 MakerNote, ARW2 cRAW blocks with tone +/// curve, PEF Pentax Huffman with AOC MakerNote, RAF with FujiIFD and RAF directory. +/// +internal static class NativeRawWriters +{ + /// Stored sensor values of placed at (left, top) of a raster, CFA anchored at the raster + /// origin, outside pixels at black. + public static SensorData Sensor(ImageBuffer scene, string camera, CfaPattern cfa, int width, int height, int left, int top, double black, double white) + { + var matrix = CameraMatrices.Find(camera) ?? throw new ArgumentException("No matrix for " + camera); + var (rgb, neutral) = SyntheticRaw.ToCamera(scene, matrix, Chromaticity.D65); + var samples = new ushort[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + int sx = x - left, sy = y - top; + var v = black; + if (sx >= 0 && sy >= 0 && sx < scene.Width && sy < scene.Height) v += rgb[cfa.ColorAt(x, y)][sy * scene.Width + sx] * (white - black); + samples[y * width + x] = (ushort)double.Clamp(double.Round(v), 0, white); + } + } + return new SensorData(samples, width, height, neutral); + } + + /// Real JPEG preview with an Exif block (make, model, orientation). + public static byte[] Preview(string make, string model, int orientation, int width = 64, int height = 48) + { + using var image = new ImageBuffer(width, height); + for (var i = 0; i < image.PlaneLength; i++) + { + image.Plane(0)[i] = 0.5f; + image.Plane(1)[i] = 0.3f; + image.Plane(2)[i] = 0.2f; + } + var exif = ExifWriter.BuildTiff(new FrameMetadata { Make = make, Model = model, Orientation = orientation }); + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [[.. "Exif\0\0"u8, .. exif]] }); + } + + /// Canon CR2: "CR" header, IFD0 JPEG preview, two dummy IFDs, IFD3 lossless raw in two slices. + public static byte[] Cr2(SensorData s, RawRect active, int orientation = 1, string model = "Canon EOS 5D Mark III") + { + const int components = 2; + var sliceWidth = s.Width / 2; + var stream = new ushort[s.Samples.Length]; + var k = 0; + foreach (var x0 in new[] { 0, sliceWidth }) + { + for (var y = 0; y < s.Height; y++) + { + for (var x = 0; x < sliceWidth; x++) stream[k++] = s.Samples[y * s.Width + x0 + x]; + } + } + var jpeg = JpegLosslessEncoder.Encode(stream, s.Width / components, s.Height, components, 14); + var sensor = new ushort[17]; + sensor[1] = (ushort)s.Width; + sensor[2] = (ushort)s.Height; + sensor[5] = (ushort)active.Left; + sensor[6] = (ushort)active.Top; + sensor[7] = (ushort)(active.Right - 1); + sensor[8] = (ushort)(active.Bottom - 1); + var colorData = new ushort[1338]; + colorData[63] = (ushort)double.Round(1024 * s.Neutral.Y / s.Neutral.X); + colorData[64] = colorData[65] = 1024; + colorData[66] = (ushort)double.Round(1024 * s.Neutral.Y / s.Neutral.Z); + var makerNote = new IfdSpec().Short(0x00E0, sensor).Short(0x4001, colorData); + var exif = new IfdSpec().Ascii(TiffTags.DateTimeOriginal, "2024:05:01 12:00:00").Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true); + var preview = Preview("Canon", model, orientation); + var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "Canon").Ascii(TiffTags.Model, model).Short(TiffTags.Orientation, (ushort)orientation) + .Short(TiffTags.Compression, 6).Strip(preview).Child(TiffTags.ExifIfd, exif); + var ifd1 = new IfdSpec().Short(TiffTags.Compression, 6); + var ifd2 = new IfdSpec().Short(TiffTags.Compression, 1); + var ifd3 = new IfdSpec().Short(TiffTags.Compression, 6).Strip(jpeg).Short(0xC640, 1, (ushort)sliceWidth, (ushort)(s.Width - sliceWidth)); + ifd0.Next = ifd1; + ifd1.Next = ifd2; + ifd2.Next = ifd3; + return TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]); + } + + /// Canonical codes of a dcraw-layout Huffman specification: symbol → (code, length). + public static Dictionary Codes(byte[] spec) + { + var max = 16; + while (spec[max - 1] == 0) max--; + var codes = new Dictionary(); + var h = 0; + var symbol = 16; + for (var len = 1; len <= max; len++) + { + for (var i = 0; i < spec[len - 1]; i++, symbol++) + { + codes.TryAdd(spec[symbol], (h >> (max - len), len)); + h += 1 << (max - len); + } + } + return codes; + } + + /// JPEG difference category and its bits (negative values one's-complement style). + public static (int Length, int Bits) Category(int diff) + { + if (diff == 0) return (0, 0); + var len = 32 - int.LeadingZeroCount(int.Abs(diff)); + return (len, diff > 0 ? diff : diff + (1 << len) - 1); + } + + /// Two-column horizontal prediction seeded by per-row-parity vertical predictors (Nikon and Pentax). + public static byte[] PredictiveHuffman(ushort[] values, int width, int height, Func> codesForRow, ushort[] initial) + { + var w = new BitWriter(); + var vpred = (int[])[initial[0], initial[1], initial[2], initial[3]]; + var hpred = new int[2]; + for (var row = 0; row < height; row++) + { + var codes = codesForRow(row); + for (var col = 0; col < width; col++) + { + int v = values[row * width + col], predicted; + if (col < 2) + { + predicted = vpred[(row & 1) * 2 + col]; + vpred[(row & 1) * 2 + col] = v; + hpred[col] = v; + } + else + { + predicted = hpred[col & 1]; + hpred[col & 1] = v; + } + var (len, bits) = Category(v - predicted); + var (code, codeLength) = codes[len]; + w.Write(code, codeLength); + w.Write(bits, len); + } + } + return w.ToArray(); + } + + /// Big-endian Nikon NEF: IFD0 thumbnail, SubIFD CFA raw, Exif with a type-3 MakerNote. + public static byte[] Nef(SensorData s, int bits, NefEncoding encoding, int orientation = 1, ushort[]? curve = null, int split = 0) + { + byte[] data; + uint compression = 34713; + var meta = new List { 0x46, 0x30 }; + ushort[] vpred = [100, 200, 300, 400]; + switch (encoding) + { + case NefEncoding.Lossless: + data = PredictiveHuffman(s.Samples, s.Width, s.Height, _ => Codes(NefTrees(bits == 14 ? 5 : 2)), vpred); + break; + case NefEncoding.LossyType1: + { + meta = [0x44, 0x10]; + var indices = Indices(s.Samples, curve!); + data = PredictiveHuffman(indices, s.Width, s.Height, _ => Codes(NefTrees(bits == 14 ? 3 : 0)), vpred); + break; + } + case NefEncoding.LossyType2: + { + meta = [0x44, 0x20]; + var indices = Indices(s.Samples, InterpolatedCurve(curve!, bits)); + var tree = bits == 14 ? 3 : 0; + data = PredictiveHuffman(indices, s.Width, s.Height, row => Codes(NefTrees(split > 0 && row >= split ? tree + 1 : tree)), vpred); + break; + } + case NefEncoding.Unpacked: + data = new byte[s.Samples.Length * 2]; + for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]); + break; + default: + compression = 1; + data = Packed(s.Samples, s.Width, s.Height, bits); + break; + } + foreach (var v in vpred) meta.AddRange([(byte)(v >> 8), (byte)v]); + if (encoding == NefEncoding.LossyType1) + { + meta.AddRange([(byte)(curve!.Length >> 8), (byte)curve.Length]); + foreach (var v in curve) meta.AddRange([(byte)(v >> 8), (byte)v]); + } + else if (encoding == NefEncoding.LossyType2) + { + // Curve sampled every 'step' codes; split row at byte 562. + meta.AddRange([(byte)(CurvePoints >> 8), unchecked((byte)CurvePoints)]); + foreach (var v in CurveSamples(curve!, bits)) meta.AddRange([(byte)(v >> 8), (byte)v]); + while (meta.Count < 562) meta.Add(0); + meta.AddRange([(byte)(split >> 8), (byte)split]); + } + else + { + meta.AddRange([0, 0]); + } + var nikon = new IfdSpec() + .Rational(0x000C, ((uint)double.Round(1e5 * s.Neutral.Y / s.Neutral.X), 100000u), ((uint)double.Round(1e5 * s.Neutral.Y / s.Neutral.Z), 100000u), (1u, 1u), (1u, 1u)) + .Short(0x003D, 600, 600, 600, 600) + .Short(0x0093, (ushort)(encoding == NefEncoding.Lossless ? 3 : encoding == NefEncoding.LossyType1 ? 1 : encoding == NefEncoding.LossyType2 ? 4 : 2)) + .Undefined(0x0096, [.. meta]); + var exif = new IfdSpec().Undefined(TiffTags.MakerNote, [.. "Nikon\0"u8, 2, 0x11, 0, 0, .. TiffFile.Build(nikon, littleEndian: false)]); + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height) + .Short(TiffTags.BitsPerSample, (ushort)bits).Short(TiffTags.Compression, (ushort)compression) + .Short(TiffTags.PhotometricInterpretation, 32803) + .Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 0, 1, 1, 2) + .Strip(data); + var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "NIKON CORPORATION").Ascii(TiffTags.Model, "NIKON D850") + .Short(TiffTags.Orientation, (ushort)orientation).Long(TiffTags.NewSubfileType, 1) + .Child(TiffTags.SubIfds, raw).Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, littleEndian: false); + } + + private static byte[] NefTrees(int index) => NefReader.Trees[index]; + + private const int CurvePoints = 257; + + private static ushort[] CurveSamples(ushort[] curve, int bits) + { + var step = (1 << bits & 0x7FFF) / (CurvePoints - 1); + return [.. Enumerable.Range(0, CurvePoints).Select(i => curve[int.Min(i * step, curve.Length - 1)])]; + } + + /// The curve a lossy type-2 decoder rebuilds: samples every step codes, linearly interpolated. + public static ushort[] InterpolatedCurve(ushort[] curve, int bits) + { + var max = 1 << bits & 0x7FFF; + var step = max / (CurvePoints - 1); + var samples = CurveSamples(curve, bits); + var result = new ushort[max]; + for (var i = 0; i < max; i++) + { + int k = i % step, a = i / step; + result[i] = (ushort)((samples[a] * (step - k) + samples[int.Min(a + 1, samples.Length - 1)] * k) / step); + } + return result; + } + + /// Curve indices whose values are nearest to the samples (monotonic curve). + public static ushort[] Indices(ushort[] samples, ushort[] curve) + { + var result = new ushort[samples.Length]; + for (var i = 0; i < samples.Length; i++) + { + var target = samples[i]; + int lo = 0, hi = curve.Length - 1; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (curve[mid] < target) lo = mid + 1; + else hi = mid; + } + if (lo > 0 && target - curve[lo - 1] < curve[lo] - target) lo--; + result[i] = (ushort)lo; + } + return result; + } + + /// MSB-first packed samples (TIFF convention), rows padded to whole bytes. + public static byte[] Packed(ushort[] samples, int width, int height, int bits) + { + var w = new BitWriter(); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) w.Write(samples[y * width + x], bits); + w.Align(); + } + return w.ToArray(); + } + + /// Sony ARW2 (cRAW): 16-pixel blocks of one colour in 32-column groups, values through the inverse tone curve. + public static byte[] Arw(SensorData s, ushort[] knots, bool compressed, int orientation = 1) + { + byte[] data; + uint compression = 32767; + if (compressed) + { + var curve = ToneCurve(knots); + var even = new ushort[2048]; + for (var i = 0; i < even.Length; i++) even[i] = curve[i << 1]; + var codes = Indices(s.Samples, even); + data = new byte[s.Width * s.Height]; + for (var y = 0; y < s.Height; y++) + { + for (var group = 0; group < s.Width; group += 32) + { + for (var parity = 0; parity < 2; parity++) + { + var block = data.AsSpan(y * s.Width + group + parity * 16, 16); + var pix = new int[16]; + for (var i = 0; i < 16; i++) pix[i] = codes[y * s.Width + group + parity + 2 * i]; + EncodeBlock(pix, block); + } + } + } + } + else + { + data = new byte[s.Samples.Length * 2]; + for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(2 * i), s.Samples[i]); + } + var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height) + .Short(TiffTags.BitsPerSample, (ushort)(compressed ? 8 : 14)).Short(TiffTags.Compression, (ushort)compression) + .Short(TiffTags.PhotometricInterpretation, 32803) + .Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 0, 1, 1, 2) + .Short(0x7010, knots).Short(0x7310, 512, 512, 512, 512) + .Strip(data); + var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "SONY").Ascii(TiffTags.Model, "ILCE-7M3").Short(TiffTags.Orientation, (ushort)orientation) + .Long(TiffTags.NewSubfileType, 1).Child(TiffTags.SubIfds, raw); + return TiffFile.Build(ifd0); + } + + /// The reader's tone curve (slopes 1, 2, 4, 8, 16 between the knots). + public static ushort[] ToneCurve(ushort[] knots) + { + int[] k = [0, knots[0] >> 2 & 0xFFF, knots[1] >> 2 & 0xFFF, knots[2] >> 2 & 0xFFF, knots[3] >> 2 & 0xFFF, 4095]; + var curve = new ushort[4096]; + for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i; + for (var i = 0; i < 5; i++) + { + for (var j = k[i] + 1; j <= k[i + 1]; j++) curve[j] = (ushort)(curve[j - 1] + (1 << i)); + } + return curve; + } + + private static void EncodeBlock(int[] pix, Span block) + { + int imax = 0, imin = 0; + for (var i = 1; i < 16; i++) + { + if (pix[i] > pix[imax]) imax = i; + if (pix[i] < pix[imin]) imin = i; + } + if (imax == imin) imin = imax == 0 ? 1 : 0; + int max = pix[imax], min = pix[imin]; + var sh = 0; + while (sh < 4 && 0x80 << sh <= max - min) sh++; + var bits = new System.Collections.BitArray(130); + void Put(int value, int at, int count) + { + for (var b = 0; b < count; b++) bits[at + b] = (value >> b & 1) != 0; + } + Put(max, 0, 11); + Put(min, 11, 11); + Put(imax, 22, 4); + Put(imin, 26, 4); + var bit = 30; + for (var i = 0; i < 16; i++) + { + if (i == imax || i == imin) continue; + Put(int.Min((pix[i] - min) >> sh, 0x7F), bit, 7); + bit += 7; + } + for (var i = 0; i < 16; i++) + { + byte v = 0; + for (var b = 0; b < 8; b++) v |= (byte)(bits[i * 8 + b] ? 1 << b : 0); + block[i] = v; + } + } + + /// Pentax PEF: big-endian, raw in IFD0, AOC MakerNote with black, WB and the Huffman table. + public static byte[] Pef(SensorData s, int bits, bool compressed, int orientation = 1) + { + // Prefix code over difference lengths 0..14 (Kraft sum below 1). + int[] lengths = [3, 3, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 10]; + var codes = new Dictionary(); + var code = 0; + var previous = lengths[0]; + for (var c = 0; c < lengths.Length; c++) + { + code <<= lengths[c] - previous; + previous = lengths[c]; + codes[c] = (code, lengths[c]); + code++; + } + var table = new List { 0, (byte)((lengths.Length - 12) & 15) }; + table.AddRange(new byte[12]); + for (var c = 0; c < lengths.Length; c++) + { + var aligned = codes[c].Code << (12 - codes[c].Length); + table.AddRange([(byte)(aligned >> 8), (byte)aligned]); + } + foreach (var len in lengths) table.Add((byte)len); + var data = compressed ? PredictiveHuffman(s.Samples, s.Width, s.Height, _ => codes, [0, 0, 0, 0]) : Packed(s.Samples, s.Width, s.Height, bits); + var levels = new ushort[] { (ushort)double.Round(1000 * s.Neutral.Y / s.Neutral.X), 1000, 1000, (ushort)double.Round(1000 * s.Neutral.Y / s.Neutral.Z) }; + var pentax = new IfdSpec().Short(0x0200, 512, 512, 512, 512).Short(0x0201, levels).Undefined(0x0220, [.. table]); + var exif = new IfdSpec().Embedded(TiffTags.MakerNote, [.. "AOC\0MM"u8], pentax, relativeToTiff: true, littleEndian: false); + var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "RICOH IMAGING COMPANY, LTD.").Ascii(TiffTags.Model, "PENTAX K-1") + .Short(TiffTags.Orientation, (ushort)orientation).Long(TiffTags.NewSubfileType, 0) + .Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height) + .Short(TiffTags.BitsPerSample, (ushort)bits).Short(TiffTags.Compression, (ushort)(compressed ? 65535 : 1)) + .Short(TiffTags.PhotometricInterpretation, 32803) + .Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 2, 1, 1, 0) + .Strip(data).Child(TiffTags.ExifIfd, exif); + return TiffFile.Build(ifd0, littleEndian: false); + } + + /// Fujifilm RAF: header, JPEG with Exif, RAF directory (crop, layout, WB), FujiIFD block with 16-bit data. + public static byte[] Raf(SensorData s, CfaPattern rasterCfa, RawRect crop, int orientation = 1, string model = "X-T2") + { + var jpeg = Preview("FUJIFILM", model, orientation); + var pattern = new byte[36]; + for (var i = 0; i < 36; i++) pattern[35 - i] = (byte)rasterCfa.ColorAt(i % 6, i / 6); + var records = new List(); + void Record(ushort tag, byte[] payload) => records.AddRange([.. Box.U16(tag), .. Box.U16((ushort)payload.Length), .. payload]); + Record(0x0100, [.. Box.U16((ushort)s.Height), .. Box.U16((ushort)s.Width)]); + Record(0x0110, [.. Box.U16((ushort)crop.Top), .. Box.U16((ushort)crop.Left)]); + Record(0x0111, [.. Box.U16((ushort)crop.Height), .. Box.U16((ushort)crop.Width)]); + Record(0x0130, [0, 8, 0, 0]); + Record(0x0131, pattern); + Record(0x2FF0, [.. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.X)), .. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.Z))]); + byte[] directory = [.. Box.U32(6), .. records]; + var data = new byte[s.Samples.Length * 2]; + for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]); + var fuji = new IfdSpec().Long(0xF001, (uint)s.Width).Long(0xF002, (uint)s.Height).Long(0xF003, 14) + .Long(0xF00A, [.. Enumerable.Repeat(1024u, 36)]).Blob(0xF007, 0xF008, data); + var block = TiffFile.Build(new IfdSpec().Child(0xF000, fuji), littleEndian: false); + var jpegOffset = 0x6C; + var directoryOffset = jpegOffset + jpeg.Length; + var blockOffset = directoryOffset + directory.Length; + var header = new byte[0x6C]; + "FUJIFILMCCD-RAW 0201FF129502"u8.CopyTo(header); + System.Text.Encoding.ASCII.GetBytes(model).CopyTo(header.AsSpan(0x1C)); + uint[] fields = [(uint)jpegOffset, (uint)jpeg.Length, (uint)directoryOffset, (uint)directory.Length, (uint)blockOffset, (uint)block.Length]; + for (var i = 0; i < fields.Length; i++) BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(0x54 + 4 * i), fields[i]); + return [.. header, .. jpeg, .. directory, .. block]; + } + + /// MSB-first bit writer. + internal sealed class BitWriter + { + private readonly List _bytes = []; + private int _accumulator; + private int _count; + + public void Write(int value, int bits) + { + for (var b = bits - 1; b >= 0; b--) + { + _accumulator = _accumulator << 1 | (value >> b & 1); + if (++_count == 8) + { + _bytes.Add((byte)_accumulator); + _accumulator = _count = 0; + } + } + } + + public void Align() + { + if (_count > 0) Write(0, 8 - _count); + } + + public byte[] ToArray() + { + Align(); + return [.. _bytes, 0, 0, 0, 0]; + } + } +} diff --git a/tests/Titano.Core.Tests/Raw/RawFuzzTests.cs b/tests/Titano.Core.Tests/Raw/RawFuzzTests.cs new file mode 100644 index 00000000..06818fdd --- /dev/null +++ b/tests/Titano.Core.Tests/Raw/RawFuzzTests.cs @@ -0,0 +1,92 @@ +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Testing; +using static Titano.Core.Tests.Raw.NativeRawWriters; + +namespace Titano.Core.Tests.Raw; + +/// Truncated and corrupted RAW files may only raise (or decode). +public sealed class RawFuzzTests(TestContext context) +{ + private const int W = 48, H = 32; + + private static byte[] Sample(string format) + { + using var scene = SyntheticRaw.Smooth(W, H); + return format switch + { + "dng" => SyntheticDng.Write(scene, new DngSpec { TileSize = 16, OpcodeList2 = GainMapList(), OpcodeList3 = new OpcodeListBuilder().Add(3, 0, p => p.F64(0.1).F64(0).F64(0).F64(0).F64(0).F64(0.5).F64(0.5)).Build() }), + "linear.dng" => SyntheticDng.Write(scene, new DngSpec { Cfa = null, Compression = 8 }), + "cr2" => Cr2(Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 80, 36, 24, 4, 2048, 16383), new RawRect(24, 4, 24 + W, 4 + H)), + "nef" => Nef(Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383), 14, NefEncoding.Lossless), + "arw" => Arw(Sensor(scene, "Sony ILCE-7M3", CfaPattern.Bayer("RGGB"), 64, H, 0, 0, 512, 16000), [8000, 10400, 12900, 14100], compressed: true), + "pef" => Pef(Sensor(scene, "Pentax K-1", CfaPattern.Bayer("BGGR"), W, H, 0, 0, 512, 16383), 14, compressed: true), + _ => Raf(Sensor(scene, "Fujifilm X-T2", DemosaicTests.XTrans, W + 6, H + 6, 3, 3, 1024, 16383), DemosaicTests.XTrans, new RawRect(3, 3, 3 + W, 3 + H)), + }; + } + + private static byte[] GainMapList() => new OpcodeListBuilder().Add(9, 0, p => + { + OpcodeListBuilder.Area(p, 0, 0, H, W); + p.U32(2).U32(2).F64(1).F64(1).F64(0).F64(0).U32(1).F32(1).F32(1.1f).F32(1.2f).F32(1.3f); + }).Build(); + + [Theory] + [Case("dng")] + [Case("linear.dng")] + [Case("cr2")] + [Case("nef")] + [Case("arw")] + [Case("pef")] + [Case("raf")] + public void TruncatedAndCorruptedFilesOnlyRaiseInvalidData(string format) + { + var file = Sample(format); + var name = "fuzz." + format.Split('.').Last(); + var options = new RawDecodeOptions { Quality = DemosaicQuality.Draft, MaxDegreeOfParallelism = 1 }; + using (var clean = RawDecoder.Decode(new MemoryStream(file), name, options)) Assert.Equal(format == "arw" ? 64 : W, clean.Image.Width); + var random = new Random(format.Length * 7919); + var outcomes = new Dictionary(); + for (var i = 0; i < 120; i++) + { + byte[] variant; + if (i < 40) + { + variant = file[..(int)((long)file.Length * i / 40)]; + } + else + { + variant = (byte[])file.Clone(); + var flips = 1 + random.Next(4); + for (var k = 0; k < flips; k++) + { + // Bias corruption toward the headers, where structure lives. + var at = random.Next(2) == 0 ? random.Next(int.Min(variant.Length, 512)) : random.Next(variant.Length); + variant[at] = (byte)random.Next(256); + } + } + var outcome = Run(variant, name, options); + outcomes[outcome] = outcomes.GetValueOrDefault(outcome) + 1; + } + context.Log($"{format}: " + string.Join(", ", outcomes.Select(o => $"{o.Key} {o.Value}"))); + } + + private static string Run(byte[] data, string name, RawDecodeOptions options) + { + try + { + RawDecoder.Probe(new MemoryStream(data), name); + using var result = RawDecoder.Decode(new MemoryStream(data), name, options); + return "decoded"; + } + catch (InvalidDataException) + { + return "invalid"; + } + catch (Exception ex) + { + Assert.Fail($"{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); + return ""; + } + } +} From 2a9f93e414c9e96d593b7edf0ab3d6979124cbba Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:16:39 +0000 Subject: [PATCH 145/188] feat(render): end-to-end self-test suite and Titano.Tools selftest 63 reusable checks (plan, export, encoder selection, codec round trips, renders into every managed format decoded back, MP4 inspection when a platform encoder is supplied, processing modules measured on rendered frames, cancellation, failures, determinism, memory) shared by the CLI and the desktop Settings page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Render/Diagnostics/SelfTest.cs | 219 +++++++ .../Render/Diagnostics/SelfTestChecks.cs | 317 ++++++++++ .../Diagnostics/SelfTestRenderChecks.cs | 558 ++++++++++++++++++ src/Titano.Tools/Commands/SelfTestCommand.cs | 79 +++ src/Titano.Tools/Program.cs | 1 + .../Titano.Core.Tests/Render/SelfTestTests.cs | 68 +++ 6 files changed, 1242 insertions(+) create mode 100644 src/Titano.Core/Render/Diagnostics/SelfTest.cs create mode 100644 src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs create mode 100644 src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs create mode 100644 src/Titano.Tools/Commands/SelfTestCommand.cs create mode 100644 tests/Titano.Core.Tests/Render/SelfTestTests.cs diff --git a/src/Titano.Core/Render/Diagnostics/SelfTest.cs b/src/Titano.Core/Render/Diagnostics/SelfTest.cs new file mode 100644 index 00000000..735ce36b --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/SelfTest.cs @@ -0,0 +1,219 @@ +using System.Diagnostics; +using System.Globalization; +using Titano.Core.Codecs.Png; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Core.Video.Managed; + +namespace Titano.Core.Render.Diagnostics; + +public enum SelfTestOutcome +{ + Passed, + Failed, + + /// The check needs something this machine does not have (e.g. an MP4 encoder). + Skipped, +} + +/// Outcome of one self-test check; carries the measured figures or the failure. +public sealed record SelfTestResult(string Id, string Group, string Description, SelfTestOutcome Outcome, string Detail, TimeSpan Elapsed); + +/// What a check may use: its own empty folder, the encoders, and the run's cancellation. +public sealed record SelfTestContext(string WorkDirectory, IReadOnlyList Encoders, IReadOnlyList PlatformEncoders, + CancellationToken Cancellation); + +/// One end-to-end check; it returns a short detail on success and throws on failure. +public sealed record SelfTestCheck(string Id, string Group, string Description, Func> Run); + +public sealed record SelfTestOptions +{ + /// Platform encoders tested in addition to the managed ones (the desktop passes Media Foundation). + public IReadOnlyList PlatformEncoders { get; init; } = []; + + /// Parent folder of the run's scratch folder (deleted afterwards); default the system temp folder. + public string? WorkDirectory { get; init; } + + /// Run only checks whose id starts with one of these prefixes (all when empty). + public IReadOnlyList Filters { get; init; } = []; +} + +/// +/// The engine's end-to-end self-test (BRIEF §20.2, §20.4), shared by Titano.Tools selftest and the desktop +/// Settings page: render plans, export resolution and naming, encoder selection, managed codec round trips, renders of +/// small synthetic sequences into every managed format (and MP4 when a platform encoder is supplied) with their outputs +/// decoded back and compared, the processing modules measured on rendered frames, and cancellation, failure, +/// determinism and memory behaviour. +/// +public static partial class SelfTest +{ + public static IReadOnlyList Checks { get; } = [.. PlanChecks(), .. ExportChecks(), .. CodecChecks(), .. RenderChecks(), .. ProcessingChecks(), .. RobustnessChecks()]; + + public static async Task> RunAsync(SelfTestOptions? options = null, IProgress? progress = null, + CancellationToken cancellationToken = default) + { + options ??= new SelfTestOptions(); + var root = Path.Combine(options.WorkDirectory ?? Path.GetTempPath(), "titano-selftest-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(root); + IVideoEncoderProvider[] encoders = [.. options.PlatformEncoders, new ManagedEncoderProvider()]; + var results = new List(); + try + { + foreach (var check in Checks) + { + if (options.Filters.Count > 0 && !options.Filters.Any(f => check.Id.StartsWith(f, StringComparison.OrdinalIgnoreCase))) continue; + cancellationToken.ThrowIfCancellationRequested(); + var directory = Path.Combine(root, check.Id); + Directory.CreateDirectory(directory); + var context = new SelfTestContext(directory, encoders, options.PlatformEncoders, cancellationToken); + var clock = Stopwatch.StartNew(); + SelfTestOutcome outcome; + string detail; + try + { + detail = await check.Run(context).ConfigureAwait(false); + outcome = SelfTestOutcome.Passed; + } + catch (SkipException skip) + { + (outcome, detail) = (SelfTestOutcome.Skipped, skip.Message); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + (outcome, detail) = (SelfTestOutcome.Failed, ex is FailureException ? ex.Message : $"{ex.GetType().Name}: {ex.Message}"); + } + var result = new SelfTestResult(check.Id, check.Group, check.Description, outcome, detail, clock.Elapsed); + results.Add(result); + progress?.Report(result); + } + } + finally + { + try + { + Directory.Delete(root, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Titano.Core.Diagnostics.Log.Warning("SelfTest", "Could not delete " + root, ex); + } + } + return results; + } + + private sealed class FailureException(string message) : Exception(message); + + private sealed class SkipException(string message) : Exception(message); + + private static void Require(bool condition, string failure) + { + if (!condition) throw new FailureException(failure); + } + + private static SelfTestCheck Check(string id, string description, Func> run) => + new(id, id[..id.IndexOf('.', StringComparison.Ordinal)], description, run); + + private static SelfTestCheck Check(string id, string description, Func run) => Check(id, description, _ => Task.FromResult(run())); + + private static string Invariant(FormattableString text) => text.ToString(CultureInfo.InvariantCulture); + + /// No module and no knee: renders reproduce the source. + private static ProjectSettings Plain { get; } = new() { Exposure = new ExposureSettings { HighlightKnee = null } }; + + private static Auto Manual(T value) => new Auto().WithManual(value); + + private static SyntheticFrameSource Synthetic(int frames, Func? configure = null, + Func? motion = null) + { + var options = new SyntheticSequenceOptions { FrameCount = frames, StartEv = 0, EndEv = 1, Seed = 5 }; + return new SyntheticFrameSource(SyntheticSequence.Create(configure is null ? options : configure(options)), motion); + } + + private static RenderInput Input(SyntheticFrameSource source, ProjectSettings? project = null) => + new() { Source = source, Frames = source.Metadata(), Project = project ?? Plain }; + + /// A built-in preset's values at the synthetic frame size (or another size; 0×0 = source). + private static ResolvedExport Preset(string id, int width = 96, int height = 64) => + ExportResolver.FromPreset(ExportPresets.Find(id)!) with { Width = width, Height = height }; + + private static RenderTarget Target(SelfTestContext context, ResolvedExport export, string name = "out") => + new(export, Path.Combine(context.WorkDirectory, name + (export.Container == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(export.Codec)))); + + private static RenderPipeline Pipeline(SelfTestContext context) => new(context.Encoders); + + /// Renders to a 16-bit PNG sequence and decodes every picture back (linear light). + private static async Task> RenderDecodedAsync(SelfTestContext context, RenderInput input, ResolvedExport? export = null, string name = "decoded") + { + var target = Target(context, (export ?? Preset("png-sequence")) with { Codec = VideoCodec.PngSequence, BitDepth = 16 }, name); + await Pipeline(context).RenderAsync(input, target, cancellationToken: context.Cancellation).ConfigureAwait(false); + var frames = new List(); + foreach (var file in Directory.GetFiles(target.OutputPath).Order(StringComparer.Ordinal)) + frames.Add(PngDecoder.DecodeToLinear(await File.ReadAllBytesAsync(file, context.Cancellation).ConfigureAwait(false))); + return frames; + } + + private static void DisposeAll(IEnumerable frames) + { + foreach (var f in frames) f.Dispose(); + } + + /// Peak signal-to-noise ratio of the 8-bit sRGB encodings, optionally inside a margin. + private static double Psnr(ImageBuffer expected, ImageBuffer actual, int margin = 0) + { + var a = PixelConvert.ToInterleaved8(expected, 3); + var b = PixelConvert.ToInterleaved8(actual, 3); + double sum = 0; + long count = 0; + for (var y = margin; y < expected.Height - margin; y++) + { + for (var i = (y * expected.Width + margin) * 3; i < (y * expected.Width + expected.Width - margin) * 3; i++) + { + sum += (a[i] - b[i]) * (a[i] - b[i]); + count++; + } + } + return sum == 0 ? double.PositiveInfinity : 10 * double.Log10(255.0 * 255 / (sum / count)); + } + + private static double Rms(IReadOnlyList values) + { + var mean = values.Average(); + return double.Sqrt(values.Sum(v => (v - mean) * (v - mean)) / values.Count); + } + + /// RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve. + private static double FrameToFrameResidual(IReadOnlyList series, IReadOnlyList truth) + { + double sum = 0; + for (var i = 1; i < series.Count; i++) + { + var d = series[i] - series[i - 1] - (truth[i] - truth[i - 1]); + sum += d * d; + } + return double.Sqrt(sum / (series.Count - 1)); + } + + /// Largest |series − truth − c| with c the mean offset (the measurement constant). + private static double MaxDeviation(IReadOnlyList series, IReadOnlyList truth) + { + var offset = 0.0; + for (var i = 0; i < series.Count; i++) offset += series[i] - truth[i]; + offset /= series.Count; + var max = 0.0; + for (var i = 0; i < series.Count; i++) max = double.Max(max, double.Abs(series[i] - truth[i] - offset)); + return max; + } + + /// Synchronous progress sink (Progress<T> would post to the thread pool). + private sealed class Sink(Action report) : IProgress + { + public void Report(T value) => report(value); + } +} diff --git a/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs b/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs new file mode 100644 index 00000000..b050927c --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs @@ -0,0 +1,317 @@ +using Titano.Core.Codecs.Apng; +using Titano.Core.Codecs.Dng; +using Titano.Core.Codecs.Gif; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Core.Video.Avi; + +namespace Titano.Core.Render.Diagnostics; + +/// Plan, export, encoder-selection and codec checks. +public static partial class SelfTest +{ + private static readonly DateTime Origin = new(2024, 6, 21, 19, 0, 0); + + private static DateTime?[] Regular(int count) => [.. Enumerable.Range(0, count).Select(i => (DateTime?)Origin.AddSeconds(10 * i))]; + + private static ProjectSettings Timing(TimingMode mode, double? fit = null, IReadOnlyList? curve = null, IReadOnlyList? excluded = null) => new() + { + Timing = new TimingSettings { Mode = Manual(mode), FitToSeconds = fit, RemapCurve = curve ?? [new(0, 0), new(1, 1)] }, + ExcludedFrames = excluded ?? [], + }; + + private static void RequireExact(RenderPlan plan) + { + Require(plan.Frames.Sum(f => f.Duration90k) == plan.Duration90k, "durations do not add up to the total"); + Require(plan.Duration90k == RenderPlan.TicksAt(plan.FrameRate, plan.SlotCount), "total differs from the period grid"); + for (var k = 1; k < plan.Frames.Count; k++) + { + Require(plan.Frames[k].Start90k == plan.Frames[k - 1].Start90k + plan.Frames[k - 1].Duration90k, "frames are not contiguous"); + Require(plan.Frames[k].SourcePosition >= plan.Frames[k - 1].SourcePosition, "source positions go backwards"); + } + } + + private static IEnumerable PlanChecks() + { + yield return Check("plan.constant", "Constant timing: one frame per period, exact durations", () => + { + var plan = RenderPlan.Build(Regular(120), Timing(TimingMode.Constant), new Rational(24, 1)); + RequireExact(plan); + Require(plan.Frames.Count == 120 && plan.Frames.All(f => f.Duration90k == 3750 && f.Slots == 1), "not one 1/24 s frame per source frame"); + return Invariant($"120 frames, {plan.DurationSeconds} s"); + }); + yield return Check("plan.ntsc", "29.97 fps durations accumulate without drift", () => + { + var plan = RenderPlan.Build(Regular(1001), Timing(TimingMode.Constant), Rational.Fps2997); + RequireExact(plan); + Require(plan.Duration90k == 1001 * 3003L, Invariant($"total {plan.Duration90k} ticks, expected {1001 * 3003L}")); + return Invariant($"1001 frames = {plan.Duration90k} ticks"); + }); + yield return Check("plan.excluded", "Excluded frames are skipped", () => + { + var plan = RenderPlan.Build(Regular(30), Timing(TimingMode.Constant, excluded: [3, 4, 17]), new Rational(30, 1)); + RequireExact(plan); + Require(plan.Frames.Count == 27 && !plan.Frames.Any(f => f.From is 3 or 4 or 17 || f.To is 3 or 4 or 17), "an excluded frame is used"); + return "27 of 30 frames"; + }); + yield return Check("plan.adaptive.gap", "Adaptive: a doubled interval holds the frame for two periods", () => + { + var times = Regular(20); + for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddSeconds(10); + var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1)); + RequireExact(plan); + Require(plan.Frames[9].Slots == 2 && plan.Frames[9].IsHeld, Invariant($"frame 9 lasts {plan.Frames[9].Slots} periods")); + return "held 2 periods"; + }); + yield return Check("plan.adaptive.pause", "Adaptive: a deliberate pause becomes a short cut", () => + { + var times = Regular(20); + for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddHours(2); + var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1)); + RequireExact(plan); + var seconds = plan.Frames[9].Duration90k / 90000.0; + Require(seconds <= 0.25 && plan.IsCutBefore(10), Invariant($"pause shown for {seconds:0.###} s")); + return Invariant($"2 h pause shown for {seconds:0.###} s"); + }); + yield return Check("plan.interpolated", "Interpolated: a missing capture is synthesised half-way", () => + { + var times = Regular(20); + for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddSeconds(10); + var plan = RenderPlan.Build(times, Timing(TimingMode.Interpolated), new Rational(24, 1)); + RequireExact(plan); + Require(plan.Frames.Count == 21 && plan.Frames.Count(f => f.IsInterpolated) == 1 && plan.Frames[10].SourcePosition == 9.5, "no synthesised frame at 9.5"); + return "21 frames, 9.5 synthesised"; + }); + yield return Check("plan.remap.monotonic", "Remapped: positions are monotone even for a non-monotone curve", () => + { + var plan = RenderPlan.Build(Regular(90), Timing(TimingMode.Remapped, curve: [new(0, 0), new(0.3, 0.6), new(0.5, 0.4), new(1, 1)]), new Rational(24, 1)); + RequireExact(plan); + Require(plan.Warnings.Contains("Render.Plan.RemapNotMonotonic"), "the curve repair is not reported"); + return Invariant($"{plan.Frames.Count} frames, {plan.Statistics.InterpolatedFrames} synthesised"); + }); + yield return Check("plan.fit", "Fit to duration rescales the plan exactly", () => + { + var plan = RenderPlan.Build(Regular(300), Timing(TimingMode.Constant, fit: 5), new Rational(25, 1)); + RequireExact(plan); + Require(plan.SlotCount == 125 && plan.Duration90k == 450_000, Invariant($"{plan.SlotCount} periods, {plan.DurationSeconds} s")); + return Invariant($"300 frames in {plan.DurationSeconds} s, speed {plan.Statistics.MaximumSpeed:0.##}×"); + }); + } + + private static IEnumerable ExportChecks() + { + yield return Check("export.presets", "Every built-in preset resolves to itself and to valid encode settings", () => + { + foreach (var preset in ExportPresets.BuiltIn) + { + var resolved = ExportResolver.Resolve(new ExportSettings { Preset = Manual(preset.Id) }); + Require(resolved.PresetId == preset.Id && resolved.Warnings.Count == 0, preset.Id + " does not resolve to itself"); + var settings = resolved.ToEncodeSettings("out", int.Max(2, preset.Width), int.Max(2, preset.Height)); + Require(settings.GopLength >= 1 && (VideoCodecInfo.IsManaged(preset.Codec) || settings.BitRate > 0), preset.Id + " has invalid encode settings"); + } + return Invariant($"{ExportPresets.BuiltIn.Count} presets"); + }); + yield return Check("export.custom", "Editing a value gives Custom; equal values restore the preset", () => + { + var edited = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { Height = 1000 } }); + var restored = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { Height = 1080, Codec = "H.264" } }); + var other = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { FrameRate = "60" } }); + Require(edited.IsCustom && restored.PresetId == "1080p-h264" && other.PresetId == "1080p60", "the Custom rule is broken"); + return "custom ↔ preset"; + }); + yield return Check("export.naming", "Name tokens expand and are sanitised", () => + { + var name = ExportNaming.Expand("{date} {title} - {preset} {width}x{height} {fps} {codec}", new ExportNameContext + { + Date = Origin, + Title = "Harbour: sunset", + PresetName = "4K", + Width = 3840, + Height = 2160, + FrameRate = Rational.Fps2997, + Codec = VideoCodec.Hevc, + }); + Require(name.IsValid && name.Name == "2024-06-21 Harbour_ sunset - 4K 3840x2160 29.97 HEVC", "expanded to \"" + name.Name + "\""); + return name.Name; + }); + yield return Check("export.collision", "Existing outputs get a numbered suffix", context => + { + var nameContext = new ExportNameContext { Date = Origin, PresetName = "GIF", Codec = VideoCodec.Gif, Title = "Clip" }; + var first = ExportNaming.OutputPath(context.WorkDirectory, "{title}", nameContext); + File.WriteAllBytes(first, [0]); + var second = ExportNaming.OutputPath(context.WorkDirectory, "{title}", nameContext); + Require(Path.GetFileName(first) == "Clip.gif" && Path.GetFileName(second) == "Clip (2).gif", "got " + Path.GetFileName(second)); + return Task.FromResult(Path.GetFileName(second)); + }); + yield return Check("export.estimate", "Size and time estimates are consistent", () => + { + var export = ExportResolver.FromPreset(ExportPresets.Find("4k-hevc")!); + var workload = new ExportWorkload(720, 720, 24, 3840, 2160, 3840L * 2160, 0, 0, true); + var bytes = ExportEstimator.EstimateBytes(export, workload); + var expected = export.EffectiveBitRate(3840, 2160) * 24 / 8.0 * 1.01; + Require(double.Abs(bytes - expected) <= 1, "video size is not bit rate × duration"); + var time = ExportEstimator.EstimateTime(export.Codec, workload, ThroughputModel.Default); + var calibrated = ThroughputModel.Default.Calibrate(time, time / 2, 1); + Require(double.Abs(ExportEstimator.EstimateTime(export.Codec, workload, calibrated).TotalSeconds * 2 - time.TotalSeconds) < 1e-6, "calibration does not rescale"); + return Invariant($"{bytes / 1e6:0.#} MB, {time.TotalSeconds:0} s"); + }); + yield return Check("select.managed", "Managed codecs select the managed encoder on clients and servers", context => + { + foreach (var host in new[] { EncoderHost.Client, EncoderHost.Server }) + { + var selection = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("png-sequence")!).ToEncodeSettings("x", 640, 360), context.Encoders, host); + Require(selection.IsReady && selection.Provider is Video.Managed.ManagedEncoderProvider, "PNG is not served by the managed encoder"); + } + return Task.FromResult("managed"); + }); + yield return Check("select.server", "MP4 on the server needs a render node", context => + { + var selection = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("1080p-h264")!).ToEncodeSettings("x.mp4", 1920, 1080), context.Encoders, EncoderHost.Server); + Require(selection.Status == EncoderSelectionStatus.NeedsRenderNode && selection.Notices.Any(n => n.Key == EncoderNotices.NeedsRenderNode), "no render-node notice"); + return Task.FromResult(selection.Notices[0].Key); + }); + yield return Check("select.client", "MP4 on this client: hardware preferred, HEVC falls back to H.264 with a reason", context => + { + var hevc = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("4k-hevc")!).ToEncodeSettings("x.mp4", 3840, 2160), context.Encoders, EncoderHost.Client); + var hasHevc = context.Encoders.Any(p => p.Capabilities.Any(c => c.Codec == VideoCodec.Hevc)); + var hasH264 = context.Encoders.Any(p => p.Capabilities.Any(c => c.Codec == VideoCodec.H264)); + if (!hasHevc) Require(hevc.Notices.Count > 0 && hevc.Notices[0].Key == EncoderNotices.FallbackToH264, "no H.264 fallback notice"); + if (!hasHevc && !hasH264) Require(hevc.Status == EncoderSelectionStatus.Unavailable, "an MP4 encoder was selected without any"); + if (hasH264) + { + var h264 = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("1080p-h264")!).ToEncodeSettings("x.mp4", 1920, 1080), context.Encoders, EncoderHost.Client); + var hardware = context.Encoders.SelectMany(p => p.Capabilities).Any(c => c.Codec == VideoCodec.H264 && c.Hardware); + Require(h264.IsReady && h264.Capability!.Hardware == hardware, "hardware H.264 is not preferred"); + return Task.FromResult($"{hevc.Status} via {hevc.Capability?.Name ?? "none"}; H.264 via {h264.Capability!.Name}"); + } + return Task.FromResult(string.Join(", ", hevc.Notices.Select(n => n.Key))); + }); + yield return Check("export.setup", "A render setup reports size, encoder, plan and estimates before rendering", context => + { + var source = Synthetic(48, o => o with { Width = 480, Height = 320 }); + var input = Input(source, Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } }); + var setup = Pipeline(context).Setup(input, Target(context, Preset("gif-preview", 480, 270))); + var estimate = setup.Estimate(); + Require(setup.Encoder.IsReady && (setup.Geometry.OutputWidth, setup.Geometry.OutputHeight) == (480, 270) && setup.Plan.Frames.Count == 48 + && setup.NeedsPreparation && setup.Geometry.WorkingLongEdge == 480 && estimate.Bytes > 0 && estimate.Time > TimeSpan.Zero, "the setup is inconsistent"); + return Task.FromResult(Invariant($"{estimate.Bytes / 1024} KiB, {estimate.Time.TotalSeconds:0.#} s estimated")); + }); + yield return Check("select.limits", "Sizes beyond the codec levels are capped with a reason", () => + { + var check = CodecLimits.Check(VideoCodec.Hevc, 7680, 4320, 240, 0); + Require(!check.Fits && check.SuggestedWidth > 0, "8K at 240 fps should exceed HEVC level 6.2"); + Require(CodecLimits.Check(VideoCodec.Hevc, check.SuggestedWidth, check.SuggestedHeight, 240, 0).Fits, "the suggested size does not fit"); + return Invariant($"8K240 → {check.SuggestedWidth}×{check.SuggestedHeight}"); + }); + } + + private static ImageBuffer CodecFrame(int seed) + { + var image = new ImageBuffer(64, 48); + for (var y = 0; y < 48; y++) + { + for (var x = 0; x < 64; x++) + { + image[0, x, y] = (x + seed * 5) % 64 / 64f; + image[1, x, y] = y / 48f * 0.8f; + image[2, x, y] = (x * y + seed) % 29 / 28f * 0.6f; + } + } + return image; + } + + private static IEnumerable CodecChecks() + { + yield return Check("codec.jpeg", "JPEG round trip", () => + { + using var frame = CodecFrame(1); + using var back = JpegDecoder.DecodeToLinear(JpegEncoder.Encode(frame, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 })); + var psnr = Psnr(frame, back); + Require(psnr > 33, Invariant($"PSNR {psnr:0.#} dB")); + return Invariant($"PSNR {psnr:0.#} dB"); + }); + yield return Check("codec.png8", "PNG 8-bit round trip is exact", () => + { + using var frame = CodecFrame(2); + Require(PngDecoder.Decode(PngEncoder.Encode(frame)).Pixels8!.AsSpan().SequenceEqual(PixelConvert.ToInterleaved8(frame, 3)), "pixels differ"); + return "exact"; + }); + yield return Check("codec.png16", "PNG 16-bit round trip is exact", () => + { + using var frame = CodecFrame(3); + Require(PngDecoder.Decode(PngEncoder.Encode(frame, 16)).Pixels16!.AsSpan().SequenceEqual(PixelConvert.ToInterleaved16(frame, 3)), "pixels differ"); + return "exact"; + }); + yield return Check("codec.tiff16", "TIFF 16-bit round trip is exact", () => + { + using var frame = CodecFrame(4); + var reader = TiffReader.Open(new MemoryStream(TiffWriter.Write(frame))) ?? throw new InvalidDataException("Not a TIFF"); + var raster = TiffImageReader.ReadRaster(reader, reader.ReadChain()[0]); + Require(raster.Samples is not null && raster.Samples.AsSpan().SequenceEqual(PixelConvert.ToInterleaved16(frame, 3)), "samples differ"); + return "exact"; + }); + yield return Check("codec.dng", "Linear DNG round trip within one 16-bit step", () => + { + using var frame = CodecFrame(5); + using var back = TiffImageReader.Decode(LinearDngWriter.Write(frame, new LinearDngOptions { TileSize = 64 })); + var error = 0.0; + for (var i = 0; i < frame.Data.Length; i++) error = double.Max(error, double.Abs(frame.Data[i] - back.Data[i])); + Require(error <= 1.0 / 65535 + 1e-7, Invariant($"error {error:E2}")); + return Invariant($"max error {error * 65535:0.##} LSB"); + }); + yield return Check("codec.gif", "GIF frames and delays round trip", () => + { + using var stream = new MemoryStream(); + var gif = new GifEncoder(stream, 64, 48); + for (var i = 0; i < 3; i++) + { + using var f = CodecFrame(i); + gif.AddFrame(f, 9000 * (i + 1)); + } + gif.Complete(); + var animation = GifReader.Decode(stream.ToArray()); + Require(animation.Frames.Count == 3 && animation.Duration90k == 54000 && animation.LoopCount == 0, "frames or delays differ"); + using var expected = CodecFrame(2); + using var decoded = animation.ToLinear(2); + var psnr = Psnr(expected, decoded); + Require(psnr > 25, Invariant($"PSNR {psnr:0.#} dB")); + return Invariant($"3 frames, 0.6 s, PSNR {psnr:0.#} dB"); + }); + yield return Check("codec.apng", "APNG frames and delays round trip exactly", () => + { + using var stream = new MemoryStream(); + var apng = new ApngEncoder(stream, 64, 48); + for (var i = 0; i < 3; i++) + { + using var f = CodecFrame(i); + apng.AddFrame(f, 6000); + } + apng.Complete(); + var animation = ApngReader.Decode(stream.ToArray()); + using var expected = CodecFrame(1); + using var decoded = animation.ToLinear(1); + var psnr = Psnr(expected, decoded); + Require(animation.Frames.Count == 3 && animation.Duration90k == 18000 && psnr > 60, Invariant($"{animation.Frames.Count} frames, {animation.Duration90k} ticks, PSNR {psnr:0.#} dB")); + return "3 frames, exact delays"; + }); + yield return Check("codec.avi", "MJPEG AVI headers and indexes", () => + { + using var stream = new MemoryStream(); + var writer = new AviMjpegWriter(stream, 64, 48, Rational.Fps2997); + using var frame = CodecFrame(0); + var jpeg = JpegEncoder.Encode(frame); + for (var i = 0; i < 5; i++) writer.WriteFrame(jpeg); + writer.Complete(); + var avi = AviReader.Read(stream.ToArray()); + Require(avi.Frames.Count == 5 && avi.HeaderFrames == 5 && avi.StreamFrames == 5 && avi.IndexEntries == 5 && avi.FrameRate == Rational.Fps2997 + && (avi.Width, avi.Height) == (64, 48), "AVI structure differs"); + return "5 frames, 30000/1001"; + }); + } +} diff --git a/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs b/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs new file mode 100644 index 00000000..540e0cb8 --- /dev/null +++ b/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs @@ -0,0 +1,558 @@ +using Titano.Core.Analysis; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Core.Video.Managed; + +namespace Titano.Core.Render.Diagnostics; + +/// Renders through the whole pipeline: output formats, processing modules and robustness. +public static partial class SelfTest +{ + private static IEnumerable RenderChecks() + { + (string Id, string Preset, int Depth, double MinPsnr)[] formats = + [ + ("render.mjpeg", "mjpeg-avi", 8, 35), ("render.jpeg", "jpeg-sequence", 8, 35), ("render.png8", "png-sequence", 8, 60), + ("render.png16", "png-sequence", 16, 60), ("render.tiff16", "tiff16-sequence", 16, 60), ("render.dng", "dng-sequence", 16, 60), + ("render.gif", "gif-preview", 8, 25), ("render.apng", "apng", 8, 60), + ]; + foreach (var (id, preset, depth, minPsnr) in formats) + yield return Check(id, $"Render a synthetic sequence to {preset} ({depth}-bit) and decode it back", context => RenderFormatAsync(context, preset, depth, minPsnr)); + yield return Check("render.mp4", "Render MP4 with this machine's platform encoders and inspect the file", RenderMp4Async); + yield return Check("render.held", "Held frames repeat on constant-rate outputs", async context => + { + var source = Synthetic(10, o => o with { TimeShifts = [new SyntheticTimeShift(5, 20)] }); + var project = Plain with { Timing = new TimingSettings { Mode = Manual(TimingMode.Adaptive) } }; + var result = await Pipeline(context).RenderAsync(Input(source, project), Target(context, Preset("mjpeg-avi")), cancellationToken: context.Cancellation).ConfigureAwait(false); + var avi = AviReader.Read(await File.ReadAllBytesAsync(result.OutputPath, context.Cancellation).ConfigureAwait(false)); + Require(result.FrameCount == 10 && avi.Frames.Count == 12, Invariant($"{result.FrameCount} pictures in {avi.Frames.Count} AVI frames")); + return "10 pictures, 12 frames"; + }); + } + + private static async Task RenderFormatAsync(SelfTestContext context, string presetId, int bitDepth, double minPsnr) + { + var source = Synthetic(12); + var export = Preset(presetId) with { BitDepth = bitDepth }; + var target = Target(context, export); + var result = await Pipeline(context).RenderAsync(Input(source), target, cancellationToken: context.Cancellation).ConfigureAwait(false); + var entries = Directory.GetFileSystemEntries(context.WorkDirectory); + Require(entries.Length == 1 && entries[0] == target.OutputPath, "the folder holds more than the output"); + Require(result.Bytes > 0 && result.FrameCount == 12, Invariant($"{result.FrameCount} frames, {result.Bytes} bytes")); + + int count; + ImageBuffer decoded; + switch (export.Codec) + { + case VideoCodec.Mjpeg: + var avi = AviReader.Read(await File.ReadAllBytesAsync(target.OutputPath, context.Cancellation).ConfigureAwait(false)); + Require(avi.FrameRate == export.FrameRate && (avi.Width, avi.Height) == (96, 64), "AVI headers differ"); + count = avi.Frames.Count; + decoded = JpegDecoder.DecodeToLinear(avi.Frames[5]); + break; + case VideoCodec.Gif or VideoCodec.Apng: + var bytes = await File.ReadAllBytesAsync(target.OutputPath, context.Cancellation).ConfigureAwait(false); + var animation = export.Codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes); + var expectedTicks = RenderPlan.TicksAt(export.FrameRate, 12); + Require(double.Abs(animation.Duration90k - expectedTicks) <= 900, Invariant($"duration {animation.Duration90k} ticks, expected {expectedTicks}")); + count = animation.Frames.Count; + decoded = animation.ToLinear(5); + break; + default: + var files = Directory.GetFiles(target.OutputPath).Order(StringComparer.Ordinal).ToArray(); + var stem = Path.GetFileName(target.OutputPath); + Require(files.Select(Path.GetFileName).SequenceEqual(Enumerable.Range(1, files.Length).Select(i => ImageSequenceSession.FrameName(stem, i, VideoCodecInfo.FileExtension(export.Codec)))), + "frame files are not numbered 1…n"); + count = files.Length; + var data = await File.ReadAllBytesAsync(files[5], context.Cancellation).ConfigureAwait(false); + decoded = export.Codec switch + { + VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(data), + VideoCodec.PngSequence => PngDecoder.DecodeToLinear(data), + _ => TiffImageReader.Decode(data), + }; + break; + } + using (decoded) + using (var expected = source.Sequence.Render(5)) + { + Require(count == 12, Invariant($"{count} pictures in the output")); + var psnr = Psnr(expected, decoded); + Require(psnr >= minPsnr, Invariant($"PSNR {psnr:0.#} dB < {minPsnr} dB")); + return Invariant($"{result.Bytes} bytes, PSNR {(double.IsPositiveInfinity(psnr) ? "∞" : psnr.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture))} dB, {result.EncoderName}"); + } + } + + private static async Task RenderMp4Async(SelfTestContext context) + { + var codecs = context.PlatformEncoders.SelectMany(p => p.Capabilities).Select(c => c.Codec).Where(c => !VideoCodecInfo.IsManaged(c)).Distinct().ToList(); + if (codecs.Count == 0) throw new SkipException("no MP4 encoder on this machine"); + var pipeline = new RenderPipeline(context.Encoders); + var details = new List(); + foreach (var codec in codecs) + { + var export = Preset("1080p-h264", 320, 180) with { Codec = codec, Profile = CodecProfile.Auto, BitRate = 0, BitsPerPixel = 0 }; + var result = await pipeline.RenderAsync(Input(Synthetic(24)), Target(context, export, codec.ToString()), cancellationToken: context.Cancellation).ConfigureAwait(false); + var report = Mp4Inspector.Inspect(result.OutputPath); + Require(report.IsValid, codec + ": " + string.Join("; ", report.Errors)); + Require(report.Codec == codec && report.FrameCount == 24 && (report.Width, report.Height) == (320, 180), Invariant($"{codec}: {report.Codec} {report.Width}×{report.Height}, {report.FrameCount} frames")); + Require(double.Abs(report.Duration.TotalSeconds - result.DurationSeconds) < 0.05, Invariant($"{codec}: duration {report.Duration.TotalSeconds:0.###} s")); + details.Add($"{codec} via {result.EncoderName}{(result.Hardware ? " (hardware)" : string.Empty)}"); + } + return string.Join(", ", details); + } + + private static IEnumerable ProcessingChecks() + { + yield return Check("proc.deflicker", "Deflicker on rendered frames: flicker −60 % or better, ramp kept within 0.05 EV (§20.4)", async context => + { + var source = Synthetic(200, o => o with { Seed = 3, StartEv = -2, EndEv = 1, FlickerEv = 0.1 }); + var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true), DeflickerWindow = Manual(21), HighlightKnee = null } }; + var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false); + var output = frames.Select(f => FrameStatistics.MeasureLogLuminance(f)).ToArray(); + DisposeAll(frames); + var input = Enumerable.Range(0, 200).Select(i => + { + using var f = source.Sequence.Render(i); + return FrameStatistics.MeasureLogLuminance(f); + }).ToArray(); + var before = FrameToFrameResidual(input, source.Sequence.SceneEv); + var after = FrameToFrameResidual(output, source.Sequence.SceneEv); + var ramp = MaxDeviation(output, source.Sequence.SceneEv); + Require(1 - after / before >= 0.6, Invariant($"flicker reduced by {1 - after / before:P0} only")); + Require(ramp <= 0.05, Invariant($"ramp deviates by {ramp:0.###} EV")); + return Invariant($"flicker −{1 - after / before:P0}, ramp within {ramp:0.###} EV"); + }); + yield return Check("proc.holygrail", "Holy grail: no output step above 0.3 EV (§20.4)", async context => + { + var source = Synthetic(80, o => o with { ExposureSteps = [new SyntheticExposureStep(40, 1.0)], StartEv = 0, EndEv = 0 }); + var project = Plain with { Exposure = new ExposureSettings { HolyGrail = Manual(true), Deflicker = Manual(true), HighlightKnee = null } }; + var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false); + var output = frames.Select(f => FrameStatistics.MeasureLogLuminance(f)).ToArray(); + DisposeAll(frames); + var step = output.Zip(output.Skip(1), (a, b) => double.Abs(b - a)).Max(); + Require(step <= 0.32, Invariant($"largest step {step:0.###} EV")); + Require(double.Abs(output[^1] - output[0] + 1) <= 0.1, "the exposure step was not kept"); + return Invariant($"largest step {step:0.###} EV"); + }); + yield return Check("proc.regions", "Region deflicker: land residual at most half of the global correction's", async context => + { + var source = Synthetic(48, o => o with { SkyFlickerEv = 0.3, LandFlickerEv = 0.3, StartEv = 0, EndEv = 0 }); + var land = new float[96 * 64]; + for (var y = 0; y < 64; y++) + { + for (var x = 0; x < 96; x++) land[y * 96 + x] = source.Sequence.IsSky(x, y) || y + 0.5 < source.Sequence.HorizonRow(x + 0.5) + 2 ? 0 : 1; + } + async Task LandResidualAsync(RegionMode mode, string name) + { + var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true), Regions = Manual(mode), HighlightKnee = null } }; + var frames = await RenderDecodedAsync(context, Input(source, project), name: name).ConfigureAwait(false); + var series = frames.Select(f => FrameStatistics.MeasureLogLuminance(f, land)).ToArray(); + DisposeAll(frames); + return Rms(series); + } + var global = await LandResidualAsync(RegionMode.Off, "global").ConfigureAwait(false); + var regions = await LandResidualAsync(RegionMode.Horizon, "regions").ConfigureAwait(false); + Require(regions <= 0.5 * global, Invariant($"land residual {regions:0.###} EV vs global {global:0.###} EV")); + return Invariant($"land residual {regions:0.###} vs {global:0.###} EV"); + }); + yield return Check("proc.whitebalance", "White-balance smoothing removes colour jitter", async context => + { + var source = Synthetic(48, o => o with { WhiteBalanceJitter = 0.1 }); + var project = Plain with { Exposure = new ExposureSettings { WhiteBalanceSmoothing = Manual(true), HighlightKnee = null } }; + var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false); + static double Ratio(ImageBuffer f) + { + var stats = FrameStatistics.Measure(f); + return double.Log2(stats.MeanRed / stats.MeanGreen); + } + var after = frames.Select(Ratio).ToArray(); + DisposeAll(frames); + var before = Enumerable.Range(0, 48).Select(i => + { + using var f = source.Sequence.Render(i); + return Ratio(f); + }).ToArray(); + static double Jitter(double[] r) => double.Sqrt(r.Zip(r.Skip(1), (a, b) => (b - a) * (b - a)).Average()); + Require(Jitter(after) < 0.3 * Jitter(before), Invariant($"R/G jitter {Jitter(before):0.####} → {Jitter(after):0.####}")); + return Invariant($"R/G jitter {Jitter(before):0.###} → {Jitter(after):0.####}"); + }); + yield return Check("proc.offset", "Exposure offset +1 EV doubles linear values", async context => + { + var source = Synthetic(2); + var plain = await RenderDecodedAsync(context, Input(source), name: "plain").ConfigureAwait(false); + var brighter = await RenderDecodedAsync(context, Input(source, Plain with { Exposure = new ExposureSettings { ExposureOffsetEv = 1, HighlightKnee = null } }), name: "bright") + .ConfigureAwait(false); + var error = 0.0; + for (var i = 0; i < plain[0].Data.Length; i++) error = double.Max(error, double.Abs(2 * plain[0].Data[i] - brighter[0].Data[i]) / (1e-3 + brighter[0].Data[i])); + DisposeAll(plain); + DisposeAll(brighter); + Require(error < 0.01, Invariant($"relative error {error:P2}")); + return Invariant($"relative error {error:P3}"); + }); + yield return Check("proc.knee", "The highlight knee keeps values below 1 and leaves shadows alone", async context => + { + var source = Synthetic(2, o => o with { StartEv = 2, EndEv = 2 }); + var hard = await RenderDecodedAsync(context, Input(source), name: "hard").ConfigureAwait(false); + var knee = await RenderDecodedAsync(context, Input(source, Plain with { Exposure = new ExposureSettings { HighlightKnee = 0.8 } }), name: "knee").ConfigureAwait(false); + var clipped = hard[0].Data.ToArray().Count(v => v >= 0.9999f); + var top = knee[0].Data.ToArray().Max(); + var shadows = true; + for (var i = 0; i < hard[0].Data.Length; i++) + { + if (hard[0].Data[i] < 0.5f) shadows &= double.Abs(hard[0].Data[i] - knee[0].Data[i]) < 1e-4; + } + DisposeAll(hard); + DisposeAll(knee); + Require(clipped > 0 && top < 0.9999f && shadows, Invariant($"{clipped} clipped samples without knee, max {top:0.####} with it")); + return Invariant($"{clipped} clipped samples → max {top:0.###}"); + }); + yield return Check("proc.aspect", "A square export crops the centre of a 3:2 frame", async context => + { + var source = Synthetic(3); + var frames = await RenderDecodedAsync(context, Input(source), Preset("png-sequence", 64, 64)).ConfigureAwait(false); + using var reference = source.Sequence.Render(1); + using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(16, 0, 64, 64), OutputWidth = 64, OutputHeight = 64 }); + var psnr = Psnr(expected, frames[1]); + DisposeAll(frames); + Require(psnr > 60, Invariant($"PSNR {psnr:0.#} dB")); + return "centre 64×64"; + }); + yield return Check("proc.crop", "The camera crop selects its region at source size", async context => + { + var source = Synthetic(3); + var project = Plain with { Camera = new CameraSettings { Crop = [0.5, 0.5, 0.5, 0.5] } }; + var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 0, 0)).ConfigureAwait(false); + using var reference = source.Sequence.Render(1); + using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(48, 32, 48, 32) }); + var size = (frames[1].Width, frames[1].Height); + var psnr = Psnr(expected, frames[1]); + DisposeAll(frames); + Require(size == (48, 32) && psnr > 60, Invariant($"{size}, PSNR {psnr:0.#} dB")); + return "quarter 48×32"; + }); + yield return Check("proc.zoom", "Virtual-camera zoom matches a direct crop and doubles the decode size", async context => + { + var source = Synthetic(3, o => o with { Width = 480, Height = 320 }); + var project = Plain with { Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 2, 0), new CameraKey(2, 0.5, 0.5, 2, 0)] } }; + var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 96, 64)).ConfigureAwait(false); + using var full = source.Sequence.Render(1); + using var expected = GeometryStage.Apply(full, new GeometrySettings { Crop = new RectD(120, 80, 240, 160), OutputWidth = 96, OutputHeight = 64 }); + var psnr = Psnr(expected, frames[1]); + DisposeAll(frames); + Require(psnr > 28 && source.LargestRenderRequest == 192, Invariant($"PSNR {psnr:0.#} dB, decoded at {source.LargestRenderRequest} px")); + return Invariant($"PSNR {psnr:0.#} dB, decode {source.LargestRenderRequest} px"); + }); + yield return Check("proc.stabilize", "Stabilisation removes 90 % of the camera shake", async context => + { + var random = new Random(11); + var shake = Enumerable.Range(0, 24).Select(_ => (X: random.NextDouble() * 6 - 3, Y: random.NextDouble() * 6 - 3)).ToArray(); + var source = new PatternFrameSource(320, 192, 24, i => shake[i]); + var project = Plain with { Motion = new MotionSettings { Stabilize = Manual(true), StabilizeSmoothing = Manual(12.0) } }; + var input = new RenderInput { Source = source, Frames = source.Metadata(), Project = project }; + var frames = await RenderDecodedAsync(context, input, Preset("png-sequence", 0, 0)).ConfigureAwait(false); + using var stabilizer = new Stabilizer(320, 192); + var motions = frames.Select(f => stabilizer.AddFrame(f).Transform).Skip(1).ToArray(); + DisposeAll(frames); + var after = double.Sqrt(motions.Average(m => m.Tx * m.Tx + m.Ty * m.Ty)); + var before = double.Sqrt(Enumerable.Range(1, 23).Average(k => double.Pow(shake[k].X - shake[k - 1].X, 2) + double.Pow(shake[k].Y - shake[k - 1].Y, 2))); + Require(after <= 0.1 * before * 1.2, Invariant($"frame-to-frame shake {before:0.##} → {after:0.###} px")); + return Invariant($"shake {before:0.##} → {after:0.###} px"); + }); + yield return Check("proc.interpolate", "Synthesised in-betweens follow the motion", async context => + { + var source = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (2.0 * i, 0)); + var project = Plain with { Timing = new TimingSettings { Mode = Manual(TimingMode.Interpolated), FrameRate = Manual("15") } }; + var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false); + var truth = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (2.0 * i + 1, 0)); + using var halfway = await truth.GetFrameAsync(2, 0, DecodePurpose.Render, context.Cancellation).ConfigureAwait(false); + var synthesised = Psnr(halfway, frames[5], 8); + var nearest = Psnr(halfway, frames[4], 8); + var count = frames.Count; + DisposeAll(frames); + Require(count == 12 && synthesised > 30 && synthesised > nearest + 5, Invariant($"{count} frames, {synthesised:0.#} dB vs nearest {nearest:0.#} dB")); + return Invariant($"{synthesised:0.#} dB (nearest whole frame {nearest:0.#} dB)"); + }); + yield return Check("proc.motionblur", "Motion blur smears along the motion and leaves still scenes alone", async context => + { + var blur = new MotionSettings { MotionBlur = Manual(true), TargetShutterAngle = Manual(360.0) }; + var moving = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (3.0 * i, 0)); + var sharp = await RenderDecodedAsync(context, Input(moving), name: "sharp").ConfigureAwait(false); + var blurred = await RenderDecodedAsync(context, Input(moving, Plain with { Motion = blur }), name: "blurred").ConfigureAwait(false); + static double Gradient(ImageBuffer f, int dx, int dy) + { + double sum = 0; + var g = f.Plane(1); + for (var y = 8; y < f.Height - 8; y++) + { + for (var x = 8; x < f.Width - 8; x++) sum += double.Abs(g[y * f.Width + x] - g[(y + dy) * f.Width + x + dx]); + } + return sum; + } + var horizontal = Gradient(blurred[3], 1, 0) / Gradient(sharp[3], 1, 0); + var vertical = Gradient(blurred[3], 0, 1) / Gradient(sharp[3], 0, 1); + DisposeAll(sharp); + DisposeAll(blurred); + var still = Synthetic(4, o => o with { StartEv = 0, EndEv = 0 }); + var a = await RenderDecodedAsync(context, Input(still), name: "still").ConfigureAwait(false); + var b = await RenderDecodedAsync(context, Input(still, Plain with { Motion = blur }), name: "still-blur").ConfigureAwait(false); + var stillPsnr = Psnr(a[2], b[2]); + DisposeAll(a); + DisposeAll(b); + Require(horizontal < 0.75 && vertical > horizontal + 0.1 && stillPsnr > 40, Invariant($"gradients ×{horizontal:0.##} along, ×{vertical:0.##} across; still {stillPsnr:0.#} dB")); + return Invariant($"gradient ×{horizontal:0.##} along, ×{vertical:0.##} across"); + }); + yield return Check("proc.median", "A median stack removes a one-frame transient", async context => + { + var source = Synthetic(9, o => o with { StartEv = 0, EndEv = 0 }); + var project = Plain with { Stack = new StackSettings { Mode = StackSetting.Median, Length = 5 } }; + var input = Input(source, project) with { Source = new TransientSource(source, 4) }; + var frames = await RenderDecodedAsync(context, input).ConfigureAwait(false); + using var clean = source.Sequence.Render(4); + var psnr = Psnr(clean, frames[4]); + DisposeAll(frames); + Require(psnr > 45, Invariant($"PSNR {psnr:0.#} dB")); + return "transient removed"; + }); + yield return Check("proc.startrails", "Star-trail luminance never decreases on 99 % of steps (§20.4)", async context => + { + var source = Synthetic(16, o => o with { StarField = true, StarCount = 60, StartEv = 0, EndEv = 0 }, i => (1.0 * i, 0.5 * i)); + var project = Plain with { Stack = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 } }; + var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false); + var luminance = frames.Select(f => FrameStatistics.MeasureLogLuminance(f, default, 0, 0)).ToArray(); + DisposeAll(frames); + var rising = luminance.Zip(luminance.Skip(1), (a, b) => b >= a - 1e-9).Count(r => r); + Require(rising >= 0.99 * (luminance.Length - 1), Invariant($"{rising} of {luminance.Length - 1} steps non-decreasing")); + return Invariant($"{rising}/{luminance.Length - 1} steps non-decreasing"); + }); + yield return Check("proc.cached", "Cached analysis skips the measuring pass and gives the same corrections", async context => + { + var source = Synthetic(30, o => o with { FlickerEv = 0.2 }); + var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } }; + var measured = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: context.Cancellation).ConfigureAwait(false); + var decodes = source.Decodes; + var cached = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = new PrecomputedAnalysis { LogLuminance = measured.MeasuredLogLuminance } }, + cancellationToken: context.Cancellation).ConfigureAwait(false); + Require(cached.Report.MeasuredFrames == 0 && source.Decodes == decodes && cached.ExposureEv.AsSpan().SequenceEqual(measured.ExposureEv), "the cache was not used as is"); + return Invariant($"{measured.Report.MeasuredFrames} frames measured once"); + }); + } + + private static IEnumerable RobustnessChecks() + { + yield return Check("robust.deterministic", "Identical inputs give byte-identical lossless outputs", async context => + { + var project = Plain with + { + Exposure = new ExposureSettings { Deflicker = Manual(true) }, + Timing = new TimingSettings { Mode = Manual(TimingMode.Interpolated), FrameRate = Manual("15") }, + }; + var a = await Pipeline(context).RenderAsync(Input(Synthetic(12, o => o with { FlickerEv = 0.2 }), project), Target(context, Preset("png-sequence"), "a"), cancellationToken: context.Cancellation) + .ConfigureAwait(false); + var b = await Pipeline(context).RenderAsync(Input(Synthetic(12, o => o with { FlickerEv = 0.2 }), project), Target(context, Preset("png-sequence"), "b"), cancellationToken: context.Cancellation) + .ConfigureAwait(false); + var filesA = Directory.GetFiles(a.OutputPath).Order(StringComparer.Ordinal).ToArray(); + var filesB = Directory.GetFiles(b.OutputPath).Order(StringComparer.Ordinal).ToArray(); + Require(filesA.Length == filesB.Length && filesA.Length > 12, "different frame counts"); + for (var i = 0; i < filesA.Length; i++) Require(File.ReadAllBytes(filesA[i]).AsSpan().SequenceEqual(File.ReadAllBytes(filesB[i])), $"frame {i + 1} differs"); + return Invariant($"{filesA.Length} frames identical"); + }); + foreach (var preset in new[] { "mjpeg-avi", "png-sequence", "gif-preview", "apng" }) + { + yield return Check("robust.cancel." + preset.Split('-')[0], $"Cancelling a {preset} render leaves no file behind (§20.4)", async context => + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation); + var progress = new Sink(p => + { + if (p.Stage == RenderStage.Rendering && p.Done == 5) cts.Cancel(); + }); + try + { + await Pipeline(context).RenderAsync(Input(Synthetic(24)), Target(context, Preset(preset)), progress: progress, cancellationToken: cts.Token).ConfigureAwait(false); + Require(false, "the render was not cancelled"); + } + catch (OperationCanceledException) when (!context.Cancellation.IsCancellationRequested) + { + } + Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output or temporary files remain"); + return "nothing left"; + }); + } + yield return Check("robust.source-failure", "A failing frame stops the render once, without output", async context => + { + var input = Input(Synthetic(12)) with { Source = new FailingSource(Synthetic(12), 7) }; + var error = await CaptureAsync(() => Pipeline(context).RenderAsync(input, Target(context, Preset("mjpeg-avi")), cancellationToken: context.Cancellation)).ConfigureAwait(false); + Require(error is IOException { Message: "frame 7 is unreadable" }, "unexpected error " + error?.GetType().Name); + Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output remains"); + return "IOException, no output"; + }); + yield return Check("robust.encoder-failure", "An encoder failure stops the render once, without output", async context => + { + var pipeline = new RenderPipeline([new FaultInjectingProvider(new ManagedEncoderProvider(), 4)]); + var error = await CaptureAsync(() => pipeline.RenderAsync(Input(Synthetic(12)), Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)).ConfigureAwait(false); + Require(error is InvalidDataException { Message: FaultInjectingProvider.Message }, "unexpected error " + error?.GetType().Name); + Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output remains"); + return "InvalidDataException, no output"; + }); + yield return Check("robust.unobserved", "Failed renders leave no unobserved task exceptions (§20.4)", async context => + { + var unobserved = 0; + void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved); + TaskScheduler.UnobservedTaskException += Handler; + try + { + for (var i = 0; i < 3; i++) + { + var pipeline = new RenderPipeline([new FaultInjectingProvider(new ManagedEncoderProvider(), 2 + i)]); + await CaptureAsync(() => pipeline.RenderAsync(Input(Synthetic(12)), Target(context, Preset("gif-preview")), cancellationToken: context.Cancellation)).ConfigureAwait(false); + var input = Input(Synthetic(12)) with { Source = new FailingSource(Synthetic(12), 3 + i) }; + await CaptureAsync(() => Pipeline(context).RenderAsync(input, Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)).ConfigureAwait(false); + } + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + finally + { + TaskScheduler.UnobservedTaskException -= Handler; + } + Require(unobserved == 0, Invariant($"{unobserved} unobserved exceptions")); + return "none"; + }); + yield return Check("robust.memory", "Peak memory does not depend on the sequence length (§20.4)", async context => + { + async Task PeakAsync(int frames, string name) + { + long peak = 0; + var progress = new Sink(p => + { + if (p.Stage == RenderStage.Rendering && p.Done % 8 == 0) peak = long.Max(peak, GC.GetTotalMemory(forceFullCollection: true)); + }); + var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } }; + await Pipeline(context).RenderAsync(Input(Synthetic(frames), project), Target(context, Preset("mjpeg-avi"), name), progress: progress, + cancellationToken: context.Cancellation).ConfigureAwait(false); + return peak; + } + await PeakAsync(16, "warm-up").ConfigureAwait(false); + var small = await PeakAsync(48, "short").ConfigureAwait(false); + var large = await PeakAsync(192, "long").ConfigureAwait(false); + Require(large - small < 2 << 20, Invariant($"live heap grew by {(large - small) / 1024} KiB from 48 to 192 frames")); + return Invariant($"48 frames {small / 1024} KiB, 192 frames {large / 1024} KiB"); + }); + yield return Check("robust.batch", "A batch renders every target and reports the ones that cannot run", async context => + { + var server = new RenderPipeline([new ManagedEncoderProvider()], EncoderHost.Server); + var results = await server.RenderBatchAsync(Input(Synthetic(12)), + [Target(context, Preset("png-sequence"), "png"), Target(context, Preset("1080p-h264"), "h264"), Target(context, Preset("apng"), "apng")], + cancellationToken: context.Cancellation).ConfigureAwait(false); + Require(results.Count == 3 && results[0].Succeeded && results[2].Succeeded, "a renderable target failed"); + Require(results[1].Error is RenderException { ReasonKey: EncoderNotices.NeedsRenderNode }, "the MP4 target was not reported as needing a render node"); + return "2 rendered, 1 needs a render node"; + }); + yield return Check("robust.progress", "Progress counts frames, estimates the end and delivers previews", async context => + { + var reports = new List(); + var options = new RenderOptions { PreviewInterval = 4, PreviewLongEdge = 48 }; + await Pipeline(context).RenderAsync(Input(Synthetic(12)), Target(context, Preset("jpeg-sequence")), options, new Sink(reports.Add), context.Cancellation) + .ConfigureAwait(false); + var rendering = reports.Where(r => r.Stage == RenderStage.Rendering).ToList(); + var previews = rendering.Where(r => r.Preview is not null).ToList(); + var ok = rendering.Select(r => r.Done).SequenceEqual(Enumerable.Range(1, 12)) && rendering.All(r => r.Remaining >= TimeSpan.Zero) + && previews.Count == 3 && previews.All(r => r.Preview!.Width == 48) && reports[^1].Stage == RenderStage.Finishing; + foreach (var r in previews) r.Preview!.Dispose(); + Require(ok, Invariant($"{rendering.Count} reports, {previews.Count} previews")); + return Invariant($"{rendering.Count} reports, {previews.Count} previews"); + }); + yield return Check("robust.excluded", "Excluding every frame is reported, not rendered", async context => + { + var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 6)] }; + var error = await CaptureAsync(() => Pipeline(context).RenderAsync(Input(Synthetic(6), project), Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)) + .ConfigureAwait(false); + Require(error is RenderException { ReasonKey: "Render.Error.NoFrames" } && Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "no NoFrames error"); + return "Render.Error.NoFrames"; + }); + } + + /// The exception throws, or null. + private static async Task CaptureAsync(Func render) + { + try + { + await render().ConfigureAwait(false); + return null; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return ex; + } + } + + /// Throws an for one frame, as an unreadable file would. + private sealed class FailingSource(IRenderFrameSource inner, int failAt) : IRenderFrameSource + { + public int FrameCount => inner.FrameCount; + public int Width => inner.Width; + public int Height => inner.Height; + + public ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) => + index == failAt ? throw new IOException($"frame {index} is unreadable") : inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken); + } + + /// Adds a bright square to one frame (a passing aircraft light). + private sealed class TransientSource(IRenderFrameSource inner, int frame) : IRenderFrameSource + { + public int FrameCount => inner.FrameCount; + public int Width => inner.Width; + public int Height => inner.Height; + + public async ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + var image = await inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken).ConfigureAwait(false); + if (index != frame) return image; + for (var c = 0; c < image.Channels; c++) + { + for (var y = image.Height / 3; y < image.Height / 3 + 10; y++) + { + for (var x = image.Width / 2; x < image.Width / 2 + 10; x++) image[c, x, y] = 1; + } + } + return image; + } + } + + /// Wraps a real provider and fails its sessions at a given frame (fault injection). + private sealed class FaultInjectingProvider(IVideoEncoderProvider inner, int failAt) : IVideoEncoderProvider + { + public const string Message = "injected encoder fault"; + + public string Name => inner.Name; + public IReadOnlyList Capabilities => inner.Capabilities; + public bool CanEncode(EncodeSettings settings) => inner.CanEncode(settings); + public IVideoEncoderSession Open(EncodeSettings settings) => new Session(inner.Open(settings), failAt); + + private sealed class Session(IVideoEncoderSession inner, int failAt) : IVideoEncoderSession + { + private int _frames; + + public string EncoderName => inner.EncoderName; + public bool IsHardware => inner.IsHardware; + + public void WriteFrame(ImageBuffer frame, long duration90k) + { + if (_frames++ == failAt) throw new InvalidDataException(Message); + inner.WriteFrame(frame, duration90k); + } + + public void Complete() => inner.Complete(); + public void Dispose() => inner.Dispose(); + } + } +} diff --git a/src/Titano.Tools/Commands/SelfTestCommand.cs b/src/Titano.Tools/Commands/SelfTestCommand.cs new file mode 100644 index 00000000..3189f769 --- /dev/null +++ b/src/Titano.Tools/Commands/SelfTestCommand.cs @@ -0,0 +1,79 @@ +using System.Diagnostics; +using System.Globalization; +using Titano.Core.Diagnostics; +using Titano.Core.Render.Diagnostics; + +namespace Titano.Tools.Commands; + +/// +/// selftest [prefix…] [--filter prefix] [--list]: the engine's end-to-end self-test (BRIEF §20.2, §20.4) with +/// the managed encoders. Prints a PASS/FAIL table; exits 1 when a check fails, 2 when no check matched. +/// +internal sealed class SelfTestCommand : ICommand +{ + public string Name => "selftest"; + public string Summary => "Render synthetic sequences end to end and verify the outputs"; + + public async Task RunAsync(string[] args) + { + var a = new Args(args, "list"); + var filters = a.Positional.ToList(); + if (a.Get("filter") is { } filter) filters.Add(filter); + if (a.Has("list")) + { + foreach (var check in SelfTest.Checks) Console.WriteLine($"{check.Id,-26} {check.Description}"); + return 0; + } + + using var cts = new CancellationTokenSource(); + ConsoleCancelEventHandler cancel = (_, e) => + { + e.Cancel = true; + cts.Cancel(); + }; + Console.CancelKeyPress += cancel; + // Expected failures (fault injection, render-node notices) are logged by the engine; the table says enough. + var level = Log.MinimumLevel; + Log.MinimumLevel = LogLevel.Error; + try + { + var clock = Stopwatch.StartNew(); + Console.WriteLine($"{"RESULT",-6} {"CHECK",-26} {"TIME",8} DETAIL"); + var results = await SelfTest.RunAsync(new SelfTestOptions { Filters = filters }, new ConsoleRows(), cts.Token); + var passed = results.Count(r => r.Outcome == SelfTestOutcome.Passed); + var failed = results.Count(r => r.Outcome == SelfTestOutcome.Failed); + var skipped = results.Count(r => r.Outcome == SelfTestOutcome.Skipped); + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{(failed == 0 ? "PASSED" : "FAILED")} {results.Count} checks: {passed} passed, {failed} failed, {skipped} skipped in {clock.Elapsed.TotalSeconds:F1} s")); + if (results.Count == 0) return 2; + return failed == 0 ? 0 : 1; + } + catch (OperationCanceledException) when (cts.IsCancellationRequested) + { + Console.Error.WriteLine("Self-test cancelled."); + return 2; + } + finally + { + Log.MinimumLevel = level; + Console.CancelKeyPress -= cancel; + } + } + + /// Prints each result as soon as its check finishes. + private sealed class ConsoleRows : IProgress + { + public void Report(SelfTestResult r) + { + var label = r.Outcome switch + { + SelfTestOutcome.Passed => "PASS", + SelfTestOutcome.Failed => "FAIL", + _ => "SKIP", + }; + var line = string.Create(CultureInfo.InvariantCulture, $"{label,-6} {r.Id,-26} {r.Elapsed.TotalMilliseconds,6:F0} ms {r.Detail}"); + if (r.Outcome == SelfTestOutcome.Failed) Console.Error.WriteLine(line); + else Console.WriteLine(line); + } + } +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index d5575d16..a08a2f7f 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -8,6 +8,7 @@ var commands = new ICommand[] new XamlLintCommand(), new PackageGuardCommand(), new ChangelogCommand(), + new SelfTestCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") diff --git a/tests/Titano.Core.Tests/Render/SelfTestTests.cs b/tests/Titano.Core.Tests/Render/SelfTestTests.cs new file mode 100644 index 00000000..38017c76 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/SelfTestTests.cs @@ -0,0 +1,68 @@ +using Titano.Core.Render.Diagnostics; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.Core.Tests.Render; + +public sealed class SelfTestTests +{ + private static readonly string[] Groups = ["plan", "export", "select", "codec", "render", "proc", "robust"]; + + private readonly TestContext _context; + + public SelfTestTests(TestContext context) => _context = context; + + [Test] + public void ChecksAreUniqueAndGrouped() + { + Assert.GreaterOrEqual(SelfTest.Checks.Count, 60); + Assert.Equal(SelfTest.Checks.Count, SelfTest.Checks.Select(c => c.Id).Distinct().Count()); + Assert.True(SelfTest.Checks.All(c => Groups.Contains(c.Group) && c.Id.StartsWith(c.Group + ".", StringComparison.Ordinal) && c.Description.Length > 0)); + Assert.True(Groups.All(g => SelfTest.Checks.Any(c => c.Group == g))); + } + + [Test] + public async Task FastGroupsPassAndCleanUp() + { + var work = _context.CreateTempDirectory(); + var reported = new List(); + var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = work, Filters = ["plan.", "export.", "select.", "codec."] }, + new RenderFixture.Sink(reported.Add), _context.Cancellation); + foreach (var r in results.Where(r => r.Outcome != SelfTestOutcome.Passed)) _context.Log($"{r.Id}: {r.Outcome} {r.Detail}"); + Assert.Equal(SelfTest.Checks.Count(c => c.Group is "plan" or "export" or "select" or "codec"), results.Count); + Assert.True(results.All(r => r.Outcome == SelfTestOutcome.Passed)); + Assert.SequenceEqual(results.Select(r => r.Id), reported.Select(r => r.Id)); + Assert.Empty(Directory.GetFileSystemEntries(work)); + } + + [Test] + public async Task RenderGroupPassesWithManagedEncoders() + { + var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = _context.CreateTempDirectory(), Filters = ["render."] }, cancellationToken: _context.Cancellation); + foreach (var r in results) _context.Log($"{r.Id}: {r.Outcome} {r.Detail}"); + Assert.Equal(SelfTestOutcome.Skipped, results.Single(r => r.Id == "render.mp4").Outcome); + Assert.True(results.Where(r => r.Id != "render.mp4").All(r => r.Outcome == SelfTestOutcome.Passed)); + } + + [Test] + public async Task FailuresAreReportedNotThrown() + { + // An "MP4 encoder" that writes nothing: the inspection of its missing file must fail the check, not the run. + var fake = new CapturingEncoderProvider("fake", new EncoderCapability(VideoCodec.H264, "Fake H.264", true, 4096, 4096, false)); + var results = await SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = _context.CreateTempDirectory(), Filters = ["render.mp4"], PlatformEncoders = [fake] }, + cancellationToken: _context.Cancellation); + var result = results.Single(); + Assert.Equal(SelfTestOutcome.Failed, result.Outcome); + Assert.Contains("FileNotFoundException", result.Detail); + } + + [Test] + public async Task CancellationStopsTheRunAndCleansUp() + { + var work = _context.CreateTempDirectory(); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_context.Cancellation); + var progress = new RenderFixture.Sink(_ => cts.Cancel()); + await Assert.ThrowsAsync(() => SelfTest.RunAsync(new SelfTestOptions { WorkDirectory = work, Filters = ["plan."] }, progress, cts.Token)); + Assert.Empty(Directory.GetFileSystemEntries(work)); + } +} From 4a817340b80721474699311ac2fb6cbd9983bed2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:17:15 +0000 Subject: [PATCH 146/188] feat(imaging): managed decoder provider, decoder chains and format tiers ManagedDecoderProvider decodes JPEG/PNG/TIFF natively, DNG and the supported RAWs through RawDecoder, and falls back to the largest suitable embedded JPEG (oriented like the main image) for other RAWs, CR3, HEIF and unsupported bodies. Requests use JPEG DCT scaling, CFA binning when MaxLongEdge allows, bilinear demosaic for thumbnails and analysis, and ForcePreview. DecoderFactory builds the client (WIC then managed) and server chains and the per-format tier table; Probe gives the per-file tier without decoding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Raw/RawDecoder.cs | 7 +- src/Titano.Core/Codecs/Raw/RawDeveloper.cs | 3 +- .../Imaging/Decoders/DecoderFactory.cs | 45 ++++ .../Decoders/ManagedDecoderProvider.cs | 221 ++++++++++++++++++ .../Decoding/ManagedDecoderProviderTests.cs | 217 +++++++++++++++++ .../Titano.Core.Tests/Raw/DngDecoderTests.cs | 2 +- tests/Titano.Core.Tests/Raw/HighlightTests.cs | 2 +- tests/Titano.Core.Tests/Raw/NativeRawTests.cs | 2 +- .../Raw/RawPerformanceTests.cs | 2 +- 9 files changed, 493 insertions(+), 8 deletions(-) create mode 100644 src/Titano.Core/Imaging/Decoders/DecoderFactory.cs create mode 100644 src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs create mode 100644 tests/Titano.Core.Tests/Decoding/ManagedDecoderProviderTests.cs diff --git a/src/Titano.Core/Codecs/Raw/RawDecoder.cs b/src/Titano.Core/Codecs/Raw/RawDecoder.cs index 51094fb1..5f2848d3 100644 --- a/src/Titano.Core/Codecs/Raw/RawDecoder.cs +++ b/src/Titano.Core/Codecs/Raw/RawDecoder.cs @@ -21,9 +21,10 @@ public sealed record RawDecodeOptions public DemosaicQuality Quality { get; init; } = DemosaicQuality.Best; - /// Bin CFA blocks into RGB pixels instead of demosaicing: half size for Bayer, one third for X-Trans. - /// Ignored for linear (already demosaiced) data and for patterns that cannot be binned. - public bool Binning { get; init; } + /// Target long edge (0 = full size). When the CFA can be binned (half size for Bayer, one third for X-Trans) + /// and the binned image keeps at least this long edge, blocks are binned into RGB pixels instead of demosaiced. The + /// result is not resized further; linear (already demosaiced) data is always developed at full size. + public int MaxLongEdge { get; init; } /// Rotate/flip according to the file's orientation. public bool ApplyOrientation { get; init; } = true; diff --git a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs index fcd185a1..0b106121 100644 --- a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs +++ b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs @@ -87,7 +87,8 @@ internal static class RawDeveloper if (stage.Cfa is { } cfa) { ScaleMosaic(stage.Pixels, cfa, wb, dop, cancellationToken); - var bin = options.Binning ? cfa.BinSize : 0; + var bin = cfa.BinSize; + if (options.MaxLongEdge <= 0 || int.Max(stage.Width, stage.Height) / int.Max(bin, 1) < options.MaxLongEdge) bin = 0; if (bin > 0) { rgb = Demosaic.Bin(stage.Pixels, cfa, bin, dop, cancellationToken); diff --git a/src/Titano.Core/Imaging/Decoders/DecoderFactory.cs b/src/Titano.Core/Imaging/Decoders/DecoderFactory.cs new file mode 100644 index 00000000..78a0cfaa --- /dev/null +++ b/src/Titano.Core/Imaging/Decoders/DecoderFactory.cs @@ -0,0 +1,45 @@ +namespace Titano.Core.Imaging.Decoders; + +/// One row of the "Settings › Formats" table: the best tier a decoder chain reaches for a format, and who +/// delivers it. +/// Format with its family and extensions. +/// Best tier across the chain's providers. +/// Name of the provider delivering that tier ("wic", "managed"), null when unavailable. +public sealed record FormatSupport(ImageFormatInfo Format, DecodeTier Tier, string? Provider); + +/// +/// Builds the decoder chains of BRIEF §8.2. The desktop client tries the Windows provider (WIC) first and the managed +/// one second ( keeps that order among providers offering the same tier); the server and +/// render nodes without WIC use the managed provider alone. +/// +public static class DecoderFactory +{ + /// Client chain: (WIC on Windows; null elsewhere) then managed. + public static ImageDecoder CreateClient(IImageDecoderProvider? windowsProvider) => + new(windowsProvider is null ? [new ManagedDecoderProvider()] : [windowsProvider, new ManagedDecoderProvider()]); + + /// Server chain: managed decoders only. + public static ImageDecoder CreateServer() => new([new ManagedDecoderProvider()]); + + /// Per-format tier on this machine for every known format, in order. + public static IReadOnlyList DescribeFormats(ImageDecoder decoder) + { + ArgumentNullException.ThrowIfNull(decoder); + var rows = new List(); + foreach (var info in ImageFormatInfo.Known) + { + var tier = DecodeTier.Unavailable; + string? provider = null; + foreach (var p in decoder.Providers) + { + if (p.TierFor(info.Format) is { } t && t < tier) + { + tier = t; + provider = p.Name; + } + } + rows.Add(new FormatSupport(info, tier, provider)); + } + return rows; + } +} diff --git a/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs b/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs new file mode 100644 index 00000000..2021371f --- /dev/null +++ b/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs @@ -0,0 +1,221 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Raw; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Diagnostics; +using Titano.Core.Metadata; + +namespace Titano.Core.Imaging.Decoders; + +/// Tier a provider would use for one specific file, with the reason when it is not native. +/// Format detected from the file's signature (extension only breaks ties). +/// Best tier available for this file. +/// Decoder that would produce it ("managed-cr2", "managed-preview"…), null when unavailable. +/// Why the native tier is not used (unsupported body or encoding), else null. +public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason); + +/// +/// The managed decoder (BRIEF §8.2), available on every platform and the only one on the server: JPEG, PNG and TIFF +/// natively; DNG and the supported camera RAWs (CR2, NEF, ARW, PEF, RAF) through ; every other +/// RAW, CR3 and HEIF through the largest suitable embedded JPEG preview; nothing for formats without either. +/// fast paths: JPEG DCT scaling and RAW CFA binning when +/// allows, bilinear demosaicing for thumbnails and analysis, and to skip native +/// RAW development. Results fit within MaxLongEdge (never upscaled) and are always RGB. +/// +public sealed class ManagedDecoderProvider : IImageDecoderProvider +{ + private const string LogCategory = "Decode"; + private const int FileBufferSize = 1 << 16; + private const long MaxPreviewBytes = 256L << 20; + + public string Name => "managed"; + + public DecodeTier? TierFor(ImageFileFormat format) + { + var info = ImageFormatInfo.Of(format); + if (format is ImageFileFormat.Jpeg or ImageFileFormat.Png or ImageFileFormat.Tiff || RawDecoder.Formats.Contains(format)) return DecodeTier.Native; + return info.Family is ImageFamily.CameraRaw or ImageFamily.Heif ? DecodeTier.EmbeddedPreview : null; + } + + /// Decodes the file, or returns null when it has no decodable pixels here (no native decoder and no preview). + /// A JPEG, PNG or TIFF is malformed. + /// The file cannot be read. + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + cancellationToken.ThrowIfCancellationRequested(); + using var stream = Open(request.Path); + var format = ImageSignature.Detect(stream, request.Path); + var family = ImageFormatInfo.Of(format).Family; + var result = family switch + { + ImageFamily.Jpeg => request.ForcePreview && Preview(stream, request, adequateOnly: true, cancellationToken) is { } p ? p : Jpeg(stream, request), + ImageFamily.Png => Png(stream, request), + ImageFamily.Tiff => Tiff(stream, request), + ImageFamily.Dng or ImageFamily.CameraRaw => Raw(stream, format, request, cancellationToken), + ImageFamily.Heif => request.AllowPreview || request.ForcePreview ? Preview(stream, request, adequateOnly: false, cancellationToken) : null, + _ => null, + }; + Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: {(result is null ? "unavailable" : $"{result.Tier} via {result.Decoder}")}"); + return result; + } + + /// The tier this provider would use for the file at , without decoding pixels. + public FileTier Probe(string path) + { + using var stream = Open(path); + var format = ImageSignature.Detect(stream, path); + var family = ImageFormatInfo.Of(format).Family; + switch (family) + { + case ImageFamily.Jpeg: + return new FileTier(format, DecodeTier.Native, "managed-jpeg", null); + case ImageFamily.Png: + return new FileTier(format, DecodeTier.Native, "managed-png", null); + case ImageFamily.Tiff: + return new FileTier(format, DecodeTier.Native, "managed-tiff", null); + } + string? reason = null; + if (family is ImageFamily.Dng or ImageFamily.CameraRaw && RawDecoder.Formats.Contains(format)) + { + var probe = RawDecoder.Probe(stream, path); + if (probe.IsSupported) return new FileTier(format, DecodeTier.Native, probe.Info!.Decoder, null); + reason = probe.Reason; + } + else if (family is ImageFamily.Dng or ImageFamily.CameraRaw or ImageFamily.Heif) + { + reason = $"no managed decoder for {format}"; + } + else + { + return new FileTier(format, DecodeTier.Unavailable, null, $"no managed decoder for {format}"); + } + var previews = MetadataReader.Read(stream, path).Previews; + return previews.Count > 0 + ? new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason) + : new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview"); + } + + private static FileStream Open(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess); + + private static DecodedImage Jpeg(Stream stream, DecodeRequest request) + { + var data = ReadAll(stream); + var info = JpegDecoder.ReadInfo(data); + var image = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = request.MaxLongEdge }, expandGray: true); + var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1; + return Finish(image, orientation, request, info.Width, info.Height, DecodeTier.Native, "managed-jpeg"); + } + + private static DecodedImage Png(Stream stream, DecodeRequest request) + { + var data = ReadAll(stream); + var image = PngDecoder.DecodeToLinear(data, expandGray: true); + var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1; + return Finish(image, orientation, request, image.Width, image.Height, DecodeTier.Native, "managed-png"); + } + + private static DecodedImage Tiff(Stream stream, DecodeRequest request) + { + var decoded = TiffImageReader.Decode(stream); + var image = decoded; + if (decoded.Channels == 1) + { + image = PixelConvert.GrayToRgb(decoded); + decoded.Dispose(); + } + var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1; + return Finish(image, orientation, request, image.Width, image.Height, DecodeTier.Native, "managed-tiff"); + } + + private static DecodedImage? Raw(Stream stream, ImageFileFormat format, DecodeRequest request, CancellationToken cancellationToken) + { + if (!request.ForcePreview && RawDecoder.Formats.Contains(format)) + { + try + { + var options = new RawDecodeOptions + { + Quality = request.Purpose is DecodePurpose.Thumbnail or DecodePurpose.Analysis ? DemosaicQuality.Draft : DemosaicQuality.Best, + MaxLongEdge = request.MaxLongEdge, + ApplyOrientation = request.ApplyOrientation, + }; + var raw = RawDecoder.Decode(stream, request.Path, options, cancellationToken); + foreach (var warning in raw.Warnings) Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: {warning}"); + return Finish(raw.Image, 1, request, raw.Info.Width, raw.Info.Height, DecodeTier.Native, raw.Info.Decoder, oriented: true); + } + catch (InvalidDataException ex) when (request.AllowPreview) + { + Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: native decode unavailable ({ex.Message}); trying the embedded preview"); + } + } + return request.AllowPreview || request.ForcePreview ? Preview(stream, request, adequateOnly: false, cancellationToken) : null; + } + + /// Embedded-preview tier: the smallest preview whose long edge still reaches MaxLongEdge (the largest when none + /// does or no limit is set; null then if ), decoded with DCT scaling and oriented like the + /// main image. + private static DecodedImage? Preview(Stream stream, DecodeRequest request, bool adequateOnly, CancellationToken cancellationToken) + { + var metadata = MetadataReader.Read(stream, request.Path, cancellationToken: cancellationToken); + if (metadata.Previews.Count == 0) return null; + EmbeddedPreview? adequate = null; + foreach (var p in metadata.Previews) + { + if (request.MaxLongEdge > 0 && int.Max(p.Width, p.Height) >= request.MaxLongEdge) adequate = p; + } + if (adequate is null && adequateOnly) return null; + var preview = adequate ?? metadata.Previews[0]; + if (preview.Length > MaxPreviewBytes || preview.Offset < 0 || preview.Offset > stream.Length - preview.Length) + throw new InvalidDataException("Preview: embedded JPEG outside the file"); + var data = new byte[preview.Length]; + stream.Position = preview.Offset; + stream.ReadExactly(data); + var image = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = request.MaxLongEdge }, expandGray: true); + var orientation = request.ApplyOrientation ? metadata.Orientation : 1; + return Finish(image, orientation, request, preview.Width, preview.Height, DecodeTier.EmbeddedPreview, "managed-preview"); + } + + /// Applies orientation, fits within MaxLongEdge, and wraps the result (takes ownership of ). + private static DecodedImage Finish(ImageBuffer image, int orientation, DecodeRequest request, int sourceWidth, int sourceHeight, DecodeTier tier, string decoder, bool oriented = false) + { + var current = image; + try + { + if (orientation is >= 2 and <= 8) + { + var rotated = PixelConvert.ApplyOrientation(current, orientation); + current.Dispose(); + current = rotated; + } + if (!oriented) (sourceWidth, sourceHeight) = PixelConvert.OrientedSize(sourceWidth, sourceHeight, orientation); + if (request.MaxLongEdge > 0) + { + var (w, h) = Resampler.FitWithin(current.Width, current.Height, request.MaxLongEdge); + if (w != current.Width || h != current.Height) + { + var filter = request.Purpose == DecodePurpose.Thumbnail ? ResampleFilter.Box : ResampleFilter.Auto; + var resized = Resampler.Resize(current, w, h, filter); + current.Dispose(); + current = resized; + } + } + return new DecodedImage(current, tier, decoder, sourceWidth, sourceHeight); + } + catch + { + current.Dispose(); + throw; + } + } + + private static byte[] ReadAll(Stream stream) + { + if (stream.Length > int.MaxValue) throw new InvalidDataException("Image file too large"); + var data = new byte[stream.Length]; + stream.Position = 0; + stream.ReadExactly(data); + return data; + } +} diff --git a/tests/Titano.Core.Tests/Decoding/ManagedDecoderProviderTests.cs b/tests/Titano.Core.Tests/Decoding/ManagedDecoderProviderTests.cs new file mode 100644 index 00000000..bcbc861e --- /dev/null +++ b/tests/Titano.Core.Tests/Decoding/ManagedDecoderProviderTests.cs @@ -0,0 +1,217 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Png; +using Titano.Core.Codecs.Raw; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Metadata; +using Titano.Core.Tests.Raw; +using Titano.Testing; +using static Titano.Core.Tests.Raw.NativeRawWriters; + +namespace Titano.Core.Tests.Decoding; + +/// Tier selection (native → embedded preview → unavailable), decoder chains and fast paths. +public sealed class ManagedDecoderProviderTests(TestContext context) +{ + private const int W = 96, H = 64; + private readonly string _dir = context.CreateTempDirectory(); + + private string Write(string name, byte[] data) + { + var path = Path.Combine(_dir, name); + File.WriteAllBytes(path, data); + return path; + } + + private static byte[] Cr2File(string model, int orientation = 1) + { + using var scene = SyntheticRaw.Smooth(W, H); + var active = new RawRect(24, 4, 24 + W, 4 + H); + return Cr2(Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383), active, orientation, model); + } + + private static byte[] JpegFile(int width, int height, int orientation) + { + using var image = SyntheticRaw.Smooth(width, height); + var exif = ExifWriter.BuildTiff(new FrameMetadata { Make = "TestCam", Model = "T1", Orientation = orientation }); + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [[.. "Exif\0\0"u8, .. exif]] }); + } + + [Test] + public void ServerFormatTableReportsTiers() + { + var rows = DecoderFactory.DescribeFormats(DecoderFactory.CreateServer()).ToDictionary(r => r.Format.Format); + foreach (var f in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff, ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Arw, ImageFileFormat.Pef, ImageFileFormat.Raf }) + { + Assert.Equal(DecodeTier.Native, rows[f].Tier); + Assert.Equal("managed", rows[f].Provider); + } + foreach (var f in new[] { ImageFileFormat.Cr3, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Heif }) Assert.Equal(DecodeTier.EmbeddedPreview, rows[f].Tier); + foreach (var f in new[] { ImageFileFormat.WebP, ImageFileFormat.JpegXl, ImageFileFormat.Gif }) + { + Assert.Equal(DecodeTier.Unavailable, rows[f].Tier); + Assert.Null(rows[f].Provider); + } + } + + [Test] + public void ClientChainPrefersTheWindowsProvider() + { + var wic = new FakeProvider(); + var decoder = DecoderFactory.CreateClient(wic); + Assert.Equal(2, decoder.Providers.Count); + var rows = DecoderFactory.DescribeFormats(decoder).ToDictionary(r => r.Format.Format); + Assert.Equal("fake", rows[ImageFileFormat.Cr3].Provider); + Assert.Equal(DecodeTier.Native, rows[ImageFileFormat.Cr3].Tier); + Assert.Equal("fake", rows[ImageFileFormat.Jpeg].Provider); + Assert.Equal("managed", rows[ImageFileFormat.Dng].Provider); + + // The Windows provider declines this file: the managed provider decodes it. + var path = Write("a.jpg", JpegFile(64, 48, 1)); + using var image = decoder.Decode(new DecodeRequest(path)); + Assert.Equal(1, wic.Calls); + Assert.Equal("managed-jpeg", image!.Decoder); + Assert.Count(1, DecoderFactory.CreateClient(null).Providers); + } + + [Test] + public void SupportedRawDecodesNatively() + { + var path = Write("IMG_1.CR2", Cr2File("Canon EOS 5D Mark III")); + var provider = new ManagedDecoderProvider(); + Assert.Equal(DecodeTier.Native, provider.Probe(path).Tier); + using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path)); + Assert.Equal(DecodeTier.Native, image!.Tier); + Assert.Equal("managed-cr2", image.Decoder); + Assert.Equal(W, image.Pixels.Width); + Assert.Equal(W, image.SourceWidth); + } + + [Test] + public void UnsupportedBodyFallsBackToTheOrientedPreview() + { + var path = Write("IMG_2.CR2", Cr2File("Canon EOS R99", orientation: 6)); + var probe = new ManagedDecoderProvider().Probe(path); + Assert.Equal(DecodeTier.EmbeddedPreview, probe.Tier); + Assert.Contains("no colour matrix", probe.Reason); + using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path)); + Assert.Equal(DecodeTier.EmbeddedPreview, image!.Tier); + Assert.Equal("managed-preview", image.Decoder); + // The 64×48 preview is rotated by the RAW's orientation (6). + Assert.Equal(48, image.Pixels.Width); + Assert.Equal(64, image.Pixels.Height); + Assert.Equal(48, image.SourceWidth); + Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(path, AllowPreview: false))); + } + + [Test] + public void ForcePreviewSkipsNativeDevelopment() + { + var path = Write("IMG_3.CR2", Cr2File("Canon EOS 5D Mark III")); + using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, ForcePreview: true)); + Assert.Equal(DecodeTier.EmbeddedPreview, image!.Tier); + Assert.Equal(64, image.Pixels.Width); + } + + [Test] + public void FilesWithoutDecoderOrPreviewAreUnavailable() + { + // A NEF whose body has no matrix and no preview, and a WebP. + using var scene = SyntheticRaw.Smooth(W, H); + var nef = Nef(Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383), 14, NefEncoding.Lossless); + var text = System.Text.Encoding.Latin1.GetString(nef).Replace("NIKON D850", "NIKON Z99X"); + var path = Write("DSC_9.NEF", System.Text.Encoding.Latin1.GetBytes(text)); + Assert.Equal(DecodeTier.Unavailable, new ManagedDecoderProvider().Probe(path).Tier); + Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(path))); + var webp = Write("x.webp", Metadata.Builders.Fixtures.WebP()); + Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(webp))); + Assert.Equal(DecodeTier.Unavailable, new ManagedDecoderProvider().Probe(webp).Tier); + } + + [Test] + public void JpegUsesDctScalingAndOrientation() + { + var path = Write("big.jpg", JpegFile(1600, 1200, 6)); + using var small = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 300)); + Assert.Equal(225, small!.Pixels.Width); + Assert.Equal(300, small.Pixels.Height); + Assert.Equal(1200, small.SourceWidth); + Assert.Equal(1600, small.SourceHeight); + using var stored = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 300, ApplyOrientation: false)); + Assert.Equal(300, stored!.Pixels.Width); + Assert.Equal(3, stored.Pixels.Channels); + } + + [Test] + public void RawFastPathsBinAndFit() + { + using var scene = SyntheticRaw.Smooth(W, H); + var path = Write("f.dng", SyntheticDng.Write(scene, new DngSpec())); + using var thumb = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 40, Purpose: DecodePurpose.Thumbnail)); + Assert.Equal(40, thumb!.Pixels.Width); + Assert.Equal(27, thumb.Pixels.Height); + Assert.Equal(W, thumb.SourceWidth); + using var expected = Resampler.Resize(scene, 40, 27, ResampleFilter.Box); + Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, thumb.Pixels, 1), 35); + } + + [Test] + public void PngAndTiffDecodeToRgb() + { + using var gray = new ImageBuffer(20, 10, 1); + gray.Plane(0).Fill(0.25f); + var png = Write("g.png", PngEncoder.Encode(gray)); + using var p = DecoderFactory.CreateServer().Decode(new DecodeRequest(png)); + Assert.Equal(3, p!.Pixels.Channels); + Assert.Approximately(0.25, p.Pixels[2, 5, 5], 0.01); + var tif = Write("g.tif", TiffWriter.Write(gray)); + using var t = DecoderFactory.CreateServer().Decode(new DecodeRequest(tif, MaxLongEdge: 10)); + Assert.Equal(3, t!.Pixels.Channels); + Assert.Equal(10, t.Pixels.Width); + Assert.Equal("managed-tiff", t.Decoder); + } + + [Test] + public void CorruptedRawFilesOnlyRaiseInvalidDataOrReturnNull() + { + var file = Cr2File("Canon EOS 5D Mark III"); + var provider = new ManagedDecoderProvider(); + var random = new Random(17); + for (var i = 0; i < 60; i++) + { + var variant = i < 20 ? file[..(file.Length * i / 20)] : (byte[])file.Clone(); + if (i >= 20) + { + for (var k = 0; k < 3; k++) variant[random.Next(variant.Length)] = (byte)random.Next(256); + } + var path = Write($"fuzz{i}.cr2", variant); + try + { + provider.Probe(path); + using var image = provider.Decode(new DecodeRequest(path, MaxLongEdge: i % 2 == 0 ? 0 : 32, Purpose: DecodePurpose.Thumbnail)); + } + catch (InvalidDataException) + { + } + catch (Exception ex) + { + Assert.Fail($"variant {i}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); + } + } + } + + /// A Windows-like provider claiming native support for everything but declining every file. + private sealed class FakeProvider : IImageDecoderProvider + { + public int Calls { get; private set; } + public string Name => "fake"; + public DecodeTier? TierFor(ImageFileFormat format) => format is ImageFileFormat.Jpeg or ImageFileFormat.Cr3 ? DecodeTier.Native : null; + + public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) + { + Calls++; + return null; + } + } +} diff --git a/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs b/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs index d0a47334..463093c6 100644 --- a/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs +++ b/tests/Titano.Core.Tests/Raw/DngDecoderTests.cs @@ -183,7 +183,7 @@ public sealed class DngDecoderTests(TestContext context) public void BinningHalvesTheSize(DemosaicQuality quality) { using var scene = SyntheticRaw.Smooth(W, H); - using var result = Decode(SyntheticDng.Write(scene, new DngSpec()), new RawDecodeOptions { Binning = true, Quality = quality }); + using var result = Decode(SyntheticDng.Write(scene, new DngSpec()), new RawDecodeOptions { MaxLongEdge = W / 2, Quality = quality }); Assert.Equal(W / 2, result.Image.Width); Assert.Equal(H / 2, result.Image.Height); using var expected = Resampler.Resize(scene, W / 2, H / 2, ResampleFilter.Box); diff --git a/tests/Titano.Core.Tests/Raw/HighlightTests.cs b/tests/Titano.Core.Tests/Raw/HighlightTests.cs index eb142ba6..1f10dbfd 100644 --- a/tests/Titano.Core.Tests/Raw/HighlightTests.cs +++ b/tests/Titano.Core.Tests/Raw/HighlightTests.cs @@ -31,7 +31,7 @@ public sealed class HighlightTests(TestContext context) { using var scene = Patches(); var dng = SyntheticDng.Write(scene, new DngSpec()); - using var result = RawDecoder.Decode(new MemoryStream(dng), "h.dng", new RawDecodeOptions { Quality = quality, Binning = binning }); + using var result = RawDecoder.Decode(new MemoryStream(dng), "h.dng", new RawDecodeOptions { Quality = quality, MaxLongEdge = binning ? 1 : 0 }); var s = binning ? 2 : 1; var (r0, g0, b0) = Pixel(result.Image, 16 / s, 32 / s); var (r1, g1, b1) = Pixel(result.Image, 48 / s, 32 / s); diff --git a/tests/Titano.Core.Tests/Raw/NativeRawTests.cs b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs index 6166181a..5dd8fae1 100644 --- a/tests/Titano.Core.Tests/Raw/NativeRawTests.cs +++ b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs @@ -114,7 +114,7 @@ public sealed class NativeRawTests(TestContext context) Assert.Equal("managed-raf", result.Info.Decoder); Assert.Equal("X-T2", result.Info.Model); AssertScene(scene, result.Image, xtrans ? 34 : 38, context); - using var binned = Decode(Raf(sensor, Expand(rasterCfa), crop), "DSCF0001.RAF", new RawDecodeOptions { Binning = true }); + using var binned = Decode(Raf(sensor, Expand(rasterCfa), crop), "DSCF0001.RAF", new RawDecodeOptions { MaxLongEdge = 1 }); Assert.Equal(W / (xtrans ? 3 : 2), binned.Image.Width); } diff --git a/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs b/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs index 0d2048ac..dee7cbda 100644 --- a/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs +++ b/tests/Titano.Core.Tests/Raw/RawPerformanceTests.cs @@ -25,7 +25,7 @@ public sealed class RawPerformanceTests(TestContext context) var dng = Mosaic(); var ahd = Best(dng, RawDecodeOptions.Default, out var size); Assert.Equal(W, size.Width); - var half = Best(dng, new RawDecodeOptions { Quality = DemosaicQuality.Draft, Binning = true }, out var halfSize); + var half = Best(dng, new RawDecodeOptions { Quality = DemosaicQuality.Draft, MaxLongEdge = W / 2 }, out var halfSize); Assert.Equal(W / 2, halfSize.Width); context.Log($"24 MP DNG: AHD full size {ahd.TotalMilliseconds:F0} ms, binned half size {half.TotalMilliseconds:F0} ms ({Environment.ProcessorCount} cores)"); Console.WriteLine($"[perf] {context.LogText.Trim()}"); From 15fe09261498179579da6eb1d7d8fd528f71d244 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:19:47 +0000 Subject: [PATCH 147/188] feat(export): output path from a project's export folder and name template Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Export/ExportNaming.cs | 11 +++++++++++ tests/Titano.Core.Tests/Export/ExportNamingTests.cs | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Titano.Core/Export/ExportNaming.cs b/src/Titano.Core/Export/ExportNaming.cs index 29fdb9f1..f594b0b1 100644 --- a/src/Titano.Core/Export/ExportNaming.cs +++ b/src/Titano.Core/Export/ExportNaming.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text; using Titano.Core.Naming; +using Titano.Core.Project; using Titano.Core.Video; namespace Titano.Core.Export; @@ -114,6 +115,16 @@ public static class ExportNaming return Unique(folder, name, extension); } + /// + /// Output path of a project's export: or, when unset, the sequence's exports folder, + /// named by . + /// + public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context) + { + ArgumentNullException.ThrowIfNull(settings); + return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context); + } + /// "name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists. public static string Unique(string folder, string name, string extension) { diff --git a/tests/Titano.Core.Tests/Export/ExportNamingTests.cs b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs index c4c69054..46b5e126 100644 --- a/tests/Titano.Core.Tests/Export/ExportNamingTests.cs +++ b/tests/Titano.Core.Tests/Export/ExportNamingTests.cs @@ -1,4 +1,5 @@ using Titano.Core.Export; +using Titano.Core.Project; using Titano.Core.Video; using Titano.Testing; @@ -68,4 +69,15 @@ public sealed class ExportNamingTests Assert.Equal(Path.Combine(dir, "Harbour sunset (2)"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence))); Assert.Equal(Path.Combine(dir, "Harbour sunset.gif"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.Gif))); } + + [Test] + public void ProjectSettingsChooseFolderAndTemplate() + { + var exports = _context.CreateTempDirectory("exports"); + var custom = _context.CreateTempDirectory("custom"); + var byDefault = ExportNaming.OutputPath(new ExportSettings(), exports, Context()); + Assert.Equal(Path.Combine(exports, "2024-06-21 Harbour sunset - 4K UHD HEVC.mp4"), byDefault); + var chosen = ExportNaming.OutputPath(new ExportSettings { Folder = custom, NameTemplate = "{title} {width}" }, exports, Context()); + Assert.Equal(Path.Combine(custom, "Harbour sunset 3840.mp4"), chosen); + } } From 6a1eca0d6c0ed7dc06976d0a00a6fde670642619 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:19:47 +0000 Subject: [PATCH 148/188] fix(render): ignore excluded frames in cached series and exposure steps An excluded test shot at another exposure created holy-grail steps, and cached deep-analysis series still fed excluded frames into the fits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Render/RenderPreparation.cs | 28 ++++++++++++++----- .../Render/RenderProcessingTests.cs | 13 +++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/Titano.Core/Render/RenderPreparation.cs b/src/Titano.Core/Render/RenderPreparation.cs index 1c75db82..408abc56 100644 --- a/src/Titano.Core/Render/RenderPreparation.cs +++ b/src/Titano.Core/Render/RenderPreparation.cs @@ -114,6 +114,9 @@ public static class RenderPreparation var cached = input.Analysis; var warnings = new List(); var included = Included(input.Project.ExcludedFrames, n); + var excluded = new bool[n]; + Array.Fill(excluded, true); + foreach (var i in included) excluded[i] = false; var deflicker = ProjectValues.Get(exposure.Deflicker, false); var holyGrail = ProjectValues.Get(exposure.HolyGrail, false); @@ -122,15 +125,15 @@ public static class RenderPreparation var stabilize = ProjectValues.Get(motion.Stabilize, false); var smoothing = ProjectValues.Get(motion.StabilizeSmoothing, new StabilizerOptions().SmoothingSigma); - var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, n) : null; + var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, excluded) : null; var measureLuminance = (deflicker || holyGrail) && luminance is null; double[]? red = null, green = null, blue = null; - if (whiteBalance && Valid(cached?.MeanRed, n) is { } r && Valid(cached?.MeanGreen, n) is { } g && Valid(cached?.MeanBlue, n) is { } b) + if (whiteBalance && Valid(cached?.MeanRed, excluded) is { } r && Valid(cached?.MeanGreen, excluded) is { } g && Valid(cached?.MeanBlue, excluded) is { } b) (red, green, blue) = (r, g, b); var measureColour = whiteBalance && red is null; RegionMask? mask = null; double[]? sky = null, land = null; - if (regionMode != RegionMode.Off && cached?.Regions is { } m && Valid(cached.SkyLogLuminance, n) is { } s && Valid(cached.LandLogLuminance, n) is { } l) + if (regionMode != RegionMode.Off && cached?.Regions is { } m && Valid(cached.SkyLogLuminance, excluded) is { } s && Valid(cached.LandLogLuminance, excluded) is { } l) (mask, sky, land) = (m, s, l); var stabilization = stabilize ? CachedStabilization(cached, n, smoothing) : null; var measureStabilization = stabilize && stabilization is null; @@ -164,10 +167,10 @@ public static class RenderPreparation } } - return Combine(input, luminance, red, green, blue, mask, sky, land, stabilization, deflicker, holyGrail, pass.MeasuredFrames, warnings); + return Combine(input, excluded, luminance, red, green, blue, mask, sky, land, stabilization, deflicker, holyGrail, pass.MeasuredFrames, warnings); } - private static RenderCorrections Combine(RenderInput input, double[]? luminance, double[]? red, double[]? green, double[]? blue, RegionMask? mask, + private static RenderCorrections Combine(RenderInput input, bool[] excluded, double[]? luminance, double[]? red, double[]? green, double[]? blue, RegionMask? mask, double[]? sky, double[]? land, StabilizationData? stabilization, bool deflicker, bool holyGrail, int measured, List warnings) { var n = input.Source.FrameCount; @@ -184,7 +187,8 @@ public static class RenderPreparation Strength = double.Clamp(ProjectValues.Get(exposure.DeflickerStrength, 1.0), 0, 1), }; var evs = new double?[n]; - for (var i = 0; i < n; i++) evs[i] = input.Frames[i].ExposureValue; + // Excluded frames (test shots, bumps) must not create exposure steps. + for (var i = 0; i < n; i++) evs[i] = excluded[i] ? null : input.Frames[i].ExposureValue; if (holyGrail) { var transition = ProjectValues.Get(exposure.TransitionLength, 0); @@ -287,7 +291,17 @@ public static class RenderPreparation return result; } - private static double[]? Valid(double[]? values, int n) => values is not null && values.Length == n ? values : null; + /// A copy of a cached series with excluded frames marked unusable, or null when it does not fit the sequence. + private static double[]? Valid(double[]? values, bool[] excluded) + { + if (values is null || values.Length != excluded.Length) return null; + var copy = (double[])values.Clone(); + for (var i = 0; i < copy.Length; i++) + { + if (excluded[i]) copy[i] = double.NaN; + } + return copy; + } private static double[] NaNs(int n) { diff --git a/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs index c7f223b7..4f3d2c21 100644 --- a/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs +++ b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs @@ -69,6 +69,19 @@ public sealed class RenderProcessingTests Assert.Approximately(-1.0, output[^1] - output[0], 0.1, "the step is kept, only spread out"); } + [Test] + public async Task ExcludedFramesDoNotCreateExposureSteps() + { + // Frame 10 is a test shot one stop darker; excluding it must leave no holy-grail step behind. + var source = Source(30, configure: o => o with { ExposureSteps = [new SyntheticExposureStep(10, 1.0), new SyntheticExposureStep(11, -1.0)], StartEv = 0, EndEv = 0 }); + var project = With(new ExposureSettings { HolyGrail = On(true), HighlightKnee = null }); + var all = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: _context.Cancellation); + var excluded = await RenderPreparation.PrepareAsync(Input(source, project with { ExcludedFrames = [10] }), cancellationToken: _context.Cancellation); + Assert.Count(2, all.Report.Transitions); + Assert.Empty(excluded.Report.Transitions); + Assert.True(double.IsNaN(excluded.MeasuredLogLuminance[10])); + } + [Test] public async Task WhiteBalanceSmoothingRemovesColourJitter() { From 9b006a9fcfa90e084887901ec0fb1ce83f1c40ce Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:21:54 +0000 Subject: [PATCH 149/188] ci: publish PR screenshots to a ci-screenshots branch A separate job with write access downloads the screenshots artifact and force-pushes it as a single commit, so screens can be reviewed with a plain git fetch. The build job keeps read-only permissions; forks are skipped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/workflows/ci.yml | 23 +++++++++++++++++++++++ docs/DECISIONS.md | 1 + 2 files changed, 24 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 951c33dd..8de0e028 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,6 +137,29 @@ jobs: path: out/publish/ retention-days: 14 + screenshots: + name: Screenshots branch + # Same-repository pull requests only: forks never get a writable token. + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + name: screenshots + path: screenshots + - name: Publish to the ci-screenshots branch (one commit, overwritten each run) + working-directory: screenshots + run: | + git init -q -b ci-screenshots + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add -A + git commit -q -m "Screenshots of ${{ github.event.pull_request.head.sha }}" + git push -q -f "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.git" HEAD:refs/heads/ci-screenshots + postgres: name: PostgreSQL ${{ matrix.pg }} integration strategy: diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 024d4cc0..df5f3c41 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -88,3 +88,4 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Automatic output stops at 4K UHD; no automatic stacking advice. | 8K / temporal-median denoise | 8K stays a manual choice; a median erases moving stars and stillness cannot be verified reliably. | | 2026-10-02 | Apply records a missing-data reason only where no advice exists; Optimise returns modules to Auto and only adds to the user's hero, exclusions, offset or output cap; a preset's own choices are stored as manual values, content-derived values stay Auto. | Overwrite | Manual values stay in force; re-analysis does not undo a chosen preset. | | 2026-10-02 | Advisor namespace is `Titano.Core.Advice` (class `Advisor`). | `Titano.Core.Advisor` | A class named like its namespace needed an alias in every `Titano.Core.*` caller. | +| 2026-10-02 | CI also force-pushes each same-repository PR run's screenshots as one commit to the `ci-screenshots` branch (separate job, only it has `contents: write`). | Artifact only | Artifacts need an authenticated download; a branch can be fetched with plain git for visual review. The branch never merges and holds a single commit. | From 56757f12d34d86afac2e7b8a64aa1c059e8a79d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:21:58 +0000 Subject: [PATCH 150/188] feat(imaging): thumbs.pack, thumbnail LRU cache and proxy builder ThumbnailPack appends self-describing CRC-checked JPEG entries (320 px, q80) and index records; a two-slot header flips to each new index, so crashes and truncation lose only the damaged tail, and compaction rewrites live entries through AtomicFile. Reads are positional and run concurrently with the writer. ThumbnailCache is a byte-budget LRU that coalesces concurrent loads. ProxyBuilder decodes at the policy long edge with orientation applied and writes JPEG q92 with the source Exif (capture time kept, orientation reset). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Imaging/Thumbnails/ProxyBuilder.cs | 64 +++ .../Imaging/Thumbnails/ThumbnailCache.cs | 156 ++++++ .../Imaging/Thumbnails/ThumbnailPack.cs | 497 ++++++++++++++++++ .../Decoding/ThumbnailTests.cs | 277 ++++++++++ 4 files changed, 994 insertions(+) create mode 100644 src/Titano.Core/Imaging/Thumbnails/ProxyBuilder.cs create mode 100644 src/Titano.Core/Imaging/Thumbnails/ThumbnailCache.cs create mode 100644 src/Titano.Core/Imaging/Thumbnails/ThumbnailPack.cs create mode 100644 tests/Titano.Core.Tests/Decoding/ThumbnailTests.cs diff --git a/src/Titano.Core/Imaging/Thumbnails/ProxyBuilder.cs b/src/Titano.Core/Imaging/Thumbnails/ProxyBuilder.cs new file mode 100644 index 00000000..3c9e403e --- /dev/null +++ b/src/Titano.Core/Imaging/Thumbnails/ProxyBuilder.cs @@ -0,0 +1,64 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.IO; +using Titano.Core.Metadata; + +namespace Titano.Core.Imaging.Thumbnails; + +/// Proxy long-edge policy (BRIEF §8.5). +public enum ProxySize +{ + /// Source resolution. + Full = 0, + Edge1280 = 1280, + Edge1920 = 1920, + Edge2560 = 2560, +} + +/// A built proxy and how its pixels were obtained. +/// JPEG file bytes with an Exif block. +/// Proxy width (oriented). +/// Proxy height (oriented). +/// Decode tier of the source (an embedded preview caps the proxy at the preview's size). +public sealed record ProxyResult(byte[] Jpeg, int Width, int Height, DecodeTier Tier); + +/// +/// Builds proxies (BRIEF §8.5): the source decoded at the policy long edge (1280/1920/2560 or full) with its orientation +/// applied, encoded as JPEG q92, carrying an Exif block written by from the +/// source metadata (capture time, camera, exposure, GPS) with orientation reset to 1 because the pixels are upright. +/// +public static class ProxyBuilder +{ + public const int Quality = 92; + + /// Default policy. + public const ProxySize DefaultSize = ProxySize.Edge1920; + + /// Decodes and encodes the proxy of ; null when no tier can decode it. + /// Source metadata; read from the file when null. + public static ProxyResult? Build(ImageDecoder decoder, string sourcePath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(decoder); + using var decoded = decoder.Decode(new DecodeRequest(sourcePath, (int)size, DecodePurpose.Proxy), cancellationToken); + if (decoded is null) return null; + metadata ??= MetadataReader.Read(sourcePath, cancellationToken); + return new ProxyResult(Encode(decoded.Pixels, metadata), decoded.Pixels.Width, decoded.Pixels.Height, decoded.Tier); + } + + /// Builds the proxy and writes it crash-safely to . + public static ProxyResult? Write(ImageDecoder decoder, string sourcePath, string proxyPath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default) + { + var result = Build(decoder, sourcePath, size, metadata, cancellationToken); + if (result is not null) AtomicFile.WriteAllBytes(proxyPath, result.Jpeg); + return result; + } + + /// Encodes upright linear-light pixels as a proxy JPEG with the source's Exif (orientation 1). + public static byte[] Encode(ImageBuffer image, FrameMetadata metadata) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentNullException.ThrowIfNull(metadata); + var segment = ExifWriter.BuildJpegApp1(metadata with { Orientation = 1, Width = image.Width, Height = image.Height }); + // The encoder takes APP1 payloads: drop the marker and length that BuildJpegApp1 puts in front. + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = Quality, App1Segments = [segment[4..]], OptimizeHuffman = true }); + } +} diff --git a/src/Titano.Core/Imaging/Thumbnails/ThumbnailCache.cs b/src/Titano.Core/Imaging/Thumbnails/ThumbnailCache.cs new file mode 100644 index 00000000..863a4bba --- /dev/null +++ b/src/Titano.Core/Imaging/Thumbnails/ThumbnailCache.cs @@ -0,0 +1,156 @@ +using Titano.Core.Codecs.Jpeg; + +namespace Titano.Core.Imaging.Thumbnails; + +/// A decoded thumbnail ready for display: interleaved 8-bit sRGB RGB. +public sealed class Thumbnail(int width, int height, byte[] rgb) +{ + public int Width { get; } = width; + public int Height { get; } = height; + + /// Width × height × 3 bytes, sRGB-encoded, top-down. + public byte[] Rgb { get; } = rgb; + + /// Memory charged against a budget. + public long ByteSize => Rgb.Length + 64; + + /// Decodes a thumbnail JPEG (gray is expanded to RGB). + /// The JPEG is malformed. + public static Thumbnail FromJpeg(ReadOnlySpan jpeg) + { + var image = JpegDecoder.Decode(jpeg); + var pixels = image.Pixels8 ?? throw new InvalidDataException("Thumbnail: not an 8-bit JPEG"); + if (image.Components == 3) return new Thumbnail(image.Width, image.Height, pixels); + var rgb = new byte[pixels.Length * 3]; + for (var i = 0; i < pixels.Length; i++) rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = pixels[i]; + return new Thumbnail(image.Width, image.Height, rgb); + } +} + +/// +/// In-memory LRU of decoded thumbnails under a byte budget (BRIEF §8.5). Thread-safe; concurrent requests for the same +/// key share one load (), so a scrolling UI never decodes a thumbnail twice. +/// +public sealed class ThumbnailCache where TKey : notnull +{ + private readonly Lock _gate = new(); + private readonly Dictionary> _map = []; + private readonly LinkedList<(TKey Key, Thumbnail Value)> _lru = new(); + private readonly Dictionary> _loading = []; + private long _bytes; + + /// Upper bound on the bytes held (a thumbnail larger than the budget is never cached). + public ThumbnailCache(long byteBudget) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(byteBudget); + Budget = byteBudget; + } + + public long Budget { get; } + + public long Bytes + { + get + { + lock (_gate) return _bytes; + } + } + + public int Count + { + get + { + lock (_gate) return _map.Count; + } + } + + /// Returns a cached thumbnail and marks it most recently used. + public bool TryGet(TKey key, out Thumbnail thumbnail) + { + lock (_gate) + { + if (_map.TryGetValue(key, out var node)) + { + _lru.Remove(node); + _lru.AddFirst(node); + thumbnail = node.Value.Value; + return true; + } + } + thumbnail = null!; + return false; + } + + /// Adds or replaces a thumbnail, evicting least recently used ones to stay within the budget. + public void Set(TKey key, Thumbnail thumbnail) + { + ArgumentNullException.ThrowIfNull(thumbnail); + lock (_gate) + { + RemoveLocked(key); + if (thumbnail.ByteSize > Budget) return; + _map[key] = _lru.AddFirst((key, thumbnail)); + _bytes += thumbnail.ByteSize; + while (_bytes > Budget && _lru.Last is { } last) + { + RemoveLocked(last.Value.Key); + } + } + } + + public bool Remove(TKey key) + { + lock (_gate) return RemoveLocked(key); + } + + public void Clear() + { + lock (_gate) + { + _map.Clear(); + _lru.Clear(); + _bytes = 0; + } + } + + /// Cached thumbnail, or the result of (cached when not null). Concurrent calls for + /// the same key await the same load; each caller's only cancels its own wait. + public async Task GetOrLoadAsync(TKey key, Func> loader, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(loader); + if (TryGet(key, out var hit)) return hit; + Task task; + lock (_gate) + { + if (!_loading.TryGetValue(key, out task!)) + { + task = LoadAsync(key, loader); + _loading[key] = task; + } + } + return await task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task LoadAsync(TKey key, Func> loader) + { + try + { + await Task.Yield(); + var value = await loader(key, CancellationToken.None).ConfigureAwait(false); + if (value is not null) Set(key, value); + return value; + } + finally + { + lock (_gate) _loading.Remove(key); + } + } + + private bool RemoveLocked(TKey key) + { + if (!_map.Remove(key, out var node)) return false; + _lru.Remove(node); + _bytes -= node.Value.Value.ByteSize; + return true; + } +} diff --git a/src/Titano.Core/Imaging/Thumbnails/ThumbnailPack.cs b/src/Titano.Core/Imaging/Thumbnails/ThumbnailPack.cs new file mode 100644 index 00000000..3d6e104d --- /dev/null +++ b/src/Titano.Core/Imaging/Thumbnails/ThumbnailPack.cs @@ -0,0 +1,497 @@ +using System.Buffers.Binary; +using System.Collections.Concurrent; +using Microsoft.Win32.SafeHandles; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Hashing; +using Titano.Core.IO; + +namespace Titano.Core.Imaging.Thumbnails; + +/// Index entry of one thumbnail in a . +/// Frame the thumbnail belongs to. +/// File offset of the entry record. +/// JPEG length in bytes. +/// Thumbnail width in pixels. +/// Thumbnail height in pixels. +/// CRC-32 of the JPEG bytes. +public readonly record struct ThumbnailEntry(Guid FrameId, long Offset, int Length, int Width, int Height, uint Crc); + +/// +/// The per-sequence thumbnail file thumbs.pack (BRIEF §8.5): 320-pixel JPEG (q80) thumbnails appended to one file. +/// Layout (little-endian): two 64-byte header slots at 0 and 64 (magic "TTPK", version, generation, offset/length/ +/// count of the current index record, the file length it covers, CRC-32); from 128, self-describing records — entries +/// ("TENT": frame id, size, JPEG length and CRC, then the JPEG) and index tables ("TIDX": count, then frame id → offset, +/// length, size, CRC per entry, then the record's CRC). +/// Writes only append. Every appends (and on /) +/// a new index record is appended and flushed, then the header slot not holding the newest generation is overwritten and +/// flushed: a crash leaves the previous slot valid. Opening takes the newest valid slot, then recovers entries appended +/// after its index by scanning forward until the first damaged record, so truncated or partially written files lose +/// only their damaged tail. rewrites live entries into a fresh file committed with +/// . Reads use positional I/O and run concurrently with one writer. +/// +public sealed class ThumbnailPack : IDisposable +{ + public const int LongEdge = 320; + public const int Quality = 80; + public const int IndexInterval = 64; + + private const uint HeaderMagic = 0x4B505454; // "TTPK" + private const uint EntryMagic = 0x544E4554; // "TENT" + private const uint IndexMagic = 0x58444954; // "TIDX" + private const ushort Version = 1; + private const int SlotSize = 64; + private const int DataStart = 2 * SlotSize; + private const int EntryHeaderSize = 32; + private const int IndexEntrySize = 36; + private const int MaxJpegBytes = 16 << 20; + + private readonly ReaderWriterLockSlim _handleLock = new(LockRecursionPolicy.NoRecursion); + private readonly Lock _writeLock = new(); + private readonly List _warnings = []; + private ConcurrentDictionary _index = new(); + private SafeFileHandle _handle; + private long _tail; + private ulong _generation; + private int _activeSlot; + private int _unindexed; + private long _liveBytes; + private bool _disposed; + + private ThumbnailPack(string path, bool writable, SafeFileHandle handle) + { + Path = path; + Writable = writable; + _handle = handle; + Load(); + } + + public string Path { get; } + public bool Writable { get; } + + /// Problems met while opening or refreshing (damaged slots, records dropped from the tail). + public IReadOnlyList Warnings + { + get + { + lock (_warnings) return [.. _warnings]; + } + } + + public int Count => Volatile.Read(ref _index).Count; + + /// Snapshot of the frames with a thumbnail. + public IReadOnlyCollection FrameIds => [.. Volatile.Read(ref _index).Keys]; + + /// Bytes held by superseded or removed entries (reclaimed by ). + public long WastedBytes => long.Max(0, _tail - DataStart - Volatile.Read(ref _liveBytes)); + + /// Opens (creating when writable and missing) a pack. + public static ThumbnailPack Open(string path, bool writable = true) + { + ArgumentException.ThrowIfNullOrEmpty(path); + if (writable && !File.Exists(path)) AtomicFile.WriteAllBytes(path, EmptyFile()); + var handle = File.OpenHandle(path, FileMode.Open, writable ? FileAccess.ReadWrite : FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess); + return new ThumbnailPack(path, writable, handle); + } + + /// Downscales a linear-light image to the thumbnail long edge and encodes it (JPEG q80). + public static (byte[] Jpeg, int Width, int Height) Encode(ImageBuffer image) + { + ArgumentNullException.ThrowIfNull(image); + using var small = Resampler.Thumbnail(image, LongEdge); + return (JpegEncoder.Encode(small, new JpegEncodeOptions { Quality = Quality }), small.Width, small.Height); + } + + public bool TryGetEntry(Guid frameId, out ThumbnailEntry entry) => Volatile.Read(ref _index).TryGetValue(frameId, out entry); + + /// The JPEG bytes of a frame's thumbnail; null when absent or damaged (CRC mismatch). + public byte[]? ReadJpeg(Guid frameId) + { + if (!TryGetEntry(frameId, out var e)) return null; + var data = new byte[e.Length]; + _handleLock.EnterReadLock(); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (RandomAccess.Read(_handle, data, e.Offset + EntryHeaderSize) != data.Length) return null; + } + finally + { + _handleLock.ExitReadLock(); + } + return Crc32.Compute(data) == e.Crc ? data : null; + } + + /// Encodes and appends the thumbnail of , replacing any previous one for the frame. + public ThumbnailEntry Add(Guid frameId, ImageBuffer image) + { + var (jpeg, w, h) = Encode(image); + return AddJpeg(frameId, jpeg, w, h); + } + + /// Appends an encoded thumbnail, replacing any previous one for the frame. + public ThumbnailEntry AddJpeg(Guid frameId, ReadOnlySpan jpeg, int width, int height) + { + if (!Writable) throw new InvalidOperationException("The pack is open read-only."); + if (jpeg.Length is 0 or > MaxJpegBytes) throw new ArgumentOutOfRangeException(nameof(jpeg)); + if (width is < 1 or > ushort.MaxValue || height is < 1 or > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(width)); + lock (_writeLock) + { + var record = new byte[EntryHeaderSize + jpeg.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(record, EntryMagic); + frameId.TryWriteBytes(record.AsSpan(4)); + BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(20), (ushort)width); + BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(22), (ushort)height); + BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(24), jpeg.Length); + var crc = Crc32.Compute(jpeg); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(28), crc); + jpeg.CopyTo(record.AsSpan(EntryHeaderSize)); + var entry = new ThumbnailEntry(frameId, _tail, jpeg.Length, width, height, crc); + WriteAt(record, _tail); + _tail += record.Length; + if (_index.TryGetValue(frameId, out var old)) Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length)); + _index[frameId] = entry; + Interlocked.Add(ref _liveBytes, record.Length); + if (++_unindexed >= IndexInterval) WriteIndex(); + return entry; + } + } + + /// Drops a frame's thumbnail from the index (its bytes stay until ). + public bool Remove(Guid frameId) + { + if (!Writable) throw new InvalidOperationException("The pack is open read-only."); + lock (_writeLock) + { + if (!_index.TryRemove(frameId, out var old)) return false; + Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length)); + _unindexed++; + return true; + } + } + + /// Writes the index now (appended record, then the alternate header slot). + public void Flush() + { + if (!Writable) return; + lock (_writeLock) + { + if (_unindexed > 0) WriteIndex(); + } + } + + /// Rewrites the live entries into a new file and atomically replaces this one. + public void Compact() + { + if (!Writable) throw new InvalidOperationException("The pack is open read-only."); + lock (_writeLock) + { + var temp = AtomicFile.TempPathFor(Path); + var entries = Volatile.Read(ref _index).Values.OrderBy(e => e.Offset).ToList(); + var moved = new ConcurrentDictionary(); + using (var output = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16)) + { + output.Write(new byte[DataStart]); + var buffer = new byte[EntryHeaderSize + MaxJpegBytes / 16]; + foreach (var e in entries) + { + var size = EntryHeaderSize + e.Length; + if (buffer.Length < size) buffer = new byte[size]; + _handleLock.EnterReadLock(); + int read; + try + { + read = RandomAccess.Read(_handle, buffer.AsSpan(0, size), e.Offset); + } + finally + { + _handleLock.ExitReadLock(); + } + if (read != size || Crc32.Compute(buffer.AsSpan(EntryHeaderSize, e.Length)) != e.Crc) + { + Warn($"Thumbnail of {e.FrameId} damaged; dropped during compaction"); + continue; + } + moved[e.FrameId] = e with { Offset = output.Position }; + output.Write(buffer, 0, size); + } + var indexOffset = output.Position; + var index = IndexRecord(moved.Values); + output.Write(index); + output.Position = 0; + output.Write(HeaderSlot(_generation + 1, indexOffset, index.Length, moved.Count, indexOffset + index.Length)); + } + _handleLock.EnterWriteLock(); + try + { + _handle.Dispose(); + AtomicFile.Commit(temp, Path); + _handle = File.OpenHandle(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess); + _index = moved; + _generation++; + _activeSlot = 0; + _tail = RandomAccess.GetLength(_handle); + _liveBytes = moved.Values.Sum(e => (long)EntryHeaderSize + e.Length); + _unindexed = 0; + } + finally + { + _handleLock.ExitWriteLock(); + } + } + } + + /// Re-reads the file (read-only instances use it to see entries written by another instance). + public void Refresh() + { + if (Writable) return; + _handleLock.EnterWriteLock(); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + _handle.Dispose(); + _handle = File.OpenHandle(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess); + } + finally + { + _handleLock.ExitWriteLock(); + } + Load(); + } + + public void Dispose() + { + if (_disposed) return; + if (Writable) + { + try + { + Flush(); + } + catch (IOException ex) + { + Warn("Index not written on close: " + ex.Message); + } + } + _handleLock.EnterWriteLock(); + try + { + _disposed = true; + _handle.Dispose(); + } + finally + { + _handleLock.ExitWriteLock(); + } + _handleLock.Dispose(); + } + + private static byte[] EmptyFile() + { + var file = new byte[DataStart]; + HeaderSlot(1, 0, 0, 0, DataStart).CopyTo(file, 0); + return file; + } + + private static byte[] HeaderSlot(ulong generation, long indexOffset, int indexLength, int count, long dataEnd) + { + var slot = new byte[SlotSize]; + BinaryPrimitives.WriteUInt32LittleEndian(slot, HeaderMagic); + BinaryPrimitives.WriteUInt16LittleEndian(slot.AsSpan(4), Version); + BinaryPrimitives.WriteUInt64LittleEndian(slot.AsSpan(8), generation); + BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(16), indexOffset); + BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(24), indexLength); + BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(28), count); + BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(32), dataEnd); + BinaryPrimitives.WriteUInt32LittleEndian(slot.AsSpan(SlotSize - 4), Crc32.Compute(slot.AsSpan(0, SlotSize - 4))); + return slot; + } + + private static byte[] IndexRecord(IEnumerable entries) + { + var list = entries.ToList(); + var record = new byte[8 + list.Count * IndexEntrySize + 4]; + BinaryPrimitives.WriteUInt32LittleEndian(record, IndexMagic); + BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(4), list.Count); + for (var i = 0; i < list.Count; i++) + { + var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize); + var e = list[i]; + e.FrameId.TryWriteBytes(s); + BinaryPrimitives.WriteInt64LittleEndian(s[16..], e.Offset); + BinaryPrimitives.WriteInt32LittleEndian(s[24..], e.Length); + BinaryPrimitives.WriteUInt16LittleEndian(s[28..], (ushort)e.Width); + BinaryPrimitives.WriteUInt16LittleEndian(s[30..], (ushort)e.Height); + BinaryPrimitives.WriteUInt32LittleEndian(s[32..], e.Crc); + } + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(record.Length - 4), Crc32.Compute(record.AsSpan(0, record.Length - 4))); + return record; + } + + /// Appends an index record, flushes, then commits it through the header slot not holding the newest generation. + private void WriteIndex() + { + var index = Volatile.Read(ref _index); + var record = IndexRecord(index.Values); + var offset = _tail; + WriteAt(record, offset); + _tail += record.Length; + RandomAccess.FlushToDisk(_handle); + var slot = 1 - _activeSlot; + WriteAt(HeaderSlot(_generation + 1, offset, record.Length, index.Count, _tail), slot * SlotSize); + RandomAccess.FlushToDisk(_handle); + _generation++; + _activeSlot = slot; + _unindexed = 0; + } + + private void WriteAt(ReadOnlySpan data, long offset) + { + _handleLock.EnterReadLock(); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + RandomAccess.Write(_handle, data, offset); + } + finally + { + _handleLock.ExitReadLock(); + } + } + + private void Warn(string message) + { + lock (_warnings) + { + if (_warnings.Count < 32) _warnings.Add(message); + } + } + + /// Reads the newest valid header slot and its index, then recovers entries appended after it. + private void Load() + { + long length; + _handleLock.EnterReadLock(); + try + { + length = RandomAccess.GetLength(_handle); + } + finally + { + _handleLock.ExitReadLock(); + } + var index = new ConcurrentDictionary(); + long scanFrom = DataStart; + (_generation, _activeSlot) = (0, 1); + var slots = new byte[DataStart]; + var slotBytes = ReadAt(slots, 0); + for (var s = 0; s < 2; s++) + { + if (slotBytes < (s + 1) * SlotSize || ParseSlot(slots.AsSpan(s * SlotSize, SlotSize)) is not { } h) + { + if (slotBytes >= (s + 1) * SlotSize && slots.AsSpan(s * SlotSize, SlotSize).ContainsAnyExcept((byte)0)) Warn($"Header slot {s} damaged"); + continue; + } + if (h.Generation <= _generation) continue; + var loaded = h.IndexLength > 0 ? ReadIndex(h.IndexOffset, h.IndexLength, length) : new ConcurrentDictionary(); + if (loaded is null) + { + Warn($"Index of header slot {s} damaged"); + continue; + } + (_generation, _activeSlot) = (h.Generation, s); + index = loaded; + scanFrom = h.DataEnd; + } + if (_generation == 0) Warn("No valid header; entries recovered by scanning"); + _tail = length <= DataStart ? DataStart : Recover(index, long.Clamp(scanFrom, DataStart, length), length); + _index = index; + _liveBytes = index.Values.Sum(e => (long)EntryHeaderSize + e.Length); + _unindexed = 0; + } + + private readonly record struct Slot(ulong Generation, long IndexOffset, int IndexLength, long DataEnd); + + private static Slot? ParseSlot(ReadOnlySpan s) + { + if (BinaryPrimitives.ReadUInt32LittleEndian(s) != HeaderMagic || BinaryPrimitives.ReadUInt16LittleEndian(s[4..]) != Version) return null; + if (Crc32.Compute(s[..(SlotSize - 4)]) != BinaryPrimitives.ReadUInt32LittleEndian(s[(SlotSize - 4)..])) return null; + return new Slot(BinaryPrimitives.ReadUInt64LittleEndian(s[8..]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]), + BinaryPrimitives.ReadInt32LittleEndian(s[24..]), BinaryPrimitives.ReadInt64LittleEndian(s[32..])); + } + + private ConcurrentDictionary? ReadIndex(long offset, int length, long fileLength) + { + if (offset < DataStart || length < 12 || offset > fileLength - length || (length - 12) % IndexEntrySize != 0) return null; + var record = new byte[length]; + if (ReadAt(record, offset) != length) return null; + if (BinaryPrimitives.ReadUInt32LittleEndian(record) != IndexMagic + || Crc32.Compute(record.AsSpan(0, length - 4)) != BinaryPrimitives.ReadUInt32LittleEndian(record.AsSpan(length - 4))) return null; + var count = BinaryPrimitives.ReadInt32LittleEndian(record.AsSpan(4)); + if (count != (length - 12) / IndexEntrySize) return null; + var index = new ConcurrentDictionary(); + for (var i = 0; i < count; i++) + { + var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize); + var e = new ThumbnailEntry(new Guid(s[..16]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]), BinaryPrimitives.ReadInt32LittleEndian(s[24..]), + BinaryPrimitives.ReadUInt16LittleEndian(s[28..]), BinaryPrimitives.ReadUInt16LittleEndian(s[30..]), BinaryPrimitives.ReadUInt32LittleEndian(s[32..])); + if (e.Offset >= DataStart && e.Length is > 0 and <= MaxJpegBytes && e.Offset <= fileLength - EntryHeaderSize - e.Length) index[e.FrameId] = e; + } + return index; + } + + /// Walks records from , adding valid entries (later ones win) and skipping index + /// records; stops at the first damaged or truncated record. Returns the end of the last good record. + private long Recover(ConcurrentDictionary index, long position, long length) + { + var head = new byte[EntryHeaderSize]; + var recovered = 0; + while (position + 12 <= length) + { + var n = ReadAt(head.AsSpan(0, (int)long.Min(EntryHeaderSize, length - position)), position); + var magic = BinaryPrimitives.ReadUInt32LittleEndian(head); + if (magic == IndexMagic && n >= 8) + { + var count = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(4)); + var size = 12L + (long)count * IndexEntrySize; + if (count < 0 || position + size > length || ReadIndex(position, (int)long.Min(size, int.MaxValue), length) is null) break; + position += size; + continue; + } + if (magic != EntryMagic || n < EntryHeaderSize) break; + var jpegLength = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(24)); + if (jpegLength is <= 0 or > MaxJpegBytes || position + EntryHeaderSize + jpegLength > length) break; + var jpeg = new byte[jpegLength]; + if (ReadAt(jpeg, position + EntryHeaderSize) != jpegLength) break; + var crc = BinaryPrimitives.ReadUInt32LittleEndian(head.AsSpan(28)); + if (Crc32.Compute(jpeg) != crc) break; + var id = new Guid(head.AsSpan(4, 16)); + index[id] = new ThumbnailEntry(id, position, jpegLength, BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(20)), BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(22)), crc); + position += EntryHeaderSize + jpegLength; + recovered++; + } + if (position < length) Warn($"Ignored {length - position} damaged bytes at the end of the pack"); + if (recovered > 0) Warn($"Recovered {recovered} thumbnail(s) appended after the last index"); + return position; + } + + private int ReadAt(Span buffer, long offset) + { + _handleLock.EnterReadLock(); + try + { + var total = 0; + while (total < buffer.Length) + { + var n = RandomAccess.Read(_handle, buffer[total..], offset + total); + if (n == 0) break; + total += n; + } + return total; + } + finally + { + _handleLock.ExitReadLock(); + } + } +} diff --git a/tests/Titano.Core.Tests/Decoding/ThumbnailTests.cs b/tests/Titano.Core.Tests/Decoding/ThumbnailTests.cs new file mode 100644 index 00000000..7690ef7c --- /dev/null +++ b/tests/Titano.Core.Tests/Decoding/ThumbnailTests.cs @@ -0,0 +1,277 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Raw; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Imaging.Thumbnails; +using Titano.Core.Metadata; +using Titano.Core.Model; +using Titano.Core.Tests.Raw; +using Titano.Testing; + +namespace Titano.Core.Tests.Decoding; + +/// format behaviour, and . +public sealed class ThumbnailTests(TestContext context) +{ + private readonly string _dir = context.CreateTempDirectory(); + + private static ImageBuffer Frame(int seed, int width = 400, int height = 300) + { + var image = new ImageBuffer(width, height); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + image[0, x, y] = (x + seed * 13) % 97 / 96f; + image[1, x, y] = (y + seed * 7) % 89 / 88f; + image[2, x, y] = seed % 5 / 5f; + } + } + return image; + } + + /// Small distinct JPEGs (cheap to make in bulk). + private static byte[] Jpeg(int seed) + { + using var image = Frame(seed, 40, 30); + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80 }); + } + + private static Guid Id(int i) => new(i, 0, 0, [0, 0, 0, 0, 0, 0, 0, 1]); + + [Test] + public void RoundTripAppendAndReplace() + { + var path = Path.Combine(_dir, "thumbs.pack"); + using (var pack = ThumbnailPack.Open(path)) + { + for (var i = 0; i < 20; i++) + { + using var frame = Frame(i); + var e = pack.Add(Id(i), frame); + Assert.Equal(320, e.Width); + Assert.Equal(240, e.Height); + } + } + using (var pack = ThumbnailPack.Open(path)) + { + Assert.Equal(20, pack.Count); + Assert.Empty(pack.Warnings); + for (var i = 20; i < 25; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30); + pack.AddJpeg(Id(3), Jpeg(1000), 40, 30); + } + using var reader = ThumbnailPack.Open(path, writable: false); + Assert.Equal(25, reader.Count); + Assert.BytesEqual(Jpeg(1000), reader.ReadJpeg(Id(3))); + Assert.BytesEqual(Jpeg(22), reader.ReadJpeg(Id(22))); + var thumb = Thumbnail.FromJpeg(reader.ReadJpeg(Id(7))!); + Assert.Equal(320, thumb.Width); + Assert.Null(reader.ReadJpeg(Id(99))); + Assert.Greater(reader.WastedBytes, 0); + } + + [Test] + public void EntriesAfterTheLastIndexAreRecovered() + { + var path = Path.Combine(_dir, "crash.pack"); + var copy = Path.Combine(_dir, "crash-copy.pack"); + var count = ThumbnailPack.IndexInterval + 6; + using (var pack = ThumbnailPack.Open(path)) + { + for (var i = 0; i < count; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30); + // Simulated crash: the file as it is before the closing index write. + File.Copy(path, copy); + } + using var recovered = ThumbnailPack.Open(copy, writable: false); + Assert.Equal(count, recovered.Count); + Assert.Contains(recovered.Warnings, w => w.Contains("Recovered 6")); + Assert.BytesEqual(Jpeg(count - 1), recovered.ReadJpeg(Id(count - 1))); + } + + [Test] + public void TruncatedAndDamagedFilesOpen() + { + var path = Path.Combine(_dir, "full.pack"); + using (var pack = ThumbnailPack.Open(path)) + { + for (var i = 0; i < 40; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30); + } + var bytes = File.ReadAllBytes(path); + for (var cut = 0; cut <= 40; cut++) + { + var file = Path.Combine(_dir, $"cut{cut}.pack"); + File.WriteAllBytes(file, bytes[..(int)((long)bytes.Length * cut / 40)]); + using var pack = ThumbnailPack.Open(file, writable: false); + foreach (var id in pack.FrameIds) Assert.NotNull(pack.ReadJpeg(id)); + Assert.LessOrEqual(pack.Count, 40); + } + // A damaged newest header slot falls back to the other one (or a scan). + var damaged = (byte[])bytes.Clone(); + for (var i = 0; i < 128; i++) damaged[i] ^= 0x5A; + var damagedPath = Path.Combine(_dir, "damaged.pack"); + File.WriteAllBytes(damagedPath, damaged); + using (var pack = ThumbnailPack.Open(damagedPath, writable: false)) + { + Assert.Equal(40, pack.Count); + Assert.Contains(pack.Warnings, w => w.Contains("No valid header")); + } + // A flipped JPEG byte is caught by its CRC on read. + var flipped = (byte[])bytes.Clone(); + flipped[128 + 40] ^= 0xFF; + var flippedPath = Path.Combine(_dir, "flipped.pack"); + File.WriteAllBytes(flippedPath, flipped); + using var f = ThumbnailPack.Open(flippedPath, writable: false); + Assert.Null(f.ReadJpeg(Id(0))); + Assert.NotNull(f.ReadJpeg(Id(1))); + } + + [Test] + public void CompactionDropsDeadEntries() + { + var path = Path.Combine(_dir, "compact.pack"); + using var pack = ThumbnailPack.Open(path); + for (var i = 0; i < 30; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30); + for (var i = 0; i < 10; i++) pack.AddJpeg(Id(i), Jpeg(i + 500), 40, 30); + for (var i = 25; i < 30; i++) Assert.True(pack.Remove(Id(i))); + pack.Flush(); + var before = new FileInfo(path).Length; + var wasted = pack.WastedBytes; + pack.Compact(); + var after = new FileInfo(path).Length; + context.Log($"compaction {before} → {after} bytes (wasted {wasted})"); + Assert.Less(after, before - wasted / 2); + Assert.Equal(25, pack.Count); + Assert.Null(pack.ReadJpeg(Id(27))); + Assert.BytesEqual(Jpeg(503), pack.ReadJpeg(Id(3))); + pack.AddJpeg(Id(100), Jpeg(100), 40, 30); + pack.Flush(); + using var reopened = ThumbnailPack.Open(path, writable: false); + Assert.Equal(26, reopened.Count); + Assert.Empty(reopened.Warnings); + Assert.BytesEqual(Jpeg(15), reopened.ReadJpeg(Id(15))); + } + + [Test] + [Timeout(20_000)] + public async Task ConcurrentReadsWhileWriting() + { + var path = Path.Combine(_dir, "concurrent.pack"); + var jpegs = Enumerable.Range(0, 200).Select(Jpeg).ToArray(); + using var pack = ThumbnailPack.Open(path); + for (var i = 0; i < 10; i++) pack.AddJpeg(Id(i), jpegs[i], 40, 30); + pack.Flush(); + using var done = new CancellationTokenSource(); + var writer = Task.Run(() => + { + for (var i = 10; i < 200; i++) pack.AddJpeg(Id(i), jpegs[i], 40, 30); + pack.Flush(); + done.Cancel(); + }); + var readers = Enumerable.Range(0, 4).Select(r => Task.Run(() => + { + var random = new Random(r); + var reads = 0; + while (!done.IsCancellationRequested || reads < 50) + { + var ids = pack.FrameIds.ToArray(); + var id = ids[random.Next(ids.Length)]; + var data = pack.ReadJpeg(id); + Assert.NotNull(data); + Assert.BytesEqual(jpegs[id.ToByteArray()[0] | id.ToByteArray()[1] << 8], data); + reads++; + } + return reads; + })).ToArray(); + var other = Task.Run(() => + { + using var view = ThumbnailPack.Open(path, writable: false); + while (!done.IsCancellationRequested) + { + view.Refresh(); + foreach (var id in view.FrameIds) Assert.NotNull(view.ReadJpeg(id)); + } + }); + await Task.WhenAll([writer, other, .. readers]); + Assert.Equal(200, pack.Count); + context.Log($"reads: {string.Join(", ", readers.Select(r => r.Result))}"); + } + + [Test] + public async Task CacheEvictsLeastRecentlyUsedAndCoalescesLoads() + { + var cache = new ThumbnailCache(3 * (300 + 64)); + Thumbnail T() => new(10, 10, new byte[300]); + cache.Set(1, T()); + cache.Set(2, T()); + cache.Set(3, T()); + Assert.True(cache.TryGet(1, out _)); + cache.Set(4, T()); + Assert.False(cache.TryGet(2, out _)); + Assert.True(cache.TryGet(1, out _)); + Assert.Equal(3, cache.Count); + Assert.LessOrEqual(cache.Bytes, cache.Budget); + cache.Set(5, new Thumbnail(100, 100, new byte[30000])); + Assert.False(cache.TryGet(5, out _)); + + var loads = 0; + var gate = new TaskCompletionSource(); + async Task Loader(int key, CancellationToken ct) + { + Interlocked.Increment(ref loads); + await gate.Task; + return Thumbnail.FromJpeg(Jpeg(key)); + } + var large = new ThumbnailCache(1 << 20); + var requests = Enumerable.Range(0, 10).Select(_ => large.GetOrLoadAsync(42, Loader)).ToArray(); + gate.SetResult(); + var results = await Task.WhenAll(requests); + Assert.Equal(1, loads); + Assert.True(results.All(r => ReferenceEquals(r, results[0]))); + Assert.Equal(40, results[0]!.Width); + Assert.True(large.TryGet(42, out _)); + } + + [Test] + public void ProxyCarriesUprightPixelsAndCaptureExif() + { + var captured = new DateTime(2025, 7, 14, 21, 3, 9, DateTimeKind.Unspecified).AddTicks(4_500_000); + var metadata = new FrameMetadata { Make = "TestCam", Model = "T1", Orientation = 6, CapturedAt = captured, UtcOffsetMinutes = 120, Iso = 800, ExposureTime = 1 / 250.0 }; + using var image = Frame(1, 2000, 1500); + var exif = ExifWriter.BuildTiff(metadata); + var source = Path.Combine(_dir, "src.jpg"); + File.WriteAllBytes(source, JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [[.. "Exif\0\0"u8, .. exif]] })); + + var proxy = ProxyBuilder.Write(DecoderFactory.CreateServer(), source, Path.Combine(_dir, "proxy.jpg"), ProxySize.Edge1280); + Assert.NotNull(proxy); + Assert.Equal(960, proxy!.Width); + Assert.Equal(1280, proxy.Height); + Assert.Equal(DecodeTier.Native, proxy.Tier); + var back = MetadataReader.Read(Path.Combine(_dir, "proxy.jpg")); + Assert.Equal(captured, back.CapturedAt); + Assert.Equal(120, back.UtcOffsetMinutes); + Assert.Equal(TimestampSource.ExifOriginal, back.TimestampSource); + Assert.Equal(1, back.Orientation); + Assert.Equal("TestCam", back.Make); + Assert.Equal(800, back.Iso); + Assert.Equal(960, back.Width); + Assert.Equal(1280, back.Height); + var info = JpegDecoder.ReadInfo(proxy.Jpeg); + Assert.Equal(960, info.Width); + + var full = ProxyBuilder.Build(DecoderFactory.CreateServer(), source, ProxySize.Full); + Assert.Equal(1500, full!.Width); + } + + [Test] + public void ProxyOfAnUnsupportedRawUsesThePreviewTier() + { + using var scene = SyntheticRaw.Smooth(96, 64); + var active = new RawRect(24, 4, 120, 68); + var cr2 = NativeRawWriters.Cr2(NativeRawWriters.Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, 24, 4, 2048, 16383), active, 1, "Canon EOS R99"); + var path = Path.Combine(_dir, "x.cr2"); + File.WriteAllBytes(path, cr2); + var proxy = ProxyBuilder.Build(DecoderFactory.CreateServer(), path); + Assert.Equal(DecodeTier.EmbeddedPreview, proxy!.Tier); + Assert.Equal(64, proxy.Width); + } +} From 555d17742c8e8f44d42a130a62dc6d571c7f1360 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:27:16 +0000 Subject: [PATCH 151/188] feat(imaging): frame window with read-ahead, budget and float32 spill FrameWindow keeps frames from position-Behind to position+Ahead, decodes ahead on background tasks within the memory budget, drops frames that leave the window and spills in-window frames farthest from the position to a delete-on-close temp file of float32 planes (renders stay bit-identical under memory pressure). The budget check and load start share one lock; leases pin frames; disposal waits for decodes, releases every buffer and deletes the spill file even after cancellation. Tests assert a hard three-frame bound for 40 and 400 frames and an identical spill-file size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Imaging/FrameWindow.cs | 487 ++++++++++++++++++ .../Decoding/FrameWindowTests.cs | 197 +++++++ 2 files changed, 684 insertions(+) create mode 100644 src/Titano.Core/Imaging/FrameWindow.cs create mode 100644 tests/Titano.Core.Tests/Decoding/FrameWindowTests.cs diff --git a/src/Titano.Core/Imaging/FrameWindow.cs b/src/Titano.Core/Imaging/FrameWindow.cs new file mode 100644 index 00000000..157d81d5 --- /dev/null +++ b/src/Titano.Core/Imaging/FrameWindow.cs @@ -0,0 +1,487 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Titano.Core.Imaging; + +/// Options for . +public sealed record FrameWindowOptions +{ + /// Frames before the render position that stay available (temporal filters look back). + public int Behind { get; init; } = 2; + + /// Frames after the render position decoded in the background. + public int Ahead { get; init; } = 4; + + /// Upper bound on the bytes of decoded frames held in memory, in-flight decodes included. + public long MemoryBudget { get; init; } = 1L << 30; + + /// Directory of the spill file (null: the system temporary directory). + public string? SpillDirectory { get; init; } + + /// Background decodes running at once. + public int MaxConcurrentLoads { get; init; } = 2; +} + +/// Counters of a , for diagnostics and the memory self-tests. +public readonly record struct FrameWindowStatistics(long LiveBytes, long PeakLiveBytes, int Loads, int SpillWrites, int SpillReads, long SpillFileBytes); + +/// A frame kept resident while the lease is held. The image must not be modified (it may be shared with a spill copy). +public sealed class FrameLease : IDisposable +{ + private FrameWindow? _window; + + internal FrameLease(FrameWindow window, int index, ImageBuffer image) + { + _window = window; + Index = index; + Image = image; + } + + public int Index { get; } + public ImageBuffer Image { get; } + + public void Dispose() => Interlocked.Exchange(ref _window, null)?.Release(Index); +} + +/// +/// Sliding window of decoded frames around the render position (BRIEF §8.4). Frames from position − Behind to +/// position + Ahead are kept; those ahead are decoded on background tasks as the memory budget allows. When a +/// demanded frame needs room, unleased frames outside the window are dropped first, then in-window frames farthest from +/// the position are evicted to a spill file and read back on demand (cheaper than decoding a RAW again). Live memory +/// therefore stays within (exceeded only by frames the caller holds +/// leases on), and the spill file within the window's size: both are independent of the sequence length. +/// The spill file stores raw float32 planes: renders stay bit-identical whether or not a frame was spilled (a +/// float16 spill would halve disk traffic but make output depend on memory pressure). It is deleted on disposal, +/// including after cancellation, and opened delete-on-close as a backstop. +/// +public sealed class FrameWindow : IDisposable, IAsyncDisposable +{ + private readonly Func> _loader; + private readonly FrameWindowOptions _options; + private readonly Lock _gate = new(); + private readonly SemaphoreSlim _demand = new(1, 1); + private readonly CancellationTokenSource _cts = new(); + private readonly Dictionary _slots = []; + private SpillFile? _spill; + private long _liveBytes, _peakLiveBytes, _estimate; + private int _position, _backgroundLoads, _loads, _spillWrites, _spillReads; + private bool _disposed; + + /// Frames in the sequence. + /// Decodes frame i; called on background threads, at most once per residency. + public FrameWindow(int frameCount, Func> loader, FrameWindowOptions? options = null) + { + ArgumentOutOfRangeException.ThrowIfNegative(frameCount); + ArgumentNullException.ThrowIfNull(loader); + _options = options ?? new FrameWindowOptions(); + ArgumentOutOfRangeException.ThrowIfNegative(_options.Behind); + ArgumentOutOfRangeException.ThrowIfNegative(_options.Ahead); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(_options.MemoryBudget); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(_options.MaxConcurrentLoads); + Count = frameCount; + _loader = loader; + } + + public int Count { get; } + + public int Position + { + get + { + lock (_gate) return _position; + } + } + + /// Path of the spill file once created (it is removed on disposal). + public string? SpillPath + { + get + { + lock (_gate) return _spill?.Path; + } + } + + public FrameWindowStatistics Statistics + { + get + { + lock (_gate) return new FrameWindowStatistics(_liveBytes, _peakLiveBytes, _loads, _spillWrites, _spillReads, _spill?.Length ?? 0); + } + } + + /// Moves the render position: frames that left the window are released and read-ahead starts. + public void MoveTo(int position) + { + ArgumentOutOfRangeException.ThrowIfNegative(position); + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _position = position; + foreach (var slot in _slots.Values.ToList()) + { + if (!InWindow(slot.Index) && slot.Leases == 0 && slot.Loading is null && !slot.Spilling) Drop(slot); + } + ScheduleReadAhead(); + } + } + + /// Returns frame , decoding it (or reading it back from the spill file) when needed. + /// Does not move the window. + /// Cancelled, or the window was disposed. + public async ValueTask GetAsync(int index, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); + var token = linked.Token; + while (true) + { + token.ThrowIfCancellationRequested(); + Task? pending; + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_slots.TryGetValue(index, out var slot) && slot.Image is { } image) + { + slot.Leases++; + return new FrameLease(this, index, image); + } + pending = slot?.Loading; + } + if (pending is not null) + { + if (await pending.WaitAsync(token).ConfigureAwait(false) is { } error) throw error is OperationCanceledException ? new OperationCanceledException(error.Message, error, token) : error; + continue; + } + await _demand.WaitAsync(token).ConfigureAwait(false); + try + { + await LoadWithinBudgetAsync(index, token).ConfigureAwait(false); + } + finally + { + _demand.Release(); + } + } + } + + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); + + /// Cancels background decodes, waits for them and for an eviction in progress, releases every frame and + /// deletes the spill file. The semaphore and token source are left undisposed on purpose: callers racing the disposal + /// may still release or observe them, and neither holds an unmanaged resource here. + public async ValueTask DisposeAsync() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + } + _cts.Cancel(); + await _demand.WaitAsync().ConfigureAwait(false); + Task[] pending; + lock (_gate) pending = [.. _slots.Values.Select(s => s.Loading).OfType()]; + await Task.WhenAll(pending).ConfigureAwait(false); + lock (_gate) + { + foreach (var slot in _slots.Values) + { + slot.Image?.Dispose(); + slot.Image = null; + } + _slots.Clear(); + _liveBytes = 0; + _spill?.Dispose(); + } + } + + internal void Release(int index) + { + lock (_gate) + { + if (_disposed || !_slots.TryGetValue(index, out var slot)) return; + slot.Leases--; + if (slot.Leases == 0 && !InWindow(index) && slot.Loading is null && !slot.Spilling) Drop(slot); + } + } + + private bool InWindow(int index) => index >= _position - _options.Behind && index <= _position + _options.Ahead; + + /// Starts the decode (or spill read) of once its size fits the budget: unleased frames + /// outside the window are dropped first, then in-window frames farthest from the position are spilled. The check and + /// the start happen under one lock so background read-ahead cannot take the room in between. The budget is exceeded + /// only when every resident frame is leased. Callers hold the demand semaphore (one eviction at a time). + private async Task LoadWithinBudgetAsync(int index, CancellationToken cancellationToken) + { + while (true) + { + Slot victim; + ImageBuffer image; + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!_slots.TryGetValue(index, out var slot)) + { + slot = new Slot(index); + _slots[index] = slot; + } + if (slot.Image is not null || slot.Loading is not null) return; + var required = slot.Spill?.Bytes ?? _estimate; + Slot? best = null; + if (_liveBytes + required > _options.MemoryBudget) + { + foreach (var s in _slots.Values) + { + if (s.Index == index || s.Image is null || s.Leases > 0 || s.Spilling) continue; + if (best is null || Priority(s) > Priority(best)) best = s; + } + } + if (best is null) + { + StartLoad(slot, background: false); + return; + } + if (!InWindow(best.Index)) + { + Drop(best); + continue; + } + if (best.Spill is not null) + { + Unload(best); + continue; + } + best.Spilling = true; + _spill ??= new SpillFile(_options.SpillDirectory); + (victim, image) = (best, best.Image!); + } + SpillExtent extent; + try + { + extent = await Task.Run(() => _spill!.Write(image), cancellationToken).ConfigureAwait(false); + } + catch + { + lock (_gate) victim.Spilling = false; + throw; + } + lock (_gate) + { + victim.Spilling = false; + victim.Spill = extent; + _spillWrites++; + if (victim.Leases == 0) Unload(victim); + } + } + } + + /// Eviction order: outside the window first, then the farthest from the position (behind before ahead). + private double Priority(Slot s) + { + var distance = s.Index < _position ? (_position - s.Index) * 1.5 : s.Index - _position; + return InWindow(s.Index) ? distance : 1e9 + distance; + } + + /// Starts a decode (or spill read) for the slot, reserving the estimated size. Caller holds the gate. + private void StartLoad(Slot slot, bool background) + { + var reserved = slot.Spill?.Bytes ?? _estimate; + slot.Reserved = reserved; + _liveBytes += reserved; + _peakLiveBytes = long.Max(_peakLiveBytes, _liveBytes); + if (background) _backgroundLoads++; + var spill = slot.Spill; + var token = _cts.Token; + slot.Loading = Task.Run(async () => + { + ImageBuffer? image = null; + try + { + if (spill is not null) image = _spill!.Read(spill); + else image = await _loader(slot.Index, token).ConfigureAwait(false); + lock (_gate) + { + slot.Loading = null; + if (background) _backgroundLoads--; + _liveBytes -= slot.Reserved; + slot.Reserved = 0; + if (_disposed) + { + image.Dispose(); + return new OperationCanceledException("The frame window was disposed."); + } + slot.Image = image; + _liveBytes += image.ByteSize; + _peakLiveBytes = long.Max(_peakLiveBytes, _liveBytes); + if (spill is null) + { + _loads++; + _estimate = image.ByteSize; + } + else + { + _spillReads++; + } + ScheduleReadAhead(); + } + return null; + } + catch (Exception ex) + { + image?.Dispose(); + lock (_gate) + { + if (slot.Loading is not null) + { + slot.Loading = null; + if (background) _backgroundLoads--; + _liveBytes -= slot.Reserved; + slot.Reserved = 0; + } + if (slot.Image is null && slot.Spill is null && slot.Leases == 0) _slots.Remove(slot.Index); + } + return (Exception?)ex; + } + }, CancellationToken.None); + } + + /// Starts background decodes of missing frames ahead while the budget allows. Caller holds the gate. + private void ScheduleReadAhead() + { + if (_disposed) return; + var last = int.Min(Count - 1, _position + _options.Ahead); + for (var i = _position; i <= last && _backgroundLoads < _options.MaxConcurrentLoads; i++) + { + if (_slots.TryGetValue(i, out var existing) && (existing.Image is not null || existing.Loading is not null || existing.Spill is not null)) continue; + // The first frame's size is unknown: allow one decode to learn it. + if (_estimate == 0 ? _loads + _backgroundLoads > 0 : _liveBytes + _estimate > _options.MemoryBudget) return; + if (existing is null) + { + existing = new Slot(i); + _slots[i] = existing; + } + StartLoad(existing, background: true); + } + } + + /// Releases the frame's memory (its spill copy, if any, stays). Caller holds the gate. + private void Unload(Slot slot) + { + if (slot.Image is null) return; + _liveBytes -= slot.Image.ByteSize; + slot.Image.Dispose(); + slot.Image = null; + } + + /// Forgets the frame entirely (memory and spill extent). Caller holds the gate. + private void Drop(Slot slot) + { + Unload(slot); + if (slot.Spill is { } extent) _spill?.Free(extent); + slot.Spill = null; + _slots.Remove(slot.Index); + } + + private sealed class Slot(int index) + { + public int Index { get; } = index; + public ImageBuffer? Image { get; set; } + public Task? Loading { get; set; } + public SpillExtent? Spill { get; set; } + public bool Spilling { get; set; } + public int Leases { get; set; } + public long Reserved { get; set; } + } + + private sealed record SpillExtent(long Offset, int Width, int Height, int Channels) + { + public long Bytes => (long)Width * Height * Channels * sizeof(float); + } + + /// Temporary file of float32 planes; freed extents are reused by frames of the same size. + private sealed class SpillFile : IDisposable + { + private readonly SafeFileHandle _handle; + private readonly List _free = []; + private readonly Lock _gate = new(); + + public SpillFile(string? directory) + { + var dir = directory ?? System.IO.Path.GetTempPath(); + Directory.CreateDirectory(dir); + Path = System.IO.Path.Combine(dir, $"titano-spill-{Guid.NewGuid():N}.tmp"); + _handle = File.OpenHandle(Path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileOptions.DeleteOnClose | FileOptions.RandomAccess); + } + + public string Path { get; } + public long Length { get; private set; } + + public SpillExtent Write(ImageBuffer image) + { + SpillExtent extent; + lock (_gate) + { + var reuse = _free.FindIndex(e => e.Width == image.Width && e.Height == image.Height && e.Channels == image.Channels); + if (reuse >= 0) + { + extent = _free[reuse]; + _free.RemoveAt(reuse); + } + else + { + extent = new SpillExtent(Length, image.Width, image.Height, image.Channels); + Length += extent.Bytes; + } + } + var planeBytes = (long)image.PlaneLength * sizeof(float); + for (var c = 0; c < image.Channels; c++) RandomAccess.Write(_handle, MemoryMarshal.AsBytes((ReadOnlySpan)image.Plane(c)), extent.Offset + c * planeBytes); + return extent; + } + + public ImageBuffer Read(SpillExtent extent) + { + var image = new ImageBuffer(extent.Width, extent.Height, extent.Channels, clear: false); + try + { + var planeBytes = (long)image.PlaneLength * sizeof(float); + for (var c = 0; c < image.Channels; c++) + { + var bytes = MemoryMarshal.AsBytes(image.Plane(c)); + var done = 0; + while (done < bytes.Length) + { + var n = RandomAccess.Read(_handle, bytes[done..], extent.Offset + c * planeBytes + done); + if (n == 0) throw new IOException("Spill file truncated"); + done += n; + } + } + return image; + } + catch + { + image.Dispose(); + throw; + } + } + + public void Free(SpillExtent extent) + { + lock (_gate) _free.Add(extent); + } + + public void Dispose() + { + _handle.Dispose(); + try + { + if (File.Exists(Path)) File.Delete(Path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + } +} diff --git a/tests/Titano.Core.Tests/Decoding/FrameWindowTests.cs b/tests/Titano.Core.Tests/Decoding/FrameWindowTests.cs new file mode 100644 index 00000000..06edd17b --- /dev/null +++ b/tests/Titano.Core.Tests/Decoding/FrameWindowTests.cs @@ -0,0 +1,197 @@ +using Titano.Core.Imaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Decoding; + +/// : memory bound independent of sequence length, spill round trip, read-ahead, +/// cancellation and deterministic disposal (BRIEF §8.4, §20.4 memory and cancellation gates). +public sealed class FrameWindowTests(TestContext context) +{ + private const int Size = 64; + private const long FrameBytes = Size * Size * 3 * sizeof(float); + + /// Synthetic loader whose frames encode their index; records every buffer it hands out. + private sealed class Source + { + private readonly List _made = []; + public int Loads; + public TimeSpan Delay; + + public async ValueTask Load(int index, CancellationToken cancellationToken) + { + Interlocked.Increment(ref Loads); + if (Delay > TimeSpan.Zero) await Task.Delay(Delay, cancellationToken); + var image = new ImageBuffer(Size, Size, 3, clear: false); + image.Data.Fill(index); + image[1, 5, 7] = index + 0.25f; + lock (_made) _made.Add(image); + return image; + } + + /// Loader-made buffers not yet disposed (independent of the window's own counters). + public int Live() + { + lock (_made) + { + var live = 0; + foreach (var b in _made) + { + try + { + _ = b.Storage; + live++; + } + catch (ObjectDisposedException) + { + } + } + return live; + } + } + } + + private static void AssertFrame(FrameLease lease) + { + Assert.Equal((float)lease.Index, lease.Image[0, 10, 10]); + Assert.Equal(lease.Index + 0.25f, lease.Image[1, 5, 7]); + } + + /// Render loop: each step moves the window and reads the frame plus its three predecessors — four frames + /// needed per step against a three-frame budget, so in-window frames must be spilled and read back. + private async Task<(FrameWindowStatistics Stats, int PeakLive, string? Spill)> Render(int frames, string spillDirectory) + { + var source = new Source(); + var options = new FrameWindowOptions { Behind = 3, Ahead = 4, MemoryBudget = 3 * FrameBytes, SpillDirectory = spillDirectory }; + var peakLive = 0; + FrameWindowStatistics stats; + string? spill; + await using (var window = new FrameWindow(frames, source.Load, options)) + { + for (var i = 0; i < frames; i++) + { + window.MoveTo(i); + using (var current = await window.GetAsync(i)) AssertFrame(current); + for (var back = 1; back <= 3 && i - back >= 0; back++) + { + using var previous = await window.GetAsync(i - back); + AssertFrame(previous); + } + peakLive = int.Max(peakLive, source.Live()); + Assert.LessOrEqual(window.Statistics.LiveBytes, options.MemoryBudget); + } + stats = window.Statistics; + spill = window.SpillPath; + Assert.FileExists(spill!); + } + Assert.Equal(0, source.Live()); + return (stats, peakLive, spill); + } + + [Test] + [Timeout(30_000)] + public async Task PeakMemoryIsBoundedAndIndependentOfSequenceLength() + { + var dir = context.CreateTempDirectory(); + var shortRun = await Render(40, dir); + var longRun = await Render(400, dir); + context.Log($"40 frames: {shortRun.Stats}, peak live {shortRun.PeakLive}; 400 frames: {longRun.Stats}, peak live {longRun.PeakLive}"); + foreach (var run in new[] { shortRun, longRun }) + { + Assert.LessOrEqual(run.Stats.PeakLiveBytes, 3 * FrameBytes); + Assert.LessOrEqual(run.PeakLive, 3); + Assert.Greater(run.Stats.SpillWrites, 0); + Assert.Greater(run.Stats.SpillReads, 0); + // Spill extents are reused: only frames inside the window (3 behind + current + 4 ahead) are ever on disk. + Assert.LessOrEqual(run.Stats.SpillFileBytes, 8 * FrameBytes); + Assert.FileMissing(run.Spill!); + } + Assert.Equal(shortRun.Stats.PeakLiveBytes, longRun.Stats.PeakLiveBytes); + Assert.Equal(shortRun.PeakLive, longRun.PeakLive); + Assert.LessOrEqual(longRun.Stats.SpillFileBytes, shortRun.Stats.SpillFileBytes); + } + + [Test] + [Timeout(10_000)] + public async Task ReadAheadDecodesInTheBackground() + { + var source = new Source(); + await using var window = new FrameWindow(100, source.Load, new FrameWindowOptions { Ahead = 3, MemoryBudget = 10 * FrameBytes }); + window.MoveTo(0); + using (var first = await window.GetAsync(0)) AssertFrame(first); + var deadline = DateTime.UtcNow.AddSeconds(5); + while (source.Loads < 4 && DateTime.UtcNow < deadline) await Task.Delay(5); + Assert.Equal(4, source.Loads); + using var ahead = await window.GetAsync(3); + AssertFrame(ahead); + Assert.Equal(4, source.Loads); + } + + [Test] + [Timeout(10_000)] + public async Task CancellationLeavesNoSpillFileAndNoUnobservedErrors() + { + var unobserved = 0; + void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved); + TaskScheduler.UnobservedTaskException += OnUnobserved; + try + { + var dir = context.CreateTempDirectory(); + var source = new Source(); + string? spill; + using var cts = new CancellationTokenSource(); + var window = new FrameWindow(50, source.Load, new FrameWindowOptions { Behind = 3, Ahead = 2, MemoryBudget = 2 * FrameBytes, SpillDirectory = dir }); + try + { + for (var i = 0; i < 6; i++) + { + window.MoveTo(i); + using var a = await window.GetAsync(i); + if (i > 0) + { + using var b = await window.GetAsync(i - 1); + } + } + spill = window.SpillPath; + Assert.NotNull(spill); + Assert.FileExists(spill!); + source.Delay = TimeSpan.FromSeconds(30); + window.MoveTo(20); + var pending = window.GetAsync(20, cts.Token); + cts.CancelAfter(50); + await Assert.ThrowsAsync(async () => await pending); + } + finally + { + await window.DisposeAsync(); + } + Assert.FileMissing(spill!); + Assert.Equal(0, source.Live()); + await Assert.ThrowsAsync(async () => await window.GetAsync(1)); + } + finally + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + TaskScheduler.UnobservedTaskException -= OnUnobserved; + } + Assert.Equal(0, unobserved); + } + + [Test] + public async Task LoaderFailuresSurfaceAndCanBeRetried() + { + var attempts = 0; + async ValueTask Flaky(int index, CancellationToken ct) + { + await Task.Yield(); + if (index == 2 && Interlocked.Increment(ref attempts) == 1) throw new InvalidDataException("bad frame"); + var image = new ImageBuffer(8, 8, 3); + image.Data.Fill(index); + return image; + } + await using var window = new FrameWindow(5, Flaky, new FrameWindowOptions { Ahead = 0 }); + await Assert.ThrowsAsync(async () => await window.GetAsync(2)); + using var retried = await window.GetAsync(2); + Assert.Equal(2f, retried.Image[0, 0, 0]); + } +} From 0bd19ebeb1648dc351c9a6e3af621e6a267056fa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:27:36 +0000 Subject: [PATCH 152/188] perf(video): encode image-sequence frames concurrently Frames are independent, so up to one per core is encoded at once with single-threaded codecs; PNG sequences no longer run Deflate on one core (1080p PNG export 1.0 to 2.5 fps on 4 cores). Failures surface on a later frame or on Complete, and discarding waits for every write first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Video/Managed/ManagedSessions.cs | 54 ++++++++++++++----- .../Export/ManagedEncoderTests.cs | 23 ++++++++ 2 files changed, 65 insertions(+), 12 deletions(-) diff --git a/src/Titano.Core/Video/Managed/ManagedSessions.cs b/src/Titano.Core/Video/Managed/ManagedSessions.cs index d46a8e5d..36efb605 100644 --- a/src/Titano.Core/Video/Managed/ManagedSessions.cs +++ b/src/Titano.Core/Video/Managed/ManagedSessions.cs @@ -203,7 +203,10 @@ internal sealed class ApngSession : SingleFileSession /// /// Numbered image files (<folder name>_000001.ext, 1-based, six digits) in the output folder. Files are written -/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion. +/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion. Frames are +/// independent, so several are encoded at once (each single-threaded, at most one per core): PNG's Deflate would +/// otherwise run on one core. A failed encode surfaces on a later or on +/// . /// internal sealed class ImageSequenceSession : ManagedSession { @@ -212,6 +215,8 @@ internal sealed class ImageSequenceSession : ManagedSession private readonly string _stem; private readonly string _extension; private readonly ConstantRateClock _clock; + private readonly Queue _inFlight = new(); + private readonly int _maxInFlight = int.Clamp(Environment.ProcessorCount, 1, 8); private int _index; public ImageSequenceSession(EncodeSettings settings, string encoderName) : base(settings, encoderName) @@ -235,20 +240,43 @@ internal sealed class ImageSequenceSession : ManagedSession { var repeats = _clock.Advance(duration90k); if (repeats == 0) return; - var bytes = Encode(frame); - for (var i = 0; i < repeats; i++) + while (_inFlight.Count >= _maxInFlight) _inFlight.Dequeue().GetAwaiter().GetResult(); + var first = _index + 1; + _index += repeats; + var copy = frame.Clone(); + _inFlight.Enqueue(Task.Run(() => { - _index++; - using var file = new FileStream(Path.Combine(_temp, FrameName(_stem, _index, _extension)), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16); - file.Write(bytes); - file.Flush(flushToDisk: true); - } + byte[] bytes; + using (copy) bytes = Encode(copy); + for (var number = first; number < first + repeats; number++) + { + using var file = new FileStream(Path.Combine(_temp, FrameName(_stem, number, _extension)), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16); + file.Write(bytes); + file.Flush(flushToDisk: true); + } + })); } - protected override void Commit() => Directory.Move(_temp, _folder); + protected override void Commit() + { + while (_inFlight.Count > 0) _inFlight.Dequeue().GetAwaiter().GetResult(); + Directory.Move(_temp, _folder); + } protected override void Discard() { + // Every encode must have stopped writing before the folder goes; their failures are already superseded. + while (_inFlight.Count > 0) + { + try + { + _inFlight.Dequeue().GetAwaiter().GetResult(); + } + catch (Exception ex) + { + Log.Warning(LogCategory, "A sequence frame failed while the encode was being discarded", ex); + } + } try { Directory.Delete(_temp, recursive: true); @@ -259,13 +287,15 @@ internal sealed class ImageSequenceSession : ManagedSession } } + /// One frame, single-threaded (frames are encoded concurrently). private byte[] Encode(ImageBuffer frame) => Settings.Codec switch { - VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)), + VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality) with { MaxDegreeOfParallelism = 1 }), VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal), - VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }), + VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16, MaxDegreeOfParallelism = 1 }), // Tiles no larger than the frame: edge padding of a 256-pixel tile would dominate small outputs. - VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame, new LinearDngOptions { TileSize = int.Clamp((int.Max(frame.Width, frame.Height) + 15) / 16 * 16, 16, 256) }), + VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame, + new LinearDngOptions { TileSize = int.Clamp((int.Max(frame.Width, frame.Height) + 15) / 16 * 16, 16, 256), MaxDegreeOfParallelism = 1 }), _ => throw new NotSupportedException($"{Settings.Codec} is not an image sequence"), }; } diff --git a/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs b/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs index 5e901acc..7e293f58 100644 --- a/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs +++ b/tests/Titano.Core.Tests/Export/ManagedEncoderTests.cs @@ -165,6 +165,29 @@ public sealed class ManagedEncoderTests Assert.Empty(Directory.GetFileSystemEntries(dir)); } + [Test] + public void SequenceWriteFailuresSurfaceAndLeaveNothing() + { + var dir = _context.CreateTempDirectory(); + var session = new ManagedEncoderProvider().Open(Settings(Path.Combine(dir, "seq"), VideoCodec.PngSequence)); + using var frame = Frame(0); + session.WriteFrame(frame, 3000); + Directory.Delete(Directory.GetDirectories(dir, ".seq.*.tmp").Single(), recursive: true); + Exception? error = null; + try + { + for (var i = 0; i < 20; i++) session.WriteFrame(frame, 3000); + session.Complete(); + } + catch (Exception ex) + { + error = ex; + } + session.Dispose(); + Assert.True(error is IOException, $"unexpected {error?.GetType().Name}"); + Assert.Empty(Directory.GetFileSystemEntries(dir)); + } + [Test] public void SessionsValidateTheirInput() { From 82f10a053e11d3bd05443c62cee5f2ee50887956 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:28:19 +0000 Subject: [PATCH 153/188] test(render): cover value-type Auto settings without advice Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Render/ProjectValuesTests.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 tests/Titano.Core.Tests/Render/ProjectValuesTests.cs diff --git a/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs b/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs new file mode 100644 index 00000000..dd550837 --- /dev/null +++ b/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs @@ -0,0 +1,20 @@ +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Testing; + +namespace Titano.Core.Tests.Render; + +public sealed class ProjectValuesTests +{ + [Test] + public void ValueTypeSettingsFallBackWithoutAdvice() + { + Assert.Equal(21, ProjectValues.Get(new Auto(), 21)); + Assert.Equal(180.0, ProjectValues.Get(new Auto(), 180.0)); + Assert.Equal(FlowQualitySetting.Balanced, ProjectValues.Get(new Auto(), FlowQualitySetting.Balanced)); + Assert.Equal(41, ProjectValues.Get(new Auto().WithAdvice(41, null), 21)); + Assert.Equal(0.5, ProjectValues.Get(new Auto().WithAdvice(0.8, null).WithManual(0.5), 1.0)); + Assert.Equal(FlowQualitySetting.Draft, ProjectValues.Get(new Auto().WithManual(FlowQualitySetting.Draft), FlowQualitySetting.Balanced)); + Assert.False(ProjectValues.Get(new Auto().WithManual(false), true)); + } +} From e5026ca72eac2764039684df903a11bc8e929de2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:30:10 +0000 Subject: [PATCH 154/188] refactor(render): keep render remarks in the Export localisation area Plan, render and encoder remarks now share the Export area with the preset names; setups reject metadata that does not match the source. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs | 2 +- .../Render/Diagnostics/SelfTestRenderChecks.cs | 4 ++-- src/Titano.Core/Render/RenderGeometry.cs | 12 ++++++------ src/Titano.Core/Render/RenderPipeline.cs | 4 ++-- src/Titano.Core/Render/RenderPlan.cs | 6 +++--- src/Titano.Core/Render/RenderPreparation.cs | 8 ++++---- src/Titano.Core/Render/RenderSetup.cs | 3 ++- .../Titano.Core.Tests/Render/RenderPipelineTests.cs | 2 +- tests/Titano.Core.Tests/Render/RenderPlanTests.cs | 6 +++--- 9 files changed, 24 insertions(+), 23 deletions(-) diff --git a/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs b/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs index b050927c..bdb76ed3 100644 --- a/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs +++ b/src/Titano.Core/Render/Diagnostics/SelfTestChecks.cs @@ -92,7 +92,7 @@ public static partial class SelfTest { var plan = RenderPlan.Build(Regular(90), Timing(TimingMode.Remapped, curve: [new(0, 0), new(0.3, 0.6), new(0.5, 0.4), new(1, 1)]), new Rational(24, 1)); RequireExact(plan); - Require(plan.Warnings.Contains("Render.Plan.RemapNotMonotonic"), "the curve repair is not reported"); + Require(plan.Warnings.Contains("Export.Plan.RemapNotMonotonic"), "the curve repair is not reported"); return Invariant($"{plan.Frames.Count} frames, {plan.Statistics.InterpolatedFrames} synthesised"); }); yield return Check("plan.fit", "Fit to duration rescales the plan exactly", () => diff --git a/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs b/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs index 540e0cb8..e2735a62 100644 --- a/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs +++ b/src/Titano.Core/Render/Diagnostics/SelfTestRenderChecks.cs @@ -476,8 +476,8 @@ public static partial class SelfTest var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 6)] }; var error = await CaptureAsync(() => Pipeline(context).RenderAsync(Input(Synthetic(6), project), Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)) .ConfigureAwait(false); - Require(error is RenderException { ReasonKey: "Render.Error.NoFrames" } && Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "no NoFrames error"); - return "Render.Error.NoFrames"; + Require(error is RenderException { ReasonKey: "Export.Render.NoFrames" } && Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "no NoFrames error"); + return "Export.Render.NoFrames"; }); } diff --git a/src/Titano.Core/Render/RenderGeometry.cs b/src/Titano.Core/Render/RenderGeometry.cs index ae8db95a..45b6f172 100644 --- a/src/Titano.Core/Render/RenderGeometry.cs +++ b/src/Titano.Core/Render/RenderGeometry.cs @@ -82,13 +82,13 @@ public sealed class RenderGeometry var crop = NormalisedCrop(camera.Crop, warnings); if (!AspectRatio.TryParse(camera.Aspect.Resolve("source"), out var aspect)) { - warnings.Add(new RenderWarning("Render.Warning.AspectIgnored", camera.Aspect.Resolve(string.Empty))); + warnings.Add(new RenderWarning("Export.Render.AspectIgnored", camera.Aspect.Resolve(string.Empty))); aspect = AspectRatio.Source; } var fixedSize = export.Width > 0 && export.Height > 0; var ratio = fixedSize ? export.Width / (double)export.Height : aspect.Resolve(sourceWidth, sourceHeight); if (fixedSize && !aspect.IsSource && double.Abs(aspect.Resolve(sourceWidth, sourceHeight) / ratio - 1) > 0.01) - warnings.Add(new RenderWarning("Render.Warning.AspectFromPreset", aspect.ToString(), string.Create(CultureInfo.InvariantCulture, $"{export.Width}:{export.Height}"))); + warnings.Add(new RenderWarning("Export.Render.AspectFromPreset", aspect.ToString(), string.Create(CultureInfo.InvariantCulture, $"{export.Width}:{export.Height}"))); var cropPixels = new RectD(crop.X * sourceWidth, crop.Y * sourceHeight, crop.Width * sourceWidth, crop.Height * sourceHeight); var fitted = AspectRatio.FitCrop(cropPixels, ratio, camera.OffsetX, camera.OffsetY); @@ -152,7 +152,7 @@ public sealed class RenderGeometry if (crop is null) return full; if (crop.Length != 4 || !crop.All(double.IsFinite)) { - warnings.Add(new RenderWarning("Render.Warning.CropIgnored")); + warnings.Add(new RenderWarning("Export.Render.CropIgnored")); return full; } var x = double.Clamp(crop[0], 0, 1); @@ -161,7 +161,7 @@ public sealed class RenderGeometry var h = double.Min(crop[3], 1 - y); if (w <= 1e-3 || h <= 1e-3) { - warnings.Add(new RenderWarning("Render.Warning.CropIgnored")); + warnings.Add(new RenderWarning("Export.Render.CropIgnored")); return full; } return new RectD(x, y, w, h); @@ -175,7 +175,7 @@ public sealed class RenderGeometry { if (!double.IsFinite(k.CenterX + k.CenterY + k.Zoom + k.Rotation)) { - warnings.Add(new RenderWarning("Render.Warning.KeyframeIgnored", k.Frame.ToString(CultureInfo.InvariantCulture))); + warnings.Add(new RenderWarning("Export.Render.KeyframeIgnored", k.Frame.ToString(CultureInfo.InvariantCulture))); continue; } frames[k.Frame] = new CameraKeyframe(k.Frame, k.CenterX, k.CenterY, double.Max(1, k.Zoom), k.Rotation) { Easing = Easing(k.Easing, warnings) }; @@ -200,7 +200,7 @@ public sealed class RenderGeometry && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var x2) && x2 is >= 0 and <= 1 && double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var y2) && double.IsFinite(y2)) return new BezierEasing(x1, y1, x2, y2); - warnings.Add(new RenderWarning("Render.Warning.EasingIgnored", text)); + warnings.Add(new RenderWarning("Export.Render.EasingIgnored", text)); return BezierEasing.EaseInOut; } } diff --git a/src/Titano.Core/Render/RenderPipeline.cs b/src/Titano.Core/Render/RenderPipeline.cs index 670c0ea8..dd2575e6 100644 --- a/src/Titano.Core/Render/RenderPipeline.cs +++ b/src/Titano.Core/Render/RenderPipeline.cs @@ -60,7 +60,7 @@ public sealed class RenderPipeline(IReadOnlyList encoders var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString()); throw new RenderException(notice.Key, $"No encoder can produce {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args); } - if (setup.Plan.Frames.Count == 0) throw new RenderException("Render.Error.NoFrames", "Every frame is excluded."); + if (setup.Plan.Frames.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded."); using var run = new RenderRun(input, corrections, setup, options, progress); return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false); } @@ -135,7 +135,7 @@ internal sealed class RenderRun : IDisposable if (exposure.HighlightKnee is { } knee) { if (knee is > 0 and < 1) _knee = (float)knee; - else _warnings.Add(new RenderWarning("Render.Warning.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture))); + else _warnings.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture))); } var motion = input.Project.Motion; _targetShutter = double.Clamp(ProjectValues.Get(motion.TargetShutterAngle, 180.0), 0, 360); diff --git a/src/Titano.Core/Render/RenderPlan.cs b/src/Titano.Core/Render/RenderPlan.cs index 8f83ed7f..1d388930 100644 --- a/src/Titano.Core/Render/RenderPlan.cs +++ b/src/Titano.Core/Render/RenderPlan.cs @@ -220,12 +220,12 @@ public sealed class RenderPlan } var median = MedianInterval(captureTimes); - if (mode is TimingMode.Adaptive or TimingMode.Interpolated && median is null) warnings.Add("Render.Plan.NoCaptureTimes"); + if (mode is TimingMode.Adaptive or TimingMode.Interpolated && median is null) warnings.Add("Export.Plan.NoCaptureTimes"); var cutBefore = new bool[n]; var entries = Timeline(captureTimes, included, mode, playback, median, options, cutBefore); if (entries.Length == 0) { - warnings.Add("Render.Plan.NoFrames"); + warnings.Add("Export.Plan.NoFrames"); var empty = new RenderPlanStatistics(n, n - included.Count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, median); return new RenderPlan(mode, frameRate, playback, [], 0, [.. included], cutBefore, empty, warnings); } @@ -404,7 +404,7 @@ public sealed class RenderPlan xs.Add(x); ys.Add(value); } - if (adjusted) warnings.Add("Render.Plan.RemapNotMonotonic"); + if (adjusted) warnings.Add("Export.Plan.RemapNotMonotonic"); return new MonotoneSpline(xs.ToArray(), ys.ToArray()); } diff --git a/src/Titano.Core/Render/RenderPreparation.cs b/src/Titano.Core/Render/RenderPreparation.cs index 408abc56..b35316d5 100644 --- a/src/Titano.Core/Render/RenderPreparation.cs +++ b/src/Titano.Core/Render/RenderPreparation.cs @@ -141,10 +141,10 @@ public static class RenderPreparation if (regionMode != RegionMode.Off && mask is null && included.Count > 0) { mask = await SegmentAsync(input.Source, included, regionMode, options.AnalysisLongEdge, cancellationToken).ConfigureAwait(false); - if (mask is null) warnings.Add(new RenderWarning("Render.Warning.RegionsUnavailable")); + if (mask is null) warnings.Add(new RenderWarning("Export.Render.RegionsUnavailable")); else if (regionMode == RegionMode.Auto && mask.Confidence < MinimumRegionConfidence) { - warnings.Add(new RenderWarning("Render.Warning.RegionsUnreliable", mask.Confidence.ToString("0.00", CultureInfo.InvariantCulture))); + warnings.Add(new RenderWarning("Export.Render.RegionsUnreliable", mask.Confidence.ToString("0.00", CultureInfo.InvariantCulture))); mask = null; } } @@ -163,7 +163,7 @@ public static class RenderPreparation if (measureStabilization) { stabilization = pass.SolveStabilization(included, n); - if (stabilization is null) warnings.Add(new RenderWarning("Render.Warning.StabilizationUnavailable")); + if (stabilization is null) warnings.Add(new RenderWarning("Export.Render.StabilizationUnavailable")); } } @@ -231,7 +231,7 @@ public static class RenderPreparation { zoom = 1 / double.Max(stabilization.CropScale, MinimumCropScale); if (stabilization.CropScale < MinimumCropScale) - warnings.Add(new RenderWarning("Render.Warning.StabilizationBorders", stabilization.CropScale.ToString("0.00", CultureInfo.InvariantCulture))); + warnings.Add(new RenderWarning("Export.Render.StabilizationBorders", stabilization.CropScale.ToString("0.00", CultureInfo.InvariantCulture))); } var measuredLuminance = luminance ?? NaNs(n); return new RenderCorrections diff --git a/src/Titano.Core/Render/RenderSetup.cs b/src/Titano.Core/Render/RenderSetup.cs index cd7ae688..ae6e1d2b 100644 --- a/src/Titano.Core/Render/RenderSetup.cs +++ b/src/Titano.Core/Render/RenderSetup.cs @@ -33,6 +33,7 @@ public sealed record RenderSetup ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(encoders); options ??= RenderOptions.Default; + if (input.Frames.Count != input.Source.FrameCount) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input)); var project = input.Project; var geometry = RenderGeometry.Create(project.Camera, target.Export, input.Source.Width, input.Source.Height, corrections?.StabilizationZoom ?? 1, options.MaxWorkingLongEdge); @@ -47,7 +48,7 @@ public sealed record RenderSetup warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args))); var stacking = project.Stack.Mode != StackSetting.None; var blur = ProjectValues.Get(project.Motion.MotionBlur, false); - if (blur && stacking) warnings.Add(new RenderWarning("Render.Warning.BlurOffWhileStacking")); + if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking")); var exposure = project.Exposure; var measuring = ProjectValues.Get(exposure.Deflicker, false) || ProjectValues.Get(exposure.HolyGrail, false) || ProjectValues.Get(exposure.WhiteBalanceSmoothing, false) || ProjectValues.Get(project.Motion.Stabilize, false); diff --git a/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs b/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs index a9ff53d6..7e726ba0 100644 --- a/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs +++ b/tests/Titano.Core.Tests/Render/RenderPipelineTests.cs @@ -158,7 +158,7 @@ public sealed class RenderPipelineTests { var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 12)] }; var error = await Assert.ThrowsAsync(() => Pipeline().RenderAsync(Input(Source(), project), Target(_context.CreateTempDirectory(), Preset("png-sequence")))); - Assert.Equal("Render.Error.NoFrames", error.ReasonKey); + Assert.Equal("Export.Render.NoFrames", error.ReasonKey); } [Test] diff --git a/tests/Titano.Core.Tests/Render/RenderPlanTests.cs b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs index c269fa0f..e42f70f0 100644 --- a/tests/Titano.Core.Tests/Render/RenderPlanTests.cs +++ b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs @@ -168,7 +168,7 @@ public sealed class RenderPlanTests Assert.Empty(ease.Warnings); var bad = RenderPlan.Build(Regular(60), Timing(TimingMode.Remapped, curve: [new(1, 1), new(0, 0.1), new(0.4, 0.8), new(0.6, 0.3)]), new Rational(24, 1)); - Assert.Contains("Render.Plan.RemapNotMonotonic", bad.Warnings); + Assert.Contains("Export.Plan.RemapNotMonotonic", bad.Warnings); AssertExactDurations(bad); Assert.Approximately(0.1 * 60, bad.Frames[0].SourcePosition, 1e-9); } @@ -179,7 +179,7 @@ public sealed class RenderPlanTests var plan = RenderPlan.Build(Regular(3), Timing(TimingMode.Constant, excluded: [0, 1, 2]), new Rational(30, 1)); Assert.Empty(plan.Frames); Assert.Equal(0L, plan.Duration90k); - Assert.Contains("Render.Plan.NoFrames", plan.Warnings); + Assert.Contains("Export.Plan.NoFrames", plan.Warnings); } [Test] @@ -187,7 +187,7 @@ public sealed class RenderPlanTests { var plan = RenderPlan.Build(new DateTime?[12], Timing(TimingMode.Adaptive), new Rational(30, 1)); Assert.Equal(12, plan.Frames.Count); - Assert.Contains("Render.Plan.NoCaptureTimes", plan.Warnings); + Assert.Contains("Export.Plan.NoCaptureTimes", plan.Warnings); AssertExactDurations(plan); } } From 9a380571690b00a5484a86e72bcf0b81514245f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:31:07 +0000 Subject: [PATCH 155/188] feat(data): server queries for uploads, jobs, render nodes and sequence edits Additive repository methods the server needs: upload state transitions, pending bytes, per-day and per-user upload counts, render-result uploads; job claim by id, node progress and completion, priority, queue counts and requeue of numbered workers; sequence edits with settings_version optimistic concurrency; audit filter by action; latest token per user. Migration 0005 adds session_key, job_id and render_json to uploads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../postgres/0005_server_uploads.sql | 9 ++ .../Migrations/sqlite/0005_server_uploads.sql | 9 ++ .../Repositories/AuditRepository.cs | 7 +- .../Repositories/FrameRepository.cs | 20 +++++ src/Titano.Data/Repositories/JobRepository.cs | 88 ++++++++++++++++++- .../Repositories/RenderNodeRepository.cs | 9 ++ .../Repositories/SequenceRepository.cs | 56 ++++++++++++ .../Repositories/TokenRepository.cs | 16 ++++ .../Repositories/UploadRepository.cs | 74 +++++++++++++++- 9 files changed, 282 insertions(+), 6 deletions(-) create mode 100644 src/Titano.Data/Migrations/postgres/0005_server_uploads.sql create mode 100644 src/Titano.Data/Migrations/sqlite/0005_server_uploads.sql diff --git a/src/Titano.Data/Migrations/postgres/0005_server_uploads.sql b/src/Titano.Data/Migrations/postgres/0005_server_uploads.sql new file mode 100644 index 00000000..271f679a --- /dev/null +++ b/src/Titano.Data/Migrations/postgres/0005_server_uploads.sql @@ -0,0 +1,9 @@ +-- Titano Server additions (PostgreSQL): automatic grouping key of frame uploads, render-result uploads of +-- render-node jobs, and the sign-in log lookup. Mirrors sqlite/0005_server_uploads.sql. + +ALTER TABLE uploads ADD COLUMN session_key text; +ALTER TABLE uploads ADD COLUMN job_id uuid; +ALTER TABLE uploads ADD COLUMN render_json jsonb; +CREATE INDEX ix_uploads_job ON uploads (job_id); + +CREATE INDEX ix_audit_log_action ON audit_log (action, at); diff --git a/src/Titano.Data/Migrations/sqlite/0005_server_uploads.sql b/src/Titano.Data/Migrations/sqlite/0005_server_uploads.sql new file mode 100644 index 00000000..ce6e5d64 --- /dev/null +++ b/src/Titano.Data/Migrations/sqlite/0005_server_uploads.sql @@ -0,0 +1,9 @@ +-- Titano Server additions (SQLite): automatic grouping key of frame uploads, render-result uploads of render-node +-- jobs, and the sign-in log lookup. Mirrors postgres/0005_server_uploads.sql. + +ALTER TABLE uploads ADD COLUMN session_key TEXT; +ALTER TABLE uploads ADD COLUMN job_id TEXT; +ALTER TABLE uploads ADD COLUMN render_json TEXT; +CREATE INDEX ix_uploads_job ON uploads (job_id); + +CREATE INDEX ix_audit_log_action ON audit_log (action, at); diff --git a/src/Titano.Data/Repositories/AuditRepository.cs b/src/Titano.Data/Repositories/AuditRepository.cs index 46e13c31..d2199979 100644 --- a/src/Titano.Data/Repositories/AuditRepository.cs +++ b/src/Titano.Data/Repositories/AuditRepository.cs @@ -17,11 +17,16 @@ public sealed class AuditRepository cancellationToken).ConfigureAwait(false); /// Entries newest first, optionally of one user. - public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) + public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) => + ListAsync(userId, action: null, limit, cursor, cancellationToken); + + /// Entries newest first, optionally of one user and one action (e.g. the sign-in log). + public Task> ListAsync(Guid? userId, string? action, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) { var p = new SqlParameters(); var where = new List(); if (userId is { } user) where.Add($"user_id = {p.Add(user)}"); + if (action is not null) where.Add($"action = {p.Add(action)}"); if (cursor is not null) { var (value, id) = Cursor.Decode("audit", cursor); diff --git a/src/Titano.Data/Repositories/FrameRepository.cs b/src/Titano.Data/Repositories/FrameRepository.cs index 30350e5e..f7c080ea 100644 --- a/src/Titano.Data/Repositories/FrameRepository.cs +++ b/src/Titano.Data/Repositories/FrameRepository.cs @@ -7,6 +7,9 @@ namespace Titano.Data.Repositories; /// Light statistics of one frame, written by the analysis job. public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh); +/// Per-format totals and flagged-frame counts of one sequence. +public sealed record SequenceFrameStats(IReadOnlyList ByFormat, long Missing, long Corrupt, long Duplicate, long Excluded); + /// Frames of sequences: bulk import, paged listing, duplicate lookup and bulk updates. public sealed class FrameRepository { @@ -112,6 +115,23 @@ public sealed class FrameRepository return updated; }, cancellationToken); + /// Formats and flagged-frame counters of one sequence. + public Task GetSequenceStatsAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + _db.RunAsync(async session => + { + var byFormat = await session.QueryListAsync( + "SELECT format, count(*), COALESCE(SUM(size), 0) FROM frames WHERE sequence_id = $1 GROUP BY format ORDER BY 2 DESC, 1", + [sequenceId], r => new FormatBucket((ImageFileFormat)r.GetInt32(0), r.GetInt64(1), r.GetInt64(2)), cancellationToken).ConfigureAwait(false); + var flags = await session.QuerySingleAsync( + "SELECT " + + $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Missing}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Corrupt}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Duplicate}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Excluded}) <> 0 THEN 1 ELSE 0 END), 0) " + + "FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false); + return new SequenceFrameStats(byFormat, flags.GetInt64(0), flags.GetInt64(1), flags.GetInt64(2), flags.GetInt64(3)); + }, cancellationToken); + /// Removes every frame of a sequence; returns how many. public Task DeleteBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) => _db.ExecuteAsync("DELETE FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken); diff --git a/src/Titano.Data/Repositories/JobRepository.cs b/src/Titano.Data/Repositories/JobRepository.cs index b3bd9857..7b9e8a44 100644 --- a/src/Titano.Data/Repositories/JobRepository.cs +++ b/src/Titano.Data/Repositories/JobRepository.cs @@ -3,6 +3,9 @@ using Titano.Core.Model; namespace Titano.Data.Repositories; +/// Jobs per state; and count those finished since a given time. +public sealed record JobCounts(int Queued, int Running, int Paused, int DoneSince, int FailedSince); + /// /// The persistent job queue (BRIEF §14.6): workers claim the oldest job of the highest priority atomically, /// write checkpoints while running, and on startup requeue what a crash left running. @@ -74,11 +77,16 @@ public sealed class JobRepository } /// Jobs, newest first, optionally of one state. - public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) + public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) => + ListAsync(state, kind: null, limit, cursor, cancellationToken); + + /// Jobs, newest first, optionally of one state and one kind. + public Task> ListAsync(JobState? state, JobKind? kind, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) { var p = new SqlParameters(); var where = new List(); if (state is { } s) where.Add($"state = {p.Add((int)s)}"); + if (kind is { } k) where.Add($"kind = {p.Add((int)k)}"); if (cursor is not null) { var (value, id) = Cursor.Decode("jobs", cursor); @@ -116,6 +124,84 @@ public sealed class JobRepository (nodeId is null ? string.Empty : " AND node_id = $1"), nodeId is null ? [] : [nodeId], cancellationToken); + /// + /// Crash recovery of one job engine: requeues running jobs claimed by or by its numbered + /// workers (workerId#n), whatever their number was in the previous run. + /// + public Task RequeueRunningWorkersAsync(string workerId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"UPDATE jobs SET state = {(int)JobState.Queued}, node_id = NULL, started = NULL WHERE state = {(int)JobState.Running} " + + "AND (node_id = $1 OR node_id LIKE $2 ESCAPE '\\')", + [workerId, SqlDialect.ContainsPattern(workerId)[1..^1] + "#%"], cancellationToken); + + public async Task SetPriorityAsync(Guid id, JobPriority priority, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE jobs SET priority = $2 WHERE id = $1", [id, (int)priority], cancellationToken).ConfigureAwait(false) > 0; + + /// Queued jobs of one kind in claim order (highest priority, then oldest). + public Task> ListQueuedAsync(JobKind kind, int limit = 50, CancellationToken cancellationToken = default) => + _db.ListAsync( + $"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 ORDER BY priority DESC, created, id LIMIT $2", + [(int)kind, Cursor.ClampLimit(limit)], Map, cancellationToken); + + /// Running jobs claimed by . + public Task> ListRunningByNodeAsync(string nodeId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Running} AND node_id = $1 ORDER BY started, id", + [nodeId], Map, cancellationToken); + + /// True when a job of for exactly is waiting in the queue. + public async Task IsQueuedAsync(JobKind kind, Guid targetId, CancellationToken cancellationToken = default) => + await _db.ScalarAsync( + $"SELECT count(*) FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 AND target_ids = $2", + [(int)kind, targetId.ToString()], cancellationToken).ConfigureAwait(false) > 0; + + /// + /// Claims one specific queued job for (render nodes pick by capability); null when another + /// claimer was faster or the job is no longer queued. + /// + public Task TryClaimAsync(Guid id, string nodeId, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var claimed = await session.ExecuteAsync( + $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $2, started = $3, finished = NULL, error = NULL, attempts = attempts + 1 " + + $"WHERE id = $1 AND state = {(int)JobState.Queued}", + [id, nodeId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + if (claimed == 0) return null; + return await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + /// Progress of a job a render node runs; false when the job is no longer running on that node. + public async Task UpdateNodeProgressAsync(Guid id, string nodeId, long done, long total, double? itemsPerSecond, TimeSpan? eta, + string? logTail, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE jobs SET progress_done = $3, progress_total = $4, items_per_second = $5, eta_seconds = $6, log_tail = $7 " + + $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}", + [id, nodeId, done, total, itemsPerSecond, eta?.TotalSeconds, logTail], cancellationToken).ConfigureAwait(false) > 0; + + /// Ends a job a render node runs (done or failed); false when it is no longer running on that node. + public async Task FinishNodeJobAsync(Guid id, string nodeId, JobState state, string? error, string? logTail, CancellationToken cancellationToken = default) + { + if (state is not (JobState.Done or JobState.Failed)) throw new ArgumentOutOfRangeException(nameof(state), state, "Only done or failed end a node job."); + return await _db.ExecuteAsync( + "UPDATE jobs SET state = $3, error = $4, finished = $5, log_tail = COALESCE($6, log_tail) " + + $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}", + [id, nodeId, (int)state, error, DateTimeOffset.UtcNow, logTail], cancellationToken).ConfigureAwait(false) > 0; + } + + /// Queue and history counters for dashboards; finished counts are those since . + public Task CountAsync(DateTimeOffset finishedSince, CancellationToken cancellationToken = default) => + _db.RunAsync(async session => + { + var row = await session.QuerySingleAsync( + "SELECT " + + $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Queued} THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Running} THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Paused} THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Done} AND finished >= $1 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Failed} AND finished >= $1 THEN 1 ELSE 0 END), 0) " + + "FROM jobs", [finishedSince], cancellationToken).ConfigureAwait(false); + return new JobCounts(row.GetInt32(0), row.GetInt32(1), row.GetInt32(2), row.GetInt32(3), row.GetInt32(4)); + }, cancellationToken); + private static Job Map(DbRow r) => new() { Id = r.GetGuid(0), diff --git a/src/Titano.Data/Repositories/RenderNodeRepository.cs b/src/Titano.Data/Repositories/RenderNodeRepository.cs index 898f1500..85099532 100644 --- a/src/Titano.Data/Repositories/RenderNodeRepository.cs +++ b/src/Titano.Data/Repositories/RenderNodeRepository.cs @@ -37,6 +37,15 @@ public sealed class RenderNodeRepository public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => await _db.ExecuteAsync("DELETE FROM render_nodes WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + /// Changes the state only (a node that stopped heart-beating keeps its last heartbeat time). + public async Task SetStateAsync(Guid id, string state, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE render_nodes SET state = $2 WHERE id = $1", [id, state], cancellationToken).ConfigureAwait(false) > 0; + + /// Nodes not in whose last heartbeat is older than . + public Task> ListSilentAsync(DateTimeOffset before, string exceptState, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM render_nodes WHERE last_heartbeat < $1 AND state <> $2 ORDER BY last_heartbeat, id", + [before, exceptState], Map, cancellationToken); + private static RenderNode Map(DbRow r) => new() { Id = r.GetGuid(0), diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs index 4912cec5..4a911dd5 100644 --- a/src/Titano.Data/Repositories/SequenceRepository.cs +++ b/src/Titano.Data/Repositories/SequenceRepository.cs @@ -60,6 +60,28 @@ public sealed record ArchiveStats( IReadOnlyList ByFormat, ArchiveHealth Health); +/// Fields a client may change on a sequence; null leaves a field unchanged, an empty title or notes clears it. +public sealed record SequenceEdit +{ + public string? Title { get; init; } + public IReadOnlyList? Tags { get; init; } + public int? Rating { get; init; } + public string? Notes { get; init; } + public string? SettingsJson { get; init; } +} + +public enum SequenceEditOutcome +{ + Updated, + NotFound, + + /// The settings version moved since the client read it. + Conflict, +} + +/// Result of : the updated sequence, or the stored one on conflict. +public sealed record SequenceEditResult(SequenceEditOutcome Outcome, Sequence? Sequence); + public sealed record YearBucket(int Year, int Sequences, long Photos, long Bytes); /// One heatmap cell: sequences and photos whose first capture falls in the month. @@ -172,6 +194,38 @@ public sealed class SequenceRepository return updated; }, cancellationToken); + /// + /// Applies a client edit atomically and bumps settings_version. With + /// the edit is refused (, carrying the stored sequence) when someone else + /// changed the sequence first (BRIEF §14.5). + /// + public Task EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken) + .ConfigureAwait(false); + if (current is null) return new SequenceEditResult(SequenceEditOutcome.NotFound, null); + if (expectedSettingsVersion is { } expected && expected != current.SettingsVersion) + return new SequenceEditResult(SequenceEditOutcome.Conflict, current); + var updated = current with + { + Title = edit.Title is null ? current.Title : NullIfEmpty(edit.Title), + Notes = edit.Notes is null ? current.Notes : NullIfEmpty(edit.Notes), + Rating = edit.Rating ?? current.Rating, + SettingsJson = edit.SettingsJson ?? current.SettingsJson, + SettingsVersion = current.SettingsVersion + 1, + UpdatedAt = DateTimeOffset.UtcNow, + }; + await UpsertRowAsync(session, updated, cancellationToken).ConfigureAwait(false); + if (edit.Tags is not null) await ReplaceTagsAsync(session, id, edit.Tags, cancellationToken).ConfigureAwait(false); + var stored = await session.QuerySingleAsync($"{_select} WHERE s.id = $1", [id], cancellationToken).ConfigureAwait(false); + return new SequenceEditResult(SequenceEditOutcome.Updated, Map(stored)); + }, cancellationToken); + + /// Gives every sequence owned by to ; returns how many. + public Task ReassignOwnerAsync(Guid fromUserId, Guid toUserId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("UPDATE sequences SET owner_user_id = $2 WHERE owner_user_id = $1", [fromUserId, toUserId], cancellationToken); + /// One page of sequences matching . public Task> ListAsync(SequenceQuery query, CancellationToken cancellationToken = default) { @@ -351,6 +405,8 @@ public sealed class SequenceRepository } } + private static string? NullIfEmpty(string value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + /// Camera wall-clock times are stored without zone, whatever kind the caller's value has. internal static DateTime? Wall(DateTime? value) => value is { } v ? DateTime.SpecifyKind(v, DateTimeKind.Unspecified) : null; diff --git a/src/Titano.Data/Repositories/TokenRepository.cs b/src/Titano.Data/Repositories/TokenRepository.cs index 8b88c0fc..1fed9606 100644 --- a/src/Titano.Data/Repositories/TokenRepository.cs +++ b/src/Titano.Data/Repositories/TokenRepository.cs @@ -37,6 +37,22 @@ public sealed class TokenRepository public Task RevokeAllAsync(Guid userId, CancellationToken cancellationToken = default) => _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE", [userId], cancellationToken); + /// Revokes every live token of a user except (password changed in that session). + public Task RevokeAllExceptAsync(Guid userId, string keepTokenHash, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND token_hash <> $2 AND revoked = FALSE", + [userId, keepTokenHash], cancellationToken); + + /// The most recently used token of every user (last seen time and client), keyed by user id. + public async Task> LatestByUserAsync(CancellationToken cancellationToken = default) + { + var tokens = await _db.ListAsync( + $"SELECT {Columns} FROM tokens t WHERE last_used = (SELECT MAX(last_used) FROM tokens l WHERE l.user_id = t.user_id)", + [], Map, cancellationToken).ConfigureAwait(false); + var latest = new Dictionary(); + foreach (var token in tokens) latest[token.UserId] = token; + return latest; + } + public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) => _db.ListAsync($"SELECT {Columns} FROM tokens WHERE user_id = $1 ORDER BY last_used DESC", [userId], Map, cancellationToken); diff --git a/src/Titano.Data/Repositories/UploadRepository.cs b/src/Titano.Data/Repositories/UploadRepository.cs index 355511ec..35c0a500 100644 --- a/src/Titano.Data/Repositories/UploadRepository.cs +++ b/src/Titano.Data/Repositories/UploadRepository.cs @@ -36,6 +36,15 @@ public sealed record Upload public DateTimeOffset Created { get; init; } public DateTimeOffset UpdatedAt { get; init; } + /// Automatic grouping key of a frame upload without a target sequence (BRIEF §14.4). + public string? SessionKey { get; init; } + + /// The render job whose output this upload carries; null for frame uploads. + public Guid? JobId { get; init; } + + /// Metadata of the render a render-result upload becomes (JSON). + public string? RenderJson { get; init; } + public int ChunkCount => (int)((Size + ChunkSize - 1) / ChunkSize); public bool IsComplete => ReceivedCount >= ChunkCount; @@ -44,11 +53,15 @@ public sealed record Upload index >= 0 && index / 8 < Received.Length && (Received[index / 8] & (1 << (index % 8))) != 0; } +/// Committed uploads of one UTC day. +public sealed record UploadDay(DateOnly Day, long Count, long Bytes); + /// Resumable uploads: creation, per-chunk bookkeeping, state changes and cleanup. public sealed class UploadRepository { private const string Columns = - "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at"; + "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at, " + + "session_key, job_id, render_json"; private readonly DbAccess _db; @@ -61,10 +74,11 @@ public sealed class UploadRepository ArgumentOutOfRangeException.ThrowIfNegative(upload.Size); var stored = upload with { Received = new byte[(upload.ChunkCount + 7) / 8], ReceivedCount = 0, Sha256 = upload.Sha256.ToLowerInvariant() }; await _db.ExecuteAsync( - $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)", + $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)", [ stored.Id, stored.UserId, stored.SequenceId, stored.FileName, stored.Size, stored.Sha256, SequenceRepository.Wall(stored.CapturedAt), stored.ChunkSize, stored.Received, 0, (int)stored.State, stored.FrameId, stored.Created, stored.UpdatedAt, + stored.SessionKey, stored.JobId, DbParam.Json(stored.RenderJson), ], cancellationToken).ConfigureAwait(false); return stored; } @@ -72,10 +86,11 @@ public sealed class UploadRepository public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => _db.SingleAsync($"SELECT {Columns} FROM uploads WHERE id = $1", [id], Map, cancellationToken); - /// An upload of the same content by the same user that is still receiving, so a client can resume it. + /// A frame upload of the same content by the same user that is still receiving, so a client can resume it. public Task FindReceivingAsync(Guid userId, string sha256, CancellationToken cancellationToken = default) => _db.SingleAsync( - $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} ORDER BY created DESC LIMIT 1", + $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} AND job_id IS NULL " + + "ORDER BY created DESC LIMIT 1", [userId, sha256.ToLowerInvariant()], Map, cancellationToken); /// @@ -115,6 +130,54 @@ public sealed class UploadRepository public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => await _db.ExecuteAsync("DELETE FROM uploads WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + /// + /// Moves an upload from to only if it is still in , + /// so two concurrent completions cannot both commit it. Returns false when the state had changed. + /// + public async Task TryTransitionAsync(Guid id, UploadState from, UploadState to, Guid? frameId = null, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE uploads SET state = $3, frame_id = COALESCE($4, frame_id), updated_at = $5 WHERE id = $1 AND state = $2", + [id, (int)from, (int)to, frameId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0; + + /// The newest upload carrying the output of render job . + public Task FindByJobAsync(Guid jobId, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM uploads WHERE job_id = $1 ORDER BY created DESC, id DESC LIMIT 1", [jobId], Map, cancellationToken); + + /// Every upload in , oldest change first. + public Task> ListByStateAsync(UploadState state, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM uploads WHERE state = $1 ORDER BY updated_at, id", [(int)state], Map, cancellationToken); + + /// Bytes a user has announced in frame uploads that are not committed yet (reserved against the quota). + public async Task PendingBytesAsync(Guid userId, CancellationToken cancellationToken = default) => + await _db.ScalarAsync( + $"SELECT COALESCE(SUM(size), 0) FROM uploads WHERE user_id = $1 AND job_id IS NULL AND state IN ({(int)UploadState.Receiving}, {(int)UploadState.Committing})", + [userId], cancellationToken).ConfigureAwait(false); + + /// Committed frame uploads per UTC day since , oldest day first. + public Task> CommittedPerDayAsync(DateTimeOffset since, CancellationToken cancellationToken = default) + { + var day = _db.Sql.IsPostgres ? "to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')" : "substr(updated_at, 1, 10)"; + return _db.ListAsync( + $"SELECT {day}, count(*), COALESCE(SUM(size), 0) FROM uploads WHERE state = {(int)UploadState.Committed} AND job_id IS NULL AND updated_at >= $1 " + + "GROUP BY 1 ORDER BY 1", + [since], r => new UploadDay(DateOnly.ParseExact(r.GetString(0), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture), r.GetInt64(1), r.GetInt64(2)), + cancellationToken); + } + + /// Committed frame uploads per user since . + public async Task> CommittedCountByUserAsync(DateTimeOffset since, CancellationToken cancellationToken = default) + { + var rows = await _db.ListAsync( + $"SELECT user_id, count(*) FROM uploads WHERE state = {(int)UploadState.Committed} AND job_id IS NULL AND updated_at >= $1 GROUP BY user_id", + [since], r => KeyValuePair.Create(r.GetGuid(0), r.GetInt64(1)), cancellationToken).ConfigureAwait(false); + return new Dictionary(rows); + } + + /// Deletes committed, failed and cancelled uploads last changed before ; returns how many. + public Task PurgeFinishedAsync(DateTimeOffset updatedBefore, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"DELETE FROM uploads WHERE state IN ({(int)UploadState.Committed}, {(int)UploadState.Failed}, {(int)UploadState.Cancelled}) AND updated_at < $1", + [updatedBefore], cancellationToken); + private static Upload Map(DbRow r) => new() { Id = r.GetGuid(0), @@ -131,5 +194,8 @@ public sealed class UploadRepository FrameId = r.GetGuidOrNull(11), Created = r.GetDateTimeOffset(12), UpdatedAt = r.GetDateTimeOffset(13), + SessionKey = r.GetStringOrNull(14), + JobId = r.GetGuidOrNull(15), + RenderJson = r.GetStringOrNull(16), }; } From 7353c17d7b0374337aad7e4e39392651bbd37ed8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:31:07 +0000 Subject: [PATCH 156/188] feat(protocol): admin, render-node and sync contracts with client calls Adds DTOs for users summary, audit, sequence stats and delete plan, archive and server settings, dashboard, logs, render job parameters and render results, plus client calls for job pause/resume/priority, node failure and chunked render-result upload (sharing the frame upload chunk loop). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Protocol/Admin.cs | 53 ++++++++++++ src/Titano.Protocol/Auth.cs | 18 +++++ src/Titano.Protocol/Client/TitanoClient.cs | 94 +++++++++++++++------- src/Titano.Protocol/Dtos.cs | 4 +- src/Titano.Protocol/Jobs.cs | 24 ++++++ src/Titano.Protocol/ProtocolJson.cs | 17 ++++ src/Titano.Protocol/Sequences.cs | 23 ++++++ 7 files changed, 203 insertions(+), 30 deletions(-) create mode 100644 src/Titano.Protocol/Admin.cs diff --git a/src/Titano.Protocol/Admin.cs b/src/Titano.Protocol/Admin.cs new file mode 100644 index 00000000..17abbd28 --- /dev/null +++ b/src/Titano.Protocol/Admin.cs @@ -0,0 +1,53 @@ +namespace Titano.Protocol; + +/// +/// GET/PUT /api/v1/server/settings (admin): the editable part of the server configuration. Settings named in +/// come from environment variables and cannot be changed here; says +/// that saved values (ports, TLS, workers, chunk size) wait for a restart. +/// +public sealed record ServerSettingsDto( + string ServerName, + int HttpPort, + int HttpsPort, + string TlsMode, + string? TlsCert, + string? TlsKey, + string Language, + int Workers, + bool Discovery, + long MaxUploadBytes, + int ChunkSizeBytes, + int JobHistoryDays, + int TokenLifetimeDays, + int UploadRetentionHours, + IReadOnlyList Locked, + bool RestartRequired); + +/// A server log file (GET /api/v1/logs/files). +public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified); + +/// The last lines of the current server log (GET /api/v1/logs). +public sealed record LogTailDto(string File, IReadOnlyList Lines); + +/// Jobs per state; done and failed count today's (UTC) jobs. +public sealed record JobCountsDto(int Queued, int Running, int Paused, int DoneToday, int FailedToday); + +/// Frames committed by uploads on one UTC day. +public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes); + +/// GET /api/v1/server/dashboard (admin): everything the dashboard page shows in one call (BRIEF §14.8). +public sealed record DashboardDto( + string ServerName, + string Version, + long UptimeSeconds, + string Database, + string TlsMode, + bool Discovery, + int Users, + ArchiveStatsDto Archive, + JobCountsDto Jobs, + int Workers, + IReadOnlyList Nodes, + IReadOnlyList Uploads, + IReadOnlyList Activity, + IReadOnlyList ActiveJobs); diff --git a/src/Titano.Protocol/Auth.cs b/src/Titano.Protocol/Auth.cs index 077009c1..fdf07086 100644 --- a/src/Titano.Protocol/Auth.cs +++ b/src/Titano.Protocol/Auth.cs @@ -29,3 +29,21 @@ public sealed record UpdateUserRequest(string? DisplayName, string? Role, long? /// Response of POST /api/v1/users and /users/{id}/reset-password: a temporary password shown once. public sealed record TemporaryPasswordResponse(UserDto User, string TemporaryPassword); + +/// POST /api/v1/users/{id}/reset-password (admin); without a password the server generates one. +public sealed record ResetPasswordRequest(string? Password); + +/// One row of the admin user list: the account plus when and from which client it was last used. +public sealed record UserSummaryDto(UserDto User, DateTimeOffset? LastSeen, string? LastClient, long UploadsLast30Days); + +/// One audit log entry (who did what to which user, sequence or setting). +public sealed record AuditEntryDto( + Guid Id, + DateTimeOffset At, + Guid? UserId, + string? Username, + string Action, + string? TargetKind, + string? TargetId, + string? Details, + string? RemoteAddress); diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs index d8f57f51..d843ca82 100644 --- a/src/Titano.Protocol/Client/TitanoClient.cs +++ b/src/Titano.Protocol/Client/TitanoClient.cs @@ -154,37 +154,59 @@ public sealed class TitanoClient : IDisposable } var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id."); - var chunkSize = start.ChunkSize; - var received = new HashSet(start.Received); - var chunks = (int)((info.Length + chunkSize - 1) / chunkSize); - var buffer = new byte[chunkSize]; - await using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan)) - { - long sent = received.Count == 0 ? 0 : received.Sum(i => (long)Math.Min(chunkSize, info.Length - (long)i * chunkSize)); - progress?.Report(new UploadProgress(sent, info.Length)); - for (var n = 0; n < chunks; n++) - { - if (received.Contains(n)) continue; - var offset = (long)n * chunkSize; - var length = (int)Math.Min(chunkSize, info.Length - offset); - file.Position = offset; - await file.ReadExactlyAsync(buffer.AsMemory(0, length), ct).ConfigureAwait(false); - await Bandwidth.AcquireAsync(length, ct).ConfigureAwait(false); - await RetryAsync(async () => - { - using var content = new ByteArrayContent(buffer, 0, length); - content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{n}", content, ct).ConfigureAwait(false); - await EnsureSuccessAsync(response, ct).ConfigureAwait(false); - return true; - }, ct).ConfigureAwait(false); - sent += length; - progress?.Report(new UploadProgress(sent, info.Length)); - } - } + await SendChunksAsync(path, info.Length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false); return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false); } + /// + /// Render node: uploads the output of a claimed job in resumable chunks, then completes the job; the server verifies + /// the SHA-256 in and files the render under the sequence's exports (BRIEF §14.7). + /// + public async Task UploadRenderResultAsync(Guid nodeId, Guid jobId, string path, RenderResultRequest result, + IProgress? progress = null, CancellationToken ct = default) + { + var length = new FileInfo(path).Length; + if (length != result.Size) throw new ArgumentException("The result size does not match the file.", nameof(result)); + var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result", result, + ProtocolJson.Default.RenderResultRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false); + var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id."); + await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false); + return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result/complete", ProtocolJson.Default.RenderDto, ct), ct) + .ConfigureAwait(false); + } + + /// Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors. + private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList alreadyReceived, + IProgress? progress, CancellationToken ct) + { + var received = new HashSet(alreadyReceived); + var chunks = (int)((length + chunkSize - 1) / chunkSize); + var buffer = new byte[chunkSize]; + await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); + long sent = received.Sum(i => Math.Min(chunkSize, length - (long)i * chunkSize)); + progress?.Report(new UploadProgress(sent, length)); + for (var n = 0; n < chunks; n++) + { + if (received.Contains(n)) continue; + var offset = (long)n * chunkSize; + var size = (int)Math.Min(chunkSize, length - offset); + file.Position = offset; + await file.ReadExactlyAsync(buffer.AsMemory(0, size), ct).ConfigureAwait(false); + await Bandwidth.AcquireAsync(size, ct).ConfigureAwait(false); + var index = n; + await RetryAsync(async () => + { + using var content = new ByteArrayContent(buffer, 0, size); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{index}", content, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + return true; + }, ct).ConfigureAwait(false); + sent += size; + progress?.Report(new UploadProgress(sent, length)); + } + } + /// Lower-case hex SHA-256 of a file, streamed. public static async Task HashFileAsync(string path, CancellationToken ct = default) { @@ -201,10 +223,22 @@ public sealed class TitanoClient : IDisposable public Task CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) => SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct); + public Task GetJobAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/jobs/{id}", ProtocolJson.Default.JobDto, ct); + public Task CancelJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/cancel", ProtocolJson.Default.JobDto, ct); public Task RetryJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/retry", ProtocolJson.Default.JobDto, ct); + public Task PauseJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/pause", ProtocolJson.Default.JobDto, ct); + + public Task ResumeJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/resume", ProtocolJson.Default.JobDto, ct); + + /// Moves a waiting job up or down the queue: is background, normal or user. + public Task SetJobPriorityAsync(Guid id, string priority, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/priority", new JobPriorityRequest(priority), ProtocolJson.Default.JobPriorityRequest, ProtocolJson.Default.JobDto, ct); + + public Task> ListNodesAsync(CancellationToken ct = default) => GetAsync("api/v1/nodes", ProtocolJson.Default.ListRenderNodeDto, ct); + public Task RegisterNodeAsync(RegisterNodeRequest request, CancellationToken ct = default) => SendAsync(HttpMethod.Post, "api/v1/nodes/register", request, ProtocolJson.Default.RegisterNodeRequest, ProtocolJson.Default.RenderNodeDto, ct); @@ -222,6 +256,10 @@ public sealed class TitanoClient : IDisposable public Task ReportNodeProgressAsync(Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/progress", progress, ProtocolJson.Default.NodeProgress, ct); + /// Gives a claimed job back as failed; a 409 means it was cancelled or reassigned meanwhile. + public Task ReportNodeFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/failed", new NodeJobFailure(error), ProtocolJson.Default.NodeJobFailure, ct); + // ---------------- Events ---------------- /// Server events over WebSocket until cancelled; reconnect is the caller's policy. diff --git a/src/Titano.Protocol/Dtos.cs b/src/Titano.Protocol/Dtos.cs index d841902d..52934196 100644 --- a/src/Titano.Protocol/Dtos.cs +++ b/src/Titano.Protocol/Dtos.cs @@ -5,8 +5,8 @@ namespace Titano.Protocol; /// Error body of every failed API call: { code, message, details } (BRIEF §14.3). public sealed record ApiError(string Code, string Message, string? Details = null); -/// Upload limits announced by the server. -public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes); +/// Upload and account limits announced by the server. +public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10); /// GET /api/v1/server/info. public sealed record ServerInfo( diff --git a/src/Titano.Protocol/Jobs.cs b/src/Titano.Protocol/Jobs.cs index e5655af4..6a6d8e5c 100644 --- a/src/Titano.Protocol/Jobs.cs +++ b/src/Titano.Protocol/Jobs.cs @@ -34,3 +34,27 @@ public sealed record ClaimedJob(JobDto Job, Guid SequenceId, string SettingsJson /// POST /api/v1/nodes/{id}/jobs/{jobId}/progress. public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine); + +/// POST /api/v1/jobs/{id}/priority: background, normal or user. +public sealed record JobPriorityRequest(string Priority); + +/// +/// parametersJson of a render job: what to encode. Render nodes claim the job when they have an encoder for +/// at × (BRIEF §14.7). +/// +public sealed record RenderJobParameters(string PresetName, string PresetJson, string Codec, int Width, int Height, bool UseProxies, string? SettingsJson); + +/// POST /api/v1/nodes/{id}/jobs/{jobId}/result: the finished output a node is about to upload in chunks. +public sealed record RenderResultRequest( + string FileName, + long Size, + string Sha256, + string PresetName, + string? Codec, + int Width, + int Height, + double Fps, + double DurationSeconds); + +/// POST /api/v1/nodes/{id}/jobs/{jobId}/failed: the node could not render the job. +public sealed record NodeJobFailure(string Error); diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs index 2f3dad46..2db29cac 100644 --- a/src/Titano.Protocol/ProtocolJson.cs +++ b/src/Titano.Protocol/ProtocolJson.cs @@ -45,4 +45,21 @@ namespace Titano.Protocol; [JsonSerializable(typeof(NodeProgress))] [JsonSerializable(typeof(ServerEvent))] [JsonSerializable(typeof(DiscoveryBeacon))] +[JsonSerializable(typeof(ResetPasswordRequest))] +[JsonSerializable(typeof(UserSummaryDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(AuditEntryDto))] +[JsonSerializable(typeof(Page))] +[JsonSerializable(typeof(SequenceStatsDto))] +[JsonSerializable(typeof(SequenceDeletePlan))] +[JsonSerializable(typeof(ArchiveSettingsDto))] +[JsonSerializable(typeof(JobPriorityRequest))] +[JsonSerializable(typeof(RenderJobParameters))] +[JsonSerializable(typeof(RenderResultRequest))] +[JsonSerializable(typeof(NodeJobFailure))] +[JsonSerializable(typeof(ServerSettingsDto))] +[JsonSerializable(typeof(LogFileDto))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(LogTailDto))] +[JsonSerializable(typeof(DashboardDto))] public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Titano.Protocol/Sequences.cs b/src/Titano.Protocol/Sequences.cs index ab3bb730..eaebcc0d 100644 --- a/src/Titano.Protocol/Sequences.cs +++ b/src/Titano.Protocol/Sequences.cs @@ -102,3 +102,26 @@ public sealed record ArchiveStatsDto( int UnverifiedSequences); public sealed record KeyValueCount(string Key, long Count, long Bytes); + +/// GET /api/v1/sequences/{id}/stats: frame totals by format and flagged frames. +public sealed record SequenceStatsDto( + Guid SequenceId, + int FrameCount, + long TotalBytes, + DateTime? FirstCapture, + DateTime? LastCapture, + double? MedianInterval, + IReadOnlyList ByFormat, + long MissingFrames, + long CorruptFrames, + long DuplicateFrames, + long ExcludedFrames); + +/// +/// DELETE /api/v1/sequences/{id}: what the delete does (with ?dryRun=true) or did. The folder is moved +/// to inside the archive, never erased. +/// +public sealed record SequenceDeletePlan(Guid SequenceId, string? Folder, string? TrashFolder, int FrameCount, long TotalBytes, int RenderCount, bool DryRun); + +/// GET/PUT /api/v1/archive/settings (admin). The root path comes from the server configuration. +public sealed record ArchiveSettingsDto(Guid Id, string Name, string RootPath, string FolderTemplate, string FileTemplate, int ProxyLongEdge); From c78747053e54e2e21375525475f527580a66b99a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:32:19 +0000 Subject: [PATCH 157/188] feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events - Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/ SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate limit and lockout, role/permission metadata on every endpoint, audit log, first-run administrator bootstrap. - Sequences with keyset paging, ETags and settings_version conflicts; sync manifest; frames, proxies, thumbnails and exports streamed with Range. - Chunked resumable uploads with hash short-circuit, quota and disk checks, staging on the archive volume, SHA-256 verification and IArchiveIngest. - Job engine host, jobs API, render nodes with heartbeat timeout and reassignment, WebSocket events, LAN discovery beacon, upload cleanup. - Windows service host over advapi32 (--service, --install-service, --uninstall-service); fails fast without the archive module services. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Server.resx | 49 +++ i18n/it/Server.it.resx | 49 +++ src/Titano.Server/Api/AdminEndpoints.cs | 112 +++++++ src/Titano.Server/Api/ApiErrors.cs | 90 +++++ src/Titano.Server/Api/ArchiveEndpoints.cs | 95 ++++++ src/Titano.Server/Api/AuthEndpoints.cs | 105 ++++++ src/Titano.Server/Api/Dto.cs | 90 +++++ src/Titano.Server/Api/FileEndpoints.cs | 59 ++++ src/Titano.Server/Api/JobEndpoints.cs | 155 +++++++++ src/Titano.Server/Api/NodeEndpoints.cs | 57 ++++ src/Titano.Server/Api/Outcome.cs | 17 + src/Titano.Server/Api/SequenceEndpoints.cs | 313 ++++++++++++++++++ src/Titano.Server/Api/SystemEndpoints.cs | 71 +++- src/Titano.Server/Api/UploadEndpoints.cs | 44 +++ src/Titano.Server/Api/UserEndpoints.cs | 157 +++++++++ .../Configuration/ServerOptions.cs | 143 ++++++-- .../Configuration/ServerSettingsStore.cs | 101 ++++++ src/Titano.Server/Events/EventEndpoints.cs | 103 ++++++ src/Titano.Server/Events/EventHub.cs | 47 +++ src/Titano.Server/Hosting/AdminPanel.cs | 48 +++ .../Hosting/DiscoveryBeaconService.cs | 99 ++++++ .../Hosting/FileLoggerProvider.cs | 11 +- .../Hosting/ResponseMiddleware.cs | 74 +++++ .../Hosting/ServerCommandLine.cs | 68 ++++ src/Titano.Server/Hosting/ServerDatabase.cs | 41 +++ src/Titano.Server/Hosting/ServerHost.cs | 186 +++++++---- .../Hosting/Windows/ServiceInstaller.cs | 83 +++++ .../Hosting/Windows/ServiceNative.cs | 93 ++++++ .../Hosting/Windows/ServiceStatusTracker.cs | 68 ++++ .../Hosting/Windows/WindowsServiceHost.cs | 117 +++++++ src/Titano.Server/Jobs/JobEngineHost.cs | 87 +++++ src/Titano.Server/Jobs/RenderNodeMonitor.cs | 72 ++++ src/Titano.Server/Jobs/RenderNodeService.cs | 240 ++++++++++++++ src/Titano.Server/Jobs/SequenceJobs.cs | 32 ++ src/Titano.Server/Program.cs | 50 ++- src/Titano.Server/Security/AccessRule.cs | 38 +++ src/Titano.Server/Security/Accounts.cs | 35 ++ src/Titano.Server/Security/AdminBootstrap.cs | 85 +++++ src/Titano.Server/Security/AuditLog.cs | 26 ++ .../Security/AuthenticationMiddleware.cs | 79 +++++ src/Titano.Server/Security/LoginGuard.cs | 92 +++++ src/Titano.Server/Security/PasswordHasher.cs | 69 ++++ src/Titano.Server/Security/SessionCookies.cs | 55 +++ .../Security/TemporaryPassword.cs | 15 + src/Titano.Server/Security/TokenService.cs | 91 +++++ src/Titano.Server/Storage/ArchivePaths.cs | 45 +++ src/Titano.Server/Storage/FileResponses.cs | 123 +++++++ .../Storage/IFrameAssetLocator.cs | 26 ++ src/Titano.Server/Storage/RenderStore.cs | 49 +++ src/Titano.Server/Storage/ServerArchive.cs | 37 +++ .../Storage/UploadMaintenance.cs | 102 ++++++ src/Titano.Server/Storage/UploadRules.cs | 45 +++ src/Titano.Server/Storage/UploadService.cs | 242 ++++++++++++++ src/Titano.Server/Storage/UploadStore.cs | 109 ++++++ tests/Titano.Server.Tests/Fakes.cs | 147 ++++++++ tests/Titano.Server.Tests/TestServer.cs | 98 +++++- 56 files changed, 4726 insertions(+), 108 deletions(-) create mode 100644 src/Titano.Server/Api/AdminEndpoints.cs create mode 100644 src/Titano.Server/Api/ApiErrors.cs create mode 100644 src/Titano.Server/Api/ArchiveEndpoints.cs create mode 100644 src/Titano.Server/Api/AuthEndpoints.cs create mode 100644 src/Titano.Server/Api/Dto.cs create mode 100644 src/Titano.Server/Api/FileEndpoints.cs create mode 100644 src/Titano.Server/Api/JobEndpoints.cs create mode 100644 src/Titano.Server/Api/NodeEndpoints.cs create mode 100644 src/Titano.Server/Api/Outcome.cs create mode 100644 src/Titano.Server/Api/SequenceEndpoints.cs create mode 100644 src/Titano.Server/Api/UploadEndpoints.cs create mode 100644 src/Titano.Server/Api/UserEndpoints.cs create mode 100644 src/Titano.Server/Configuration/ServerSettingsStore.cs create mode 100644 src/Titano.Server/Events/EventEndpoints.cs create mode 100644 src/Titano.Server/Events/EventHub.cs create mode 100644 src/Titano.Server/Hosting/AdminPanel.cs create mode 100644 src/Titano.Server/Hosting/DiscoveryBeaconService.cs create mode 100644 src/Titano.Server/Hosting/ResponseMiddleware.cs create mode 100644 src/Titano.Server/Hosting/ServerCommandLine.cs create mode 100644 src/Titano.Server/Hosting/ServerDatabase.cs create mode 100644 src/Titano.Server/Hosting/Windows/ServiceInstaller.cs create mode 100644 src/Titano.Server/Hosting/Windows/ServiceNative.cs create mode 100644 src/Titano.Server/Hosting/Windows/ServiceStatusTracker.cs create mode 100644 src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs create mode 100644 src/Titano.Server/Jobs/JobEngineHost.cs create mode 100644 src/Titano.Server/Jobs/RenderNodeMonitor.cs create mode 100644 src/Titano.Server/Jobs/RenderNodeService.cs create mode 100644 src/Titano.Server/Jobs/SequenceJobs.cs create mode 100644 src/Titano.Server/Security/AccessRule.cs create mode 100644 src/Titano.Server/Security/Accounts.cs create mode 100644 src/Titano.Server/Security/AdminBootstrap.cs create mode 100644 src/Titano.Server/Security/AuditLog.cs create mode 100644 src/Titano.Server/Security/AuthenticationMiddleware.cs create mode 100644 src/Titano.Server/Security/LoginGuard.cs create mode 100644 src/Titano.Server/Security/PasswordHasher.cs create mode 100644 src/Titano.Server/Security/SessionCookies.cs create mode 100644 src/Titano.Server/Security/TemporaryPassword.cs create mode 100644 src/Titano.Server/Security/TokenService.cs create mode 100644 src/Titano.Server/Storage/ArchivePaths.cs create mode 100644 src/Titano.Server/Storage/FileResponses.cs create mode 100644 src/Titano.Server/Storage/IFrameAssetLocator.cs create mode 100644 src/Titano.Server/Storage/RenderStore.cs create mode 100644 src/Titano.Server/Storage/ServerArchive.cs create mode 100644 src/Titano.Server/Storage/UploadMaintenance.cs create mode 100644 src/Titano.Server/Storage/UploadRules.cs create mode 100644 src/Titano.Server/Storage/UploadService.cs create mode 100644 src/Titano.Server/Storage/UploadStore.cs create mode 100644 tests/Titano.Server.Tests/Fakes.cs diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index b9ba718d..32f9f1f6 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -5,4 +5,53 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Not connected to a server + Too many failed sign-ins; the account is locked for a while.long + The request is not valid.long + This upload has no such chunk.long + The chunk has the wrong size.long + The file could not be stored in the archive; try again.long + The security token is missing; reload the page.long + Your account cannot do this.long + The file arrived damaged; upload it again.long + Open the admin panel over HTTPS to sign in.long + Some chunks are still missing.long + The server is out of disk space.long + Unexpected server error; try again.long + Wrong user name or password.long + The paging cursor is not valid; start from the first page.long + The file name is not valid.long + A filter value is not valid.long + The SHA-256 must be 64 hexadecimal characters.long + This job kind cannot be started here.long + The job parameters are not valid.long + The priority must be background, normal or user.long + The role must be admin, editor, uploader or viewer.long + The setting {0} is not valid.long + The settings must be valid JSON.long + The job cannot do that in its current state.long + The naming template is not valid.long + Use letters, digits, dot, dash or underscore.long + This job is no longer assigned to this node.long + This server cannot run that kind of job.long + The last administrator cannot be removed or disabled.long + This method is not allowed here.long + Not found.long + Change your password first.long + This upload would exceed your quota.long + Too many attempts; wait a minute and try again.long + Choose a password different from the current one.long + You cannot do this to your own account.long + An environment variable sets this; change it there.long + The sequence changed on the server; reload it and apply your edit again.long + The request is larger than the server accepts.long + Too many uploads at once; retry shortly.long + Sign in to continue.long + Send the body as JSON.long + This upload is not accepting that request now.long + That user name is taken.long + Use at least {0} characters.long + Connect with a WebSocket.long + The current password is wrong.long + This upload belongs to a render job.long + Titano time-lapse archive, uploads, jobs and rendering server.long diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index d80ac2f7..beeafe59 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -5,4 +5,53 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Non connesso a un server + Troppi accessi falliti; l'account è bloccato per un po'. + La richiesta non è valida. + Questo caricamento non ha quel blocco. + Il blocco ha la dimensione sbagliata. + Il file non è stato salvato nell'archivio; riprova. + Manca il token di sicurezza; ricarica la pagina. + Il tuo account non può farlo. + Il file è arrivato danneggiato; caricalo di nuovo. + Apri il pannello di amministrazione in HTTPS per accedere. + Mancano ancora alcuni blocchi. + Il server ha esaurito lo spazio su disco. + Errore imprevisto del server; riprova. + Nome utente o password errati. + Il cursore di paginazione non è valido; ricomincia dalla prima pagina. + Il nome del file non è valido. + Un valore di filtro non è valido. + Lo SHA-256 deve avere 64 caratteri esadecimali. + Questo tipo di job non si può avviare qui. + I parametri del job non sono validi. + La priorità deve essere background, normal o user. + Il ruolo deve essere admin, editor, uploader o viewer. + L'impostazione {0} non è valida. + Le impostazioni devono essere JSON valido. + Il job non può farlo nello stato attuale. + Il modello dei nomi non è valido. + Usa lettere, cifre, punto, trattino o trattino basso. + Questo job non è più assegnato a questo nodo. + Questo server non può eseguire quel tipo di job. + L'ultimo amministratore non può essere rimosso o disattivato. + Metodo non consentito qui. + Non trovato. + Cambia prima la password. + Questo caricamento supererebbe la tua quota. + Troppi tentativi; attendi un minuto e riprova. + Scegli una password diversa da quella attuale. + Non puoi farlo sul tuo account. + È impostato da una variabile d'ambiente; modificala lì. + La sequenza è cambiata sul server; ricaricala e riapplica la modifica. + La richiesta supera la dimensione accettata dal server. + Troppi caricamenti insieme; riprova tra poco. + Accedi per continuare. + Invia il corpo come JSON. + Questo caricamento ora non accetta la richiesta. + Questo nome utente è già in uso. + Usa almeno {0} caratteri. + Connettiti con un WebSocket. + La password attuale è errata. + Questo caricamento appartiene a un job di rendering. + Server Titano per archivio time-lapse, caricamenti, job e rendering. diff --git a/src/Titano.Server/Api/AdminEndpoints.cs b/src/Titano.Server/Api/AdminEndpoints.cs new file mode 100644 index 00000000..45826700 --- /dev/null +++ b/src/Titano.Server/Api/AdminEndpoints.cs @@ -0,0 +1,112 @@ +using System.Text; +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Configuration; +using Titano.Server.Jobs; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// Administration (BRIEF §14.8): dashboard figures, server settings, log tail and downloads, audit log. +public static class AdminEndpoints +{ + private const int MaxTailLines = 2000; + private const int TailWindowBytes = 1 << 20; + + public static void Map(RouteGroupBuilder api) + { + api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers); + api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto)) + .Requires(Permissions.ManageArchive); + api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive); + api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive); + + var logs = api.MapGroup("/logs").Requires(Permissions.ManageArchive); + logs.MapGet("", TailAsync); + logs.MapGet("/files", (ServerOptions options) => Results.Json(LogFiles(options).Select(f => new LogFileDto(f.Name, f.Length, f.LastWriteTimeUtc)).ToList(), + ProtocolJson.Default.ListLogFileDto)); + logs.MapGet("/files/{name}", (HttpContext context, string name, ServerOptions options) => + { + // Only names of existing log files are served: the name never becomes part of a path. + if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log"); + context.Response.Headers.CacheControl = "no-store"; + return Results.File(file.FullName, "text/plain; charset=utf-8", file.Name, file.LastWriteTimeUtc, enableRangeProcessing: true); + }); + } + + private static async Task DashboardAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, ServerOptions options, ServerState state, + JobEngineHost jobs, TimeProvider time) + { + var ct = context.RequestAborted; + var now = time.GetUtcNow(); + var today = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero); + var users = await db.Users.ListAsync(ct); + var names = users.ToDictionary(u => u.Id, u => u.Username); + var counts = await db.Jobs.CountAsync(today, ct); + var running = await db.Jobs.ListAsync(JobState.Running, null, 10, null, ct); + var queued = await db.Jobs.ListAsync(JobState.Queued, null, 10, null, ct); + var nodes = await db.RenderNodes.ListAsync(ct); + var uploads = await db.Uploads.CommittedPerDayAsync(today.AddDays(-29), ct); + var activity = await db.Audit.ListAsync(null, null, 12, null, ct); + return Results.Json(new DashboardDto( + options.ServerName, + SystemEndpoints.Version, + (long)(now - state.StartedAt).TotalSeconds, + state.Database, + options.TlsMode.ToString().ToLowerInvariant(), + options.Discovery, + users.Count, + await ArchiveEndpoints.StatsAsync(db, archive, ct), + new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince), + jobs.Workers, + [.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))], + [.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))], + [.. activity.Items.Select(Dto.Audit)], + [.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]), + ProtocolJson.Default.DashboardDto); + } + + private static async Task SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit) + { + switch (store.Save(request)) + { + case ("setting_locked", var setting): + return ApiErrors.Conflict(context, "setting_locked", setting); + case (var code, var setting): + return ApiErrors.BadRequest(context, code, setting, setting); + } + await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName); + return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto); + } + + private static async Task AuditAsync(HttpContext context, TitanoDatabase db, Guid? user, string? action, string? cursor, int? limit) + { + var page = await db.Audit.ListAsync(user, string.IsNullOrWhiteSpace(action) ? null : action, limit ?? 100, + string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted); + return Results.Json(new Page([.. page.Items.Select(Dto.Audit)], page.NextCursor, null), ProtocolJson.Default.PageAuditEntryDto); + } + + /// The last lines lines (default 300) of the newest server log. + private static async Task TailAsync(HttpContext context, ServerOptions options, int? lines) + { + var take = Math.Clamp(lines ?? 300, 1, MaxTailLines); + if (LogFiles(options).FirstOrDefault() is not { } file) return Results.Json(new LogTailDto(string.Empty, []), ProtocolJson.Default.LogTailDto); + await using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var start = Math.Max(0, stream.Length - TailWindowBytes); + stream.Position = start; + using var reader = new StreamReader(stream, Encoding.UTF8); + var text = await reader.ReadToEndAsync(context.RequestAborted); + var all = text.Split('\n', StringSplitOptions.RemoveEmptyEntries); + // A window that starts mid-file begins with a partial line. + var complete = start > 0 && all.Length > 0 ? all[1..] : all; + return Results.Json(new LogTailDto(file.Name, [.. complete.TakeLast(take).Select(l => l.TrimEnd('\r'))]), ProtocolJson.Default.LogTailDto); + } + + /// Server log files, newest first. + private static List LogFiles(ServerOptions options) => + Directory.Exists(options.LogPath) + ? [.. new DirectoryInfo(options.LogPath).EnumerateFiles("*.log").OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name)] + : []; +} diff --git a/src/Titano.Server/Api/ApiErrors.cs b/src/Titano.Server/Api/ApiErrors.cs new file mode 100644 index 00000000..372962c5 --- /dev/null +++ b/src/Titano.Server/Api/ApiErrors.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using System.Text; +using Microsoft.Net.Http.Headers; +using Titano.Core.Localization; +using Titano.Protocol; +using Titano.Server.Configuration; + +namespace Titano.Server.Api; + +/// +/// Error responses of API v1: { code, message, details } (BRIEF §14.3). code is a stable snake_case +/// identifier for programs; message is one localised sentence (resource Server.Error.<Code>, language +/// from Accept-Language, else the server language); details is optional machine-readable context. +/// +public static class ApiErrors +{ + public static IResult Result(HttpContext context, int status, string code, string? details = null, params object?[] args) => + Results.Json(new ApiError(code, Message(context, code, args), details), ProtocolJson.Default.ApiError, statusCode: status); + + public static Task WriteAsync(HttpContext context, int status, string code, string? details = null) => + Result(context, status, code, details).ExecuteAsync(context); + + public static IResult NotFound(HttpContext context, string? what = null) => Result(context, StatusCodes.Status404NotFound, "not_found", what); + + public static IResult BadRequest(HttpContext context, string code, string? details = null, params object?[] args) => + Result(context, StatusCodes.Status400BadRequest, code, details, args); + + public static IResult Conflict(HttpContext context, string code, string? details = null) => Result(context, StatusCodes.Status409Conflict, code, details); + + public static IResult Forbidden(HttpContext context) => Result(context, StatusCodes.Status403Forbidden, "forbidden"); + + public static string Message(HttpContext context, string code, params object?[] args) + { + var culture = RequestCulture.Of(context); + var template = Loc.Get("Server.Error." + Pascal(code), culture) ?? code; + return args.Length == 0 ? template : string.Format(culture, template, args); + } + + private static string Pascal(string code) + { + var sb = new StringBuilder(code.Length); + var upper = true; + foreach (var c in code) + { + if (c == '_') + { + upper = true; + continue; + } + sb.Append(upper ? char.ToUpperInvariant(c) : c); + upper = false; + } + return sb.ToString(); + } +} + +/// The language of a request's messages: the best shipped match of Accept-Language, else the server language. +public static class RequestCulture +{ + public static CultureInfo Of(HttpContext context) + { + if (context.Items.TryGetValue(typeof(RequestCulture), out var cached) && cached is CultureInfo known) return known; + var fallback = context.RequestServices.GetRequiredService().Language; + var culture = FromHeader(context.Request.Headers.AcceptLanguage.ToString()) ?? Parse(fallback) ?? CultureInfo.GetCultureInfo("en"); + context.Items[typeof(RequestCulture)] = culture; + return culture; + } + + private static CultureInfo? FromHeader(string header) + { + if (string.IsNullOrWhiteSpace(header) || !StringWithQualityHeaderValue.TryParseList([header], out var values)) return null; + foreach (var value in values.OrderByDescending(v => v.Quality ?? 1)) + { + if (value.Value.Value is { } tag && tag != "*" && Parse(tag) is { } culture) return culture; + } + return null; + } + + private static CultureInfo? Parse(string tag) + { + try + { + return Languages.BestMatch(CultureInfo.GetCultureInfo(tag)); + } + catch (CultureNotFoundException) + { + return null; + } + } +} diff --git a/src/Titano.Server/Api/ArchiveEndpoints.cs b/src/Titano.Server/Api/ArchiveEndpoints.cs new file mode 100644 index 00000000..daf097d1 --- /dev/null +++ b/src/Titano.Server/Api/ArchiveEndpoints.cs @@ -0,0 +1,95 @@ +using Titano.Core.Model; +using Titano.Core.Naming; +using Titano.Data; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Server.Jobs; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics. +public static class ArchiveEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive); + archive.MapGet("/settings", (ServerArchive a) => Results.Json(Settings(a.Current), ProtocolJson.Default.ArchiveSettingsDto)); + archive.MapPut("/settings", UpdateAsync); + archive.MapGet("/stats", async (HttpContext c, TitanoDatabase db, ServerArchive a) => + Results.Json(await StatsAsync(db, a, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto)); + foreach (var (path, kind) in new[] { ("scan", JobKind.Scan), ("rebuild", JobKind.Rebuild), ("verify", JobKind.Verify), ("maintenance", JobKind.Maintenance) }) + { + archive.MapPost("/" + path, (HttpContext c, Caller caller, ServerArchive a, JobEngineHost host, AuditLog audit) => EnqueueAsync(c, caller, a, host, audit, kind)); + } + } + + /// Totals, distributions, free space and health of the archive (also shown on the dashboard). + public static async Task StatsAsync(TitanoDatabase db, ServerArchive archive, CancellationToken cancellationToken) + { + var stats = await db.Sequences.GetStatsAsync(archive.Id, cancellationToken); + var withoutProxies = await db.Sequences.CountAsync( + new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt }, cancellationToken); + long free = 0, capacity = 0; + try + { + var drive = new DriveInfo(archive.Root); + free = drive.AvailableFreeSpace; + capacity = drive.TotalSize; + } + catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException) + { + // An offline archive volume reports no space figures. + } + return new ArchiveStatsDto( + stats.Sequences, + stats.Photos, + stats.Bytes, + free, + capacity, + stats.ByCamera.Count(c => c.Model is not null), + stats.ByYear.Count > 0 ? stats.ByYear[0].Year : null, + stats.ByYear.Count > 0 ? stats.ByYear[^1].Year : null, + [.. stats.ByYear.Select(y => new KeyValueCount(y.Year.ToString(System.Globalization.CultureInfo.InvariantCulture), y.Photos, y.Bytes))], + [.. stats.ByMonth.Select(m => new KeyValueCount($"{m.Year:D4}-{m.Month:D2}", m.Photos, 0))], + [.. stats.ByCamera.Select(c => new KeyValueCount(string.Join(' ', new[] { c.Make, c.Model }.Where(v => !string.IsNullOrEmpty(v))), c.Photos, c.Bytes))], + [.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))], + withoutProxies, + stats.Health.Unverified); + } + + private static async Task UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive, AuditLog audit) + { + var name = request.Name?.Trim(); + if (string.IsNullOrEmpty(name) || name.Length > 100) return ApiErrors.BadRequest(context, "bad_request", "name"); + foreach (var (field, template) in new[] { ("folderTemplate", request.FolderTemplate), ("fileTemplate", request.FileTemplate) }) + { + if (string.IsNullOrWhiteSpace(template) || !PathTemplate.Parse(template).IsValid) return ApiErrors.BadRequest(context, "invalid_template", field); + } + if (request.ProxyLongEdge is not (-1 or 0) and (< 256 or > 8192)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge"); + + var updated = archive.Current with + { + Name = name, + FolderTemplate = request.FolderTemplate, + FileTemplate = request.FileTemplate, + ProxyLongEdge = request.ProxyLongEdge, + }; + await db.Archives.UpsertAsync(updated, context.RequestAborted); + archive.Current = updated; + await audit.WriteAsync(caller, context, "archive_settings", "archive", updated.Id.ToString(), $"{updated.FolderTemplate} · {updated.FileTemplate}"); + return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto); + } + + 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)); + var job = await host.Engine.EnqueueAsync(kind, [archive.Id], archive.Current.Name, priority: JobPriority.User, createdBy: caller.Id, + cancellationToken: context.RequestAborted); + await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), JobWire.Kind(kind)); + return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted); + } + + private static ArchiveSettingsDto Settings(Archive a) => new(a.Id, a.Name, a.RootPath, a.FolderTemplate, a.FileTemplate, a.ProxyLongEdge); +} diff --git a/src/Titano.Server/Api/AuthEndpoints.cs b/src/Titano.Server/Api/AuthEndpoints.cs new file mode 100644 index 00000000..6f9d30f3 --- /dev/null +++ b/src/Titano.Server/Api/AuthEndpoints.cs @@ -0,0 +1,105 @@ +using System.Globalization; +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Configuration; +using Titano.Server.Security; + +namespace Titano.Server.Api; + +/// /api/v1/auth: sign-in (token or admin cookie), sign-out, password change, current account. +public static class AuthEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + api.MapPost("/auth/login", LoginAsync).AllowAnonymousCaller(); + api.MapPost("/auth/logout", LogoutAsync).AllowDuringPasswordChange(); + api.MapPost("/auth/password", ChangePasswordAsync).AllowDuringPasswordChange(); + api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange(); + } + + private static async Task LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard, + AuditLog audit, TimeProvider time) + { + var ct = context.RequestAborted; + if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait); + var account = Accounts.Key(request.Username); + if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password)) + return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials"); + if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait); + if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required"); + + var user = await db.Users.GetByUsernameAsync(account, ct); + bool valid; + if (user is null) + { + PasswordHasher.VerifyDummy(request.Password); + valid = false; + } + else + { + valid = PasswordHasher.Verify(request.Password, user.PasswordHash) && !user.Disabled; + } + if (!valid) + { + guard.RecordFailure(account); + await audit.WriteAsync(user?.Id, account, context, "login_failed", "user", user?.Id.ToString()); + return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials"); + } + + guard.RecordSuccess(account); + var signedIn = user! with { LastLogin = time.GetUtcNow() }; + if (PasswordHasher.NeedsRehash(signedIn.PasswordHash)) + { + signedIn = signedIn with { PasswordHash = PasswordHasher.Hash(request.Password) }; + await db.Users.UpdateAsync(signedIn, ct); + } + else + { + await db.Users.RecordLoginAsync(signedIn.Id, signedIn.LastLogin.Value, ct); + } + var issued = await tokens.IssueAsync(signedIn, request.ClientName, ct); + await audit.WriteAsync(signedIn.Id, signedIn.Username, context, "login", "user", signedIn.Id.ToString(), issued.Stored.ClientName); + + string? secret = issued.Secret; + if (request.Cookie) + { + // The admin panel never sees the token itself; it travels only in the HttpOnly cookie. + SessionCookies.Issue(context, issued); + secret = null; + } + return Results.Json(new LoginResponse(secret, Dto.User(signedIn), signedIn.MustChangePassword, issued.Stored.Expires), ProtocolJson.Default.LoginResponse); + } + + private static async Task LogoutAsync(HttpContext context, Caller caller, TitanoDatabase db) + { + await db.Tokens.RevokeAsync(caller.TokenHash, context.RequestAborted); + if (caller.Source == CredentialSource.Cookie) SessionCookies.Clear(context); + return Results.NoContent(); + } + + private static async Task ChangePasswordAsync(HttpContext context, Caller caller, ChangePasswordRequest request, TitanoDatabase db, + AuditLog audit, ServerOptions options) + { + var ct = context.RequestAborted; + if (string.IsNullOrEmpty(request.CurrentPassword) || !PasswordHasher.Verify(request.CurrentPassword, caller.User.PasswordHash)) + return ApiErrors.BadRequest(context, "wrong_password"); + if (!PasswordHasher.IsAcceptable(request.NewPassword)) + return ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength); + if (request.NewPassword == request.CurrentPassword) return ApiErrors.BadRequest(context, "same_password"); + + var updated = caller.User with { PasswordHash = PasswordHasher.Hash(request.NewPassword), MustChangePassword = false }; + await db.Users.UpdateAsync(updated, ct); + await db.Tokens.RevokeAllExceptAsync(caller.Id, caller.TokenHash, ct); + await audit.WriteAsync(caller, context, "password_changed", "user", caller.Id.ToString()); + if (caller.User.Role == UserRole.Admin) AdminBootstrap.ForgetInitialPassword(options); + return Results.NoContent(); + } + + private static IResult TooMany(HttpContext context, string code, TimeSpan wait) + { + var seconds = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)); + context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture); + return ApiErrors.Result(context, StatusCodes.Status429TooManyRequests, code, seconds.ToString(CultureInfo.InvariantCulture)); + } +} diff --git a/src/Titano.Server/Api/Dto.cs b/src/Titano.Server/Api/Dto.cs new file mode 100644 index 00000000..7d02ecd3 --- /dev/null +++ b/src/Titano.Server/Api/Dto.cs @@ -0,0 +1,90 @@ +using System.Text; +using System.Text.Json; +using Titano.Core.Model; +using Titano.Protocol; + +namespace Titano.Server.Api; + +/// Domain entities → API v1 contracts. +public static class Dto +{ + public static UserDto User(User u) => new( + u.Id, u.Username, u.DisplayName, Role(u.Role), (long)u.Permissions, u.QuotaBytes, u.UsedBytes, u.Disabled, u.MustChangePassword, + u.Created, u.LastLogin); + + public static string Role(UserRole role) => role.ToString().ToLowerInvariant(); + + public static SequenceDto Sequence(Sequence s) => new( + s.Id, s.Title, s.DisplayTitle, s.Folder, s.CameraMake, s.CameraModel, s.Lens, s.FirstCapture, s.LastCapture, s.FrameCount, + s.MedianInterval, s.TotalBytes, (long)s.Status, s.RenderedCount, s.HeroFrameId, s.Tags, s.Rating, s.Notes, s.SettingsVersion, + s.FramesVersion, s.WarningCount, s.OwnerUserId, s.UpdatedAt); + + public static FrameDto Frame(Frame f) => new( + f.Id, f.SequenceId, f.Index, f.FileName, f.Size, f.Sha256, f.CapturedAt, f.UtcOffsetMinutes, f.ExposureTime, f.FNumber, f.Iso, + f.FocalLength, f.Orientation, f.Width, f.Height, f.Format.ToString().ToLowerInvariant(), (long)f.Flags); + + public static RenderDto Render(Render r) => new(r.Id, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy); + + public static JobDto Job(Job j) => new( + j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone, + j.ProgressTotal, j.ItemsPerSecond, j.Eta?.TotalSeconds, j.LogTail, j.NodeId, j.Attempts, j.Error, j.Created, j.Started, j.Finished); + + public static AuditEntryDto Audit(AuditEntry a) => new(a.Id, a.At, a.UserId, a.Username, a.Action, a.TargetKind, a.TargetId, a.Details, a.RemoteAddress); + + public static RenderNodeDto Node(RenderNode node, string username) => + new(node.Id, node.ClientName, username, Capabilities(node)?.Encoders ?? [], node.LastHeartbeat, node.State); + + /// What a node announced at registration (stored as its capabilities JSON). + public static RegisterNodeRequest? Capabilities(RenderNode node) + { + if (node.CapabilitiesJson is null) return null; + try + { + return JsonSerializer.Deserialize(node.CapabilitiesJson, ProtocolJson.Default.RegisterNodeRequest); + } + catch (JsonException) + { + return null; + } + } +} + +/// Wire names of job kinds, states and priorities: kebab-case (deep-analyse) and lower-case (running). +public static class JobWire +{ + public static string Kind(JobKind kind) + { + var name = kind.ToString(); + var sb = new StringBuilder(name.Length + 4); + for (var i = 0; i < name.Length; i++) + { + if (i > 0 && char.IsUpper(name[i])) sb.Append('-'); + sb.Append(char.ToLowerInvariant(name[i])); + } + return sb.ToString(); + } + + public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind); + + public static string State(JobState state) => state.ToString().ToLowerInvariant(); + + public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state); + + public static string Priority(JobPriority priority) => priority.ToString().ToLowerInvariant(); + + public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority); + + private static bool TryParse(string? text, Func name, out T value) where T : struct, Enum + { + foreach (var candidate in Enum.GetValues()) + { + if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase)) + { + value = candidate; + return true; + } + } + value = default; + return false; + } +} diff --git a/src/Titano.Server/Api/FileEndpoints.cs b/src/Titano.Server/Api/FileEndpoints.cs new file mode 100644 index 00000000..71bfc53e --- /dev/null +++ b/src/Titano.Server/Api/FileEndpoints.cs @@ -0,0 +1,59 @@ +using System.Globalization; +using Titano.Core.Model; +using Titano.Data; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// +/// Streamed archive files with Range support (BRIEF §14.3): originals, proxies, thumbnails and exports. Paths come +/// from the database by id and are resolved under the archive root only. +/// +public static class FileEndpoints +{ + private const string Immutable = "private, max-age=31536000, immutable"; + private const string Regenerable = "private, max-age=3600"; + + public static void Map(RouteGroupBuilder api) + { + // Originals feed editing clients and render nodes; viewers browse proxies, thumbnails and exports. + api.MapGet("/frames/{id:guid}/original", OriginalAsync).Requires(Permissions.Edit | Permissions.RenderNode); + api.MapGet("/frames/{id:guid}/proxy", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Proxy, db, a, l)) + .Requires(Permissions.Read | Permissions.RenderNode); + api.MapGet("/frames/{id:guid}/thumb", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Thumbnail, db, a, l)) + .Requires(Permissions.Read); + api.MapGet("/renders/{id:guid}/file", RenderAsync).Requires(Permissions.Read); + } + + private static async Task OriginalAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) + { + if (await db.Frames.GetAsync(id, context.RequestAborted) is not { } frame) return ApiErrors.NotFound(context, "frame"); + if (ArchivePaths.ExistingFile(archive.Root, frame.RelativePath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); + return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(frame.FileName), Immutable, frame.Sha256, frame.FileName) + ?? ApiErrors.NotFound(context, "file_missing"); + } + + private static async Task AssetAsync(HttpContext context, Guid id, FrameAsset kind, TitanoDatabase db, ServerArchive archive, IFrameAssetLocator locator) + { + var ct = context.RequestAborted; + if (await db.Frames.GetAsync(id, ct) is not { } frame || await db.Sequences.GetAsync(frame.SequenceId, ct) is not { } sequence) + return ApiErrors.NotFound(context, "frame"); + var location = await locator.LocateAsync(archive.Current, sequence, frame, kind, ct); + if (location is null || !ArchivePaths.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "asset_missing"); + var file = new FileInfo(location.Path); + if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "asset_missing"); + var etag = string.Create(CultureInfo.InvariantCulture, $"{kind}-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}"); + return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag) + ?? ApiErrors.NotFound(context, "asset_missing"); + } + + private static async Task RenderAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) + { + if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render) return ApiErrors.NotFound(context, "render"); + if (ArchivePaths.ExistingFile(archive.Root, render.OutputPath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); + var etag = string.Create(CultureInfo.InvariantCulture, $"r-{render.Id:N}-{file.Length}-{file.LastWriteTimeUtc.Ticks}"); + return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(file.Name), Immutable, etag, file.Name) + ?? ApiErrors.NotFound(context, "file_missing"); + } +} diff --git a/src/Titano.Server/Api/JobEndpoints.cs b/src/Titano.Server/Api/JobEndpoints.cs new file mode 100644 index 00000000..c07e5f00 --- /dev/null +++ b/src/Titano.Server/Api/JobEndpoints.cs @@ -0,0 +1,155 @@ +using System.Text.Json; +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Jobs; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// +/// /api/v1/jobs (BRIEF §14.6): queue and history, creation, cancel, pause, resume, retry and priority. Changes +/// reach WebSocket clients as jobState and jobProgress events. +/// +public static class JobEndpoints +{ + /// Kinds that work on sequences (targets are sequence ids) and need the edit right. + private static readonly HashSet SequenceKinds = [JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Proxies, JobKind.Thumbs, JobKind.Verify]; + + /// Archive-wide maintenance (target: the archive) for administrators. + private static readonly HashSet ArchiveKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans]; + + public static void Map(RouteGroupBuilder api) + { + var jobs = api.MapGroup("/jobs").Requires(Permissions.Read); + jobs.MapGet("", ListAsync); + jobs.MapPost("", CreateAsync); + jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, TitanoDatabase db) => + await db.Jobs.GetAsync(id, context.RequestAborted) is { } job + ? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto) + : ApiErrors.NotFound(context, "job")); + jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) => + ActAsync(c, caller, id, db, [JobState.Queued, JobState.Running, JobState.Paused], (job, ct) => host.Engine.CancelAsync(job.Id, ct))); + jobs.MapPost("/{id:guid}/pause", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) => + ActAsync(c, caller, id, db, [JobState.Queued, JobState.Running], (job, ct) => host.Engine.PauseAsync(job.Id, ct))); + jobs.MapPost("/{id:guid}/resume", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) => + ActAsync(c, caller, id, db, [JobState.Paused], (job, ct) => host.Engine.ResumeAsync(job.Id, ct))); + jobs.MapPost("/{id:guid}/retry", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) => + ActAsync(c, caller, id, db, [JobState.Failed, JobState.Cancelled], (job, ct) => host.Engine.ResumeAsync(job.Id, ct))); + jobs.MapPost("/{id:guid}/priority", PriorityAsync); + } + + private static async Task ListAsync(HttpContext context, TitanoDatabase db, string? state, string? kind, string? cursor, int? limit) + { + JobState? stateFilter = null; + JobKind? kindFilter = null; + if (!string.IsNullOrEmpty(state)) + { + if (!JobWire.TryParseState(state, out var s)) return ApiErrors.BadRequest(context, "invalid_filter", "state"); + stateFilter = s; + } + if (!string.IsNullOrEmpty(kind)) + { + if (!JobWire.TryParseKind(kind, out var k)) return ApiErrors.BadRequest(context, "invalid_filter", "kind"); + kindFilter = k; + } + var page = await db.Jobs.ListAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted); + return Results.Json(new Page([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto); + } + + private static async Task CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, TitanoDatabase db, JobEngineHost host, + ServerArchive archive, AuditLog audit) + { + var ct = context.RequestAborted; + if (!JobWire.TryParseKind(request.Kind, out var kind) || !(kind == JobKind.Render || SequenceKinds.Contains(kind) || ArchiveKinds.Contains(kind))) + return ApiErrors.BadRequest(context, "invalid_job_kind"); + var needed = kind == JobKind.Render ? Permissions.Render : SequenceKinds.Contains(kind) ? Permissions.Edit : Permissions.ManageArchive; + if (!caller.Has(needed)) return ApiErrors.Forbidden(context); + if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind)); + + IReadOnlyList targets; + string label; + if (ArchiveKinds.Contains(kind)) + { + targets = [archive.Id]; + label = archive.Current.Name; + } + else + { + var ids = request.Target ?? []; + if (ids.Count == 0 || (kind == JobKind.Render && ids.Count != 1)) return ApiErrors.BadRequest(context, "invalid_parameters", "target"); + var titles = new List(ids.Count); + foreach (var id in ids) + { + if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + titles.Add(sequence.DisplayTitle); + } + targets = ids; + label = titles.Count == 1 ? titles[0] : string.Join(", ", titles.Take(3)) + (titles.Count > 3 ? " …" : string.Empty); + } + if (kind == JobKind.Render) + { + if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson"); + label = $"{label} → {render.PresetName}"; + } + else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson)) + { + return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson"); + } + + var job = await host.Engine.EnqueueAsync(kind, targets, label, request.ParametersJson, JobPriority.User, caller.Id, ct); + await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}"); + return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted); + } + + private static async Task PriorityAsync(HttpContext context, Caller caller, Guid id, JobPriorityRequest request, TitanoDatabase db, JobEngineHost host) + { + if (!JobWire.TryParsePriority(request.Priority, out var priority)) return ApiErrors.BadRequest(context, "invalid_priority"); + return await ActAsync(context, caller, id, db, [JobState.Queued, JobState.Paused], async (job, ct) => + { + await db.Jobs.SetPriorityAsync(job.Id, priority, ct); + host.Publish(job with { Priority = priority }); + }); + } + + /// Applies when the job is in one of states and the caller created it or administers the archive. + private static async Task ActAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, JobState[] allowed, Func action) + { + var ct = context.RequestAborted; + if (await db.Jobs.GetAsync(id, ct) is not { } job) return ApiErrors.NotFound(context, "job"); + if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context); + if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State)); + await action(job, ct); + var updated = await db.Jobs.GetAsync(id, ct) ?? job; + return Results.Json(Dto.Job(updated), ProtocolJson.Default.JobDto); + } + + /// Render parameters, or null when they are missing or incomplete. + public static RenderJobParameters? ParseRender(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + var p = JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderJobParameters); + return p is { PresetName.Length: > 0, PresetJson.Length: > 0, Codec.Length: > 0, Width: > 0, Height: > 0 } && IsJsonObject(p.PresetJson) ? p : null; + } + catch (JsonException) + { + return null; + } + } + + private static bool IsJsonObject(string json) + { + try + { + using var document = JsonDocument.Parse(json); + return document.RootElement.ValueKind == JsonValueKind.Object; + } + catch (JsonException) + { + return false; + } + } +} diff --git a/src/Titano.Server/Api/NodeEndpoints.cs b/src/Titano.Server/Api/NodeEndpoints.cs new file mode 100644 index 00000000..24594b1d --- /dev/null +++ b/src/Titano.Server/Api/NodeEndpoints.cs @@ -0,0 +1,57 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Events; +using Titano.Server.Jobs; +using Titano.Server.Security; + +namespace Titano.Server.Api; + +/// /api/v1/nodes (BRIEF §14.7): render node registration, heartbeat, claim, progress, failure and output upload. +public static class NodeEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + api.MapGet("/nodes", ListAsync).Requires(Permissions.Read | Permissions.RenderNode); + api.MapDelete("/nodes/{id:guid}", DeleteAsync).Requires(Permissions.RenderNode | Permissions.ManageArchive); + + var nodes = api.MapGroup("/nodes").Requires(Permissions.RenderNode); + nodes.MapPost("/register", async (HttpContext c, Caller caller, RegisterNodeRequest request, RenderNodeService service) => + (await service.RegisterAsync(caller, request, c.RequestAborted)).ToResult(c, n => Results.Json(n, ProtocolJson.Default.RenderNodeDto))); + nodes.MapPost("/{id:guid}/heartbeat", async (HttpContext c, Caller caller, Guid id, RenderNodeService service) => + (await service.HeartbeatAsync(caller, id, c.RequestAborted)).ToResult(c, _ => Results.NoContent())); + nodes.MapPost("/{id:guid}/claim", async (HttpContext c, Caller caller, Guid id, RenderNodeService service) => + (await service.ClaimAsync(caller, id, c.RequestAborted)).ToResult(c, job => job is null ? Results.NoContent() : Results.Json(job, ProtocolJson.Default.ClaimedJob))); + nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/progress", async (HttpContext c, Caller caller, Guid id, Guid jobId, NodeProgress progress, RenderNodeService service) => + (await service.ProgressAsync(caller, id, jobId, progress, c.RequestAborted)).ToResult(c, _ => Results.NoContent())); + nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/failed", async (HttpContext c, Caller caller, Guid id, Guid jobId, NodeJobFailure failure, RenderNodeService service) => + (await service.FailAsync(caller, id, jobId, failure, c.RequestAborted)).ToResult(c, _ => Results.NoContent())); + nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/result", async (HttpContext c, Caller caller, Guid id, Guid jobId, RenderResultRequest request, RenderNodeService service) => + (await service.StartResultAsync(caller, id, jobId, request, c.RequestAborted)) + .ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse, statusCode: StatusCodes.Status201Created))); + nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/result/complete", async (HttpContext c, Caller caller, Guid id, Guid jobId, RenderNodeService service, + IHostApplicationLifetime lifetime) => + // The commit runs to the end even if the node disconnects meanwhile. + (await service.CompleteResultAsync(caller, id, jobId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto))); + } + + private static async Task ListAsync(HttpContext context, TitanoDatabase db) + { + var ct = context.RequestAborted; + var users = (await db.Users.ListAsync(ct)).ToDictionary(u => u.Id, u => u.Username); + var nodes = await db.RenderNodes.ListAsync(ct); + return Results.Json(nodes.Select(n => Dto.Node(n, users.GetValueOrDefault(n.UserId, string.Empty))).ToList(), ProtocolJson.Default.ListRenderNodeDto); + } + + /// Forgets a node (its owner or an archive admin); its running jobs go back to the queue. + private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, EventHub events) + { + var ct = context.RequestAborted; + if (await db.RenderNodes.GetAsync(id, ct) is not { } node) return ApiErrors.NotFound(context, "node"); + if (node.UserId != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context); + await db.Jobs.RequeueRunningAsync(RenderNodeService.NodeKey(node), ct); + await db.RenderNodes.DeleteAsync(id, ct); + events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline)); + return Results.NoContent(); + } +} diff --git a/src/Titano.Server/Api/Outcome.cs b/src/Titano.Server/Api/Outcome.cs new file mode 100644 index 00000000..faf8d4df --- /dev/null +++ b/src/Titano.Server/Api/Outcome.cs @@ -0,0 +1,17 @@ +namespace Titano.Server.Api; + +/// Result of a server operation: a value, or an HTTP status with an API error code (and optional details). +public readonly record struct Outcome(T? Value, int Status, string? Code, string? Details) +{ + public bool Succeeded => Code is null; + + public static Outcome Ok(T value) => new(value, StatusCodes.Status200OK, null, null); + + public static Outcome Fail(int status, string code, string? details = null) => new(default, status, code, details); + + /// The API response: for a value, the error body otherwise. + public IResult ToResult(HttpContext context, Func ok) => + Succeeded ? ok(Value!) : ApiErrors.Result(context, Status, Code!, Details); + + public static implicit operator Outcome(T value) => Ok(value); +} diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs new file mode 100644 index 00000000..dd687af4 --- /dev/null +++ b/src/Titano.Server/Api/SequenceEndpoints.cs @@ -0,0 +1,313 @@ +using System.Buffers.Text; +using System.Globalization; +using System.Text; +using System.Text.Json; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Server.Configuration; +using Titano.Server.Events; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// +/// /api/v1/sequences: library listing with filters and keyset paging, detail with ETag, edits with +/// settings_version optimistic concurrency, the sync manifest, frames, analysis, statistics and renders. +/// +public static class SequenceEndpoints +{ + private const int MaxTitle = 200; + private const int MaxNotes = 2000; + private const int MaxTags = 50; + + public static void Map(RouteGroupBuilder api) + { + // Uploaders list sequences to pick an upload target. + var sequences = api.MapGroup("/sequences").Requires(Permissions.Read | Permissions.Upload); + sequences.MapGet("", ListAsync); + sequences.MapPost("", CreateAsync).Requires(Permissions.Upload | Permissions.Edit); + sequences.MapGet("/{id:guid}", GetAsync); + sequences.MapPatch("/{id:guid}", UpdateAsync).Requires(Permissions.Edit); + sequences.MapDelete("/{id:guid}", DeleteAsync).Requires(Permissions.Delete); + sequences.MapGet("/{id:guid}/manifest", ManifestAsync).Requires(Permissions.Read); + sequences.MapGet("/{id:guid}/frames", FramesAsync).Requires(Permissions.Read); + sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read); + sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read); + sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read); + } + + private static async Task ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status, + string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller) + { + if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status"); + if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort"); + Guid? ownerId = null; + if (owner == "me") ownerId = caller.Id; + else if (owner is not null && Guid.TryParse(owner, out var parsed)) ownerId = parsed; + else if (owner is not null) return ApiErrors.BadRequest(context, "invalid_filter", "owner"); + + var query = new SequenceQuery + { + ArchiveId = archive.Id, + Year = year, + Camera = string.IsNullOrWhiteSpace(camera) ? null : camera, + WithStatus = with, + WithoutStatus = without, + Tag = string.IsNullOrWhiteSpace(tag) ? null : tag, + Text = string.IsNullOrWhiteSpace(q) ? null : q, + OwnerUserId = ownerId, + Sort = order, + Limit = limit ?? 100, + Cursor = string.IsNullOrEmpty(cursor) ? null : cursor, + }; + var page = await db.Sequences.ListAsync(query, context.RequestAborted); + long? total = query.Cursor is null ? await db.Sequences.CountAsync(query, context.RequestAborted) : null; + return Results.Json(new Titano.Protocol.Page([.. page.Items.Select(Dto.Sequence)], page.NextCursor, total), ProtocolJson.Default.PageSequenceDto); + } + + private static async Task CreateAsync(HttpContext context, Caller caller, CreateSequenceRequest request, TitanoDatabase db, ServerArchive archive, + AuditLog audit, EventHub events, TimeProvider time) + { + var title = request.Title?.Trim(); + if (title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title"); + var hint = request.CameraHint?.Trim(); + var sequence = new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archive.Id, + Title = string.IsNullOrEmpty(title) ? null : title, + // Placed in the archive by the ingest when its first frame arrives. + Folder = string.Empty, + CameraModel = string.IsNullOrEmpty(hint) ? null : hint[..Math.Min(hint.Length, MaxTitle)], + Origin = SequenceOrigin.Server, + SyncState = SyncState.InSync, + OwnerUserId = caller.Id, + UpdatedAt = time.GetUtcNow(), + }; + await db.Sequences.UpsertAsync(sequence, context.RequestAborted); + await audit.WriteAsync(caller, context, "sequence_created", "sequence", sequence.Id.ToString(), sequence.DisplayTitle); + events.Publish(new SequenceChangedEvent(sequence.Id, "created", sequence.FramesVersion, sequence.SettingsVersion)); + context.Response.Headers.ETag = ETag(sequence); + return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto, statusCode: StatusCodes.Status201Created); + } + + private static async Task GetAsync(HttpContext context, Guid id, TitanoDatabase db) + { + if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + var etag = ETag(sequence); + if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified); + context.Response.Headers.ETag = etag; + return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto); + } + + private static async Task UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, TitanoDatabase db, + AuditLog audit, EventHub events) + { + if (request.Title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title"); + if (request.Notes is { Length: > MaxNotes }) return ApiErrors.BadRequest(context, "bad_request", "notes"); + if (request.Rating is < 0 or > 5) return ApiErrors.BadRequest(context, "bad_request", "rating"); + if (request.Tags is { } tags && (tags.Count > MaxTags || tags.Any(t => t is null || t.Trim().Length > TagRepository.MaxLength))) + return ApiErrors.BadRequest(context, "bad_request", "tags"); + if (request.SettingsJson is not null && !IsJson(request.SettingsJson)) return ApiErrors.BadRequest(context, "invalid_settings"); + + var expected = request.ExpectedSettingsVersion ?? IfMatchVersion(context); + var edit = new SequenceEdit { Title = request.Title, Tags = request.Tags, Rating = request.Rating, Notes = request.Notes, SettingsJson = request.SettingsJson }; + var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted); + switch (result.Outcome) + { + case SequenceEditOutcome.NotFound: + return ApiErrors.NotFound(context, "sequence"); + case SequenceEditOutcome.Conflict: + context.Response.Headers.ETag = ETag(result.Sequence!); + return ApiErrors.Conflict(context, "settings_conflict", result.Sequence!.SettingsVersion.ToString(CultureInfo.InvariantCulture)); + } + var sequence = result.Sequence!; + await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request)); + events.Publish(new SequenceChangedEvent(id, "settings", sequence.FramesVersion, sequence.SettingsVersion)); + context.Response.Headers.ETag = ETag(sequence); + return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto); + } + + /// + /// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is + /// erased). ?dryRun=true only reports what would happen. Owners and admins only. + /// + private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive, + ServerOptions options, AuditLog audit, EventHub events) + { + if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context); + var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePaths.Resolve(archive.Root, sequence.Folder); + var trash = Path.Combine(options.TrashPath, id.ToString("N")); + var hasFolder = folder is not null && Directory.Exists(folder); + var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null, + sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true); + if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan); + + if (hasFolder) + { + Directory.CreateDirectory(options.TrashPath); + Directory.Move(folder!, trash); + } + await db.Sequences.DeleteAsync(id, context.RequestAborted); + await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle); + events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion)); + return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan); + } + + /// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters. + private static async Task ManifestAsync(HttpContext context, Guid id, TitanoDatabase db) + { + var ct = context.RequestAborted; + if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); + var etag = string.Create(CultureInfo.InvariantCulture, $"\"m{sequence.SettingsVersion}-{sequence.FramesVersion}-{sequence.RenderedCount}\""); + if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified); + + var hasProxy = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt); + var hasThumb = sequence.Status.HasFlag(SequenceStatus.ThumbsBuilt); + var frames = new List(sequence.FrameCount); + var after = -1; + while (true) + { + var batch = await db.Frames.ListBySequenceAsync(id, after, 1000, ct); + frames.AddRange(batch.Select(f => new ManifestFrame(f.Id, f.Index, f.FileName, f.Size, f.Sha256 ?? string.Empty, hasProxy, hasThumb))); + if (batch.Count < 1000) break; + after = batch[^1].Index; + } + var renders = await db.Renders.ListBySequenceAsync(id, ct); + context.Response.Headers.ETag = etag; + return Results.Json(new SequenceManifest(id, sequence.FramesVersion, sequence.SettingsVersion, sequence.SettingsJson, sequence.Tags, frames, + [.. renders.Select(Dto.Render)]), ProtocolJson.Default.SequenceManifest); + } + + private static async Task FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, TitanoDatabase db) + { + var ct = context.RequestAborted; + if (await db.Sequences.GetAsync(id, ct) is null) return ApiErrors.NotFound(context, "sequence"); + var after = -1; + if (!string.IsNullOrEmpty(cursor) && !FrameCursor.TryDecode(cursor, out after)) return ApiErrors.BadRequest(context, "invalid_cursor"); + var take = Math.Clamp(limit ?? 500, 1, 1000); + var frames = await db.Frames.ListBySequenceAsync(id, after, take, ct); + var next = frames.Count == take ? FrameCursor.Encode(frames[^1].Index) : null; + return Results.Json(new Titano.Protocol.Page([.. frames.Select(Dto.Frame)], next, null), ProtocolJson.Default.PageFrameDto); + } + + private static async Task AnalysisAsync(HttpContext context, Guid id, TitanoDatabase db) => + await db.Sequences.GetAsync(id, context.RequestAborted) switch + { + null => ApiErrors.NotFound(context, "sequence"), + { AnalysisJson: { } json } => Results.Text(json, "application/json; charset=utf-8"), + _ => ApiErrors.NotFound(context, "analysis"), + }; + + private static async Task StatsAsync(HttpContext context, Guid id, TitanoDatabase db) + { + if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } s) return ApiErrors.NotFound(context, "sequence"); + var stats = await db.Frames.GetSequenceStatsAsync(id, context.RequestAborted); + return Results.Json(new SequenceStatsDto( + id, s.FrameCount, s.TotalBytes, s.FirstCapture, s.LastCapture, s.MedianInterval, + [.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))], + stats.Missing, stats.Corrupt, stats.Duplicate, stats.Excluded), ProtocolJson.Default.SequenceStatsDto); + } + + private static async Task RendersAsync(HttpContext context, Guid id, TitanoDatabase db) + { + if (await db.Sequences.GetAsync(id, context.RequestAborted) is null) return ApiErrors.NotFound(context, "sequence"); + var renders = await db.Renders.ListBySequenceAsync(id, context.RequestAborted); + return Results.Json(renders.Select(Dto.Render).ToList(), ProtocolJson.Default.ListRenderDto); + } + + /// Changes whenever anything the sequence representation shows changes (versions, status, statistics). + private static string ETag(Sequence s) => + string.Create(CultureInfo.InvariantCulture, $"\"{s.SettingsVersion}-{s.FramesVersion}-{s.UpdatedAt.UtcTicks}\""); + + /// The settings version named by an If-Match ETag of , if any. + private static int? IfMatchVersion(HttpContext context) + { + var header = context.Request.Headers.IfMatch.ToString().Trim('"', ' '); + var dash = header.IndexOf('-', StringComparison.Ordinal); + return dash > 0 && int.TryParse(header.AsSpan(0, dash), NumberStyles.None, CultureInfo.InvariantCulture, out var version) ? version : null; + } + + private static bool TryParseStatus(string? text, out SequenceStatus with, out SequenceStatus without) + { + with = without = SequenceStatus.None; + if (string.IsNullOrWhiteSpace(text)) return true; + foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var clear = part.StartsWith('-'); + var name = clear ? part[1..] : part; + var flag = Enum.GetValues().FirstOrDefault(v => v != SequenceStatus.None && v.ToString().Equals(name, StringComparison.OrdinalIgnoreCase)); + if (flag == SequenceStatus.None) return false; + if (clear) without |= flag; + else with |= flag; + } + return true; + } + + private static bool TryParseSort(string? text, out SequenceSort sort) + { + sort = SequenceSort.Newest; + if (string.IsNullOrEmpty(text)) return true; + foreach (var candidate in Enum.GetValues()) + { + if (candidate.ToString().Equals(text, StringComparison.OrdinalIgnoreCase)) + { + sort = candidate; + return true; + } + } + return false; + } + + private static bool IsJson(string text) + { + try + { + using var _ = JsonDocument.Parse(text); + return true; + } + catch (JsonException) + { + return false; + } + } + + private static string Changes(UpdateSequenceRequest r) + { + var fields = new List(); + if (r.Title is not null) fields.Add("title"); + if (r.Tags is not null) fields.Add("tags"); + if (r.Rating is not null) fields.Add("rating"); + if (r.Notes is not null) fields.Add("notes"); + if (r.SettingsJson is not null) fields.Add("settings"); + return string.Join(", ", fields); + } + + /// Opaque cursor of the frame listing: the index of the last frame returned. + private static class FrameCursor + { + private const string Prefix = "frames|"; + + public static string Encode(int index) => + Base64Url.EncodeToString(Encoding.UTF8.GetBytes(Prefix + index.ToString(CultureInfo.InvariantCulture))); + + public static bool TryDecode(string cursor, out int index) + { + index = -1; + try + { + var text = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor)); + return text.StartsWith(Prefix, StringComparison.Ordinal) + && int.TryParse(text.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index); + } + catch (FormatException) + { + return false; + } + } + } +} diff --git a/src/Titano.Server/Api/SystemEndpoints.cs b/src/Titano.Server/Api/SystemEndpoints.cs index a7da0fe4..d104bde0 100644 --- a/src/Titano.Server/Api/SystemEndpoints.cs +++ b/src/Titano.Server/Api/SystemEndpoints.cs @@ -1,40 +1,48 @@ using System.Globalization; using System.Reflection; using Titano.Core.Localization; +using Titano.Data; using Titano.Protocol; using Titano.Server.Configuration; +using Titano.Server.Security; namespace Titano.Server.Api; -/// /health, /api/v1/server/info and /api/v1/i18n/{culture}. +/// /health, /api/v1/server/info and /api/v1/i18n/{culture} (all anonymous). public static class SystemEndpoints { private static readonly string[] AdminAreas = ["Common", "Admin"]; + /// Languages with translated resources (English plus every satellite of the catalog), for the admin language menu. + private static readonly Lazy AdminLanguages = new(() => string.Join(',', Languages.Shipped.Where(code => + { + if (code == "en") return true; + try + { + typeof(Loc).Assembly.GetSatelliteAssembly(CultureInfo.GetCultureInfo(code)); + return true; + } + catch (FileNotFoundException) + { + return false; + } + }))); + public static string Version { get; } = typeof(SystemEndpoints).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; - public static void Map(WebApplication app, ServerOptions options, ServerState state) + public static void Map(WebApplication app, RouteGroupBuilder api) { - app.MapGet("/health", () => - { - var checks = new Dictionary(StringComparer.Ordinal) - { - ["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing", - ["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing", - }; - return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus); - }); + app.MapGet("/health", HealthAsync); - var api = app.MapGroup("/api/v1"); - api.MapGet("/server/info", () => Results.Json(new ServerInfo( + api.MapGet("/server/info", (ServerOptions options, ServerState state) => Results.Json(new ServerInfo( options.ServerName, Version, ApiVersion.Current, state.Capabilities, state.TlsFingerprint, ["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"], - new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo)); + new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller(); api.MapGet("/i18n/{culture}", (string culture) => { @@ -52,15 +60,46 @@ public static class SystemEndpoints foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v; strings["$culture"] = ci.Name; strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false"; + strings["$languages"] = AdminLanguages.Value; return Results.Json(strings, ProtocolJson.Default.DictionaryStringString); - }); + }).AllowAnonymousCaller(); + } + + /// Liveness for the container health check: 503 while the database cannot be reached. + private static async Task HealthAsync(HttpContext context, ServerOptions options, TitanoDatabase db) + { + var checks = new Dictionary(StringComparer.Ordinal) + { + ["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing", + ["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing", + }; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); + timeout.CancelAfter(TimeSpan.FromSeconds(3)); + try + { + await using var session = await db.Database.OpenAsync(timeout.Token); + await session.ExecuteAsync("SELECT 1", [], timeout.Token); + checks["database"] = "ok"; + } + catch (Exception ex) when (ex is DatabaseException or OperationCanceledException or IOException) + { + checks["database"] = "unavailable"; + } + var healthy = checks["database"] == "ok"; + return Results.Json(new HealthStatus(healthy ? "ok" : "unavailable", Version, checks), ProtocolJson.Default.HealthStatus, + statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable); } } /// Process-wide facts computed at startup. public sealed class ServerState { - public string? TlsFingerprint { get; set; } + public string? TlsFingerprint { get; init; } + + /// Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1"). + public string Database { get; init; } = string.Empty; + public List Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"]; + public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; } diff --git a/src/Titano.Server/Api/UploadEndpoints.cs b/src/Titano.Server/Api/UploadEndpoints.cs new file mode 100644 index 00000000..92ccfa53 --- /dev/null +++ b/src/Titano.Server/Api/UploadEndpoints.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Http.Features; +using Titano.Core.Model; +using Titano.Protocol; +using Titano.Server.Configuration; +using Titano.Server.Security; +using Titano.Server.Storage; + +namespace Titano.Server.Api; + +/// +/// /api/v1/uploads (BRIEF §14.4). Chunk, state and cancel calls also serve render nodes uploading their output, +/// which start and complete through the node endpoints. +/// +public static class UploadEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + var uploads = api.MapGroup("/uploads").Requires(Permissions.Upload | Permissions.RenderNode); + uploads.MapPost("", StartAsync).Requires(Permissions.Upload); + uploads.MapPut("/{id:guid}/chunks/{index:int}", ChunkAsync); + uploads.MapGet("/{id:guid}", async (HttpContext context, Caller caller, Guid id, UploadService service) => + (await service.GetStateAsync(caller, id, context.RequestAborted)).ToResult(context, s => Results.Json(s, ProtocolJson.Default.UploadState))); + uploads.MapDelete("/{id:guid}", async (HttpContext context, Caller caller, Guid id, UploadService service) => + (await service.CancelAsync(caller, id, context.RequestAborted)).ToResult(context, _ => Results.NoContent())); + uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, UploadService service) => + (await service.CompleteAsync(caller, id)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse))) + .Requires(Permissions.Upload); + } + + private static async Task StartAsync(HttpContext context, Caller caller, StartUploadRequest request, UploadService service) + { + var outcome = await service.StartAsync(caller, request, context.RequestAborted); + return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse, + statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created)); + } + + private static async Task ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service, ServerOptions options) + { + // Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit. + if (context.Features.Get() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = options.ChunkSizeBytes; + var outcome = await service.ReceiveChunkAsync(caller, id, index, context.Request, context.RequestAborted); + return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.ChunkReceived)); + } +} diff --git a/src/Titano.Server/Api/UserEndpoints.cs b/src/Titano.Server/Api/UserEndpoints.cs new file mode 100644 index 00000000..2a4099fc --- /dev/null +++ b/src/Titano.Server/Api/UserEndpoints.cs @@ -0,0 +1,157 @@ +using System.Globalization; +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Security; + +namespace Titano.Server.Api; + +/// /api/v1/users (admin): accounts, roles, quotas, render-node right, temporary passwords. +public static class UserEndpoints +{ + private const int MaxDisplayName = 100; + + public static void Map(RouteGroupBuilder api) + { + var users = api.MapGroup("/users").Requires(Permissions.ManageUsers); + users.MapGet("", ListAsync); + users.MapPost("", CreateAsync); + users.MapGet("/{id:guid}", GetAsync); + users.MapPatch("/{id:guid}", UpdateAsync); + users.MapDelete("/{id:guid}", DeleteAsync); + users.MapPost("/{id:guid}/reset-password", ResetPasswordAsync); + } + + private static async Task ListAsync(HttpContext context, TitanoDatabase db, TimeProvider time) + { + var ct = context.RequestAborted; + var users = await db.Users.ListAsync(ct); + var latest = await db.Tokens.LatestByUserAsync(ct); + var uploads = await db.Uploads.CommittedCountByUserAsync(time.GetUtcNow().AddDays(-30), ct); + var rows = users.Select(u => + { + var token = latest.GetValueOrDefault(u.Id); + return new UserSummaryDto(Dto.User(u), token?.LastUsed ?? u.LastLogin, token?.ClientName, uploads.GetValueOrDefault(u.Id)); + }).ToList(); + return Results.Json(rows, ProtocolJson.Default.ListUserSummaryDto); + } + + private static async Task GetAsync(HttpContext context, Guid id, TitanoDatabase db) => + await db.Users.GetAsync(id, context.RequestAborted) is { } user + ? Results.Json(Dto.User(user), ProtocolJson.Default.UserDto) + : ApiErrors.NotFound(context, "user"); + + private static async Task CreateAsync(HttpContext context, Caller caller, CreateUserRequest request, TitanoDatabase db, AuditLog audit, TimeProvider time) + { + var username = request.Username?.Trim(); + if (!Accounts.IsValidUsername(username)) return ApiErrors.BadRequest(context, "invalid_username"); + if (!Accounts.TryParseRole(request.Role, out var role)) return ApiErrors.BadRequest(context, "invalid_role"); + if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes"); + var password = string.IsNullOrEmpty(request.Password) ? TemporaryPassword.Generate() : request.Password; + if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context); + + var user = new User + { + Id = Guid.CreateVersion7(), + Username = username!, + DisplayName = Clean(request.DisplayName), + PasswordHash = PasswordHasher.Hash(password), + Role = role, + Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode), + QuotaBytes = request.QuotaBytes, + MustChangePassword = true, + Created = time.GetUtcNow(), + }; + try + { + await db.Users.CreateAsync(user, context.RequestAborted); + } + catch (DatabaseException ex) when (ex.IsUniqueViolation) + { + return ApiErrors.Conflict(context, "username_taken"); + } + await audit.WriteAsync(caller, context, "user_created", "user", user.Id.ToString(), $"{user.Username} · {Dto.Role(role)}"); + return Results.Json(new TemporaryPasswordResponse(Dto.User(user), password), ProtocolJson.Default.TemporaryPasswordResponse, statusCode: StatusCodes.Status201Created); + } + + private static async Task UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateUserRequest request, TitanoDatabase db, AuditLog audit) + { + var ct = context.RequestAborted; + if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); + var role = user.Role; + if (request.Role is not null && !Accounts.TryParseRole(request.Role, out role)) return ApiErrors.BadRequest(context, "invalid_role"); + if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes"); + var updated = user with + { + DisplayName = request.DisplayName is null ? user.DisplayName : Clean(request.DisplayName), + Role = role, + Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode ?? user.Permissions.HasFlag(Permissions.RenderNode)), + QuotaBytes = request.QuotaBytes ?? user.QuotaBytes, + Disabled = request.Disabled ?? user.Disabled, + }; + var losesAdmin = IsActiveAdmin(user) && !IsActiveAdmin(updated); + if (losesAdmin && user.Id == caller.Id) return ApiErrors.Conflict(context, "self"); + if (losesAdmin && !await HasOtherActiveAdminAsync(db, user.Id, ct)) return ApiErrors.Conflict(context, "last_admin"); + + await db.Users.UpdateAsync(updated, ct); + if (updated.Disabled && !user.Disabled) await db.Tokens.RevokeAllAsync(id, ct); + await audit.WriteAsync(caller, context, "user_updated", "user", id.ToString(), Changes(user, updated)); + return Results.Json(Dto.User(updated), ProtocolJson.Default.UserDto); + } + + private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, AuditLog audit) + { + var ct = context.RequestAborted; + if (id == caller.Id) return ApiErrors.Conflict(context, "self"); + if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); + if (IsActiveAdmin(user) && !await HasOtherActiveAdminAsync(db, id, ct)) return ApiErrors.Conflict(context, "last_admin"); + + // Render jobs of the user's nodes go back to the queue before the nodes disappear with the account. + foreach (var node in (await db.RenderNodes.ListAsync(ct)).Where(n => n.UserId == id)) + await db.Jobs.RequeueRunningAsync(node.Id.ToString(), ct); + var reassigned = await db.Sequences.ReassignOwnerAsync(id, caller.Id, ct); + await db.Users.DeleteAsync(id, ct); + await audit.WriteAsync(caller, context, "user_deleted", "user", id.ToString(), + $"{user.Username} · {reassigned.ToString(CultureInfo.InvariantCulture)}"); + return Results.NoContent(); + } + + private static async Task ResetPasswordAsync(HttpContext context, Caller caller, Guid id, ResetPasswordRequest? request, TitanoDatabase db, AuditLog audit) + { + var ct = context.RequestAborted; + if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); + var password = string.IsNullOrEmpty(request?.Password) ? TemporaryPassword.Generate() : request.Password; + if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context); + var updated = user with { PasswordHash = PasswordHasher.Hash(password), MustChangePassword = true }; + await db.Users.UpdateAsync(updated, ct); + await db.Tokens.RevokeAllAsync(id, ct); + await audit.WriteAsync(caller, context, "password_reset", "user", id.ToString(), user.Username); + return Results.Json(new TemporaryPasswordResponse(Dto.User(updated), password), ProtocolJson.Default.TemporaryPasswordResponse); + } + + private static bool IsActiveAdmin(User user) => user.Role == UserRole.Admin && !user.Disabled; + + private static async Task HasOtherActiveAdminAsync(TitanoDatabase db, Guid except, CancellationToken ct) => + (await db.Users.ListAsync(ct)).Any(u => u.Id != except && IsActiveAdmin(u)); + + private static IResult WeakPassword(HttpContext context) => + ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength); + + private static string? Clean(string? displayName) + { + var trimmed = displayName?.Trim(); + return string.IsNullOrEmpty(trimmed) ? null : trimmed[..Math.Min(trimmed.Length, MaxDisplayName)]; + } + + /// Audit detail listing the fields an edit changed (never secrets). + private static string Changes(User before, User after) + { + var changes = new List(); + if (before.DisplayName != after.DisplayName) changes.Add("displayName"); + if (before.Role != after.Role) changes.Add("role=" + Dto.Role(after.Role)); + if (before.Permissions != after.Permissions) changes.Add("permissions"); + if (before.QuotaBytes != after.QuotaBytes) changes.Add("quota=" + after.QuotaBytes.ToString(CultureInfo.InvariantCulture)); + if (before.Disabled != after.Disabled) changes.Add(after.Disabled ? "disabled" : "enabled"); + return string.Join(", ", changes); + } +} diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs index d1bcbfa8..b6658bcc 100644 --- a/src/Titano.Server/Configuration/ServerOptions.cs +++ b/src/Titano.Server/Configuration/ServerOptions.cs @@ -1,5 +1,7 @@ +using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; +using Titano.Data; namespace Titano.Server.Configuration; @@ -23,15 +25,44 @@ public enum DatabaseKind /// /// Server configuration (BRIEF §14.9): environment variables override /data/server.json, which overrides defaults. +/// Settings applied from the environment are listed in ; the admin panel cannot change them. /// public sealed class ServerOptions { + /// Environment variable → setting it fixes, and how its text is applied. + private static readonly (string Variable, string Setting, Action Apply)[] Variables = + [ + ("TITANO_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v), + ("TITANO_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v), + ("TITANO_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v), + ("TITANO_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v), + ("TITANO_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)), + ("TITANO_DB_HOST", nameof(DbHost), (o, v) => o.DbHost = v), + ("TITANO_DB_PORT", nameof(DbPort), (o, v) => o.DbPort = Int("TITANO_DB_PORT", v)), + ("TITANO_DB_NAME", nameof(DbName), (o, v) => o.DbName = v), + ("TITANO_DB_USER", nameof(DbUser), (o, v) => o.DbUser = v), + ("TITANO_DB_PASSWORD", nameof(DbPassword), (o, v) => o.DbPassword = v), + ("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v), + ("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)), + ("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)), + ("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse(v, ignoreCase: true)), + ("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v), + ("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v), + ("TITANO_LANG", nameof(Language), (o, v) => o.Language = v), + ("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))), + ("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)), + ]; + public string ServerName { get; set; } = "Titano Server"; public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive"; public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data"; public string? AdminUser { get; set; } public string? AdminPassword { get; set; } public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres; + + /// Complete connection string (from TITANO_DB when it holds one); overrides the Db* parts. + public string? DbConnectionString { get; set; } + public string DbHost { get; set; } = "postgres"; public int DbPort { get; set; } = 5432; public string DbName { get; set; } = "titano"; @@ -51,6 +82,27 @@ public sealed class ServerOptions public int JobHistoryDays { get; set; } = 90; public int TokenLifetimeDays { get; set; } = 30; + /// Uploads untouched for this long are abandoned: their partial files are deleted. + public int UploadRetentionHours { get; set; } = 48; + + /// Sign-in attempts accepted per minute and client address (BRIEF §14.2: 5). + public int LoginAttemptsPerMinute { get; set; } = 5; + + /// Consecutive failed sign-ins that lock an account name for . + public int LockoutThreshold { get; set; } = 10; + + public int LockoutMinutes { get; set; } = 15; + + /// A render node silent for this long is offline and its jobs go back to the queue. + public int NodeTimeoutSeconds { get; set; } = 90; + + /// Chunk uploads one user may run at the same time; more are answered 429. + public int ConcurrentChunksPerUser { get; set; } = 8; + + /// Settings fixed by environment variables (names of the properties above). + [JsonIgnore] + public IReadOnlyCollection Locked { get; private set; } = []; + [JsonIgnore] public string LogPath => Path.Combine(DataPath, "logs"); @@ -60,6 +112,17 @@ public sealed class ServerOptions [JsonIgnore] public string UploadsPath => Path.Combine(DataPath, "uploads"); + [JsonIgnore] + public string SettingsFile => Path.Combine(DataPath, "server.json"); + + /// Verified uploads wait here, on the archive volume, until the archive ingest moves them into place. + [JsonIgnore] + public string StagingPath => Path.Combine(ArchivePath, ".titano", "staging"); + + /// Deleted sequences are moved here (never erased by the server). + [JsonIgnore] + public string TrashPath => Path.Combine(ArchivePath, ".titano", "trash"); + /// Loads {DataPath}/server.json (if present) then applies TITANO_* environment variables. public static ServerOptions Load(IReadOnlyDictionary? environment = null) { @@ -82,35 +145,38 @@ public sealed class ServerOptions } options.DataPath = dataPath; - options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName; - options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath; - options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser; - options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword; - if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse(db, ignoreCase: true); - options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost; - if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture); - options.DbName = Env("TITANO_DB_NAME") ?? options.DbName; - options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser; - options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword; - options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode; - if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture); - if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture); - if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse(tls, ignoreCase: true); - options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert; - options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey; - options.Language = Env("TITANO_LANG") ?? options.Language; - if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture)); - if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery); + var locked = new List(); + foreach (var (variable, setting, apply) in Variables) + { + if (Env(variable) is not { } value) continue; + try + { + apply(options, value); + } + catch (Exception ex) when (ex is FormatException or ArgumentException) + { + throw new InvalidOperationException($"{variable} has an invalid value.", ex); + } + locked.Add(setting); + } + options.Locked = locked; options.Validate(); return options; } - private static Dictionary ReadEnvironment() + /// The database to open: , the SQLite file in the data folder, or PostgreSQL from the parts. + public DatabaseOptions ToDatabaseOptions() { - // Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins. - var result = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value; - return result; + if (DbConnectionString is { Length: > 0 } cs) return DatabaseOptions.Parse(cs); + if (Database == DatabaseKind.Sqlite) return DatabaseOptions.Sqlite(Path.Combine(DataPath, "titano.db")); + var builder = new System.Text.StringBuilder() + .Append("Host=").Append(Quote(DbHost)) + .Append(";Port=").Append(DbPort.ToString(CultureInfo.InvariantCulture)) + .Append(";Database=").Append(Quote(DbName)) + .Append(";Username=").Append(Quote(DbUser)) + .Append(";SslMode=").Append(Quote(DbSslMode)); + if (DbPassword is not null) builder.Append(";Password=").Append(Quote(DbPassword)); + return DatabaseOptions.Postgres(builder.ToString()); } public void Validate() @@ -122,6 +188,35 @@ public sealed class ServerOptions // Port 0 asks the OS for a free port (used by the in-process test host). if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535) throw new InvalidOperationException("Ports must be between 0 and 65535."); + if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) + throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB."); + if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1) + throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive."); + } + + /// TITANO_DB is postgres, sqlite or a complete connection string (Host=… / Data Source=…). + private void ApplyDatabase(string value) + { + if (value.Contains('=', StringComparison.Ordinal)) + { + DbConnectionString = value; + Database = DatabaseOptions.Parse(value).Dialect == Dialect.Postgres ? DatabaseKind.Postgres : DatabaseKind.Sqlite; + return; + } + Database = Enum.Parse(value, ignoreCase: true); + } + + private static int Int(string variable, string value) => + int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : throw new FormatException($"{variable} must be a number."); + + private static string Quote(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'"; + + private static Dictionary ReadEnvironment() + { + // Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins. + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value; + return result; } } diff --git a/src/Titano.Server/Configuration/ServerSettingsStore.cs b/src/Titano.Server/Configuration/ServerSettingsStore.cs new file mode 100644 index 00000000..5d830471 --- /dev/null +++ b/src/Titano.Server/Configuration/ServerSettingsStore.cs @@ -0,0 +1,101 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Titano.Core.IO; +using Titano.Core.Localization; +using Titano.Protocol; + +namespace Titano.Server.Configuration; + +/// +/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes /data/server.json (only the +/// edited keys; secrets and environment values are never written) and applies what can change while running; ports, +/// TLS, workers, chunk size and job history wait for a restart. +/// +public sealed class ServerSettingsStore(ServerOptions options) +{ + private readonly Lock _gate = new(); + private ServerSettingsDto? _saved; + + public ServerSettingsDto Current() + { + lock (_gate) return _saved ?? Snapshot(options, restartRequired: false); + } + + /// Validates and saves; returns the error code and the offending setting, or null on success. + public (string Code, string Setting)? Save(ServerSettingsDto request) + { + if (Validate(request) is { } invalid) return ("invalid_setting", invalid); + lock (_gate) + { + var current = _saved ?? Snapshot(options, restartRequired: false); + var changes = Changes(current, request); + if (changes.FirstOrDefault(c => options.Locked.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked); + if (changes.Count == 0) return null; + + var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : []; + foreach (var (name, value) in changes) file[name] = value; + Directory.CreateDirectory(options.DataPath); + AtomicFile.WriteAllText(options.SettingsFile, file.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + + options.ServerName = request.ServerName.Trim(); + options.Discovery = request.Discovery; + options.Language = request.Language; + options.MaxUploadBytes = request.MaxUploadBytes; + options.TokenLifetimeDays = request.TokenLifetimeDays; + options.UploadRetentionHours = request.UploadRetentionHours; + var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort + || !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase) + || request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey || request.Workers != options.Workers + || request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays; + _saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart }; + return null; + } + } + + private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new( + o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Workers, o.Discovery, + o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired); + + private static string? Validate(ServerSettingsDto r) + { + if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName); + if (r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort); + if (r.HttpsPort is < 1 or > 65535 || r.HttpsPort == r.HttpPort) return nameof(ServerOptions.HttpsPort); + if (!Enum.TryParse(r.TlsMode, ignoreCase: true, out var tls) || !Enum.IsDefined(tls)) return nameof(ServerOptions.TlsMode); + if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsCert) || !File.Exists(r.TlsCert))) return nameof(ServerOptions.TlsCert); + if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsKey) || !File.Exists(r.TlsKey))) return nameof(ServerOptions.TlsKey); + if (!Languages.Shipped.Contains(r.Language, StringComparer.OrdinalIgnoreCase)) return nameof(ServerOptions.Language); + if (r.Workers is < 1 or > 64) return nameof(ServerOptions.Workers); + if (r.MaxUploadBytes < 1024 * 1024) return nameof(ServerOptions.MaxUploadBytes); + if (r.ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) return nameof(ServerOptions.ChunkSizeBytes); + if (r.JobHistoryDays is < 1 or > 3650) return nameof(ServerOptions.JobHistoryDays); + if (r.TokenLifetimeDays is < 1 or > 365) return nameof(ServerOptions.TokenLifetimeDays); + if (r.UploadRetentionHours is < 1 or > 8760) return nameof(ServerOptions.UploadRetentionHours); + return null; + } + + /// Settings whose value differs, as server.json keys and JSON values. + private static List<(string Name, JsonNode? Value)> Changes(ServerSettingsDto a, ServerSettingsDto b) + { + var changes = new List<(string, JsonNode?)>(); + void Add(string name, T before, T after, Func json) + { + if (!EqualityComparer.Default.Equals(before, after)) changes.Add((name, json(after))); + } + Add(nameof(ServerOptions.ServerName), a.ServerName, b.ServerName.Trim(), v => JsonValue.Create(v)); + Add(nameof(ServerOptions.HttpPort), a.HttpPort, b.HttpPort, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.HttpsPort), a.HttpsPort, b.HttpsPort, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.TlsMode), a.TlsMode.ToLowerInvariant(), b.TlsMode.ToLowerInvariant(), v => JsonValue.Create(v)); + Add(nameof(ServerOptions.TlsCert), a.TlsCert, b.TlsCert, v => v is null ? null : JsonValue.Create(v)); + Add(nameof(ServerOptions.TlsKey), a.TlsKey, b.TlsKey, v => v is null ? null : JsonValue.Create(v)); + Add(nameof(ServerOptions.Language), a.Language, b.Language, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.Workers), a.Workers, b.Workers, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.Discovery), a.Discovery, b.Discovery, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.MaxUploadBytes), a.MaxUploadBytes, b.MaxUploadBytes, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.ChunkSizeBytes), a.ChunkSizeBytes, b.ChunkSizeBytes, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.JobHistoryDays), a.JobHistoryDays, b.JobHistoryDays, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.TokenLifetimeDays), a.TokenLifetimeDays, b.TokenLifetimeDays, v => JsonValue.Create(v)); + Add(nameof(ServerOptions.UploadRetentionHours), a.UploadRetentionHours, b.UploadRetentionHours, v => JsonValue.Create(v)); + return changes; + } +} diff --git a/src/Titano.Server/Events/EventEndpoints.cs b/src/Titano.Server/Events/EventEndpoints.cs new file mode 100644 index 00000000..aa315548 --- /dev/null +++ b/src/Titano.Server/Events/EventEndpoints.cs @@ -0,0 +1,103 @@ +using System.Net.WebSockets; +using System.Text.Json; +using Titano.Core.Model; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Security; + +namespace Titano.Server.Events; + +/// +/// WS /api/v1/events: server events as one JSON text message each (, discriminated by +/// type). The handshake is authenticated like any API call (bearer header, or the admin cookie from this origin); +/// the token is checked again every minute and the socket closes once it is revoked or expires. +/// +public static class EventEndpoints +{ + private static readonly TimeSpan Revalidate = TimeSpan.FromSeconds(60); + + public static void Map(RouteGroupBuilder api) => api.MapGet("/events", RunAsync).Requires(Permissions.Read); + + private static async Task RunAsync(HttpContext context, Caller caller, EventHub hub, TokenService tokens, IHostApplicationLifetime lifetime) + { + if (!context.WebSockets.IsWebSocketRequest) return ApiErrors.BadRequest(context, "websocket_required"); + using var socket = await context.WebSockets.AcceptWebSocketAsync(); + using var subscription = hub.Subscribe(); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted, lifetime.ApplicationStopping); + var receiving = ReceiveUntilClosedAsync(socket, stop); + var status = WebSocketCloseStatus.NormalClosure; + try + { + status = await SendAsync(socket, subscription, caller, tokens, stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or WebSocketException) + { + status = lifetime.ApplicationStopping.IsCancellationRequested ? WebSocketCloseStatus.EndpointUnavailable : WebSocketCloseStatus.NormalClosure; + } + finally + { + await stop.CancelAsync(); + await receiving; + } + if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + try + { + await socket.CloseOutputAsync(status, null, timeout.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or WebSocketException) + { + // The peer is gone. + } + } + return Results.Empty; + } + + /// Forwards events until cancelled; returns the close status when the caller's token stops being valid. + private static async Task SendAsync(WebSocket socket, EventHub.Subscription subscription, Caller caller, TokenService tokens, + CancellationToken cancellationToken) + { + while (true) + { + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + wait.CancelAfter(Revalidate); + try + { + while (await subscription.Reader.WaitToReadAsync(wait.Token)) + { + while (subscription.Reader.TryRead(out var e)) + { + var payload = JsonSerializer.SerializeToUtf8Bytes(e, ProtocolJson.Default.ServerEvent); + await socket.SendAsync(payload, WebSocketMessageType.Text, endOfMessage: true, cancellationToken); + } + } + return WebSocketCloseStatus.NormalClosure; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // Quiet minute: fall through to the token check. + } + } + if (!await tokens.IsStillValidAsync(caller, cancellationToken)) return WebSocketCloseStatus.PolicyViolation; + } + } + + private static async Task ReceiveUntilClosedAsync(WebSocket socket, CancellationTokenSource stop) + { + var buffer = new byte[1024]; + try + { + while (!stop.IsCancellationRequested) + { + var result = await socket.ReceiveAsync(buffer, stop.Token); + if (result.MessageType == WebSocketMessageType.Close) break; + } + } + catch (Exception ex) when (ex is OperationCanceledException or WebSocketException) + { + } + await stop.CancelAsync(); + } +} diff --git a/src/Titano.Server/Events/EventHub.cs b/src/Titano.Server/Events/EventHub.cs new file mode 100644 index 00000000..3240ad4d --- /dev/null +++ b/src/Titano.Server/Events/EventHub.cs @@ -0,0 +1,47 @@ +using System.Threading.Channels; +using Titano.Protocol; + +namespace Titano.Server.Events; + +/// +/// Fan-out of server events to WebSocket subscribers (BRIEF §14.3). Each subscriber has a bounded queue that drops +/// its oldest events when it falls behind, so a slow client never holds up the server. +/// +public sealed class EventHub +{ + private const int QueueLength = 512; + private readonly Lock _gate = new(); + private Channel[] _subscribers = []; + + public int SubscriberCount => Volatile.Read(ref _subscribers).Length; + + public Subscription Subscribe() + { + var channel = Channel.CreateBounded(new BoundedChannelOptions(QueueLength) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + }); + lock (_gate) _subscribers = [.. _subscribers, channel]; + return new Subscription(this, channel); + } + + public void Publish(ServerEvent e) + { + foreach (var subscriber in Volatile.Read(ref _subscribers)) subscriber.Writer.TryWrite(e); + } + + private void Remove(Channel channel) + { + lock (_gate) _subscribers = [.. _subscribers.Where(c => c != channel)]; + channel.Writer.TryComplete(); + } + + /// One subscriber's queue; dispose to unsubscribe. + public sealed class Subscription(EventHub hub, Channel channel) : IDisposable + { + public ChannelReader Reader => channel.Reader; + + public void Dispose() => hub.Remove(channel); + } +} diff --git a/src/Titano.Server/Hosting/AdminPanel.cs b/src/Titano.Server/Hosting/AdminPanel.cs new file mode 100644 index 00000000..d92fde09 --- /dev/null +++ b/src/Titano.Server/Hosting/AdminPanel.cs @@ -0,0 +1,48 @@ +using System.Net; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// Serves the embedded admin panel at /admin. Requests over plain HTTP from another machine are redirected to +/// the HTTPS listener, because the session cookie is Secure (BRIEF §14.2) and would not survive plain HTTP. +/// +public static class AdminPanel +{ + public static void Map(WebApplication app, ServerOptions options) + { + var files = new EmbeddedStaticFiles(typeof(AdminPanel).Assembly, "admin/"); + var server = app.Services.GetRequiredService(); + app.MapGet("/", () => Results.Redirect("/admin/")); + app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) => + { + if (HttpsLocation(context, options, server) is { } secure) + { + context.Response.Redirect(secure); + return; + } + // Relative asset URLs need the trailing slash. + if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path)) + { + context.Response.Redirect("/admin/"); + return; + } + if (!await files.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound; + }); + } + + private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server) + { + if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null; + if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null; + foreach (var address in server.Features.Get()?.Addresses ?? []) + { + if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue; + var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/'); + return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}"; + } + return null; + } +} diff --git a/src/Titano.Server/Hosting/DiscoveryBeaconService.cs b/src/Titano.Server/Hosting/DiscoveryBeaconService.cs new file mode 100644 index 00000000..3f2e8f29 --- /dev/null +++ b/src/Titano.Server/Hosting/DiscoveryBeaconService.cs @@ -0,0 +1,99 @@ +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// LAN discovery (BRIEF §14.9, TITANO_DISCOVERY): every few seconds a is broadcast on +/// UDP port of every IPv4 network, so clients can offer this server on first run. +/// Switching discovery off in the settings stops it without a restart. +/// +public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger logger) : BackgroundService +{ + private static readonly TimeSpan Interval = TimeSpan.FromSeconds(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var udp = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true }; + var warned = false; + while (!stoppingToken.IsCancellationRequested) + { + if (options.Discovery) + { + try + { + await SendOnceAsync(udp, BroadcastTargets(), stoppingToken); + } + catch (SocketException ex) when (!warned) + { + warned = true; + logger.LogInformation("LAN discovery beacon cannot be sent: {Reason}", ex.Message); + } + catch (SocketException) + { + // Already reported once; networks may come and go. + } + } + try + { + await Task.Delay(Interval, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } + + /// The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere). + public DiscoveryBeacon CreateBeacon() => new( + options.ServerName, + SystemEndpoints.Version, + BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort, + state.TlsFingerprint is null ? 0 : BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort, + state.TlsFingerprint); + + public async Task SendOnceAsync(UdpClient udp, IEnumerable targets, CancellationToken cancellationToken) + { + var datagram = CreateBeacon().ToBytes(); + foreach (var target in targets) await udp.SendAsync(datagram, target, cancellationToken); + } + + /// The limited broadcast address plus the directed broadcast of each IPv4 interface that is up. + private static List BroadcastTargets() + { + var targets = new List { new(IPAddress.Broadcast, DiscoveryBeacon.Port) }; + foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) + { + if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; + foreach (var unicast in nic.GetIPProperties().UnicastAddresses) + { + if (unicast.Address.AddressFamily != AddressFamily.InterNetwork || unicast.IPv4Mask is not { } mask) continue; + var address = unicast.Address.GetAddressBytes(); + var bits = mask.GetAddressBytes(); + for (var i = 0; i < 4; i++) address[i] = (byte)(address[i] | ~bits[i]); + var broadcast = new IPEndPoint(new IPAddress(address), DiscoveryBeacon.Port); + if (!targets.Contains(broadcast)) targets.Add(broadcast); + } + } + return targets; + } + + private int? BoundPort(string scheme) + { + var addresses = server.Features.Get()?.Addresses ?? []; + foreach (var address in addresses) + { + if (Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal), + UriKind.Absolute, out var uri) && uri.Scheme == scheme) + return uri.Port; + } + return null; + } +} diff --git a/src/Titano.Server/Hosting/FileLoggerProvider.cs b/src/Titano.Server/Hosting/FileLoggerProvider.cs index 7052813b..8f5c4f63 100644 --- a/src/Titano.Server/Hosting/FileLoggerProvider.cs +++ b/src/Titano.Server/Hosting/FileLoggerProvider.cs @@ -38,7 +38,16 @@ public sealed class LoggerSink(ILoggerFactory factory) : ILogSink { public void Write(CoreLogLevel level, string category, string message, Exception? exception) { - var logger = factory.CreateLogger("Titano." + category); + ILogger logger; + try + { + logger = factory.CreateLogger("Titano." + category); + } + catch (ObjectDisposedException) + { + // The host that installed this sink has shut down (engine code may outlive it); the line is dropped. + return; + } var ms = level switch { CoreLogLevel.Trace => MsLogLevel.Trace, diff --git a/src/Titano.Server/Hosting/ResponseMiddleware.cs b/src/Titano.Server/Hosting/ResponseMiddleware.cs new file mode 100644 index 00000000..5536bf57 --- /dev/null +++ b/src/Titano.Server/Hosting/ResponseMiddleware.cs @@ -0,0 +1,74 @@ +using Titano.Protocol; +using Titano.Server.Api; + +namespace Titano.Server.Hosting; + +/// +/// First middleware of the pipeline: API version and security headers on every response, and the +/// { code, message, details } error body for failures that did not produce one (bad requests, unhandled +/// exceptions, unknown methods). +/// +public sealed class ResponseMiddleware(RequestDelegate next, ILogger logger) +{ + /// The admin panel loads nothing from elsewhere and is never framed. + private const string AdminPolicy = + "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; " + + "frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + + public async Task InvokeAsync(HttpContext context) + { + var headers = context.Response.Headers; + headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture); + headers.XContentTypeOptions = "nosniff"; + headers["Referrer-Policy"] = "no-referrer"; + var api = context.Request.Path.StartsWithSegments("/api"); + if (api) headers.CacheControl = "no-store"; + if (context.Request.Path.StartsWithSegments("/admin")) + { + headers.ContentSecurityPolicy = AdminPolicy; + headers.XFrameOptions = "DENY"; + } + + try + { + await next(context); + } + catch (BadHttpRequestException ex) when (!context.Response.HasStarted) + { + await ApiErrors.WriteAsync(context, ex.StatusCode, CodeFor(ex.StatusCode)); + return; + } + catch (FormatException) when (!context.Response.HasStarted && context.Request.Query.ContainsKey("cursor")) + { + // Repositories reject cursors that do not belong to the listing. + await ApiErrors.WriteAsync(context, StatusCodes.Status400BadRequest, "invalid_cursor"); + return; + } + catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) + { + return; + } + catch (Exception ex) when (!context.Response.HasStarted) + { + logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path); + await ApiErrors.WriteAsync(context, StatusCodes.Status500InternalServerError, "internal"); + return; + } + + var response = context.Response; + if (api && response.StatusCode >= 400 && !response.HasStarted && response.ContentType is null) + await ApiErrors.WriteAsync(context, response.StatusCode, CodeFor(response.StatusCode)); + } + + private static string CodeFor(int status) => status switch + { + StatusCodes.Status400BadRequest => "bad_request", + StatusCodes.Status401Unauthorized => "unauthorized", + StatusCodes.Status403Forbidden => "forbidden", + StatusCodes.Status404NotFound => "not_found", + StatusCodes.Status405MethodNotAllowed => "method_not_allowed", + StatusCodes.Status413PayloadTooLarge => "too_large", + StatusCodes.Status415UnsupportedMediaType => "unsupported_media_type", + _ => "internal", + }; +} diff --git a/src/Titano.Server/Hosting/ServerCommandLine.cs b/src/Titano.Server/Hosting/ServerCommandLine.cs new file mode 100644 index 00000000..a4751919 --- /dev/null +++ b/src/Titano.Server/Hosting/ServerCommandLine.cs @@ -0,0 +1,68 @@ +namespace Titano.Server.Hosting; + +/// What Titano.Server was asked to do. +public enum ServerCommand +{ + /// Run in the console (Docker, Linux, development). + Run, + + /// Run under the Windows Service Control Manager (the command line the installed service uses). + Service, + + InstallService, + UninstallService, + + /// Probe /health of the local server and exit 0/1 (container health check). + HealthCheck, + + Help, +} + +/// Command-line switches of the server; anything else is passed on to the web host. +public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList HostArguments, string? Error) +{ + public const string Usage = """ + Titano Server — time-lapse archive, uploads, jobs and rendering. + + Usage: Titano.Server [--service | --install-service | --uninstall-service | --healthcheck | --help] + + (no switch) run in the console until Ctrl+C + --service run under the Windows Service Control Manager + --install-service register the "TitanoServer" Windows service (automatic start, LocalSystem) + --uninstall-service stop and remove the Windows service + --healthcheck exit 0 when the local server answers /health, 1 otherwise + + Configuration: /data/server.json (TITANO_DATA_PATH) overridden by environment variables: + TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD + TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER + TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy) + TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS TITANO_DISCOVERY + """; + + public static ServerCommandLine Parse(IReadOnlyList args) + { + var command = ServerCommand.Run; + var rest = new List(); + string? error = null; + foreach (var arg in args) + { + ServerCommand? parsed = arg switch + { + "--service" => ServerCommand.Service, + "--install-service" => ServerCommand.InstallService, + "--uninstall-service" => ServerCommand.UninstallService, + "--healthcheck" => ServerCommand.HealthCheck, + "--help" or "-h" or "-?" or "/?" => ServerCommand.Help, + _ => null, + }; + if (parsed is not { } switchCommand) + { + rest.Add(arg); + continue; + } + if (command != ServerCommand.Run && command != switchCommand) error = $"{arg} cannot be combined with another command switch."; + command = switchCommand; + } + return new ServerCommandLine(command, rest, error); + } +} diff --git a/src/Titano.Server/Hosting/ServerDatabase.cs b/src/Titano.Server/Hosting/ServerDatabase.cs new file mode 100644 index 00000000..19db1ce9 --- /dev/null +++ b/src/Titano.Server/Hosting/ServerDatabase.cs @@ -0,0 +1,41 @@ +using Titano.Data; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// Opens and migrates the server database at startup (BRIEF §6.1), waiting for a PostgreSQL container that is still starting. +public static class ServerDatabase +{ + private const int Attempts = 10; + private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(3); + + public static async Task OpenAsync(ServerOptions options, ILogger logger, CancellationToken cancellationToken) + { + var settings = options.ToDatabaseOptions(); + for (var attempt = 1; ; attempt++) + { + try + { + var db = await TitanoDatabase.OpenAsync(settings, cancellationToken).ConfigureAwait(false); + logger.LogInformation("Database {Dialect} ready, schema version {Version}", db.Dialect, db.SchemaVersion); + return db; + } + catch (DatabaseConnectionException ex) when (attempt < Attempts) + { + logger.LogWarning("Database not reachable yet ({Reason}); retry {Attempt} of {Attempts} in {Delay} s", + ex.Message, attempt, Attempts - 1, RetryDelay.TotalSeconds); + await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); + } + } + } + + /// Engine and version, e.g. "PostgreSQL 17.2" or "SQLite 3.45.1". + public static async Task DescribeAsync(TitanoDatabase db, CancellationToken cancellationToken) + { + await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false); + var postgres = db.Dialect == Dialect.Postgres; + var version = await session.ScalarAsync(postgres ? "SHOW server_version" : "SELECT sqlite_version()", [], cancellationToken).ConfigureAwait(false); + var number = version?.Split(' ', 2)[0] ?? string.Empty; + return (postgres ? "PostgreSQL " : "SQLite ") + number; + } +} diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs index 592a15d7..cda06dfa 100644 --- a/src/Titano.Server/Hosting/ServerHost.cs +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -1,21 +1,37 @@ using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Server.Kestrel.Core; using Titano.Core.Diagnostics; +using Titano.Data; +using Titano.Data.Archiving; using Titano.Protocol; using Titano.Server.Api; using Titano.Server.Configuration; +using Titano.Server.Events; +using Titano.Server.Jobs; +using Titano.Server.Security; +using Titano.Server.Storage; namespace Titano.Server.Hosting; -/// Builds the Titano Server web application from (used by Program and tests). +/// +/// Builds the Titano Server web application from (used by Program, the Windows service +/// host and tests). The archive module plugs in through of : +/// it must register and , and may add +/// s; the server refuses to start without the first two. +/// public static class ServerHost { - public static WebApplication Build(ServerOptions options, string[] args) + /// Request bodies other than upload chunks stay small (BRIEF §14.2 limits). + public const long JsonBodyLimit = 1024 * 1024; + + public static WebApplication Build(ServerOptions options, string[] args, Action? configureServices = null) { Directory.CreateDirectory(options.DataPath); Directory.CreateDirectory(options.LogPath); + Directory.CreateDirectory(options.UploadsPath); + Directory.CreateDirectory(options.ArchivePath); - var builder = WebApplication.CreateSlimBuilder(args); + var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory }); builder.Logging.ClearProviders(); builder.Logging.AddSimpleConsole(c => c.SingleLine = true); builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server"))); @@ -23,26 +39,67 @@ public static class ServerHost builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information); using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true)); - var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server")); - var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) }; - - builder.WebHost.ConfigureKestrel(k => + var bootLogger = bootLoggerFactory.CreateLogger("Titano.Server"); + var certificate = CertificateStore.Load(options, bootLogger); + var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult(); + try { - k.AddServerHeader = false; - k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024; - k.ListenAnyIP(options.HttpPort); - if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => + var archive = ServerArchive.OpenAsync(database, options, TimeProvider.System, CancellationToken.None).GetAwaiter().GetResult(); + AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult(); + var state = new ServerState { - l.Protocols = HttpProtocols.Http1AndHttp2; - l.UseHttps(certificate); + TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate), + Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(), + }; + + builder.WebHost.ConfigureKestrel(k => + { + k.AddServerHeader = false; + k.Limits.MaxRequestBodySize = JsonBodyLimit; + k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30); + k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2); + k.ListenAnyIP(options.HttpPort); + if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => + { + l.Protocols = HttpProtocols.Http1AndHttp2; + l.UseHttps(certificate); + }); }); - }); - builder.Services.AddSingleton(options); - builder.Services.AddSingleton(state); - builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); + ConfigureServices(builder.Services, options, state, database, archive); + configureServices?.Invoke(builder.Services); + + var app = builder.Build(); + RequireArchiveModule(app.Services); + Log.SetSink(new LoggerSink(app.Services.GetRequiredService())); + ConfigurePipeline(app, options); + app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}", + SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode, + state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint); + app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping")); + app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult()); + return app; + } + catch + { + database.DisposeAsync().AsTask().GetAwaiter().GetResult(); + throw; + } + } + + /// The single composition root of the server's services. + public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, TitanoDatabase database, ServerArchive archive) + { + services.AddSingleton(options); + services.AddSingleton(state); + services.AddSingleton(database); + services.AddSingleton(archive); + services.AddSingleton(TimeProvider.System); + services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); + services.Configure(o => o.ThrowOnBadRequest = true); + services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30)); if (options.TlsMode == TlsMode.Proxy) { - builder.Services.Configure(f => + services.Configure(f => { f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; f.KnownIPNetworks.Clear(); @@ -50,49 +107,62 @@ public static class ServerHost }); } - var app = builder.Build(); - Log.SetSink(new LoggerSink(app.Services.GetRequiredService())); - var logger = app.Logger; - logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}", - SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode, - state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + } + private static void ConfigurePipeline(WebApplication app, ServerOptions options) + { if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders(); + app.UseMiddleware(); + app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) }); + app.UseRouting(); + app.UseMiddleware(); - app.Use(async (context, next) => + AdminPanel.Map(app, options); + var api = app.MapGroup("/api/v1"); + SystemEndpoints.Map(app, api); + AuthEndpoints.Map(api); + UserEndpoints.Map(api); + SequenceEndpoints.Map(api); + FileEndpoints.Map(api); + UploadEndpoints.Map(api); + JobEndpoints.Map(api); + NodeEndpoints.Map(api); + ArchiveEndpoints.Map(api); + AdminEndpoints.Map(api); + EventEndpoints.Map(api); + app.MapFallback("/api/{**path}", (HttpContext context) => ApiErrors.NotFound(context)).AllowAnonymousCaller(); + } + + /// Fails fast when the archive module's services are missing (the server would accept uploads it cannot commit). + private static void RequireArchiveModule(IServiceProvider services) + { + var registry = services.GetRequiredService(); + var missing = new List(); + if (!registry.IsService(typeof(IArchiveIngest))) missing.Add($"{typeof(IArchiveIngest).FullName} (commits verified uploads into the archive layout)"); + if (!registry.IsService(typeof(IFrameAssetLocator))) missing.Add($"{typeof(IFrameAssetLocator).FullName} (finds proxies and thumbnails)"); + if (missing.Count > 0) { - context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture); - context.Response.Headers.XContentTypeOptions = "nosniff"; - context.Response.Headers["Referrer-Policy"] = "no-referrer"; - try - { - await next(context); - } - catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException) - { - logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError); - } - }); - - var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/"); - app.MapGet("/", () => Results.Redirect("/admin/")); - app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) => - { - // Relative asset URLs need the trailing slash. - if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path)) - { - context.Response.Redirect("/admin/"); - return; - } - if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound; - }); - - SystemEndpoints.Map(app, options, state); - - app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404)); - app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping")); - return app; + throw new InvalidOperationException( + "Titano Server cannot start: no implementation is registered for " + string.Join(" and ", missing) + + ". Register them in the services callback of ServerHost.Build."); + } } } diff --git a/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs new file mode 100644 index 00000000..7d3adc8f --- /dev/null +++ b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs @@ -0,0 +1,83 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Titano.Core.Localization; +using static Titano.Server.Hosting.Windows.ServiceNative; + +namespace Titano.Server.Hosting.Windows; + +/// +/// --install-service / --uninstall-service: registers the server with the Service Control Manager +/// (automatic start, LocalSystem, command line "…\Titano.Server.exe" --service) or stops and removes it. +/// Both need an elevated prompt; failures surface as . +/// +[SupportedOSPlatform("windows")] +public static unsafe class ServiceInstaller +{ + private const string DisplayName = "Titano Server"; + + public static void Install() + { + var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService); + if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + try + { + var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart, + ServiceErrorNormal, CommandLine(), null, 0, null, null, null); + if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + try + { + fixed (char* text = Loc.L("Server.Service.Description")) + { + var description = new ServiceDescription { Description = text }; + ChangeServiceConfig2W(service, ServiceConfigDescription, &description); + } + } + finally + { + CloseServiceHandle(service); + } + } + finally + { + CloseServiceHandle(manager); + } + } + + public static void Uninstall() + { + var manager = OpenSCManagerW(null, null, ScManagerConnect); + if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + try + { + var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus); + if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + try + { + ServiceStatus status; + if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive) + throw new Win32Exception(stopError); + if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete) + throw new Win32Exception(deleteError); + } + finally + { + CloseServiceHandle(service); + } + } + finally + { + CloseServiceHandle(manager); + } + } + + /// The service's command line: this executable (or dotnet plus this assembly) with --service. + private static string CommandLine() + { + var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown."); + var assembly = typeof(ServiceInstaller).Assembly.Location; + return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase) + ? $"\"{process}\" \"{assembly}\" --service" + : $"\"{process}\" --service"; + } +} diff --git a/src/Titano.Server/Hosting/Windows/ServiceNative.cs b/src/Titano.Server/Hosting/Windows/ServiceNative.cs new file mode 100644 index 00000000..1b89fd1e --- /dev/null +++ b/src/Titano.Server/Hosting/Windows/ServiceNative.cs @@ -0,0 +1,93 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace Titano.Server.Hosting.Windows; + +/// Service Control Manager functions of advapi32 (no Windows-only package needed). +[SupportedOSPlatform("windows")] +internal static unsafe partial class ServiceNative +{ + public const uint ServiceWin32OwnProcess = 0x10; + public const uint ServiceAutoStart = 2; + public const uint ServiceErrorNormal = 1; + public const uint ScManagerConnect = 0x1; + public const uint ScManagerCreateService = 0x2; + public const uint ServiceAllAccess = 0xF01FF; + public const uint ServiceQueryStatus = 0x4; + public const uint ServiceStop = 0x20; + public const uint Delete = 0x10000; + public const uint ServiceConfigDescription = 1; + + public const uint ControlStop = 1; + public const uint ControlInterrogate = 4; + public const uint ControlShutdown = 5; + + public const int ErrorFailedServiceControllerConnect = 1063; + public const int ErrorServiceNotActive = 1062; + public const int ErrorServiceMarkedForDelete = 1072; + public const uint NoError = 0; + public const uint ErrorCallNotImplemented = 120; + public const uint ErrorExceptionInService = 1064; + + [StructLayout(LayoutKind.Sequential)] + public struct ServiceStatus + { + public uint ServiceType; + public uint CurrentState; + public uint ControlsAccepted; + public uint Win32ExitCode; + public uint ServiceSpecificExitCode; + public uint CheckPoint; + public uint WaitHint; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ServiceTableEntry + { + public char* ServiceName; + public delegate* unmanaged[Stdcall] ServiceProc; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ServiceDescription + { + public char* Description; + } + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool StartServiceCtrlDispatcherW(ServiceTableEntry* table); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint RegisterServiceCtrlHandlerExW(string serviceName, delegate* unmanaged[Stdcall] handler, nint context); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool SetServiceStatus(nint statusHandle, ServiceStatus* status); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType, + uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool ChangeServiceConfig2W(nint service, uint infoLevel, void* info); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool ControlService(nint service, uint control, ServiceStatus* status); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DeleteService(nint service); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool CloseServiceHandle(nint handle); +} diff --git a/src/Titano.Server/Hosting/Windows/ServiceStatusTracker.cs b/src/Titano.Server/Hosting/Windows/ServiceStatusTracker.cs new file mode 100644 index 00000000..01d55ad4 --- /dev/null +++ b/src/Titano.Server/Hosting/Windows/ServiceStatusTracker.cs @@ -0,0 +1,68 @@ +namespace Titano.Server.Hosting.Windows; + +/// SERVICE_STATUS.dwCurrentState values the server reports. +public enum ServiceState : uint +{ + Stopped = 1, + StartPending = 2, + StopPending = 3, + Running = 4, +} + +/// One status report for SetServiceStatus. +public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode); + +/// +/// The service's state machine and the rules of SERVICE_STATUS: no controls are accepted while pending, the check point +/// grows with every pending report and is zero otherwise, a stopped service carries its exit code. +/// +public sealed class ServiceStatusTracker +{ + public const uint AcceptStop = 0x1; + public const uint AcceptShutdown = 0x4; + + private readonly Lock _gate = new(); + private uint _checkPoint; + + public ServiceStatusReport Current { get; private set; } = new(ServiceState.Stopped, 0, 0, 0, 0); + + public ServiceStatusReport StartPending(uint waitHintMilliseconds) => Pending(ServiceState.StartPending, waitHintMilliseconds, ServiceState.Stopped, ServiceState.StartPending); + + public ServiceStatusReport Running() + { + lock (_gate) + { + Require(ServiceState.StartPending); + _checkPoint = 0; + return Current = new ServiceStatusReport(ServiceState.Running, AcceptStop | AcceptShutdown, 0, 0, 0); + } + } + + /// Stopping from start-up or from running; repeating it reports progress (a higher check point). + public ServiceStatusReport StopPending(uint waitHintMilliseconds) => + Pending(ServiceState.StopPending, waitHintMilliseconds, ServiceState.StartPending, ServiceState.Running, ServiceState.StopPending); + + public ServiceStatusReport Stopped(uint exitCode) + { + lock (_gate) + { + _checkPoint = 0; + return Current = new ServiceStatusReport(ServiceState.Stopped, 0, 0, 0, exitCode); + } + } + + private ServiceStatusReport Pending(ServiceState state, uint waitHintMilliseconds, params ServiceState[] from) + { + lock (_gate) + { + Require(from); + _checkPoint = Current.State == state ? _checkPoint + 1 : 1; + return Current = new ServiceStatusReport(state, 0, _checkPoint, waitHintMilliseconds, 0); + } + } + + private void Require(params ServiceState[] allowed) + { + if (!allowed.Contains(Current.State)) throw new InvalidOperationException($"A service cannot go from {Current.State} to that state."); + } +} diff --git a/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs b/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs new file mode 100644 index 00000000..d08a87e7 --- /dev/null +++ b/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs @@ -0,0 +1,117 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using static Titano.Server.Hosting.Windows.ServiceNative; + +namespace Titano.Server.Hosting.Windows; + +/// +/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW, +/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running +/// jobs keep their checkpoints and resume at the next start. +/// +[SupportedOSPlatform("windows")] +public static class WindowsServiceHost +{ + public const string ServiceName = "TitanoServer"; + private const uint StartWaitHint = 60_000; + private const uint StopWaitHint = 35_000; + + private static readonly ServiceStatusTracker Status = new(); + private static Func? _build; + private static WebApplication? _app; + private static nint _statusHandle; + + /// + /// Hands the process to the Service Control Manager and returns when the service has stopped. False when the + /// process was not started by the SCM (for example from a console). + /// + public static unsafe bool Run(Func build) + { + _build = build; + fixed (char* name = ServiceName) + { + var table = stackalloc ServiceTableEntry[2]; + table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain }; + table[1] = default; + if (StartServiceCtrlDispatcherW(table)) return true; + } + var error = Marshal.GetLastPInvokeError(); + if (error == ErrorFailedServiceControllerConnect) return false; + throw new Win32Exception(error); + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static unsafe void ServiceMain(uint argc, char** argv) + { + _statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0); + if (_statusHandle == 0) return; + Report(Status.StartPending(StartWaitHint)); + try + { + _app = _build!(); + _app.StartAsync().GetAwaiter().GetResult(); + Report(Status.Running()); + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + Report(Status.Stopped(ErrorExceptionInService)); + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context) + { + switch (control) + { + case ControlStop or ControlShutdown: + if (Status.Current.State is ServiceState.Running or ServiceState.StartPending) + { + Report(Status.StopPending(StopWaitHint)); + // The handler must return at once; the host stops on the thread pool. + _ = Task.Run(StopAsync); + } + return NoError; + case ControlInterrogate: + Report(Status.Current); + return NoError; + default: + return ErrorCallNotImplemented; + } + } + + private static async Task StopAsync() + { + uint exitCode = 0; + try + { + if (_app is { } app) + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + exitCode = ErrorExceptionInService; + } + Report(Status.Stopped(exitCode)); + } + + private static unsafe void Report(ServiceStatusReport report) + { + var status = new ServiceStatus + { + ServiceType = ServiceWin32OwnProcess, + CurrentState = (uint)report.State, + ControlsAccepted = report.ControlsAccepted, + Win32ExitCode = report.ExitCode, + CheckPoint = report.CheckPoint, + WaitHint = report.WaitHintMilliseconds, + }; + SetServiceStatus(_statusHandle, &status); + } +} diff --git a/src/Titano.Server/Jobs/JobEngineHost.cs b/src/Titano.Server/Jobs/JobEngineHost.cs new file mode 100644 index 00000000..eda9eac4 --- /dev/null +++ b/src/Titano.Server/Jobs/JobEngineHost.cs @@ -0,0 +1,87 @@ +using System.Diagnostics; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Jobs; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; +using Titano.Server.Events; + +namespace Titano.Server.Jobs; + +/// +/// Hosts the server's (BRIEF §14.6) with the s registered in DI and +/// relays its state changes and progress as WebSocket events. Render jobs are never run here: render nodes claim them +/// (BRIEF §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. +/// +public sealed class JobEngineHost : IHostedService +{ + private static readonly long ProgressInterval = Stopwatch.Frequency / 4; + + private readonly TitanoDatabase _db; + private readonly EventHub _events; + private readonly HashSet _kinds; + private readonly Dictionary _lastProgress = []; + private readonly Lock _gate = new(); + + public JobEngineHost(TitanoDatabase db, IEnumerable handlers, ServerOptions options, EventHub events) + { + _db = db; + _events = events; + var local = handlers.Where(h => h.Kind != JobKind.Render).ToList(); + _kinds = [.. local.Select(h => h.Kind)]; + // Without handlers no worker starts: an engine with an empty kind list would claim every kind. + Workers = _kinds.Count == 0 ? 0 : options.Workers; + Engine = new JobEngine(db, local, new JobEngineOptions + { + Workers = Workers, + WorkerId = WorkerId, + Kinds = _kinds, + HistoryRetention = TimeSpan.FromDays(options.JobHistoryDays), + }); + Engine.JobChanged += OnJobChanged; + Engine.Progress += OnProgress; + } + + /// Node id stamped on jobs this server runs (its workers use WorkerId#n). + public static string WorkerId { get; } = "server:" + Environment.MachineName; + + public JobEngine Engine { get; } + + public int Workers { get; } + + /// True when a job of has somewhere to run: a local handler, or render nodes for renders. + public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind); + + public async Task StartAsync(CancellationToken cancellationToken) + { + // The engine requeues only its exact worker id; numbered workers of the previous run are requeued here. + await _db.Jobs.RequeueRunningWorkersAsync(WorkerId, cancellationToken); + await Engine.StartAsync(cancellationToken); + } + + public async Task StopAsync(CancellationToken cancellationToken) => await Engine.DisposeAsync(); + + /// Publishes a state change made outside the engine (render nodes, cancellation of node jobs). + public void Publish(Job job) => OnJobChanged(job); + + private void OnJobChanged(Job job) + { + if (job.State != JobState.Running) + { + lock (_gate) _lastProgress.Remove(job.Id); + } + _events.Publish(new JobStateEvent(job.Id, JobWire.State(job.State), job.Error)); + } + + private void OnProgress(JobProgressInfo progress) + { + var now = Stopwatch.GetTimestamp(); + lock (_gate) + { + if (_lastProgress.TryGetValue(progress.JobId, out var last) && now - last < ProgressInterval && progress.Done < progress.Total) return; + _lastProgress[progress.JobId] = now; + } + _events.Publish(new JobProgressEvent(progress.JobId, progress.Done, progress.Total, progress.ItemsPerSecond, progress.Eta?.TotalSeconds)); + } +} diff --git a/src/Titano.Server/Jobs/RenderNodeMonitor.cs b/src/Titano.Server/Jobs/RenderNodeMonitor.cs new file mode 100644 index 00000000..f8d5b73d --- /dev/null +++ b/src/Titano.Server/Jobs/RenderNodeMonitor.cs @@ -0,0 +1,72 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; +using Titano.Server.Configuration; +using Titano.Server.Events; + +namespace Titano.Server.Jobs; + +/// +/// Marks render nodes offline when they miss heartbeats for and gives +/// their running jobs back to the queue for another node; a job that lost its node times fails. +/// +public sealed class RenderNodeMonitor(TitanoDatabase db, ServerOptions options, JobEngineHost jobs, EventHub events, TimeProvider time, + ILogger logger) : BackgroundService +{ + public const int MaxAttempts = 5; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var interval = TimeSpan.FromSeconds(Math.Clamp(options.NodeTimeoutSeconds / 3.0, 1, 30)); + while (!stoppingToken.IsCancellationRequested) + { + try + { + await SweepAsync(stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, "Render node check failed"); + } + try + { + await Task.Delay(interval, time, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } + + /// One pass: silent nodes go offline and their jobs are requeued (or failed after too many attempts). + public async Task SweepAsync(CancellationToken cancellationToken) + { + var silentSince = time.GetUtcNow() - TimeSpan.FromSeconds(options.NodeTimeoutSeconds); + foreach (var node in await db.RenderNodes.ListSilentAsync(silentSince, RenderNodeService.Offline, cancellationToken)) + { + await db.RenderNodes.SetStateAsync(node.Id, RenderNodeService.Offline, cancellationToken); + events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline)); + var key = RenderNodeService.NodeKey(node); + var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken); + foreach (var job in lost) + { + var line = RenderNodeService.AppendLog(job.LogTail, $"Render node {node.ClientName} stopped responding."); + if (job.Attempts >= MaxAttempts) + { + await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken); + } + else + { + await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken); + } + } + var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken); + logger.LogWarning("Render node {Node} is offline; {Count} job(s) back in the queue", node.ClientName, requeued); + foreach (var job in lost) + { + if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current); + } + } + } +} diff --git a/src/Titano.Server/Jobs/RenderNodeService.cs b/src/Titano.Server/Jobs/RenderNodeService.cs new file mode 100644 index 00000000..1e6f5e6a --- /dev/null +++ b/src/Titano.Server/Jobs/RenderNodeService.cs @@ -0,0 +1,240 @@ +using System.Globalization; +using System.Text.Json; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; +using Titano.Server.Events; +using Titano.Server.Security; +using Titano.Server.Storage; +using UploadState = Titano.Data.Repositories.UploadState; + +namespace Titano.Server.Jobs; + +/// +/// Render nodes (BRIEF §14.7): clients with the render-node right register their encoders, heartbeat, claim queued +/// render jobs they can encode, report progress, and upload the output in resumable chunks that become a render of +/// the sequence. A node that stops heart-beating loses its jobs to the queue (). +/// +public sealed class RenderNodeService( + TitanoDatabase db, + ServerOptions options, + UploadService uploads, + UploadStore store, + RenderStore renders, + JobEngineHost jobs, + EventHub events, + TimeProvider time) +{ + public const string Idle = "idle"; + public const string Busy = "busy"; + public const string Offline = "offline"; + private const int LogTailLines = 40; + + public async Task> RegisterAsync(Caller caller, RegisterNodeRequest request, CancellationToken cancellationToken) + { + var name = request.ClientName?.Trim(); + if (string.IsNullOrEmpty(name) || name.Length > 100) return Outcome.Fail(400, "bad_request", "clientName"); + if (request.Encoders is null || request.Encoders.Count > 64 || request.Encoders.Any(e => string.IsNullOrWhiteSpace(e?.Codec))) + return Outcome.Fail(400, "bad_request", "encoders"); + + var existing = (await db.RenderNodes.ListAsync(cancellationToken)).FirstOrDefault(n => n.UserId == caller.Id && n.ClientName == name); + var id = existing?.Id ?? Guid.CreateVersion7(); + var running = await db.Jobs.ListRunningByNodeAsync(id.ToString(), cancellationToken); + var node = new RenderNode + { + Id = id, + UserId = caller.Id, + ClientName = name, + CapabilitiesJson = JsonSerializer.Serialize(request with { ClientName = name }, ProtocolJson.Default.RegisterNodeRequest), + LastHeartbeat = time.GetUtcNow(), + State = running.Count > 0 ? Busy : Idle, + }; + await db.RenderNodes.RegisterAsync(node, cancellationToken); + events.Publish(new NodeStateEvent(node.Id, node.ClientName, node.State)); + return Dto.Node(node, caller.User.Username); + } + + public async Task> HeartbeatAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + await TouchAsync(node, cancellationToken); + return true; + } + + /// The next queued render job this node can encode (highest priority, then oldest), or null when none fits. + public async Task> ClaimAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + var capabilities = Dto.Capabilities(node); + foreach (var queued in await db.Jobs.ListQueuedAsync(JobKind.Render, 50, cancellationToken)) + { + if (JobEndpoints.ParseRender(queued.ParametersJson) is not { } parameters || capabilities is null || !CanEncode(capabilities, parameters)) continue; + if (await db.Jobs.TryClaimAsync(queued.Id, NodeKey(node), cancellationToken) is not { } job) continue; + jobs.Publish(job); + if (job.TargetIds.Count != 1 || await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken) is not { } sequence) + { + await FinishAsync(node, job, JobState.Failed, "The sequence no longer exists.", cancellationToken); + continue; + } + await TouchAsync(node, cancellationToken); + return new ClaimedJob(Dto.Job(job), sequence.Id, parameters.SettingsJson ?? sequence.SettingsJson ?? "{}", parameters.PresetJson, + parameters.UseProxies, await ManifestFramesAsync(sequence, cancellationToken)); + } + await TouchAsync(node, cancellationToken); + return (ClaimedJob?)null; + } + + public async Task> ProgressAsync(Caller caller, Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + if (await AssignedJobAsync(node, jobId, cancellationToken) is not { } job) return Outcome.Fail(409, "job_not_assigned"); + double? eta = progress.ItemsPerSecond is > 0 && progress.Total > progress.Done ? (progress.Total - progress.Done) / progress.ItemsPerSecond.Value : null; + var tail = AppendLog(job.LogTail, progress.LogLine); + if (!await db.Jobs.UpdateNodeProgressAsync(jobId, NodeKey(node), progress.Done, progress.Total, progress.ItemsPerSecond, + eta is { } seconds ? TimeSpan.FromSeconds(seconds) : null, tail, cancellationToken)) + return Outcome.Fail(409, "job_not_assigned"); + await TouchAsync(node, cancellationToken); + events.Publish(new JobProgressEvent(jobId, progress.Done, progress.Total, progress.ItemsPerSecond, eta)); + return true; + } + + public async Task> FailAsync(Caller caller, Guid nodeId, Guid jobId, NodeJobFailure failure, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + if (await AssignedJobAsync(node, jobId, cancellationToken) is not { } job) return Outcome.Fail(409, "job_not_assigned"); + var error = string.IsNullOrWhiteSpace(failure.Error) ? "Render failed on the node." : failure.Error.Trim()[..Math.Min(failure.Error.Trim().Length, 500)]; + return await FinishAsync(node, job, JobState.Failed, error, cancellationToken) ? true : Outcome.Fail(409, "job_not_assigned"); + } + + /// Starts (or resumes) the chunked upload of a job's output. + public async Task> StartResultAsync(Caller caller, Guid nodeId, Guid jobId, RenderResultRequest request, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + if (await AssignedJobAsync(node, jobId, cancellationToken) is not { } job) return Outcome.Fail(409, "job_not_assigned"); + if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome.Fail(400, "invalid_file_name"); + if (!UploadRules.IsSha256(request.Sha256)) return Outcome.Fail(400, "invalid_hash"); + if (request.Size <= 0) return Outcome.Fail(400, "bad_request", "size"); + if (request.Size > options.MaxUploadBytes) + return Outcome.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture)); + if (string.IsNullOrWhiteSpace(request.PresetName)) return Outcome.Fail(400, "bad_request", "presetName"); + + var sha = request.Sha256.ToLowerInvariant(); + if (await db.Uploads.FindByJobAsync(jobId, cancellationToken) is { State: UploadState.Receiving } open && open.Sha256 == sha && open.Size == request.Size + && store.Exists(open.Id)) + return Started(open); + if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome.Fail(507, "insufficient_storage"); + + var now = time.GetUtcNow(); + var upload = await db.Uploads.CreateAsync(new Upload + { + Id = Guid.CreateVersion7(), + UserId = caller.Id, + SequenceId = job.TargetIds.Count == 1 ? job.TargetIds[0] : null, + FileName = fileName, + Size = request.Size, + Sha256 = sha, + ChunkSize = options.ChunkSizeBytes, + State = UploadState.Receiving, + Created = now, + UpdatedAt = now, + JobId = jobId, + RenderJson = JsonSerializer.Serialize(request with { FileName = fileName, Sha256 = sha }, ProtocolJson.Default.RenderResultRequest), + }, cancellationToken); + store.Create(upload.Id, upload.Size); + return Started(upload); + } + + /// Verifies the uploaded output, files it as a render of the sequence and marks the job done. + public async Task> CompleteResultAsync(Caller caller, Guid nodeId, Guid jobId, CancellationToken cancellationToken) + { + if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome.Fail(404, "not_found", "node"); + if (await AssignedJobAsync(node, jobId, cancellationToken) is not { } job) return Outcome.Fail(409, "job_not_assigned"); + var upload = await db.Uploads.FindByJobAsync(jobId, cancellationToken); + if (upload is not { State: UploadState.Receiving } || upload.RenderJson is null) return Outcome.Fail(409, "upload_state"); + if (!upload.IsComplete) + return Outcome.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture)); + if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken)) + return Outcome.Fail(409, "upload_state"); + + if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome.Fail(422, "hash_mismatch"); + var output = JsonSerializer.Deserialize(upload.RenderJson, ProtocolJson.Default.RenderResultRequest)!; + var sequence = await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken); + var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken); + if (render is null) + { + UploadStore.TryDelete(staged); + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None); + store.Delete(upload.Id); + await FinishAsync(node, job, JobState.Failed, "The sequence has no folder in the archive.", CancellationToken.None); + return Outcome.Fail(409, "upload_state", "sequence"); + } + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, cancellationToken: CancellationToken.None); + store.Delete(upload.Id); + await FinishAsync(node, job, JobState.Done, null, CancellationToken.None); + if (await db.Sequences.GetAsync(sequence!.Id, CancellationToken.None) is { } updated) + events.Publish(new SequenceChangedEvent(updated.Id, "renders", updated.FramesVersion, updated.SettingsVersion)); + return Dto.Render(render); + } + + /// Running-job owner key stored in jobs.node_id. + public static string NodeKey(RenderNode node) => node.Id.ToString(); + + private async Task OwnedNodeAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) => + await db.RenderNodes.GetAsync(nodeId, cancellationToken) is { } node && node.UserId == caller.Id ? node : null; + + private async Task AssignedJobAsync(RenderNode node, Guid jobId, CancellationToken cancellationToken) => + await db.Jobs.GetAsync(jobId, cancellationToken) is { State: JobState.Running } job && job.NodeId == NodeKey(node) ? job : null; + + private async Task FinishAsync(RenderNode node, Job job, JobState state, string? error, CancellationToken cancellationToken) + { + var tail = error is null ? null : AppendLog(job.LogTail, error); + if (!await db.Jobs.FinishNodeJobAsync(job.Id, NodeKey(node), state, error, tail, cancellationToken)) return false; + if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } finished) jobs.Publish(finished); + await TouchAsync(node, cancellationToken); + return true; + } + + /// Records a sign of life and publishes the node's state when it changed. + private async Task TouchAsync(RenderNode node, CancellationToken cancellationToken) + { + var state = (await db.Jobs.ListRunningByNodeAsync(NodeKey(node), cancellationToken)).Count > 0 ? Busy : Idle; + await db.RenderNodes.HeartbeatAsync(node.Id, state, time.GetUtcNow(), cancellationToken); + if (state != node.State) events.Publish(new NodeStateEvent(node.Id, node.ClientName, state)); + } + + private async Task> ManifestFramesAsync(Sequence sequence, CancellationToken cancellationToken) + { + var hasProxy = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt); + var hasThumb = sequence.Status.HasFlag(SequenceStatus.ThumbsBuilt); + var frames = new List(sequence.FrameCount); + var after = -1; + while (true) + { + var batch = await db.Frames.ListBySequenceAsync(sequence.Id, after, 1000, cancellationToken); + frames.AddRange(batch.Where(f => !f.Flags.HasFlag(FrameFlags.Excluded)) + .Select(f => new ManifestFrame(f.Id, f.Index, f.FileName, f.Size, f.Sha256 ?? string.Empty, hasProxy, hasThumb))); + if (batch.Count < 1000) return frames; + after = batch[^1].Index; + } + } + + /// The node has an encoder for the job's codec and handles its resolution (0 = no announced limit). + private static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) => + node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase)) + && (node.MaxWidth <= 0 || job.Width <= node.MaxWidth) + && (node.MaxHeight <= 0 || job.Height <= node.MaxHeight); + + internal static string? AppendLog(string? tail, string? line) + { + if (string.IsNullOrWhiteSpace(line)) return tail; + var lines = (tail ?? string.Empty).Split('\n', StringSplitOptions.RemoveEmptyEntries).ToList(); + lines.Add(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:HH:mm:ss} {line.Trim()[..Math.Min(line.Trim().Length, 300)]}")); + return string.Join('\n', lines.TakeLast(LogTailLines)); + } + + private static StartUploadResponse Started(Upload upload) => + new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null); +} diff --git a/src/Titano.Server/Jobs/SequenceJobs.cs b/src/Titano.Server/Jobs/SequenceJobs.cs new file mode 100644 index 00000000..f53c962f --- /dev/null +++ b/src/Titano.Server/Jobs/SequenceJobs.cs @@ -0,0 +1,32 @@ +using Titano.Core.Model; +using Titano.Data; + +namespace Titano.Server.Jobs; + +/// +/// Follow-up work after frames arrive (BRIEF §14.4): thumbnails, proxies and light analysis of the sequence, queued at +/// background priority once per sequence while one is still waiting, and only for kinds this server can run. +/// +public sealed class SequenceJobs(TitanoDatabase db, JobEngineHost jobs) +{ + private static readonly JobKind[] AfterNewFrames = [JobKind.Thumbs, JobKind.Proxies, JobKind.LightAnalyse]; + + private readonly SemaphoreSlim _gate = new(1, 1); + + public async Task FramesAddedAsync(Sequence sequence, CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken); + try + { + foreach (var kind in AfterNewFrames) + { + if (!jobs.CanRun(kind) || await db.Jobs.IsQueuedAsync(kind, sequence.Id, cancellationToken)) continue; + await jobs.Engine.EnqueueAsync(kind, [sequence.Id], sequence.DisplayTitle, priority: JobPriority.Background, cancellationToken: cancellationToken); + } + } + finally + { + _gate.Release(); + } + } +} diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs index 9bfebd2c..bb9e439f 100644 --- a/src/Titano.Server/Program.cs +++ b/src/Titano.Server/Program.cs @@ -1,11 +1,53 @@ +using System.ComponentModel; using Titano.Server.Configuration; using Titano.Server.Hosting; +using Titano.Server.Hosting.Windows; -if (args.Contains("--healthcheck")) return await HealthProbe.RunAsync(); +var command = ServerCommandLine.Parse(args); +if (command.Error is not null) +{ + await Console.Error.WriteLineAsync(command.Error); + return 2; +} -var app = ServerHost.Build(ServerOptions.Load(), args); -await app.RunAsync(); -return 0; +switch (command.Command) +{ + case ServerCommand.Help: + Console.WriteLine(ServerCommandLine.Usage); + return 0; + case ServerCommand.HealthCheck: + return await HealthProbe.RunAsync(); + case ServerCommand.Service or ServerCommand.InstallService or ServerCommand.UninstallService when !OperatingSystem.IsWindows(): + await Console.Error.WriteLineAsync("Windows services are available on Windows only."); + return 2; + case ServerCommand.InstallService when OperatingSystem.IsWindows(): + return ServiceAction(ServiceInstaller.Install, $"Installed the {WindowsServiceHost.ServiceName} service."); + case ServerCommand.UninstallService when OperatingSystem.IsWindows(): + return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service."); + case ServerCommand.Service when OperatingSystem.IsWindows(): + if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments]))) return 0; + await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start TitanoServer'."); + return 1; + default: + var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments]); + await app.RunAsync(); + return 0; +} + +static int ServiceAction(Action action, string done) +{ + try + { + action(); + Console.WriteLine(done); + return 0; + } + catch (Win32Exception ex) + { + Console.Error.WriteLine(ex.Message); + return 1; + } +} /// Entry point type, visible to the in-process test host. public partial class Program; diff --git a/src/Titano.Server/Security/AccessRule.cs b/src/Titano.Server/Security/AccessRule.cs new file mode 100644 index 00000000..923829a7 --- /dev/null +++ b/src/Titano.Server/Security/AccessRule.cs @@ -0,0 +1,38 @@ +using Titano.Core.Model; + +namespace Titano.Server.Security; + +/// +/// Endpoint metadata read by . Every /api endpoint requires a signed-in +/// caller unless it carries ; the most specific rule (endpoint over group) wins whole. +/// +public sealed class AccessRule +{ + public static readonly AccessRule Anonymous = new() { AllowAnonymous = true }; + + public static readonly AccessRule SignedIn = new(); + + public bool AllowAnonymous { get; private init; } + + /// The caller needs at least one of these permissions; = any signed-in caller. + public Permissions AnyOf { get; private init; } + + /// Reachable while the account must still replace its temporary password (me, password, logout). + public bool DuringPasswordChange { get; private init; } + + public static AccessRule Requiring(Permissions anyOf) => new() { AnyOf = anyOf }; + + public static AccessRule PasswordChange { get; } = new() { DuringPasswordChange = true }; +} + +public static class AccessRuleExtensions +{ + public static TBuilder AllowAnonymousCaller(this TBuilder builder) where TBuilder : IEndpointConventionBuilder => + builder.WithMetadata(AccessRule.Anonymous); + + public static TBuilder Requires(this TBuilder builder, Permissions anyOf) where TBuilder : IEndpointConventionBuilder => + builder.WithMetadata(AccessRule.Requiring(anyOf)); + + public static TBuilder AllowDuringPasswordChange(this TBuilder builder) where TBuilder : IEndpointConventionBuilder => + builder.WithMetadata(AccessRule.PasswordChange); +} diff --git a/src/Titano.Server/Security/Accounts.cs b/src/Titano.Server/Security/Accounts.cs new file mode 100644 index 00000000..96ce6969 --- /dev/null +++ b/src/Titano.Server/Security/Accounts.cs @@ -0,0 +1,35 @@ +using Titano.Core.Model; + +namespace Titano.Server.Security; + +/// Account rules shared by bootstrap, sign-in and user management. +public static class Accounts +{ + public const int MaxUsernameLength = 64; + + /// Letters, digits, dot, dash and underscore; 1–64 characters. + public static bool IsValidUsername(string? name) => + name is { Length: > 0 and <= MaxUsernameLength } && name.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_'); + + /// The case-insensitive key of a user name (lock-out bookkeeping). + public static string Key(string? name) => (name ?? string.Empty).Trim().ToLowerInvariant(); + + /// The role's default permissions with the render-node right granted or withheld explicitly. + public static Permissions PermissionsFor(UserRole role, bool renderNode) => + (RolePermissions.Default(role) & ~Permissions.RenderNode) | (renderNode ? Permissions.RenderNode : Permissions.None); + + /// Parses a role name (admin, editor, uploader, viewer); numbers are not accepted. + public static bool TryParseRole(string? text, out UserRole role) + { + foreach (var candidate in Enum.GetValues()) + { + if (string.Equals(candidate.ToString(), text, StringComparison.OrdinalIgnoreCase)) + { + role = candidate; + return true; + } + } + role = default; + return false; + } +} diff --git a/src/Titano.Server/Security/AdminBootstrap.cs b/src/Titano.Server/Security/AdminBootstrap.cs new file mode 100644 index 00000000..027c94ef --- /dev/null +++ b/src/Titano.Server/Security/AdminBootstrap.cs @@ -0,0 +1,85 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Server.Configuration; + +namespace Titano.Server.Security; + +/// +/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from +/// TITANO_ADMIN_USER/TITANO_ADMIN_PASSWORD and must change its password at first sign-in. Without a +/// configured password a temporary one is generated and written to /data/initial-admin-password.txt (owner-only), +/// never to the log; the file is removed once an administrator changes their password. +/// +public static class AdminBootstrap +{ + public const string DefaultUsername = "admin"; + private const string PasswordFileName = "initial-admin-password.txt"; + + public static async Task RunAsync(TitanoDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken) + { + var users = await db.Users.ListAsync(cancellationToken).ConfigureAwait(false); + if (users.Any(u => u.Role == UserRole.Admin)) + { + if (!string.IsNullOrEmpty(options.AdminPassword)) + logger.LogInformation("An administrator exists; TITANO_ADMIN_USER and TITANO_ADMIN_PASSWORD are ignored"); + return; + } + + var username = string.IsNullOrWhiteSpace(options.AdminUser) ? DefaultUsername : options.AdminUser.Trim(); + if (!Accounts.IsValidUsername(username)) + throw new InvalidOperationException("TITANO_ADMIN_USER may only contain letters, digits, dot, dash and underscore (up to 64 characters)."); + if (users.Any(u => Accounts.Key(u.Username) == Accounts.Key(username))) + throw new InvalidOperationException($"No administrator exists and TITANO_ADMIN_USER '{username}' names an existing account; choose another name."); + + var password = options.AdminPassword; + string? passwordFile = null; + if (string.IsNullOrEmpty(password)) + { + password = TemporaryPassword.Generate(); + passwordFile = Path.Combine(options.DataPath, PasswordFileName); + await File.WriteAllTextAsync(passwordFile, password + Environment.NewLine, cancellationToken).ConfigureAwait(false); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(passwordFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + + var admin = new User + { + Id = Guid.CreateVersion7(), + Username = username, + DisplayName = null, + PasswordHash = PasswordHasher.Hash(password), + Role = UserRole.Admin, + Permissions = Permissions.All, + MustChangePassword = true, + Created = time.GetUtcNow(), + }; + await db.Users.CreateAsync(admin, cancellationToken).ConfigureAwait(false); + await db.Audit.AppendAsync(new AuditEntry + { + Id = Guid.CreateVersion7(), + At = admin.Created, + Action = "user_created", + TargetKind = "user", + TargetId = admin.Id.ToString(), + Details = "admin", + Username = username, + }, cancellationToken).ConfigureAwait(false); + + if (passwordFile is null) + logger.LogWarning("Created administrator '{User}' from TITANO_ADMIN_USER/TITANO_ADMIN_PASSWORD; the password must be changed at first sign-in", username); + else + logger.LogWarning("Created administrator '{User}'; its temporary password is in {File} and must be changed at first sign-in", username, passwordFile); + } + + /// Removes the generated password file (called when an administrator sets their own password). + public static void ForgetInitialPassword(ServerOptions options) + { + try + { + File.Delete(Path.Combine(options.DataPath, PasswordFileName)); + } + catch (IOException) + { + // Best effort: the file holds a password that no longer works. + } + } +} diff --git a/src/Titano.Server/Security/AuditLog.cs b/src/Titano.Server/Security/AuditLog.cs new file mode 100644 index 00000000..7afadcca --- /dev/null +++ b/src/Titano.Server/Security/AuditLog.cs @@ -0,0 +1,26 @@ +using Titano.Core.Model; +using Titano.Data; + +namespace Titano.Server.Security; + +/// Appends who did what to the audit log (BRIEF §14.2): sign-ins, user, sequence, archive and setting changes. +public sealed class AuditLog(TitanoDatabase db, TimeProvider time) +{ + public Task WriteAsync(Caller caller, HttpContext context, string action, string? targetKind = null, string? targetId = null, string? details = null) => + WriteAsync(caller.Id, caller.User.Username, context, action, targetKind, targetId, details); + + public Task WriteAsync(Guid? userId, string? username, HttpContext? context, string action, string? targetKind = null, string? targetId = null, + string? details = null) => + db.Audit.AppendAsync(new AuditEntry + { + Id = Guid.CreateVersion7(), + At = time.GetUtcNow(), + UserId = userId, + Username = username, + Action = action, + TargetKind = targetKind, + TargetId = targetId, + Details = details, + RemoteAddress = context?.Connection.RemoteIpAddress?.ToString(), + }); +} diff --git a/src/Titano.Server/Security/AuthenticationMiddleware.cs b/src/Titano.Server/Security/AuthenticationMiddleware.cs new file mode 100644 index 00000000..b0e18541 --- /dev/null +++ b/src/Titano.Server/Security/AuthenticationMiddleware.cs @@ -0,0 +1,79 @@ +using Titano.Core.Model; +using Titano.Server.Api; + +namespace Titano.Server.Security; + +/// +/// Resolves the caller of every /api request (bearer token or admin cookie) and enforces the endpoint's +/// : 401 without a valid token, 403 for a missing permission, a missing CSRF header on a +/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. +/// +public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens) +{ + public async Task InvokeAsync(HttpContext context) + { + var rule = context.GetEndpoint()?.Metadata.GetMetadata(); + if (rule is null && !context.Request.Path.StartsWithSegments("/api")) + { + await next(context); + return; + } + rule ??= AccessRule.SignedIn; + if (rule.AllowAnonymous) + { + await next(context); + return; + } + + var caller = await AuthenticateAsync(context); + if (caller is null) + { + context.Response.Headers.WWWAuthenticate = "Bearer"; + await ApiErrors.WriteAsync(context, StatusCodes.Status401Unauthorized, "unauthorized"); + return; + } + if (caller.Source == CredentialSource.Cookie && !IsSameSiteRequest(context, caller)) + { + await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "csrf_failed"); + return; + } + if (caller.User.MustChangePassword && !rule.DuringPasswordChange) + { + await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "password_change_required"); + return; + } + if (rule.AnyOf != Permissions.None && !caller.Has(rule.AnyOf)) + { + await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "forbidden"); + return; + } + context.Features.Set(caller); + await next(context); + } + + private Task AuthenticateAsync(HttpContext context) + { + var authorization = context.Request.Headers.Authorization.ToString(); + if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + return tokens.ValidateAsync(authorization[7..].Trim(), CredentialSource.Bearer, context.RequestAborted); + if (context.Request.Cookies.TryGetValue(SessionCookies.Session, out var cookie)) + return tokens.ValidateAsync(cookie, CredentialSource.Cookie, context.RequestAborted); + return Task.FromResult(null); + } + + /// + /// Cookie requests must prove they come from the admin panel: unsafe methods carry the CSRF header, WebSocket + /// upgrades (which cannot) must come from this origin. + /// + private static bool IsSameSiteRequest(HttpContext context, Caller caller) + { + if (context.WebSockets.IsWebSocketRequest) + { + var origin = context.Request.Headers.Origin.ToString(); + return origin.Equals($"{context.Request.Scheme}://{context.Request.Host}", StringComparison.OrdinalIgnoreCase); + } + var method = context.Request.Method; + if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method)) return true; + return SessionCookies.HasValidCsrf(context, caller); + } +} diff --git a/src/Titano.Server/Security/LoginGuard.cs b/src/Titano.Server/Security/LoginGuard.cs new file mode 100644 index 00000000..8e1e49f9 --- /dev/null +++ b/src/Titano.Server/Security/LoginGuard.cs @@ -0,0 +1,92 @@ +using Titano.Server.Configuration; + +namespace Titano.Server.Security; + +/// +/// Sign-in throttling (BRIEF §14.2): at most attempts per client +/// address and minute, and an account name locked for after +/// consecutive failures. Names without an account are tracked the same +/// way, so a lockout reveals nothing about which names exist. State is per process and resets at restart. +/// +public sealed class LoginGuard(ServerOptions options, TimeProvider time) +{ + private static readonly TimeSpan Window = TimeSpan.FromMinutes(1); + private const int PruneAbove = 10_000; + + private readonly Lock _gate = new(); + private readonly Dictionary> _attempts = new(StringComparer.Ordinal); + private readonly Dictionary _accounts = new(StringComparer.Ordinal); + + /// Counts an attempt from ; false, with the time to wait, once its budget is spent. + public bool TryAttempt(string address, out TimeSpan retryAfter) + { + var now = time.GetUtcNow(); + lock (_gate) + { + if (_attempts.Count > PruneAbove) Prune(now); + if (!_attempts.TryGetValue(address, out var recent)) _attempts[address] = recent = new Queue(); + while (recent.Count > 0 && now - recent.Peek() >= Window) recent.Dequeue(); + if (recent.Count >= options.LoginAttemptsPerMinute) + { + retryAfter = Window - (now - recent.Peek()); + return false; + } + recent.Enqueue(now); + retryAfter = TimeSpan.Zero; + return true; + } + } + + /// True while (a normalised user name) is locked. + public bool IsLocked(string account, out TimeSpan retryAfter) + { + var now = time.GetUtcNow(); + lock (_gate) + { + if (_accounts.TryGetValue(account, out var state) && state.LockedUntil is { } until && until > now) + { + retryAfter = until - now; + return true; + } + retryAfter = TimeSpan.Zero; + return false; + } + } + + public void RecordFailure(string account) + { + var now = time.GetUtcNow(); + var span = TimeSpan.FromMinutes(options.LockoutMinutes); + lock (_gate) + { + if (_accounts.Count > PruneAbove) Prune(now); + var state = _accounts.GetValueOrDefault(account); + if (state?.LockedUntil is { } until && until > now) return; + if (state is null || state.LockedUntil is not null || now - state.FirstFailure > span) state = new AccountState(0, now, null); + var failures = state.Failures + 1; + _accounts[account] = failures >= options.LockoutThreshold + ? new AccountState(0, now, now + span) + : state with { Failures = failures }; + } + } + + public void RecordSuccess(string account) + { + lock (_gate) _accounts.Remove(account); + } + + private void Prune(DateTimeOffset now) + { + foreach (var (address, recent) in _attempts.ToList()) + { + if (recent.Count == 0 || now - recent.Last() >= Window) _attempts.Remove(address); + } + var span = TimeSpan.FromMinutes(options.LockoutMinutes); + foreach (var (account, state) in _accounts.ToList()) + { + if ((state.LockedUntil ?? state.FirstFailure + span) < now) _accounts.Remove(account); + } + } + + private sealed record AccountState(int Failures, DateTimeOffset FirstFailure, DateTimeOffset? LockedUntil); +} diff --git a/src/Titano.Server/Security/PasswordHasher.cs b/src/Titano.Server/Security/PasswordHasher.cs new file mode 100644 index 00000000..5f66b357 --- /dev/null +++ b/src/Titano.Server/Security/PasswordHasher.cs @@ -0,0 +1,69 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Server.Security; + +/// +/// Password hashes (BRIEF §14.2): PBKDF2-SHA512, 210,000 iterations, 16-byte random salt per hash, stored as +/// pbkdf2-sha512$<iterations>$<salt>$<hash> (base64). The format names its algorithm and cost, so +/// older hashes keep verifying and are upgraded at the next sign-in. +/// +public static class PasswordHasher +{ + public const int MinimumLength = 10; + public const int Iterations = 210_000; + private const string Algorithm = "pbkdf2-sha512"; + private const int SaltBytes = 16; + private const int HashBytes = 64; + + /// Verified against unknown user names so a miss costs as much time as a wrong password. + private static readonly Lazy DummyHash = new(() => Hash(Convert.ToBase64String(RandomNumberGenerator.GetBytes(18)))); + + public static string Hash(string password) + { + var salt = RandomNumberGenerator.GetBytes(SaltBytes); + var hash = Derive(password, salt, Iterations); + return string.Create(CultureInfo.InvariantCulture, $"{Algorithm}${Iterations}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}"); + } + + /// Constant-time check of against a stored hash; malformed hashes never match. + public static bool Verify(string password, string storedHash) + { + var parts = storedHash.Split('$'); + if (parts.Length != 4 || parts[0] != Algorithm + || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var iterations) || iterations < 1) + return false; + byte[] salt, expected; + try + { + salt = Convert.FromBase64String(parts[2]); + expected = Convert.FromBase64String(parts[3]); + } + catch (FormatException) + { + return false; + } + if (salt.Length == 0 || expected.Length == 0) return false; + var actual = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, expected.Length); + return CryptographicOperations.FixedTimeEquals(actual, expected); + } + + /// Spends the same time as for a name that has no account. + public static void VerifyDummy(string password) => Verify(password, DummyHash.Value); + + /// True when the hash was made with fewer iterations than the current policy. + public static bool NeedsRehash(string storedHash) + { + var parts = storedHash.Split('$'); + return parts.Length != 4 || parts[0] != Algorithm + || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var iterations) || iterations < Iterations; + } + + /// Policy check for passwords users choose: at least characters, not only spaces. + public static bool IsAcceptable(string? password) => + password is not null && password.Length >= MinimumLength && !string.IsNullOrWhiteSpace(password); + + private static byte[] Derive(string password, byte[] salt, int iterations) => + Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, HashBytes); +} diff --git a/src/Titano.Server/Security/SessionCookies.cs b/src/Titano.Server/Security/SessionCookies.cs new file mode 100644 index 00000000..8e49a4df --- /dev/null +++ b/src/Titano.Server/Security/SessionCookies.cs @@ -0,0 +1,55 @@ +using System.Buffers.Text; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Server.Security; + +/// +/// The web admin's cookie session (BRIEF §14.2): the token in an HttpOnly; Secure; SameSite=Strict cookie, plus a +/// script-readable CSRF cookie whose value must come back in on every unsafe request. The CSRF +/// value is derived from the session token, so a planted cookie pair cannot forge it. +/// +public static class SessionCookies +{ + public const string Session = "titano_session"; + public const string Csrf = "titano_csrf"; + public const string CsrfHeader = "X-CSRF-Token"; + + public static void Issue(HttpContext context, IssuedToken token) + { + context.Response.Cookies.Append(Session, token.Secret, Options(httpOnly: true)); + context.Response.Cookies.Append(Csrf, CsrfFor(token.Stored.TokenHash), Options(httpOnly: false)); + } + + public static void Clear(HttpContext context) + { + context.Response.Cookies.Delete(Session, Options(httpOnly: true)); + context.Response.Cookies.Delete(Csrf, Options(httpOnly: false)); + } + + /// Constant-time check of the request's CSRF header against the caller's session. + public static bool HasValidCsrf(HttpContext context, Caller caller) + { + var header = context.Request.Headers[CsrfHeader].ToString(); + var expected = CsrfFor(caller.TokenHash); + return header.Length == expected.Length + && CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(header), Encoding.ASCII.GetBytes(expected)); + } + + /// Secure cookies only travel over HTTPS (or to the machine itself, which browsers treat as secure). + public static bool IsSecureTransport(HttpContext context) => + context.Request.IsHttps || (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)); + + private static string CsrfFor(string tokenHash) => + Base64Url.EncodeToString(SHA256.HashData(Encoding.UTF8.GetBytes("titano-csrf|" + tokenHash))); + + private static CookieOptions Options(bool httpOnly) => new() + { + HttpOnly = httpOnly, + Secure = true, + SameSite = SameSiteMode.Strict, + Path = "/", + IsEssential = true, + }; +} diff --git a/src/Titano.Server/Security/TemporaryPassword.cs b/src/Titano.Server/Security/TemporaryPassword.cs new file mode 100644 index 00000000..bf6874f1 --- /dev/null +++ b/src/Titano.Server/Security/TemporaryPassword.cs @@ -0,0 +1,15 @@ +using System.Security.Cryptography; + +namespace Titano.Server.Security; + +/// One-time passwords for new accounts and resets: three groups of four unambiguous characters (≈ 70 bits). +public static class TemporaryPassword +{ + private const string Alphabet = "abcdefghjkmnpqrstuvwxyz23456789"; + + public static string Generate() + { + var chars = RandomNumberGenerator.GetItems(Alphabet, 12); + return $"{new string(chars, 0, 4)}-{new string(chars, 4, 4)}-{new string(chars, 8, 4)}"; + } +} diff --git a/src/Titano.Server/Security/TokenService.cs b/src/Titano.Server/Security/TokenService.cs new file mode 100644 index 00000000..d364f51d --- /dev/null +++ b/src/Titano.Server/Security/TokenService.cs @@ -0,0 +1,91 @@ +using System.Buffers.Text; +using System.Security.Cryptography; +using System.Text; +using Titano.Core.Model; +using Titano.Data; +using Titano.Server.Configuration; + +namespace Titano.Server.Security; + +/// How a request presented its token. +public enum CredentialSource +{ + /// Authorization: Bearer (desktop client, uploader, render node). + Bearer, + + /// HttpOnly session cookie of the web admin; unsafe methods also need the CSRF header. + Cookie, +} + +/// The signed-in account behind a request. +public sealed record Caller(User User, string TokenHash, CredentialSource Source, string? ClientName) +{ + public Guid Id => User.Id; + + public bool IsAdmin => User.Role == UserRole.Admin; + + /// True when the account holds at least one of . + public bool Has(Permissions any) => (User.Permissions & any) != 0; + + /// Minimal-API binding: endpoint handlers take the caller resolved by . + public static ValueTask BindAsync(HttpContext context) => ValueTask.FromResult(context.Features.Get()); +} + +/// A freshly issued token: the secret (returned once) and what is stored (its hash). +public sealed record IssuedToken(string Secret, SessionToken Stored); + +/// +/// Opaque bearer tokens (BRIEF §14.2): 32 random bytes, stored only as their SHA-256, sliding expiry, revocation. +/// The same tokens back the admin panel's cookie session. +/// +public sealed class TokenService(TitanoDatabase db, ServerOptions options, TimeProvider time) +{ + /// Sliding expiry is written at most this often per token, not on every request. + private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1); + + private TimeSpan Lifetime => TimeSpan.FromDays(options.TokenLifetimeDays); + + public async Task IssueAsync(User user, string? clientName, CancellationToken cancellationToken) + { + var secret = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32)); + var now = time.GetUtcNow(); + var name = clientName?.Trim(); + var token = new SessionToken + { + TokenHash = HashOf(secret), + UserId = user.Id, + ClientName = string.IsNullOrEmpty(name) ? null : name[..Math.Min(name.Length, 100)], + Created = now, + Expires = now + Lifetime, + LastUsed = now, + }; + await db.Tokens.InsertAsync(token, cancellationToken).ConfigureAwait(false); + return new IssuedToken(secret, token); + } + + /// The caller a token belongs to, or null when it is unknown, revoked, expired or its account is disabled. + public async Task ValidateAsync(string secret, CredentialSource source, CancellationToken cancellationToken) + { + if (secret.Length is 0 or > 128) return null; + var hash = HashOf(secret); + var token = await db.Tokens.GetAsync(hash, cancellationToken).ConfigureAwait(false); + var now = time.GetUtcNow(); + if (token is null || token.Revoked || token.Expires <= now) return null; + var user = await db.Users.GetAsync(token.UserId, cancellationToken).ConfigureAwait(false); + if (user is null || user.Disabled) return null; + if (now - token.LastUsed >= TouchInterval && !await db.Tokens.TouchAsync(hash, now, now + Lifetime, cancellationToken).ConfigureAwait(false)) + return null; + return new Caller(user, hash, source, token.ClientName); + } + + /// True while the caller's token is still live and its account enabled (long-lived WebSocket sessions). + public async Task IsStillValidAsync(Caller caller, CancellationToken cancellationToken) + { + var token = await db.Tokens.GetAsync(caller.TokenHash, cancellationToken).ConfigureAwait(false); + if (token is null || token.Revoked || token.Expires <= time.GetUtcNow()) return false; + return await db.Users.GetAsync(caller.Id, cancellationToken).ConfigureAwait(false) is { Disabled: false }; + } + + /// Stored form of a token: lower-case hex SHA-256 of its text. + public static string HashOf(string secret) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(secret))); +} diff --git a/src/Titano.Server/Storage/ArchivePaths.cs b/src/Titano.Server/Storage/ArchivePaths.cs new file mode 100644 index 00000000..bb8e16f2 --- /dev/null +++ b/src/Titano.Server/Storage/ArchivePaths.cs @@ -0,0 +1,45 @@ +namespace Titano.Server.Storage; + +/// +/// Archive-relative paths from the database → absolute paths, refusing anything that would leave the archive root +/// (BRIEF §14.2: path traversal impossible). Clients never send paths; only ids that the database maps to these. +/// +public static class ArchivePaths +{ + private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// The absolute path of under , or null when it escapes the root. + public static string? Resolve(string root, string? relative) + { + if (string.IsNullOrWhiteSpace(relative) || relative.Contains('\0', StringComparison.Ordinal)) return null; + var portable = relative.Replace('\\', '/'); + if (Path.IsPathRooted(portable) || portable.StartsWith('/')) return null; + string full; + try + { + full = Path.GetFullPath(Path.Combine(Root(root), portable)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return null; + } + return IsInside(root, full) ? full : null; + } + + /// True when lies strictly inside . + public static bool IsInside(string root, string path) + { + var full = Path.GetFullPath(path); + return full.StartsWith(Root(root) + Path.DirectorySeparatorChar, PathComparison); + } + + /// A file of the archive that may be served: inside the root, existing, and not a symbolic link. + public static FileInfo? ExistingFile(string root, string? relative) + { + if (Resolve(root, relative) is not { } full) return null; + var file = new FileInfo(full); + return file.Exists && file.LinkTarget is null ? file : null; + } + + private static string Root(string root) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); +} diff --git a/src/Titano.Server/Storage/FileResponses.cs b/src/Titano.Server/Storage/FileResponses.cs new file mode 100644 index 00000000..c105d428 --- /dev/null +++ b/src/Titano.Server/Storage/FileResponses.cs @@ -0,0 +1,123 @@ +using System.Collections.Frozen; +using Microsoft.Net.Http.Headers; + +namespace Titano.Server.Storage; + +/// Streams archive files (originals, proxies, thumbnails, exports) with Range, If-Range and conditional GET support. +public static class FileResponses +{ + private static readonly FrozenDictionary Types = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [".jpg"] = "image/jpeg", + [".jpeg"] = "image/jpeg", + [".png"] = "image/png", + [".gif"] = "image/gif", + [".tif"] = "image/tiff", + [".tiff"] = "image/tiff", + [".dng"] = "image/x-adobe-dng", + [".heic"] = "image/heic", + [".heif"] = "image/heif", + [".webp"] = "image/webp", + [".avif"] = "image/avif", + [".mp4"] = "video/mp4", + [".mov"] = "video/quicktime", + [".avi"] = "video/x-msvideo", + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + public static string ContentTypeOf(string fileName) => + Types.TryGetValue(Path.GetExtension(fileName), out var type) ? type : "application/octet-stream"; + + /// + /// The byte range [, offset + ) of as a + /// range-capable response; null when the range does not fit the file (the asset changed under the index). + /// + public static IResult? Serve(HttpContext context, FileInfo file, long offset, long length, string contentType, string cacheControl, + string? etag = null, string? downloadName = null) + { + if (offset < 0 || length < 0 || offset > file.Length - length) return null; + context.Response.Headers.CacheControl = cacheControl; + return Results.Stream(new FileSlice(file.FullName, offset, length), contentType, downloadName, file.LastWriteTimeUtc, + etag is null ? null : new EntityTagHeaderValue("\"" + etag + "\""), enableRangeProcessing: true); + } + + /// Read-only, seekable view of part of a file (one thumbnail inside a pack, or the whole file). + private sealed class FileSlice : Stream + { + private readonly FileStream _file; + private readonly long _offset; + private readonly long _length; + private long _position; + + public FileSlice(string path, long offset, long length) + { + _file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); + _offset = offset; + _length = length; + } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => _length; + + public override long Position + { + get => _position; + set => _position = Math.Clamp(value, 0, _length); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var count = Available(buffer.Length); + if (count == 0) return 0; + _file.Position = _offset + _position; + var read = _file.Read(buffer[..count]); + _position += read; + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var count = Available(buffer.Length); + if (count == 0) return 0; + _file.Position = _offset + _position; + var read = await _file.ReadAsync(buffer[..count], cancellationToken).ConfigureAwait(false); + _position += read; + return read; + } + + public override long Seek(long offset, SeekOrigin origin) => Position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => _length + offset, + }; + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _file.Dispose(); + base.Dispose(disposing); + } + + public override async ValueTask DisposeAsync() + { + await _file.DisposeAsync().ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); + } + + private int Available(int requested) => (int)Math.Min(requested, _length - _position); + } +} diff --git a/src/Titano.Server/Storage/IFrameAssetLocator.cs b/src/Titano.Server/Storage/IFrameAssetLocator.cs new file mode 100644 index 00000000..3148f286 --- /dev/null +++ b/src/Titano.Server/Storage/IFrameAssetLocator.cs @@ -0,0 +1,26 @@ +using Titano.Core.Model; + +namespace Titano.Server.Storage; + +/// Regenerable images derived from an original (BRIEF §8.5). +public enum FrameAsset +{ + /// JPEG proxy under the sequence's proxies/ folder. + Proxy, + + /// Thumbnail inside the sequence's packed thumbnail file. + Thumbnail, +} + +/// Where a derived image lives: a byte range of a file inside the archive (a whole proxy file or one thumbnail of a pack). +public sealed record AssetLocation(string Path, long Offset, long Length, string ContentType); + +/// +/// Finds proxies and thumbnails in the archive layout, which the archive module owns (BRIEF §7). The server streams +/// what it returns with Range support after checking the path stays inside the archive root; null means not built yet. +/// Registered by the host composition alongside . +/// +public interface IFrameAssetLocator +{ + ValueTask LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken); +} diff --git a/src/Titano.Server/Storage/RenderStore.cs b/src/Titano.Server/Storage/RenderStore.cs new file mode 100644 index 00000000..9748accd --- /dev/null +++ b/src/Titano.Server/Storage/RenderStore.cs @@ -0,0 +1,49 @@ +using Titano.Core.IO; +using Titano.Core.Model; +using Titano.Data; +using Titano.Protocol; + +namespace Titano.Server.Storage; + +/// Files a verified render output under the sequence's exports/ folder (BRIEF §7) and records it. +public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimeProvider time) +{ + /// + /// Moves (on the archive volume) to <sequence folder>/exports/, never + /// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet. + /// + public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(sequence.Folder) || ArchivePaths.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports) + return null; + Directory.CreateDirectory(exports); + var target = Unique(exports, output.FileName); + File.Move(stagedFile, target); + var render = new Render + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + PresetName = output.PresetName, + OutputPath = LongPath.ToPortableRelative(archive.Root, target), + Codec = output.Codec, + Width = output.Width, + Height = output.Height, + Fps = output.Fps, + DurationSeconds = output.DurationSeconds, + Bytes = output.Size, + Created = time.GetUtcNow(), + ProducedBy = producedBy, + }; + await db.Renders.InsertAsync(render, cancellationToken); + return render; + } + + private static string Unique(string folder, string fileName) + { + var candidate = Path.Combine(folder, fileName); + var stem = Path.GetFileNameWithoutExtension(fileName); + var extension = Path.GetExtension(fileName); + for (var n = 2; File.Exists(candidate); n++) candidate = Path.Combine(folder, $"{stem} ({n}){extension}"); + return candidate; + } +} diff --git a/src/Titano.Server/Storage/ServerArchive.cs b/src/Titano.Server/Storage/ServerArchive.cs new file mode 100644 index 00000000..d7e1ae8d --- /dev/null +++ b/src/Titano.Server/Storage/ServerArchive.cs @@ -0,0 +1,37 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Server.Configuration; + +namespace Titano.Server.Storage; + +/// +/// The archive this server serves () and its database row, created at first +/// start. The admin panel can change its name, templates and proxy policy at runtime. +/// +public sealed class ServerArchive(Archive archive) +{ + private volatile Archive _current = archive; + + public Archive Current + { + get => _current; + set => _current = value; + } + + public Guid Id => _current.Id; + + public string Root => _current.RootPath; + + /// Finds the archive row for the configured root, or creates it with the default templates. + public static async Task OpenAsync(TitanoDatabase db, ServerOptions options, TimeProvider time, CancellationToken cancellationToken) + { + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath)); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var existing = (await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(a => string.Equals(Path.TrimEndingDirectorySeparator(a.RootPath), root, comparison)); + if (existing is not null) return new ServerArchive(existing); + var created = new Archive { Id = Guid.CreateVersion7(), Name = options.ServerName, RootPath = root, Created = time.GetUtcNow() }; + await db.Archives.UpsertAsync(created, cancellationToken).ConfigureAwait(false); + return new ServerArchive(created); + } +} diff --git a/src/Titano.Server/Storage/UploadMaintenance.cs b/src/Titano.Server/Storage/UploadMaintenance.cs new file mode 100644 index 00000000..3abe04c1 --- /dev/null +++ b/src/Titano.Server/Storage/UploadMaintenance.cs @@ -0,0 +1,102 @@ +using Titano.Data; +using Titano.Data.Repositories; +using Titano.Server.Configuration; + +namespace Titano.Server.Storage; + +/// +/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour +/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged. +/// +public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, UploadStore store, TimeProvider time, ILogger logger) + : BackgroundService +{ + private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30); + private static readonly TimeSpan FinishedRetention = TimeSpan.FromDays(90); + private static readonly TimeSpan StagingRetention = TimeSpan.FromDays(1); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await RecoverAsync(stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Upload recovery failed"); + } + while (!stoppingToken.IsCancellationRequested) + { + try + { + await SweepAsync(stoppingToken); + await Task.Delay(Interval, time, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Upload cleanup failed"); + } + } + } + + /// + /// Uploads left committing by a crash: committed when the frame with their hash exists, otherwise back to receiving + /// (the partial file is intact, so the client simply completes again). + /// + public async Task RecoverAsync(CancellationToken cancellationToken) + { + foreach (var upload in await db.Uploads.ListByStateAsync(UploadState.Committing, cancellationToken)) + { + var frame = upload.JobId is null ? (await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken)).FirstOrDefault() : null; + if (frame is not null) + { + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, frame.Id, cancellationToken); + store.Delete(upload.Id); + } + else + { + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: cancellationToken); + } + logger.LogInformation("Recovered interrupted upload {Upload} ({File})", upload.Id, upload.FileName); + } + } + + public async Task SweepAsync(CancellationToken cancellationToken) + { + var now = time.GetUtcNow(); + var abandonedBefore = now - TimeSpan.FromHours(options.UploadRetentionHours); + var expired = 0; + foreach (var upload in await db.Uploads.ListStaleAsync(abandonedBefore, cancellationToken)) + { + if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Cancelled, cancellationToken: cancellationToken)) continue; + store.Delete(upload.Id); + expired++; + } + + var active = new HashSet(); + foreach (var state in new[] { UploadState.Receiving, UploadState.Committing }) + active.UnionWith((await db.Uploads.ListByStateAsync(state, cancellationToken)).Select(u => u.Id)); + foreach (var (id, _) in store.List().ToList()) + { + if (!active.Contains(id)) store.Delete(id); + } + if (Directory.Exists(options.StagingPath)) + { + // Only this server's staging files (named by upload id) are touched; clients may share the archive. + foreach (var file in new DirectoryInfo(options.StagingPath).EnumerateFiles()) + { + if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) && !active.Contains(id) + && file.LastWriteTimeUtc < now.UtcDateTime - StagingRetention) + UploadStore.TryDelete(file.FullName); + } + } + + await db.Uploads.PurgeFinishedAsync(now - FinishedRetention, cancellationToken); + await db.Tokens.PurgeAsync(now, cancellationToken); + if (expired > 0) logger.LogInformation("Expired {Count} abandoned upload(s)", expired); + } +} diff --git a/src/Titano.Server/Storage/UploadRules.cs b/src/Titano.Server/Storage/UploadRules.cs new file mode 100644 index 00000000..9dd31eef --- /dev/null +++ b/src/Titano.Server/Storage/UploadRules.cs @@ -0,0 +1,45 @@ +namespace Titano.Server.Storage; + +/// Validation shared by frame and render uploads. +public static class UploadRules +{ + /// A plain file name (no folders, no characters Windows or Linux refuse), or null. + public static string? SafeFileName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return null; + var trimmed = name.Trim(); + if (trimmed.Length > 255 || trimmed is "." or ".." || trimmed.EndsWith('.')) return null; + foreach (var c in trimmed) + { + if (char.IsControl(c) || c is '/' or '\\' or '<' or '>' or ':' or '"' or '|' or '?' or '*') return null; + } + return trimmed; + } + + /// 64 hexadecimal characters. + public static bool IsSha256(string? value) => value is { Length: 64 } && value.All(char.IsAsciiHexDigit); + + /// Indices of the chunks set in a received-chunk bitmap. + public static List ReceivedChunks(Titano.Data.Repositories.Upload upload) + { + var received = new List(upload.ReceivedCount); + for (var i = 0; i < upload.ChunkCount; i++) + { + if (upload.HasChunk(i)) received.Add(i); + } + return received; + } + + /// Free bytes on the volume holding , or null when the platform cannot tell. + public static long? FreeBytes(string path) + { + try + { + return new DriveInfo(Path.GetFullPath(path)).AvailableFreeSpace; + } + catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException) + { + return null; + } + } +} diff --git a/src/Titano.Server/Storage/UploadService.cs b/src/Titano.Server/Storage/UploadService.cs new file mode 100644 index 00000000..cef9f2ff --- /dev/null +++ b/src/Titano.Server/Storage/UploadService.cs @@ -0,0 +1,242 @@ +using System.Collections.Concurrent; +using System.Globalization; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; +using Titano.Server.Events; +using Titano.Server.Jobs; +using Titano.Server.Security; +using UploadState = Titano.Data.Repositories.UploadState; +using UploadStateDto = Titano.Protocol.UploadState; + +namespace Titano.Server.Storage; + +/// +/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256, resume an +/// unfinished upload, quota and disk checks), idempotent chunks, and completion that stages the file on the archive +/// volume, verifies its hash and hands it to . +/// +public sealed class UploadService( + TitanoDatabase db, + ServerOptions options, + ServerArchive archive, + UploadStore store, + IArchiveIngest ingest, + SequenceJobs sequenceJobs, + EventHub events, + IHostApplicationLifetime lifetime, + TimeProvider time, + ILogger logger) +{ + /// Space kept free on the upload volume beyond the announced size. + private const long DiskReserve = 64L * 1024 * 1024; + + private readonly ConcurrentDictionary _chunksInFlight = new(); + + public async Task> StartAsync(Caller caller, StartUploadRequest request, CancellationToken cancellationToken) + { + if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Fail(400, "invalid_file_name"); + if (!UploadRules.IsSha256(request.Sha256)) return Fail(400, "invalid_hash"); + if (request.Size <= 0) return Fail(400, "bad_request", "size"); + if (request.Size > options.MaxUploadBytes) return Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture)); + if (request.SessionKey is { Length: > 200 }) return Fail(400, "bad_request", "sessionKey"); + if (request.SequenceId is { } target && await db.Sequences.GetAsync(target, cancellationToken) is null) + return Fail(404, "not_found", "sequence"); + + var sha = request.Sha256.ToLowerInvariant(); + var known = await db.Frames.FindBySha256Async(sha, cancellationToken); + if (known.Count > 0) + { + var frame = known.FirstOrDefault(f => f.SequenceId == request.SequenceId) ?? known[0]; + return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, frame.Id); + } + + var resumable = await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken); + if (resumable is not null && resumable.Size == request.Size && resumable.SequenceId == request.SequenceId && store.Exists(resumable.Id)) + return Started(resumable); + + if (caller.User.QuotaBytes > 0) + { + var pending = await db.Uploads.PendingBytesAsync(caller.Id, cancellationToken); + if (caller.User.UsedBytes + pending + request.Size > caller.User.QuotaBytes) + return Fail(403, "quota_exceeded", caller.User.QuotaBytes.ToString(CultureInfo.InvariantCulture)); + } + if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size + DiskReserve) + return Fail(507, "insufficient_storage"); + + var now = time.GetUtcNow(); + var upload = await db.Uploads.CreateAsync(new Upload + { + Id = Guid.CreateVersion7(), + UserId = caller.Id, + SequenceId = request.SequenceId, + FileName = fileName, + Size = request.Size, + Sha256 = sha, + CapturedAt = request.CapturedAt, + ChunkSize = options.ChunkSizeBytes, + State = UploadState.Receiving, + Created = now, + UpdatedAt = now, + SessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim(), + }, cancellationToken); + store.Create(upload.Id, upload.Size); + return Started(upload); + } + + /// Stores chunk of an upload the caller owns; repeating a received chunk changes nothing. + public async Task> ReceiveChunkAsync(Caller caller, Guid id, int index, HttpRequest request, CancellationToken cancellationToken) + { + var upload = await db.Uploads.GetAsync(id, cancellationToken); + if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload"); + if (upload.State != UploadState.Receiving) return Fail(409, "upload_state"); + if (index < 0 || index >= upload.ChunkCount) return Fail(400, "chunk_out_of_range"); + var expected = Math.Min(upload.ChunkSize, upload.Size - (long)index * upload.ChunkSize); + if (request.ContentLength is { } announced && announced != expected) return Fail(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture)); + if (upload.HasChunk(index)) return new ChunkReceived(index, UploadRules.ReceivedChunks(upload)); + + if (_chunksInFlight.AddOrUpdate(caller.Id, 1, (_, n) => n + 1) > options.ConcurrentChunksPerUser) + { + Release(caller.Id); + return Fail(429, "too_many_uploads"); + } + try + { + if (!await store.WriteChunkAsync(id, (long)index * upload.ChunkSize, request.Body, expected, cancellationToken)) + return Fail(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture)); + } + finally + { + Release(caller.Id); + } + var updated = await db.Uploads.MarkChunkReceivedAsync(id, index, cancellationToken); + return updated is null ? Fail(404, "not_found", "upload") : new ChunkReceived(index, UploadRules.ReceivedChunks(updated)); + } + + public async Task> GetStateAsync(Caller caller, Guid id, CancellationToken cancellationToken) + { + var upload = await db.Uploads.GetAsync(id, cancellationToken); + if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload"); + return new UploadStateDto(upload.Id, upload.FileName, upload.Size, upload.Sha256, upload.ChunkSize, UploadRules.ReceivedChunks(upload), + upload.State.ToString().ToLowerInvariant()); + } + + /// Abandons an upload that is still receiving and deletes its partial file. + public async Task> CancelAsync(Caller caller, Guid id, CancellationToken cancellationToken) + { + var upload = await db.Uploads.GetAsync(id, cancellationToken); + if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload"); + if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Cancelled, cancellationToken: cancellationToken)) + return Fail(409, "upload_state"); + store.Delete(id); + return true; + } + + /// + /// Verifies and commits a frame upload. Completing an already committed upload answers its frame again, so a client + /// may retry a completion whose response it lost. Runs to the end even if the client disconnects. + /// + public async Task> CompleteAsync(Caller caller, Guid id) + { + var stopping = lifetime.ApplicationStopping; + var upload = await db.Uploads.GetAsync(id, stopping); + if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload"); + if (upload.JobId is not null) return Fail(409, "wrong_upload_kind"); + if (upload is { State: UploadState.Committed, FrameId: { } committed } && await db.Frames.GetAsync(committed, stopping) is { } done) + return new CompleteUploadResponse(done.Id, done.SequenceId, done.Index); + if (upload.State != UploadState.Receiving) return Fail(409, "upload_state"); + if (!upload.IsComplete) + return Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture)); + if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: stopping)) + return Fail(409, "upload_state"); + + var user = await db.Users.GetAsync(caller.Id, stopping); + if (user is { QuotaBytes: > 0 } && user.UsedBytes + upload.Size > user.QuotaBytes) + { + await FailAsync(upload); + return Fail(403, "quota_exceeded", user.QuotaBytes.ToString(CultureInfo.InvariantCulture)); + } + + var staged = await StageVerifiedAsync(upload, stopping); + if (staged is null) return Fail(422, "hash_mismatch"); + + IngestResult result; + try + { + result = await ingest.CommitAsync(new IngestRequest( + archive.Id, + upload.SequenceId, + NewSequenceTitle: null, + upload.SequenceId is null ? upload.SessionKey ?? "user-" + caller.Id.ToString("N") : null, + staged, + upload.FileName, + upload.Size, + upload.Sha256, + upload.CapturedAt, + caller.Id), stopping); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // The part file is intact: the client may complete again. + logger.LogError(ex, "Archive ingest of upload {Upload} ({File}) failed", id, upload.FileName); + UploadStore.TryDelete(staged); + await db.Uploads.TryTransitionAsync(id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None); + return Fail(503, "commit_failed"); + } + + await db.Uploads.TryTransitionAsync(id, UploadState.Committing, UploadState.Committed, result.FrameId, CancellationToken.None); + store.Delete(id); + if (File.Exists(staged)) UploadStore.TryDelete(staged); + if (!result.Duplicate) await db.Users.AddUsedBytesAsync(caller.Id, upload.Size, CancellationToken.None); + if (await db.Sequences.GetAsync(result.SequenceId, CancellationToken.None) is { } sequence) + { + await sequenceJobs.FramesAddedAsync(sequence, CancellationToken.None); + events.Publish(new SequenceChangedEvent(sequence.Id, "frames", sequence.FramesVersion, sequence.SettingsVersion)); + } + return new CompleteUploadResponse(result.FrameId, result.SequenceId, result.Index); + } + + /// + /// Copies a fully received upload to the archive staging folder and checks its SHA-256. On a mismatch the upload + /// fails, its files are deleted and null is returned; the client starts over. + /// + public async Task StageVerifiedAsync(Upload upload, CancellationToken cancellationToken) + { + var staged = Path.Combine(options.StagingPath, upload.Id.ToString("N") + Path.GetExtension(upload.FileName).ToLowerInvariant()); + string hash; + try + { + hash = await store.StageAsync(upload.Id, staged, cancellationToken); + } + catch + { + UploadStore.TryDelete(staged); + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None); + throw; + } + if (hash == upload.Sha256) return staged; + logger.LogWarning("Upload {Upload} ({File}) arrived damaged: SHA-256 {Actual} instead of {Expected}", upload.Id, upload.FileName, hash, upload.Sha256); + UploadStore.TryDelete(staged); + await FailAsync(upload); + return null; + } + + private async Task FailAsync(Upload upload) + { + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None); + store.Delete(upload.Id); + } + + private StartUploadResponse Started(Upload upload) => + new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null); + + private void Release(Guid userId) + { + if (_chunksInFlight.AddOrUpdate(userId, 0, (_, n) => n - 1) <= 0) _chunksInFlight.TryRemove(new KeyValuePair(userId, 0)); + } + + private static Outcome Fail(int status, string code, string? details = null) => Outcome.Fail(status, code, details); +} diff --git a/src/Titano.Server/Storage/UploadStore.cs b/src/Titano.Server/Storage/UploadStore.cs new file mode 100644 index 00000000..7e5c447b --- /dev/null +++ b/src/Titano.Server/Storage/UploadStore.cs @@ -0,0 +1,109 @@ +using System.Buffers; +using System.Security.Cryptography; +using Titano.Server.Configuration; + +namespace Titano.Server.Storage; + +/// +/// Files behind resumable uploads (BRIEF §14.4): /data/uploads/{id}.part receives chunks at their offsets in any +/// order; at completion it is copied, hashing on the way, to a staging file on the archive volume. +/// +public sealed class UploadStore(ServerOptions options) +{ + private const string Extension = ".part"; + + public string PartPath(Guid id) => Path.Combine(options.UploadsPath, id.ToString("N") + Extension); + + public bool Exists(Guid id) => File.Exists(PartPath(id)); + + /// Creates the part file at its final size, so chunks can land at their offsets. + public void Create(Guid id, long size) + { + Directory.CreateDirectory(options.UploadsPath); + using var file = new FileStream(PartPath(id), FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); + file.SetLength(size); + } + + /// + /// Writes exactly bytes of at and flushes + /// them to disk; false when the body is shorter or longer (nothing is marked received then). + /// + public async Task WriteChunkAsync(Guid id, long offset, Stream body, long length, CancellationToken cancellationToken) + { + var buffer = ArrayPool.Shared.Rent(1 << 16); + try + { + await using var file = new FileStream(PartPath(id), FileMode.Open, FileAccess.Write, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous); + file.Position = offset; + long total = 0; + int read; + while ((read = await body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + total += read; + if (total > length) return false; + await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + } + if (total != length) return false; + await file.FlushAsync(cancellationToken).ConfigureAwait(false); + file.Flush(flushToDisk: true); + return true; + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Copies the assembled upload to (synced to disk) and returns its lower-case hex SHA-256. + public async Task StageAsync(Guid id, string stagingPath, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(stagingPath)!); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = ArrayPool.Shared.Rent(1 << 20); + try + { + await using var source = new FileStream(PartPath(id), FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); + await using var target = new FileStream(stagingPath, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous); + int read; + while ((read = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + hash.AppendData(buffer, 0, read); + await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + } + await target.FlushAsync(cancellationToken).ConfigureAwait(false); + target.Flush(flushToDisk: true); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } + + public void Delete(Guid id) => TryDelete(PartPath(id)); + + /// Every part file with its last write time (cleanup of uploads the database no longer knows). + public IEnumerable<(Guid Id, DateTime LastWriteUtc)> List() + { + if (!Directory.Exists(options.UploadsPath)) yield break; + foreach (var path in Directory.EnumerateFiles(options.UploadsPath, "*" + Extension)) + { + if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(path), "N", out var id)) yield return (id, File.GetLastWriteTimeUtc(path)); + } + } + + public static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // Retried by the next cleanup pass. + } + catch (UnauthorizedAccessException) + { + } + } +} diff --git a/tests/Titano.Server.Tests/Fakes.cs b/tests/Titano.Server.Tests/Fakes.cs new file mode 100644 index 00000000..d4f3d080 --- /dev/null +++ b/tests/Titano.Server.Tests/Fakes.cs @@ -0,0 +1,147 @@ +using System.Collections.Concurrent; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Server.Storage; + +namespace Titano.Server.Tests; + +/// +/// Stand-in for the archive module's ingest: files staged uploads as <folder>/originals/<name>, one +/// sequence per session key, and records every request it received. +/// +public sealed class FakeArchiveIngest(TitanoDatabase db) : IArchiveIngest +{ + private readonly ConcurrentDictionary _sessions = new(StringComparer.Ordinal); + private readonly SemaphoreSlim _gate = new(1, 1); + + public ConcurrentQueue Requests { get; } = new(); + + public async Task CommitAsync(IngestRequest request, CancellationToken cancellationToken = default) + { + Requests.Enqueue(request); + await _gate.WaitAsync(cancellationToken); + try + { + var archive = (await db.Archives.GetAsync(request.ArchiveId, cancellationToken))!; + var sequence = await SequenceForAsync(request, archive, cancellationToken); + var existing = (await db.Frames.FindBySha256Async(request.Sha256, cancellationToken)).FirstOrDefault(f => f.SequenceId == sequence.Id); + if (existing is not null) + { + File.Delete(request.StagedPath); + return new IngestResult(sequence.Id, existing.Id, existing.Index, existing.RelativePath, Duplicate: true); + } + var index = sequence.FrameCount; + var relative = $"{sequence.Folder}/originals/{index:D4}_{request.OriginalFileName}"; + var target = Path.Combine(archive.RootPath, relative); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Move(request.StagedPath, target); + var frame = new Frame + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + Index = index, + RelativePath = relative, + FileName = Path.GetFileName(relative), + OriginalFileName = request.OriginalFileName, + Size = request.Size, + Sha256 = request.Sha256, + CapturedAt = request.ClientCapturedAt, + }; + await db.Frames.InsertAsync(frame, cancellationToken); + await db.Sequences.RefreshStatsAsync(sequence.Id, cancellationToken); + return new IngestResult(sequence.Id, frame.Id, index, relative, Duplicate: false); + } + finally + { + _gate.Release(); + } + } + + private async Task SequenceForAsync(IngestRequest request, Archive archive, CancellationToken cancellationToken) + { + Sequence? sequence = null; + if (request.SequenceId is { } id) sequence = await db.Sequences.GetAsync(id, cancellationToken); + else if (request.SessionKey is { } key && _sessions.TryGetValue(key, out var known)) sequence = await db.Sequences.GetAsync(known, cancellationToken); + if (sequence is null) + { + sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = archive.Id, Folder = string.Empty, Title = request.NewSequenceTitle, OwnerUserId = request.UserId }; + if (request.SessionKey is { } key) _sessions[key] = sequence.Id; + } + if (string.IsNullOrEmpty(sequence.Folder)) + { + sequence = sequence with { Folder = $"2026/{sequence.Id:N}", UpdatedAt = DateTimeOffset.UtcNow }; + await db.Sequences.UpsertAsync(sequence, cancellationToken); + } + return sequence; + } +} + +/// Proxies at <folder>/proxies/NNNN.jpg; thumbnails as 64-byte slots of <folder>/.titano/thumbs.pack. +public sealed class FakeAssetLocator : IFrameAssetLocator +{ + public const int ThumbnailSize = 64; + + /// When set, every lookup answers this location (path traversal tests). + public AssetLocation? Override { get; set; } + + public ValueTask LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken) + { + if (Override is not null) return ValueTask.FromResult(Override); + var folder = Path.Combine(archive.RootPath, sequence.Folder); + AssetLocation? location = asset == FrameAsset.Proxy + ? new AssetLocation(Path.Combine(folder, "proxies", $"{frame.Index:D4}.jpg"), 0, -1, "image/jpeg") + : new AssetLocation(Path.Combine(folder, ".titano", "thumbs.pack"), (long)frame.Index * ThumbnailSize, ThumbnailSize, "image/jpeg"); + if (!File.Exists(location.Path)) return ValueTask.FromResult(null); + if (location.Length < 0) location = location with { Length = new FileInfo(location.Path).Length }; + return ValueTask.FromResult(location); + } +} + +/// A clock tests move by hand (token expiry, heartbeat timeouts). +public sealed class ManualTimeProvider : TimeProvider +{ + private long _ticks = DateTimeOffset.UtcNow.UtcTicks; + + public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero); + + public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks); +} + +/// +/// A job handler that reports progress and then waits until (or cancellation), so tests can +/// observe running, paused and cancelled states. +/// +public sealed class BlockingJobHandler(JobKind kind) : IJobHandler +{ + private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public JobKind Kind => kind; + + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// When set, the next run fails with this message. + public string? FailWith { get; set; } + + public void Release() => _release.TrySetResult(); + + public async Task RunAsync(JobContext context) + { + await context.ReportAsync(1, 4, "started"); + Started.TrySetResult(); + if (FailWith is { } message) + { + FailWith = null; + throw new InvalidOperationException(message); + } + for (var i = 2; i <= 3; i++) + { + await Task.Delay(50, context.Cancellation); + await context.ReportAsync(i, 4); + } + await _release.Task.WaitAsync(context.Cancellation); + _release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await context.ReportAsync(4, 4); + } +} diff --git a/tests/Titano.Server.Tests/TestServer.cs b/tests/Titano.Server.Tests/TestServer.cs index 2e099360..0a528bbc 100644 --- a/tests/Titano.Server.Tests/TestServer.cs +++ b/tests/Titano.Server.Tests/TestServer.cs @@ -1,17 +1,33 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Protocol; using Titano.Server.Configuration; using Titano.Server.Hosting; +using Titano.Server.Storage; using Titano.Testing; namespace Titano.Server.Tests; -/// In-process Kestrel on ephemeral ports with temporary archive/data folders (BRIEF §20.1). +/// +/// In-process Kestrel on ephemeral ports with temporary archive/data folders and a SQLite database (BRIEF §20.1). +/// The archive module is replaced by and . +/// public sealed class TestServer : IAsyncDisposable { + public const string AdminPassword = "first-admin-pass"; + public const string Password = "a-good-password-1"; + private readonly WebApplication _app; + private readonly List _clients = []; + private string _adminPassword = AdminPassword; private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https) { @@ -19,16 +35,21 @@ public sealed class TestServer : IAsyncDisposable Options = options; HttpBase = http; HttpsBase = https; - Client = new HttpClient { BaseAddress = http, Timeout = TimeSpan.FromSeconds(30) }; + Client = NewClient(); } public ServerOptions Options { get; } public Uri HttpBase { get; } public Uri? HttpsBase { get; } + + /// An anonymous client. public HttpClient Client { get; } + public IServiceProvider Services => _app.Services; - public static async Task StartAsync(TestContext context, Action? configure = null) + public TitanoDatabase Database => Services.GetRequiredService(); + + public static async Task StartAsync(TestContext context, Action? configure = null, Action? services = null) { var root = context.CreateTempDirectory("server"); var options = new ServerOptions @@ -39,10 +60,21 @@ public sealed class TestServer : IAsyncDisposable HttpsPort = 0, TlsMode = TlsMode.Auto, Database = DatabaseKind.Sqlite, + Discovery = false, + Workers = 2, + AdminUser = "admin", + AdminPassword = AdminPassword, }; Directory.CreateDirectory(options.ArchivePath); configure?.Invoke(options); - var app = ServerHost.Build(options, []); + var app = ServerHost.Build(options, [], s => + { + s.AddSingleton(); + s.TryAddSingleton(sp => sp.GetRequiredService()); + s.AddSingleton(); + s.TryAddSingleton(sp => sp.GetRequiredService()); + services?.Invoke(s); + }); await app.StartAsync(context.Cancellation); var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses .Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal))) @@ -52,9 +84,65 @@ public sealed class TestServer : IAsyncDisposable return new TestServer(app, options, http, https); } + /// A plain HTTP client (owned by the server, disposed with it). + public HttpClient NewClient(string? token = null) + { + var client = new HttpClient { BaseAddress = HttpBase, Timeout = TimeSpan.FromSeconds(60) }; + if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _clients.Add(client); + return client; + } + + /// An HTTPS client with a cookie jar that trusts the self-signed certificate (admin panel sessions). + public HttpClient NewCookieClient(CookieContainer cookies) + { + var handler = new HttpClientHandler { CookieContainer = cookies, ServerCertificateCustomValidationCallback = (_, _, _, _) => true }; + var client = new HttpClient(handler) { BaseAddress = HttpsBase, Timeout = TimeSpan.FromSeconds(60) }; + _clients.Add(client); + return client; + } + + public async Task LoginAsync(string username, string password, string clientName = "tests") + { + using var response = await Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, password, clientName), ProtocolJson.Default.LoginRequest); + if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Login of {username} failed: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); + return (await response.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!; + } + + /// The bootstrap administrator, signed in; its first sign-in replaces the bootstrap password with . + public async Task AdminAsync() + { + var login = await LoginAsync("admin", _adminPassword); + var client = NewClient(login.Token); + if (login.MustChangePassword) + { + using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(_adminPassword, Password), + ProtocolJson.Default.ChangePasswordRequest); + changed.EnsureSuccessStatusCode(); + _adminPassword = Password; + } + return client; + } + + /// Creates a user (through the admin API) who has set , and returns a client signed in as them. + public async Task<(HttpClient Client, UserDto User, string Token)> UserAsync(string username, string role, long quotaBytes = 0, bool renderNode = false) + { + var admin = await AdminAsync(); + using var created = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest(username, null, role, quotaBytes, null, renderNode), + ProtocolJson.Default.CreateUserRequest); + created.EnsureSuccessStatusCode(); + var temporary = (await created.Content.ReadFromJsonAsync(ProtocolJson.Default.TemporaryPasswordResponse))!; + var first = await LoginAsync(username, temporary.TemporaryPassword); + var client = NewClient(first.Token); + using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary.TemporaryPassword, Password), + ProtocolJson.Default.ChangePasswordRequest); + changed.EnsureSuccessStatusCode(); + return (client, temporary.User, first.Token!); + } + public async ValueTask DisposeAsync() { - Client.Dispose(); + foreach (var client in _clients) client.Dispose(); await _app.StopAsync(); await _app.DisposeAsync(); } From 93be5853dcd6e24c4be43382ef88d571f6a2fec5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:32:58 +0000 Subject: [PATCH 158/188] test(render): cover the target luminance curve and the decode-size cap Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Core.Tests/Render/RenderProcessingTests.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs index 4f3d2c21..442ed4be 100644 --- a/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs +++ b/tests/Titano.Core.Tests/Render/RenderProcessingTests.cs @@ -153,6 +153,9 @@ public sealed class RenderProcessingTests var camera = With(camera: new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 2, 0), new CameraKey(3, 0.5, 0.5, 2, 0)] }); var (encode, _) = await CaptureAsync(Input(zoomed, camera), Preset("png-sequence", 96, 64), cancellationToken: _context.Cancellation); Assert.Equal(192, zoomed.LargestRenderRequest); + var capped = Source(4, width: 480, height: 320); + await CaptureAsync(Input(capped, camera), Preset("png-sequence", 96, 64), new RenderOptions { MaxWorkingLongEdge = 120 }, _context.Cancellation); + Assert.Equal(120, capped.LargestRenderRequest); using var full = zoomed.Sequence.Render(1); using var expected = GeometryStage.Apply(full, new GeometrySettings { Crop = new RectD(120, 80, 240, 160), OutputWidth = 96, OutputHeight = 64 }); var psnr = Psnr(expected, encode.Frames[1]); @@ -296,6 +299,10 @@ public sealed class RenderProcessingTests Assert.Equal(0, reused.Report.MeasuredFrames); Assert.Equal(decodes, source.Decodes); Assert.SequenceEqual(measured.ExposureEv, reused.ExposureEv); + var target = measured.TargetLogLuminance(); + Assert.Approximately(measured.MeasuredLogLuminance[7] + measured.ExposureEv[7], target[7], 1e-12); + static double[] Steps(double[] v) => [.. v.Zip(v.Skip(1), (a, b) => b - a)]; + Assert.Less(Rms(Steps(target)), 0.5 * Rms(Steps(measured.MeasuredLogLuminance))); var wrongLength = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = new PrecomputedAnalysis { LogLuminance = new double[3] } }, cancellationToken: _context.Cancellation); From 0f3fbfdad40c6ce3343a788514bda7fe64fc9638 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:32:59 +0000 Subject: [PATCH 159/188] feat(tools): diagnose and fixtures commands with the CC0 RAW manifest diagnose prints per file the format, managed decode tier (and why it is not native), delivered size, camera and capture time with its source, then a per-format summary; --formats prints the tier table. fixtures downloads tests/fixtures/manifest.json into tests/fixtures/external with HTTP range resume and SHA-256 verification, skipping verified files and recording the hash of first downloads whose manifest hash is null. External fixture tests (skipped when absent) check native decoding, size and agreement with the embedded preview. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Decoders/ManagedDecoderProvider.cs | 39 +++-- src/Titano.Tools/Commands/DiagnoseCommand.cs | 100 ++++++++++++ src/Titano.Tools/Commands/FixturesCommand.cs | 147 ++++++++++++++++++ src/Titano.Tools/Program.cs | 2 + .../Decoding/ExternalFixtureTests.cs | 84 ++++++++++ tests/fixtures/manifest.json | 78 ++++++++++ 6 files changed, 429 insertions(+), 21 deletions(-) create mode 100644 src/Titano.Tools/Commands/DiagnoseCommand.cs create mode 100644 src/Titano.Tools/Commands/FixturesCommand.cs create mode 100644 tests/Titano.Core.Tests/Decoding/ExternalFixtureTests.cs create mode 100644 tests/fixtures/manifest.json diff --git a/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs b/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs index 2021371f..9b8c7e2f 100644 --- a/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs +++ b/src/Titano.Core/Imaging/Decoders/ManagedDecoderProvider.cs @@ -12,7 +12,9 @@ namespace Titano.Core.Imaging.Decoders; /// Best tier available for this file. /// Decoder that would produce it ("managed-cr2", "managed-preview"…), null when unavailable. /// Why the native tier is not used (unsupported body or encoding), else null. -public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason); +/// Full-size width that tier delivers (developed RAW, preview or image size), oriented; 0 when unknown. +/// Full-size height, oriented; 0 when unknown. +public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason, int Width, int Height); /// /// The managed decoder (BRIEF §8.2), available on every platform and the only one on the server: JPEG, PNG and TIFF @@ -66,34 +68,29 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider using var stream = Open(path); var format = ImageSignature.Detect(stream, path); var family = ImageFormatInfo.Of(format).Family; - switch (family) + if (family is ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff) { - case ImageFamily.Jpeg: - return new FileTier(format, DecodeTier.Native, "managed-jpeg", null); - case ImageFamily.Png: - return new FileTier(format, DecodeTier.Native, "managed-png", null); - case ImageFamily.Tiff: - return new FileTier(format, DecodeTier.Native, "managed-tiff", null); + var (w, h) = MetadataReader.Read(stream, path).OrientedSize; + var decoder = family switch { ImageFamily.Jpeg => "managed-jpeg", ImageFamily.Png => "managed-png", _ => "managed-tiff" }; + return new FileTier(format, DecodeTier.Native, decoder, null, w, h); } - string? reason = null; - if (family is ImageFamily.Dng or ImageFamily.CameraRaw && RawDecoder.Formats.Contains(format)) + if (family is not (ImageFamily.Dng or ImageFamily.CameraRaw or ImageFamily.Heif)) + return new FileTier(format, DecodeTier.Unavailable, null, $"no managed decoder for {format}", 0, 0); + string reason; + if (RawDecoder.Formats.Contains(format)) { var probe = RawDecoder.Probe(stream, path); - if (probe.IsSupported) return new FileTier(format, DecodeTier.Native, probe.Info!.Decoder, null); - reason = probe.Reason; - } - else if (family is ImageFamily.Dng or ImageFamily.CameraRaw or ImageFamily.Heif) - { - reason = $"no managed decoder for {format}"; + if (probe.Info is { } info) return new FileTier(format, DecodeTier.Native, info.Decoder, null, info.Width, info.Height); + reason = probe.Reason ?? "unsupported"; } else { - return new FileTier(format, DecodeTier.Unavailable, null, $"no managed decoder for {format}"); + reason = $"no managed decoder for {format}"; } - var previews = MetadataReader.Read(stream, path).Previews; - return previews.Count > 0 - ? new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason) - : new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview"); + var metadata = MetadataReader.Read(stream, path); + if (metadata.LargestPreview is not { } preview) return new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview", 0, 0); + var (pw, ph) = PixelConvert.OrientedSize(preview.Width, preview.Height, metadata.Orientation); + return new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason, pw, ph); } private static FileStream Open(string path) => diff --git a/src/Titano.Tools/Commands/DiagnoseCommand.cs b/src/Titano.Tools/Commands/DiagnoseCommand.cs new file mode 100644 index 00000000..d6c1d958 --- /dev/null +++ b/src/Titano.Tools/Commands/DiagnoseCommand.cs @@ -0,0 +1,100 @@ +using System.Globalization; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Metadata; + +namespace Titano.Tools.Commands; + +/// +/// Per-file decode report for a folder of photos: format, the tier the managed decoders reach (the server's view — WIC +/// does not exist in this tool), dimensions, camera, capture time and its source, warnings; then a summary per format. +/// +internal sealed class DiagnoseCommand : ICommand +{ + public string Name => "diagnose"; + public string Summary => "Decode tiers and metadata of the photos in a folder (--recursive, --formats)"; + + public Task RunAsync(string[] args) + { + var a = new Args(args, "recursive", "formats"); + if (a.Has("formats")) PrintFormats(); + if (a.Positional.Count == 0) + { + if (a.Has("formats")) return Task.FromResult(0); + throw new ToolException("Usage: diagnose [--recursive] [--formats]"); + } + var folder = Path.GetFullPath(a.Positional[0]); + if (!Directory.Exists(folder)) throw new ToolException($"Folder not found: {folder}"); + var files = Directory.EnumerateFiles(folder, "*", a.Has("recursive") ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) + .Where(ImageFormatInfo.IsSupportedExtension) + .Order(StringComparer.OrdinalIgnoreCase) + .ToList(); + Console.WriteLine($"{files.Count} photo(s) in {folder}. Tiers are the managed (server) view; WIC is not available in Titano.Tools."); + var provider = new ManagedDecoderProvider(); + var summary = new SortedDictionary(StringComparer.Ordinal); + foreach (var file in files) + { + var line = Describe(provider, folder, file, out var format, out var tier); + Console.WriteLine(line); + if (!summary.TryGetValue(format, out var counts)) summary[format] = counts = new int[3]; + counts[(int)tier - 1]++; + } + if (summary.Count > 0) + { + Console.WriteLine(); + Console.WriteLine($"{"Format",-8} {"Files",6} {"Native",7} {"Preview",8} {"None",5}"); + foreach (var (format, c) in summary) Console.WriteLine($"{format,-8} {c.Sum(),6} {c[0],7} {c[1],8} {c[2],5}"); + } + return Task.FromResult(0); + } + + private static string Describe(ManagedDecoderProvider provider, string folder, string file, out string format, out DecodeTier tier) + { + var name = Path.GetRelativePath(folder, file); + FrameMetadata metadata; + FileTier fileTier; + try + { + metadata = MetadataReader.Read(file); + fileTier = provider.Probe(file); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + format = ImageFormatInfo.FromPath(file).Format.ToString(); + tier = DecodeTier.Unavailable; + return $"{name}\n unreadable: {ex.Message}"; + } + format = fileTier.Format.ToString(); + tier = fileTier.Tier; + var (w, h) = fileTier.Width > 0 ? (fileTier.Width, fileTier.Height) : metadata.OrientedSize; + var camera = string.Join(' ', new[] { metadata.Make, metadata.Model }.Where(s => !string.IsNullOrEmpty(s))); + var captured = metadata.CapturedAt is { } t + ? $"{t.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)} ({metadata.TimestampSource})" + : "unknown"; + var tierText = fileTier.Tier switch + { + DecodeTier.Native => $"native ({fileTier.Decoder})", + DecodeTier.EmbeddedPreview => "embedded preview", + _ => "unavailable", + }; + var lines = new List { $"{name}\n {format,-5} {tierText,-24} {$"{w}x{h}",-11} {(camera.Length > 0 ? camera : "camera unknown")}; captured {captured}" }; + if (fileTier.Reason is { } reason) lines.Add($" reason: {reason}"); + lines.AddRange(metadata.Warnings.Select(warning => $" warning: {warning}")); + return string.Join('\n', lines); + } + + private static void PrintFormats() + { + Console.WriteLine("Format tiers (managed decoders):"); + foreach (var row in DecoderFactory.DescribeFormats(DecoderFactory.CreateServer())) + { + var tier = row.Tier switch + { + DecodeTier.Native => "native", + DecodeTier.EmbeddedPreview => "embedded preview", + _ => "unavailable", + }; + Console.WriteLine($" {row.Format.Format,-8} {string.Join(' ', row.Format.Extensions),-18} {tier}"); + } + } +} diff --git a/src/Titano.Tools/Commands/FixturesCommand.cs b/src/Titano.Tools/Commands/FixturesCommand.cs new file mode 100644 index 00000000..65d823af --- /dev/null +++ b/src/Titano.Tools/Commands/FixturesCommand.cs @@ -0,0 +1,147 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text.Json; + +namespace Titano.Tools.Commands; + +/// +/// Fetches the CC0 RAW samples listed in tests/fixtures/manifest.json into tests/fixtures/external (BRIEF +/// §20.2): interrupted downloads resume from their .part file with an HTTP range request, every file is verified +/// against its SHA-256, and verified files are skipped. An entry whose sha256 is null gets the hash of its first +/// download recorded in external/recorded-hashes.json (later runs verify against it) and printed so it can be +/// copied into the manifest. +/// +internal sealed class FixturesCommand : ICommand +{ + private const string RecordedHashesFile = "recorded-hashes.json"; + + public string Name => "fixtures"; + public string Summary => "Download and verify the CC0 RAW samples in tests/fixtures/manifest.json (--manifest, --out)"; + + public async Task RunAsync(string[] args) + { + var a = new Args(args); + var root = Args.RepoRoot(); + var manifestPath = a.Get("manifest") ?? Path.Combine(root, "tests", "fixtures", "manifest.json"); + var outDir = a.Get("out") ?? Path.Combine(root, "tests", "fixtures", "external"); + if (!File.Exists(manifestPath)) throw new ToolException($"Manifest not found: {manifestPath}"); + var entries = ReadManifest(manifestPath); + Directory.CreateDirectory(outDir); + var recordedPath = Path.Combine(outDir, RecordedHashesFile); + var recorded = File.Exists(recordedPath) + ? JsonSerializer.Deserialize>(await File.ReadAllTextAsync(recordedPath)) ?? [] + : []; + var newlyRecorded = new List(); + var failures = 0; + using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("Titano.Tools/1.0 (+fixtures)"); + foreach (var entry in entries) + { + var target = Path.Combine(outDir, entry.Name); + var expected = entry.Sha256 ?? recorded.GetValueOrDefault(entry.Name); + try + { + if (File.Exists(target)) + { + var hash = await HashAsync(target); + if (expected is null || hash.Equals(expected, StringComparison.OrdinalIgnoreCase)) + { + if (expected is null) Record(entry.Name, hash); + Console.WriteLine($"ok {entry.Name} (verified)"); + continue; + } + Console.WriteLine($"mismatch {entry.Name}: downloading again"); + File.Delete(target); + } + var actual = await DownloadAsync(http, entry, target); + if (expected is not null && !actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) + { + File.Delete(target); + throw new InvalidDataException($"SHA-256 {actual} does not match {expected}"); + } + if (expected is null) Record(entry.Name, actual); + Console.WriteLine($"fetched {entry.Name} ({new FileInfo(target).Length / 1e6:F1} MB)"); + } + catch (Exception ex) when (ex is HttpRequestException or IOException or InvalidDataException or TaskCanceledException or UnauthorizedAccessException) + { + failures++; + Console.Error.WriteLine($"failed {entry.Name}: {ex.Message}"); + } + } + await File.WriteAllTextAsync(recordedPath, JsonSerializer.Serialize(recorded, new JsonSerializerOptions { WriteIndented = true })); + if (newlyRecorded.Count > 0) + { + Console.WriteLine("Recorded SHA-256 of first downloads (copy into the manifest to pin them):"); + foreach (var line in newlyRecorded) Console.WriteLine(" " + line); + } + Console.WriteLine(failures == 0 ? $"{entries.Count} fixture(s) ready in {outDir}" : $"{failures} of {entries.Count} fixture(s) failed"); + return failures == 0 ? 0 : 1; + + void Record(string name, string hash) + { + if (recorded.GetValueOrDefault(name) == hash) return; + recorded[name] = hash; + newlyRecorded.Add($"{name}: {hash}"); + } + } + + internal sealed record Entry(string Name, Uri Url, string? Sha256, long? Size); + + internal static List ReadManifest(string path) + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + if (!doc.RootElement.TryGetProperty("files", out var files) || files.ValueKind != JsonValueKind.Array) throw new ToolException("Manifest has no 'files' array"); + var entries = new List(); + foreach (var f in files.EnumerateArray()) + { + var name = f.GetProperty("name").GetString() ?? throw new ToolException("Fixture without a name"); + if (name != Path.GetFileName(name) || name.StartsWith('.')) throw new ToolException($"Fixture name must be a plain file name: {name}"); + if (!Uri.TryCreate(f.GetProperty("url").GetString(), UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps) + throw new ToolException($"Fixture {name} needs an https URL"); + var sha = f.TryGetProperty("sha256", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null; + long? size = f.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number ? z.GetInt64() : null; + entries.Add(new Entry(name, url, sha, size)); + } + return entries; + } + + /// Downloads into target.part, resuming from its length with a range request, then renames it. + private static async Task DownloadAsync(HttpClient http, Entry entry, string target) + { + var part = target + ".part"; + var existing = File.Exists(part) ? new FileInfo(part).Length : 0; + if (entry.Size is not { } size || existing < size) + { + using var request = new HttpRequestMessage(HttpMethod.Get, entry.Url); + if (existing > 0) request.Headers.Range = new RangeHeaderValue(existing, null); + using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + if (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && existing > 0) + { + // The partial file is already complete (or the server lost it): verified below. + } + else + { + response.EnsureSuccessStatusCode(); + var resume = response.StatusCode == HttpStatusCode.PartialContent; + await using var output = new FileStream(part, resume ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous); + await using var input = await response.Content.ReadAsStreamAsync(); + await input.CopyToAsync(output); + } + } + if (entry.Size is { } expected && new FileInfo(part).Length is var length && length != expected) + { + File.Delete(part); + throw new InvalidDataException($"size {length} differs from {expected}"); + } + var hash = await HashAsync(part); + File.Move(part, target, overwrite: true); + return hash; + } + + private static async Task HashAsync(string path) + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream)); + } +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index d5575d16..550f05a4 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -8,6 +8,8 @@ var commands = new ICommand[] new XamlLintCommand(), new PackageGuardCommand(), new ChangelogCommand(), + new DiagnoseCommand(), + new FixturesCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") diff --git a/tests/Titano.Core.Tests/Decoding/ExternalFixtureTests.cs b/tests/Titano.Core.Tests/Decoding/ExternalFixtureTests.cs new file mode 100644 index 00000000..f641ff7c --- /dev/null +++ b/tests/Titano.Core.Tests/Decoding/ExternalFixtureTests.cs @@ -0,0 +1,84 @@ +using System.Text.Json; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Metadata; +using Titano.Testing; + +namespace Titano.Core.Tests.Decoding; + +/// Real camera files from tests/fixtures/manifest.json (fetched by Titano.Tools fixtures); each test is +/// skipped when its file is absent. A native decode must reach the expected size and look like the camera's own +/// embedded preview (luminance correlation), which catches wrong byte orders, CFA phases or colour matrices. +public sealed class ExternalFixtureTests(TestContext context) +{ + private const int Edge = 256; + + private static JsonElement Entry(string name) + { + var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(TestContext.FixturesDirectory, "manifest.json"))); + foreach (var f in manifest.RootElement.GetProperty("files").EnumerateArray()) + { + if (f.GetProperty("name").GetString() == name) return f.Clone(); + } + throw new InvalidOperationException("No manifest entry " + name); + } + + [Theory] + [Case("google-pixel-4a.dng")] + [Case("canon-eos-5d-mark-iii.cr2")] + [Case("nikon-d850.nef")] + [Case("sony-ilce-7m3.arw")] + [Case("fujifilm-x-t2.raf")] + [Case("pentax-k-1.pef")] + [Timeout(20_000)] + public void DecodesNativelyAndMatchesThePreview(string name) + { + var path = Path.Combine(TestContext.FixturesDirectory, "external", name); + if (!File.Exists(path)) TestContext.Skip($"{name} not fetched (run Titano.Tools fixtures)"); + var entry = Entry(name); + var metadata = MetadataReader.Read(path); + Assert.Equal(entry.GetProperty("format").GetString(), metadata.Format.ToString()); + var probe = new ManagedDecoderProvider().Probe(path); + context.Log($"{name}: {probe}; {metadata.Make} {metadata.Model}, {metadata.Width}x{metadata.Height}, orientation {metadata.Orientation}"); + Assert.Equal(DecodeTier.Native, probe.Tier); + + var decoder = DecoderFactory.CreateServer(); + using var native = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false)); + Assert.Equal(DecodeTier.Native, native!.Tier); + var (w, h) = (entry.GetProperty("width").GetInt32(), entry.GetProperty("height").GetInt32()); + Assert.InRange(native.SourceWidth, w * 0.98, w * 1.02); + Assert.InRange(native.SourceHeight, h * 0.98, h * 1.02); + foreach (var v in native.Pixels.Data) + { + if (!float.IsFinite(v)) Assert.Fail("non-finite pixel"); + } + + using var preview = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false, ForcePreview: true)); + if (preview is null || preview.Tier != DecodeTier.EmbeddedPreview) TestContext.Skip("no embedded preview to compare with"); + var correlation = Correlation(native.Pixels, preview.Pixels); + context.Log($"luminance correlation with the embedded preview: {correlation:F3}"); + Assert.Greater(correlation, 0.8); + } + + /// Pearson correlation of sRGB-encoded luminance after resizing both to a common 64-pixel-wide grid. + private static double Correlation(ImageBuffer a, ImageBuffer b) + { + var height = int.Max(1, (int)double.Round(64.0 * a.Height / a.Width)); + using var ra = Resampler.Resize(a, 64, height, ResampleFilter.Box); + using var rb = Resampler.Resize(b, 64, height, ResampleFilter.Box); + var n = ra.PlaneLength; + double sa = 0, sb = 0, saa = 0, sbb = 0, sab = 0; + for (var i = 0; i < n; i++) + { + double la = ColorSpace.EncodeFast(ColorSpace.Luminance(ra.Plane(0)[i], ra.Plane(1)[i], ra.Plane(2)[i])); + double lb = ColorSpace.EncodeFast(ColorSpace.Luminance(rb.Plane(0)[i], rb.Plane(1)[i], rb.Plane(2)[i])); + sa += la; + sb += lb; + saa += la * la; + sbb += lb * lb; + sab += la * lb; + } + var cov = sab / n - sa / n * (sb / n); + return cov / double.Sqrt(double.Max(saa / n - sa / n * (sa / n), 1e-12) * double.Max(sbb / n - sb / n * (sb / n), 1e-12)); + } +} diff --git a/tests/fixtures/manifest.json b/tests/fixtures/manifest.json new file mode 100644 index 00000000..73815b4d --- /dev/null +++ b/tests/fixtures/manifest.json @@ -0,0 +1,78 @@ +{ + "description": "CC0 RAW samples from raw.pixls.us (one per managed RAW decoder), fetched by 'Titano.Tools fixtures' into tests/fixtures/external (git-ignored, CI-cached on this file). sha256 null: the first download records its hash in external/recorded-hashes.json and prints it for pinning here. width/height: size the managed decoder develops (before orientation). urlVerified false: the URL follows the site's data/// layout but was written without network access; replace it with the sample's download link if the fetch reports 404.", + "license": "CC0-1.0", + "files": [ + { + "name": "google-pixel-4a.dng", + "url": "https://raw.pixls.us/data/Google/Pixel%204a/PXL_20201101_120000000.dng", + "sha256": null, + "size": null, + "format": "Dng", + "make": "Google", + "model": "Pixel 4a", + "width": 4032, + "height": 3024, + "urlVerified": false + }, + { + "name": "canon-eos-5d-mark-iii.cr2", + "url": "https://raw.pixls.us/data/Canon/EOS%205D%20Mark%20III/IMG_0001.CR2", + "sha256": null, + "size": null, + "format": "Cr2", + "make": "Canon", + "model": "Canon EOS 5D Mark III", + "width": 5760, + "height": 3840, + "urlVerified": false + }, + { + "name": "nikon-d850.nef", + "url": "https://raw.pixls.us/data/Nikon/D850/DSC_0001.NEF", + "sha256": null, + "size": null, + "format": "Nef", + "make": "NIKON CORPORATION", + "model": "NIKON D850", + "width": 8288, + "height": 5520, + "urlVerified": false + }, + { + "name": "sony-ilce-7m3.arw", + "url": "https://raw.pixls.us/data/Sony/ILCE-7M3/DSC00001.ARW", + "sha256": null, + "size": null, + "format": "Arw", + "make": "SONY", + "model": "ILCE-7M3", + "width": 6048, + "height": 4024, + "urlVerified": false + }, + { + "name": "fujifilm-x-t2.raf", + "url": "https://raw.pixls.us/data/Fujifilm/X-T2/DSCF0001.RAF", + "sha256": null, + "size": null, + "format": "Raf", + "make": "FUJIFILM", + "model": "X-T2", + "width": 6000, + "height": 4000, + "urlVerified": false + }, + { + "name": "pentax-k-1.pef", + "url": "https://raw.pixls.us/data/Pentax/K-1/IMGP0001.PEF", + "sha256": null, + "size": null, + "format": "Pef", + "make": "RICOH IMAGING COMPANY, LTD.", + "model": "PENTAX K-1", + "width": 7392, + "height": 4950, + "urlVerified": false + } + ] +} From a0c2b1b28c82b4ad00f03598f9bf268d877a23ca Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:33:43 +0000 Subject: [PATCH 160/188] fix(render): report an unreadable playback rate instead of ignoring it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Render/RenderPlan.cs | 4 +++- tests/Titano.Core.Tests/Render/RenderPlanTests.cs | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Titano.Core/Render/RenderPlan.cs b/src/Titano.Core/Render/RenderPlan.cs index 1d388930..6ddc6c1b 100644 --- a/src/Titano.Core/Render/RenderPlan.cs +++ b/src/Titano.Core/Render/RenderPlan.cs @@ -205,8 +205,10 @@ public sealed class RenderPlan var n = captureTimes.Count; var timing = project.Timing; var mode = ProjectValues.Get(timing.Mode, TimingMode.Constant); - var playback = FrameRateText.TryParse(timing.FrameRate.Resolve(string.Empty), out var rate) ? rate.Value : frameRate.Value; var warnings = new List(); + var playbackText = timing.FrameRate.Resolve(string.Empty); + var playback = FrameRateText.TryParse(playbackText, out var rate) ? rate.Value : frameRate.Value; + if (playbackText.Length > 0 && rate.Numerator == 0) warnings.Add("Export.Plan.FrameRateIgnored"); var excluded = new bool[n]; foreach (var i in project.ExcludedFrames) diff --git a/tests/Titano.Core.Tests/Render/RenderPlanTests.cs b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs index e42f70f0..26758d9a 100644 --- a/tests/Titano.Core.Tests/Render/RenderPlanTests.cs +++ b/tests/Titano.Core.Tests/Render/RenderPlanTests.cs @@ -173,6 +173,15 @@ public sealed class RenderPlanTests Assert.Approximately(0.1 * 60, bad.Frames[0].SourcePosition, 1e-9); } + [Test] + public void AnUnreadablePlaybackRateFallsBackToTheOutputRate() + { + var plan = RenderPlan.Build(Regular(10), Timing(TimingMode.Constant, playback: "fast"), new Rational(25, 1)); + Assert.Contains("Export.Plan.FrameRateIgnored", plan.Warnings); + Assert.Equal(10, plan.SlotCount); + Assert.Equal(25.0, plan.PlaybackRate); + } + [Test] public void EverythingExcludedGivesAnEmptyPlan() { From bcf0510a8e8abfc619be7dd5c9d1b8267da0f4f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 11:43:45 +0000 Subject: [PATCH 161/188] fix(raw): match LibRaw on RAF and unpacked NEF layouts; drop frame copies Cross-checking synthetic files with LibRaw's dcraw_emu showed it reads uncompressed RAF samples as little-endian words and unpacked data under the Nikon compression tag as big-endian words shifted left by four; the readers and test writers now do the same (CR2, lossless NEF, ARW2 and PEF already decoded identically, ~86 dB). The default crop and the final orientation step no longer copy a full frame when they change nothing, lowering the 24 MP peak by two frame copies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Raw/NativeRaw.cs | 7 +- src/Titano.Core/Codecs/Raw/NefReader.cs | 10 ++- src/Titano.Core/Codecs/Raw/RafReader.cs | 5 +- src/Titano.Core/Codecs/Raw/RawDeveloper.cs | 87 ++++++++++++------- tests/Titano.Core.Tests/Raw/NativeRawTests.cs | 2 +- .../Titano.Core.Tests/Raw/NativeRawWriters.cs | 4 +- 6 files changed, 72 insertions(+), 43 deletions(-) diff --git a/src/Titano.Core/Codecs/Raw/NativeRaw.cs b/src/Titano.Core/Codecs/Raw/NativeRaw.cs index 342d110b..632c46cb 100644 --- a/src/Titano.Core/Codecs/Raw/NativeRaw.cs +++ b/src/Titano.Core/Codecs/Raw/NativeRaw.cs @@ -140,8 +140,9 @@ internal static class NativeRaw } } -/// Uncompressed raw payloads: 16-bit words (either byte order) or MSB-first packed samples (TIFF convention). -internal sealed class PlainRawLoader(long offset, long length, int width, int height, int bits, bool words, bool littleEndian) : RawLoader +/// Uncompressed raw payloads: 16-bit words (either byte order, optionally holding the value shifted left by +/// bits) or MSB-first packed samples (TIFF convention). +internal sealed class PlainRawLoader(long offset, long length, int width, int height, int bits, bool words, bool littleEndian, int shift = 0) : RawLoader { public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken) { @@ -157,7 +158,7 @@ internal sealed class PlainRawLoader(long offset, long length, int width, int he if (words) { for (var x = 0; x < width; x++) - dst[x] = (ushort)((littleEndian ? row[2 * x] | row[2 * x + 1] << 8 : row[2 * x] << 8 | row[2 * x + 1]) & mask); + dst[x] = (ushort)((littleEndian ? row[2 * x] | row[2 * x + 1] << 8 : row[2 * x] << 8 | row[2 * x + 1]) >> shift & mask); return; } long bit = 0; diff --git a/src/Titano.Core/Codecs/Raw/NefReader.cs b/src/Titano.Core/Codecs/Raw/NefReader.cs index e42d8fc5..1b71277b 100644 --- a/src/Titano.Core/Codecs/Raw/NefReader.cs +++ b/src/Titano.Core/Codecs/Raw/NefReader.cs @@ -63,10 +63,14 @@ internal static class NefReader white = decode.White; loader = new NikonHuffmanLoader(offset, length, width, height, decode); } - else if (compression is CompressionNikon or 1 && length >= (long)width * height * 2) + else if (compression == CompressionNikon) { - // Nikon writes unpacked "compressed" data big-endian; plain uncompressed follows the TIFF byte order. - loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: compression == 1 && r.LittleEndian); + // Unpacked data under the Nikon compression tag: big-endian words holding the value shifted left by 4 (LibRaw). + loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: false, shift: 4); + } + else if (compression == 1 && length >= (long)width * height * 2) + { + loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: r.LittleEndian); } else if (compression == 1 && length >= ((long)width * bits + 7) / 8 * height) { diff --git a/src/Titano.Core/Codecs/Raw/RafReader.cs b/src/Titano.Core/Codecs/Raw/RafReader.cs index 2219b7ee..c7a34290 100644 --- a/src/Titano.Core/Codecs/Raw/RafReader.cs +++ b/src/Titano.Core/Codecs/Raw/RafReader.cs @@ -10,7 +10,8 @@ namespace Titano.Core.Codecs.Raw; /// gives the raster size (0xF001/0xF002), bit depth (0xF003), the data offset relative to that block (0xF007), its length /// (0xF008) and black levels (0xF00A); the RAF directory supplies the crop (0x0110 top-left, 0x0111 size), the 6×6 /// colour layout (0x0131, stored reversed, anchored at the raster origin; Bayer bodies describe their 2×2 pattern the same -/// way) and the as-shot GRGB levels (0x2FF0). Samples are 16-bit words in the block's byte order. Compressed RAFs and +/// way) and the as-shot GRGB levels (0x2FF0). Samples are little-endian 16-bit words whatever the block's byte order, as +/// LibRaw reads them. Compressed RAFs and /// SuperCCD (45°) layouts are not supported and fall back to the preview. /// internal static class RafReader @@ -87,7 +88,7 @@ internal static class RafReader if (g > 0) multipliers = new Vector3D(red / g, 1, blue / g); } var metadata = MetadataReader.Read(stream, "frame.raf"); - var loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: r.LittleEndian); + var loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: true); return NativeRaw.Frame("managed-raf", width, height, cfa, active, black, (1 << bits) - 1, multipliers, metadata.Orientation, metadata.Make ?? "FUJIFILM", metadata.Model, loader, warnings); } diff --git a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs index 0b106121..33eac0fa 100644 --- a/src/Titano.Core/Codecs/Raw/RawDeveloper.cs +++ b/src/Titano.Core/Codecs/Raw/RawDeveloper.cs @@ -123,14 +123,23 @@ internal static class RawDeveloper DngOpcodes.Apply(list3, image, warnings, cancellationToken); if (unbalance) ScalePlanes(image.Pixels, wb); } - using var cropped = Crop(frame, image); - ApplyMatrix(cropped, colour.BalancedToRec709, dop, cancellationToken); - return Finish(frame, cropped, options); } - finally + catch { image.Pixels.Dispose(); + throw; } + var cropped = Crop(frame, image); + try + { + ApplyMatrix(cropped, colour.BalancedToRec709, dop, cancellationToken); + } + catch + { + cropped.Dispose(); + throw; + } + return Finish(frame, cropped, options); } private static ImageBuffer DevelopMonochrome(RawFrame frame, OpcodeImage stage, RawDecodeOptions options, ICollection warnings, CancellationToken cancellationToken) @@ -139,40 +148,51 @@ internal static class RawDeveloper try { DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList3, 3, warnings), image, warnings, cancellationToken); - using var cropped = Crop(frame, image); - Scale(cropped.Plane(0), (float)double.Exp2(frame.Color.BaselineExposure)); - using var rgb = PixelConvert.GrayToRgb(cropped); - return Finish(frame, rgb, options); } - finally + catch { image.Pixels.Dispose(); + throw; + } + ImageBuffer rgb; + using (var cropped = Crop(frame, image)) + { + Scale(cropped.Plane(0), (float)double.Exp2(frame.Color.BaselineExposure)); + rgb = PixelConvert.GrayToRgb(cropped); + } + return Finish(frame, rgb, options); + } + + /// Default scale, then orientation. Takes ownership of : returns it when nothing + /// changes, otherwise a new buffer (the input is disposed). + private static ImageBuffer Finish(RawFrame frame, ImageBuffer image, RawDecodeOptions options) + { + var current = image; + try + { + var (sh, sv) = frame.DefaultScale; + if (sh != sv && sh > 0 && sv > 0) + { + // Only the ratio matters for square output pixels; stretch the axis with the larger factor. + var ratio = sh / sv; + var (w, h) = ratio > 1 ? ((int)double.Round(current.Width * ratio), current.Height) : (current.Width, (int)double.Round(current.Height / ratio)); + current = Replace(current, Resampler.Resize(current, int.Max(1, w), int.Max(1, h))); + } + if (options.ApplyOrientation && frame.Orientation is >= 2 and <= 8) + current = Replace(current, PixelConvert.ApplyOrientation(current, frame.Orientation)); + return current; + } + catch + { + current.Dispose(); + throw; } } - /// Default scale, then orientation; always returns a new buffer. - private static ImageBuffer Finish(RawFrame frame, ImageBuffer image, RawDecodeOptions options) + private static ImageBuffer Replace(ImageBuffer old, ImageBuffer next) { - var (sh, sv) = frame.DefaultScale; - ImageBuffer? scaled = null; - if (sh != sv && sh > 0 && sv > 0) - { - // Only the ratio matters for square output pixels; stretch the axis with the larger factor. - var ratio = sh / sv; - var (w, h) = ratio > 1 ? ((int)double.Round(image.Width * ratio), image.Height) : (image.Width, (int)double.Round(image.Height / ratio)); - scaled = Resampler.Resize(image, int.Max(1, w), int.Max(1, h)); - } - var source = scaled ?? image; - try - { - return options.ApplyOrientation && frame.Orientation is >= 2 and <= 8 - ? PixelConvert.ApplyOrientation(source, frame.Orientation) - : source.Clone(); - } - finally - { - scaled?.Dispose(); - } + old.Dispose(); + return next; } /// Stored values as floats divided by 65535 (the stage-1 domain of the opcodes), sample planes split. @@ -294,7 +314,8 @@ internal static class RawDeveloper for (var i = 0; i < values.Length; i++) values[i] *= factor; } - /// Default crop (stage coordinates relative to the active area) intersected with what the opcodes left. + /// Default crop (stage coordinates relative to the active area) intersected with what the opcodes left. Takes + /// ownership of the image's pixels: returns them when nothing is cut, otherwise a new buffer (the input is disposed). private static ImageBuffer Crop(RawFrame frame, OpcodeImage image) { var crop = frame.DefaultCrop ?? new RawRect(0, 0, frame.ActiveArea.Width, frame.ActiveArea.Height); @@ -305,11 +326,13 @@ internal static class RawDeveloper var x1 = int.Clamp((int)double.Floor(image.BufferX(area.Right - 1) + 1e-9) + 1, x0 + 1, image.Width); var y1 = int.Clamp((int)double.Floor(image.BufferY(area.Bottom - 1) + 1e-9) + 1, y0 + 1, image.Height); var src = image.Pixels; + if (x0 == 0 && y0 == 0 && x1 == src.Width && y1 == src.Height) return src; var dst = new ImageBuffer(x1 - x0, y1 - y0, src.Channels, clear: false); for (var c = 0; c < src.Channels; c++) { for (var y = y0; y < y1; y++) src.Row(c, y).Slice(x0, x1 - x0).CopyTo(dst.Row(c, y - y0)); } + src.Dispose(); return dst; } diff --git a/tests/Titano.Core.Tests/Raw/NativeRawTests.cs b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs index 5dd8fae1..f2ecac84 100644 --- a/tests/Titano.Core.Tests/Raw/NativeRawTests.cs +++ b/tests/Titano.Core.Tests/Raw/NativeRawTests.cs @@ -43,7 +43,7 @@ public sealed class NativeRawTests(TestContext context) [Theory] [Case(NefEncoding.Lossless, 14)] [Case(NefEncoding.Lossless, 12)] - [Case(NefEncoding.Unpacked, 14)] + [Case(NefEncoding.Unpacked, 12)] [Case(NefEncoding.Packed, 12)] public void NefEncodings(NefEncoding encoding, int bits) { diff --git a/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs b/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs index 9fa3bce0..4c566598 100644 --- a/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs +++ b/tests/Titano.Core.Tests/Raw/NativeRawWriters.cs @@ -191,7 +191,7 @@ internal static class NativeRawWriters } case NefEncoding.Unpacked: data = new byte[s.Samples.Length * 2]; - for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]); + for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), (ushort)(s.Samples[i] << 4)); break; default: compression = 1; @@ -436,7 +436,7 @@ internal static class NativeRawWriters Record(0x2FF0, [.. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.X)), .. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.Z))]); byte[] directory = [.. Box.U32(6), .. records]; var data = new byte[s.Samples.Length * 2]; - for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]); + for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(2 * i), s.Samples[i]); var fuji = new IfdSpec().Long(0xF001, (uint)s.Width).Long(0xF002, (uint)s.Height).Long(0xF003, 14) .Long(0xF00A, [.. Enumerable.Repeat(1024u, 36)]).Blob(0xF007, 0xF008, data); var block = TiffFile.Build(new IfdSpec().Child(0xF000, fuji), littleEndian: false); From f78a76513c3263a62b04b20828274b336418c526 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:26:17 +0000 Subject: [PATCH 162/188] fix(core): tell value-type Auto settings without advice from an advised default Auto.Resolve returned default instead of the fallback for value types because AutoValue cannot be null there. Auto now records HasAdvice; the render pipeline's ProjectValues workaround and the advisor's ReasonKey heuristic are removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Advice/ParameterBindings.cs | 8 ++------ src/Titano.Core/Project/Auto.cs | 10 +++++++--- src/Titano.Core/Render/ProjectValues.cs | 17 ---------------- src/Titano.Core/Render/RenderPipeline.cs | 4 ++-- src/Titano.Core/Render/RenderPlan.cs | 2 +- src/Titano.Core/Render/RenderPreparation.cs | 18 ++++++++--------- src/Titano.Core/Render/RenderSetup.cs | 6 +++--- .../Project/ProjectSettingsTests.cs | 17 ++++++++++++++++ .../Render/ProjectValuesTests.cs | 20 ------------------- 9 files changed, 41 insertions(+), 61 deletions(-) delete mode 100644 src/Titano.Core/Render/ProjectValues.cs delete mode 100644 tests/Titano.Core.Tests/Render/ProjectValuesTests.cs diff --git a/src/Titano.Core/Advice/ParameterBindings.cs b/src/Titano.Core/Advice/ParameterBindings.cs index f3566556..956dd530 100644 --- a/src/Titano.Core/Advice/ParameterBindings.cs +++ b/src/Titano.Core/Advice/ParameterBindings.cs @@ -94,10 +94,6 @@ internal static class ParameterBindings public static string Size(int width, int height) => string.Create(CultureInfo.InvariantCulture, $"{width}x{height}"); - public static bool HasAdvice(Auto auto) => typeof(T).IsValueType - ? auto.ReasonKey is not null && !auto.ReasonKey.StartsWith(AdvisorKeys.MissingPrefix, StringComparison.Ordinal) - : auto.AutoValue is not null; - private static ParameterBinding AutoField(string parameter, AdvisorSection section, bool module, Func> get, Func, ProjectSettings> set) => new() { Parameter = parameter, @@ -108,7 +104,7 @@ internal static class ParameterBindings ResetToAuto = s => set(s, get(s).Reset()), }; - private static object? EffectiveOf(Auto auto) => !auto.IsAuto && auto.Manual is not null ? auto.Manual : HasAdvice(auto) ? auto.AutoValue : null; + private static object? EffectiveOf(Auto auto) => !auto.IsAuto && auto.Manual is not null ? auto.Manual : auto.HasAdvice ? auto.AutoValue : null; /// /// Stores a value with its reason. Missing data changes no value: the missing-data reason is stored only when the @@ -118,7 +114,7 @@ internal static class ParameterBindings { var args = Strings(recommendation.ReasonArgs); if (recommendation.Value is null) - return HasAdvice(auto) ? auto : auto with { ReasonKey = recommendation.ReasonKey, ReasonArgs = args }; + return auto.HasAdvice ? auto : auto with { ReasonKey = recommendation.ReasonKey, ReasonArgs = args }; if (recommendation.Value is not T value) throw new InvalidOperationException($"{recommendation.Parameter} expects {typeof(T).Name}, got {recommendation.Value.GetType().Name}."); return auto.WithAdvice(value, recommendation.ReasonKey, args); diff --git a/src/Titano.Core/Project/Auto.cs b/src/Titano.Core/Project/Auto.cs index 469ce46c..4a1dcfa8 100644 --- a/src/Titano.Core/Project/Auto.cs +++ b/src/Titano.Core/Project/Auto.cs @@ -9,9 +9,13 @@ public sealed record Auto { public bool IsAuto { get; init; } = true; - /// The advisor's value (null until analysis provides one). + /// The advisor's value; meaningful only when . public T? AutoValue { get; init; } + /// True once the advisor stored a value. Needed because a value type's is never + /// null: without it "no advice" and an advised 0 or false look the same. + public bool HasAdvice { get; init; } + /// The user's value when is false. public T? Manual { get; init; } @@ -21,11 +25,11 @@ public sealed record Auto public IReadOnlyList? ReasonArgs { get; init; } /// The value in force: manual when set by the user, otherwise the advisor's, otherwise . - public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : AutoValue ?? fallback; + public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : HasAdvice && AutoValue is not null ? AutoValue : fallback; public Auto WithManual(T value) => this with { IsAuto = false, Manual = value }; public Auto Reset() => this with { IsAuto = true, Manual = default }; - public Auto WithAdvice(T value, string? reasonKey, params string[] args) => this with { AutoValue = value, ReasonKey = reasonKey, ReasonArgs = args }; + public Auto WithAdvice(T value, string? reasonKey, params string[] args) => this with { AutoValue = value, HasAdvice = true, ReasonKey = reasonKey, ReasonArgs = args }; } diff --git a/src/Titano.Core/Render/ProjectValues.cs b/src/Titano.Core/Render/ProjectValues.cs deleted file mode 100644 index 67b3f40c..00000000 --- a/src/Titano.Core/Render/ProjectValues.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Titano.Core.Project; - -namespace Titano.Core.Render; - -/// -/// Reads value-type settings. For value types is never null (an -/// unconstrained T? is T), so returns default instead of the fallback -/// when there is no advice; here a default automatic value means "no advice" and yields the fallback. -/// -internal static class ProjectValues -{ - public static T Get(Auto setting, T fallback) where T : struct - { - if (!setting.IsAuto) return setting.Manual; - return EqualityComparer.Default.Equals(setting.AutoValue, default) ? fallback : setting.AutoValue; - } -} diff --git a/src/Titano.Core/Render/RenderPipeline.cs b/src/Titano.Core/Render/RenderPipeline.cs index dd2575e6..a984dcb1 100644 --- a/src/Titano.Core/Render/RenderPipeline.cs +++ b/src/Titano.Core/Render/RenderPipeline.cs @@ -138,8 +138,8 @@ internal sealed class RenderRun : IDisposable else _warnings.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture))); } var motion = input.Project.Motion; - _targetShutter = double.Clamp(ProjectValues.Get(motion.TargetShutterAngle, 180.0), 0, 360); - _flowQuality = ProjectValues.Get(motion.FlowQuality, FlowQualitySetting.Balanced) switch + _targetShutter = double.Clamp(motion.TargetShutterAngle.Resolve(180.0), 0, 360); + _flowQuality = motion.FlowQuality.Resolve(FlowQualitySetting.Balanced) switch { FlowQualitySetting.Draft => FlowQuality.Draft, FlowQualitySetting.Best => FlowQuality.Best, diff --git a/src/Titano.Core/Render/RenderPlan.cs b/src/Titano.Core/Render/RenderPlan.cs index 6ddc6c1b..c9a4938e 100644 --- a/src/Titano.Core/Render/RenderPlan.cs +++ b/src/Titano.Core/Render/RenderPlan.cs @@ -204,7 +204,7 @@ public sealed class RenderPlan options ??= RenderPlanOptions.Default; var n = captureTimes.Count; var timing = project.Timing; - var mode = ProjectValues.Get(timing.Mode, TimingMode.Constant); + var mode = timing.Mode.Resolve(TimingMode.Constant); var warnings = new List(); var playbackText = timing.FrameRate.Resolve(string.Empty); var playback = FrameRateText.TryParse(playbackText, out var rate) ? rate.Value : frameRate.Value; diff --git a/src/Titano.Core/Render/RenderPreparation.cs b/src/Titano.Core/Render/RenderPreparation.cs index b35316d5..1892e6c2 100644 --- a/src/Titano.Core/Render/RenderPreparation.cs +++ b/src/Titano.Core/Render/RenderPreparation.cs @@ -118,12 +118,12 @@ public static class RenderPreparation Array.Fill(excluded, true); foreach (var i in included) excluded[i] = false; - var deflicker = ProjectValues.Get(exposure.Deflicker, false); - var holyGrail = ProjectValues.Get(exposure.HolyGrail, false); - var regionMode = deflicker ? ProjectValues.Get(exposure.Regions, RegionMode.Off) : RegionMode.Off; - var whiteBalance = ProjectValues.Get(exposure.WhiteBalanceSmoothing, false); - var stabilize = ProjectValues.Get(motion.Stabilize, false); - var smoothing = ProjectValues.Get(motion.StabilizeSmoothing, new StabilizerOptions().SmoothingSigma); + var deflicker = exposure.Deflicker.Resolve(false); + var holyGrail = exposure.HolyGrail.Resolve(false); + var regionMode = deflicker ? exposure.Regions.Resolve(RegionMode.Off) : RegionMode.Off; + var whiteBalance = exposure.WhiteBalanceSmoothing.Resolve(false); + var stabilize = motion.Stabilize.Resolve(false); + var smoothing = motion.StabilizeSmoothing.Resolve(new StabilizerOptions().SmoothingSigma); var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, excluded) : null; var measureLuminance = (deflicker || holyGrail) && luminance is null; @@ -183,15 +183,15 @@ public static class RenderPreparation { var options = new DeflickerOptions { - Window = int.Max(3, ProjectValues.Get(exposure.DeflickerWindow, 0) is var w and > 0 ? w : RecommendedWindow(luminance)), - Strength = double.Clamp(ProjectValues.Get(exposure.DeflickerStrength, 1.0), 0, 1), + Window = int.Max(3, exposure.DeflickerWindow.Resolve(0) is var w and > 0 ? w : RecommendedWindow(luminance)), + Strength = double.Clamp(exposure.DeflickerStrength.Resolve(1.0), 0, 1), }; var evs = new double?[n]; // Excluded frames (test shots, bumps) must not create exposure steps. for (var i = 0; i < n; i++) evs[i] = excluded[i] ? null : input.Frames[i].ExposureValue; if (holyGrail) { - var transition = ProjectValues.Get(exposure.TransitionLength, 0); + var transition = exposure.TransitionLength.Resolve(0); hg = HolyGrailEngine.Compute(luminance, evs, new HolyGrailOptions { TransitionFrames = transition > 0 ? transition : null, Deflicker = options }); } var offsets = hg?.StepOffsets ?? DeflickerEngine.OffsetsFromExposure(evs); diff --git a/src/Titano.Core/Render/RenderSetup.cs b/src/Titano.Core/Render/RenderSetup.cs index ae6e1d2b..b58de9cf 100644 --- a/src/Titano.Core/Render/RenderSetup.cs +++ b/src/Titano.Core/Render/RenderSetup.cs @@ -47,11 +47,11 @@ public sealed record RenderSetup warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k))); warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args))); var stacking = project.Stack.Mode != StackSetting.None; - var blur = ProjectValues.Get(project.Motion.MotionBlur, false); + var blur = project.Motion.MotionBlur.Resolve(false); if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking")); var exposure = project.Exposure; - var measuring = ProjectValues.Get(exposure.Deflicker, false) || ProjectValues.Get(exposure.HolyGrail, false) - || ProjectValues.Get(exposure.WhiteBalanceSmoothing, false) || ProjectValues.Get(project.Motion.Stabilize, false); + var measuring = exposure.Deflicker.Resolve(false) || exposure.HolyGrail.Resolve(false) + || exposure.WhiteBalanceSmoothing.Resolve(false) || project.Motion.Stabilize.Resolve(false); return new RenderSetup { Target = target, diff --git a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs index 99712dd2..c22c0835 100644 --- a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs +++ b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs @@ -30,6 +30,23 @@ public sealed class ProjectSettingsTests Assert.Contains("\"deflickerWindow\"", settings.ToJson()); } + [Test] + public void ValueTypesFallBackOnlyWithoutAdvice() + { + Assert.Equal(21, new Auto().Resolve(21)); + Assert.Equal(FlowQualitySetting.Balanced, new Auto().Resolve(FlowQualitySetting.Balanced)); + Assert.Equal(0, new Auto().WithAdvice(0, null).Resolve(21)); + Assert.False(new Auto().WithAdvice(false, null).Resolve(true)); + Assert.Equal(0.5, new Auto().WithAdvice(0.8, null).WithManual(0.5).Resolve(1.0)); + Assert.False(new Auto().WithManual(false).Resolve(true)); + var back = ProjectSettings.FromJson(new ProjectSettings + { + Exposure = new ExposureSettings { Deflicker = new Auto().WithAdvice(false, null) }, + }.ToJson()); + Assert.False(back.Exposure.Deflicker.Resolve(true)); + Assert.True(ProjectSettings.FromJson(new ProjectSettings().ToJson()).Exposure.Deflicker.Resolve(true)); + } + [Test] public void ResetReturnsToAdvice() { diff --git a/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs b/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs deleted file mode 100644 index dd550837..00000000 --- a/tests/Titano.Core.Tests/Render/ProjectValuesTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Titano.Core.Project; -using Titano.Core.Render; -using Titano.Testing; - -namespace Titano.Core.Tests.Render; - -public sealed class ProjectValuesTests -{ - [Test] - public void ValueTypeSettingsFallBackWithoutAdvice() - { - Assert.Equal(21, ProjectValues.Get(new Auto(), 21)); - Assert.Equal(180.0, ProjectValues.Get(new Auto(), 180.0)); - Assert.Equal(FlowQualitySetting.Balanced, ProjectValues.Get(new Auto(), FlowQualitySetting.Balanced)); - Assert.Equal(41, ProjectValues.Get(new Auto().WithAdvice(41, null), 21)); - Assert.Equal(0.5, ProjectValues.Get(new Auto().WithAdvice(0.8, null).WithManual(0.5), 1.0)); - Assert.Equal(FlowQualitySetting.Draft, ProjectValues.Get(new Auto().WithManual(FlowQualitySetting.Draft), FlowQualitySetting.Balanced)); - Assert.False(ProjectValues.Get(new Auto().WithManual(false), true)); - } -} From 87c70eef4e40cf3b4882f775c67f6d2e3be74d70 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:26:18 +0000 Subject: [PATCH 163/188] feat(i18n): export, render and encoder messages; check keys passed as data Adds the Export catalog (en, it) for preset names, plan and render warnings and encoder notices. i18n check now treats C# string literals shaped Area.Group.Name with an existing area as used keys, which is how these 53 keys had gone unnoticed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Export.resx | 60 ++++++++++++++++++++++++ i18n/it/Export.it.resx | 60 ++++++++++++++++++++++++ src/Titano.Tools/Commands/I18nCommand.cs | 19 ++++++-- 3 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 i18n/en/Export.resx create mode 100644 i18n/it/Export.it.resx diff --git a/i18n/en/Export.resx b/i18n/en/Export.resx new file mode 100644 index 00000000..b5dafdeb --- /dev/null +++ b/i18n/en/Export.resx @@ -0,0 +1,60 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0}-bit output is not available with this encoder; encoding at {1}-bit.long; {0} requested bit depth; {1} bit depth used + Bit rate capped at {1} bit/s, the maximum of level {0}.long; {0} codec level name; {1} maximum bit rate in bit/s + No {0} encoder on this PC; H.264 is used instead.long; {0} codec name + The server cannot encode {0}; a render node or the desktop client will.long; {0} codec name + No encoder available for {0}.long; {0} codec name + Resolution reduced to {1}, the maximum of {0}.long; {0} encoder name; {1} size as WIDTHxHEIGHT + Resolution reduced to {1}, the maximum of level {0}.long; {0} codec level name; {1} size as WIDTHxHEIGHT + No hardware encoder: {0} encodes in software, which is slower.long; {0} encoder name + {0} cannot encode 10-bit; 8-bit is used.long; {0} encoder name + Playback rate not understood; the export frame rate is used.long + No capture times: frames are spaced evenly.long + Every frame is excluded.long + The time curve went backwards and was straightened.long + 1080p 60 fpsinvariant + Share 1080p + 1440p H.264invariant + 4K 60 fpsinvariant + 4K archive + 4K AV1invariant + 4K H.264invariant + 4K HEVCinvariant + 8K archive + Animated PNG + Cinema 21:9invariant + DCI 4Kinvariant + Animated GIF + JPEG frames + Linear DNG + MJPEG AVIinvariant + PNG frames + Portrait 4:5 + Preview 720p + Square 1:1 + TIFF 16-bit + Vertical 9:16 + The preset's {1} frame replaces the {0} aspect ratio.long; {0} requested aspect ratio; {1} preset frame as W:H + Aspect ratio “{0}” not understood; the source aspect ratio is used.long; {0} aspect ratio text as entered + Motion blur is off while frames are stacked.long + The crop lies outside the frame and is ignored.long + Easing “{0}” not understood; linear is used.long; {0} easing name as entered + The keyframe at frame {0} is invalid and was skipped.long; {0} source frame number + Highlight knee {0} is out of range and is ignored.long; {0} knee value as entered + Every frame is excluded; there is nothing to render.long + No sky and land mask; deflicker uses the whole frame.long + The sky and land mask is uncertain (confidence {0}); deflicker uses the whole frame.long; {0} mask confidence between 0 and 1 + Strong shake: stabilisation would keep only {0} of the frame, so borders may show.long; {0} kept fraction of the frame between 0 and 1 + Stabilisation is unavailable: too little detail to track.long + The container does not suit the codec; the codec's container is used.long + Unknown codec; the preset's codec is used.long + Unknown frame rate; the preset's frame rate is used.long + Unknown preset; the default preset is used.long + Unknown profile; the codec's default profile is used.long + Unknown rate control; the preset's rate control is used.long + diff --git a/i18n/it/Export.it.resx b/i18n/it/Export.it.resx new file mode 100644 index 00000000..513b88a6 --- /dev/null +++ b/i18n/it/Export.it.resx @@ -0,0 +1,60 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Uscita a {0} bit non disponibile con questo encoder; codifica a {1} bit. + Bit rate limitato a {1} bit/s, il massimo del livello {0}. + Nessun encoder {0} su questo PC; viene usato H.264. + Il server non può codificare {0}; lo farà un nodo di rendering o il client desktop. + Nessun encoder disponibile per {0}. + Risoluzione ridotta a {1}, il massimo di {0}. + Risoluzione ridotta a {1}, il massimo del livello {0}. + Nessun encoder hardware: {0} codifica via software, più lentamente. + {0} non codifica a 10 bit; viene usato 8 bit. + Velocità di riproduzione non valida; viene usata la frequenza di esportazione. + Nessun orario di scatto: fotogrammi distribuiti in modo uniforme. + Tutti i fotogrammi sono esclusi. + La curva del tempo tornava indietro ed è stata corretta. + 1080p 60 fps + Condivisione 1080p + 1440p H.264 + 4K 60 fps + Archivio 4K + 4K AV1 + 4K H.264 + 4K HEVC + Archivio 8K + PNG animato + Cinema 21:9 + DCI 4K + GIF animata + Fotogrammi JPEG + DNG lineare + MJPEG AVI + Fotogrammi PNG + Ritratto 4:5 + Anteprima 720p + Quadrato 1:1 + TIFF 16 bit + Verticale 9:16 + Il formato {1} del preset sostituisce le proporzioni {0}. + Proporzioni «{0}» non valide; vengono usate quelle della sorgente. + La sfocatura di movimento è disattivata mentre i fotogrammi sono sovrapposti. + Il ritaglio è fuori dall'immagine e viene ignorato. + Andamento «{0}» non valido; viene usato quello lineare. + Il fotogramma chiave {0} non è valido ed è stato saltato. + Compressione delle alte luci {0} fuori intervallo, ignorata. + Tutti i fotogrammi sono esclusi: non c'è nulla da renderizzare. + Nessuna maschera cielo/terra; il deflicker usa l'intera immagine. + La maschera cielo/terra è incerta (affidabilità {0}); il deflicker usa l'intera immagine. + Vibrazioni forti: la stabilizzazione conserverebbe solo {0} dell'immagine, i bordi possono vedersi. + Stabilizzazione non disponibile: troppo pochi dettagli da tracciare. + Il contenitore non è adatto al codec; viene usato quello del codec. + Codec sconosciuto; viene usato quello del preset. + Frequenza sconosciuta; viene usata quella del preset. + Preset sconosciuto; viene usato quello predefinito. + Profilo sconosciuto; viene usato quello predefinito del codec. + Controllo del bit rate sconosciuto; viene usato quello del preset. + diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs index fa657663..dc4fa4d2 100644 --- a/src/Titano.Tools/Commands/I18nCommand.cs +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -80,7 +80,8 @@ internal sealed partial class I18nCommand : ICommand errors.Add($"{culture}: orphan key {key}"); } - foreach (var (file, key) in UsedKeys(root)) + var areas = en.Keys.Select(k => k[..k.IndexOf('.')]).ToHashSet(StringComparer.Ordinal); + foreach (var (file, key) in UsedKeys(root, areas)) { if (en.ContainsKey(key)) continue; // Prefix lookups such as L("Settings.Page." + page) are satisfied by any key under the prefix. @@ -133,8 +134,12 @@ internal sealed partial class I18nCommand : ICommand private static HashSet Placeholders(string s) => [.. PlaceholderRegex().Matches(s).Select(m => m.Groups[1].Value)]; - /// Keys referenced from C# (L("…"), Plural("…"), Loc.Get("…")), XAML ({l:Loc …}) and admin JS (t("…")). - private static IEnumerable<(string File, string Key)> UsedKeys(string root) + /// + /// Keys referenced from C# (L("…"), Plural("…"), Loc.Get("…"), and any string literal shaped + /// Area.Group.Name whose area has a catalog, since reason and warning keys travel as data), XAML + /// ({l:Loc …}) and admin JS (t("…")). + /// + private static IEnumerable<(string File, string Key)> UsedKeys(string root, IReadOnlySet areas) { var src = Path.Combine(root, "src"); foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories)) @@ -152,6 +157,11 @@ internal sealed partial class I18nCommand : ICommand if (regex is null) continue; var text = File.ReadAllText(file); foreach (Match m in regex.Matches(text)) yield return (file, m.Groups[1].Value); + if (ext != ".cs") continue; + foreach (Match m in CsKeyLiteralRegex().Matches(text)) + { + if (areas.Contains(m.Groups[2].Value)) yield return (file, m.Groups[1].Value); + } } } @@ -161,6 +171,9 @@ internal sealed partial class I18nCommand : ICommand [GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")] private static partial Regex CsKeyRegex(); + [GeneratedRegex(@"(? Date: Fri, 2 Oct 2026 12:26:18 +0000 Subject: [PATCH 164/188] docs: record render pipeline and i18n decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/DECISIONS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index df5f3c41..eba802eb 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -89,3 +89,12 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Apply records a missing-data reason only where no advice exists; Optimise returns modules to Auto and only adds to the user's hero, exclusions, offset or output cap; a preset's own choices are stored as manual values, content-derived values stay Auto. | Overwrite | Manual values stay in force; re-analysis does not undo a chosen preset. | | 2026-10-02 | Advisor namespace is `Titano.Core.Advice` (class `Advisor`). | `Titano.Core.Advisor` | A class named like its namespace needed an alias in every `Titano.Core.*` caller. | | 2026-10-02 | CI also force-pushes each same-repository PR run's screenshots as one commit to the `ci-screenshots` branch (separate job, only it has `contents: write`). | Artifact only | Artifacts need an authenticated download; a branch can be fetched with plain git for visual review. The branch never merges and holds a single commit. | +| 2026-10-02 | Export fps is the encoded grid; `Timing.FrameRate` is the playback rate (source frames per video second, default = export fps). Durations are quantised to output periods on rounded 90 kHz boundaries; whole frames are sampled at the period centre. | One fps / free durations | Presets keep their meaning, Interpolated can synthesise slow motion, AVI and image sequences stay exact. | +| 2026-10-02 | Adaptive timing is proportional up to 3× the median interval; longer gaps show for 3 + log2(r/3) frames (max 5); pauses ≥ 20× median and ≥ 120 s become a 0.2 s cut. Interpolated fills gaps of up to 3 missing/excluded frames. | Fixed clamps | Bursts stay faithful and long gaps cannot stall the video. | +| 2026-10-02 | A non-monotonic time-remap curve is repaired (sorted, clamped, made non-decreasing) with a warning; virtual-camera keyframes are keyed to source frame positions. | Reject the curve / output frame index | The remap is always monotone; keyframes stay on the content when timing or fps change. | +| 2026-10-02 | Per frame: exposure → one warp (stabilisation⁻¹ ∘ camera ∘ crop) to output size → flow, synthesis and blur in output space → stacking → knee. Stabilisation zooms by 1/max(crop scale, 0.75), warning below 0.75. Modules run only when Auto resolves true. | Flow in source space / no zoom | A single resample; flow sees stabilised content; borders stay hidden. | +| 2026-10-02 | Blur fraction = BlurFraction(target × speed, real) / steps, speed clamped to 4, no blur across cuts. | Fixed fraction | The look survives speed changes. | +| 2026-10-02 | Encoding overlaps processing by one frame; image sequences encode up to one frame per core into a hidden `.tmp` folder renamed at the end, named `/_000001.ext`. | Strictly sequential / `frame_%05d` | 1080p PNG 1.0 → 2.5 fps; crash-safe and editor-friendly. | +| 2026-10-02 | JPEG/MJPEG use 4:4:4 at quality ≥ 90, else 4:2:0; HEVC/AV1 → H.264 fallback rescales the bit rate by bits-per-pixel; size capped to the highest level, then the encoder maximum; managed bit depth moves to the shallowest supported depth ≥ the request; linear DNG tiles are sized to the frame (≤ 256 px). | — | Predictable quality and sizes; small DNGs are ~3× smaller. | +| 2026-10-02 | `Auto` carries `HasAdvice`; `Resolve` falls back only when there is no advice. | Treat `default` as "no advice" | A value type's advised 0/false was indistinguishable from "no advice". | +| 2026-10-02 | `i18n check` also treats any C# string literal shaped `Area.Group.Name` with an existing area as a used key. | Marker functions such as `LocKey(…)` | Reason and warning keys travel as data; 53 render/export keys had no resources and the check did not notice. | From ffbea7cb74e8a47e27e55d25c0b3504916d2d5e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:26:58 +0000 Subject: [PATCH 165/188] feat(app): library, jobs, settings, server, welcome and about screens Local-mode composition root (SQLite index, one JobEngine fed by a single handler registration list), keyset-paged library with thumbnail cache and hover scrub, live job list with throttled updates and the shell job bar, settings with live template validation and encoder self-test, server connection with trust-on-first-use and DPAPI token, first-run welcome, About with update check, and --capture screenshots with synthetic data. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/About.resx | 14 + i18n/en/Common.resx | 1 + i18n/en/Errors.resx | 16 + i18n/en/Jobs.resx | 58 ++ i18n/en/Library.resx | 59 ++ i18n/en/Server.resx | 44 + i18n/en/Settings.resx | 85 ++ i18n/en/Shell.resx | 15 + i18n/en/Tooltips.resx | 156 ++++ i18n/it/About.it.resx | 14 + i18n/it/Common.it.resx | 1 + i18n/it/Errors.it.resx | 16 + i18n/it/Jobs.it.resx | 58 ++ i18n/it/Library.it.resx | 59 ++ i18n/it/Server.it.resx | 43 + i18n/it/Settings.it.resx | 85 ++ i18n/it/Shell.it.resx | 15 + i18n/it/Tooltips.it.resx | 156 ++++ src/Titano.App/About/UpdateCheck.cs | 76 ++ src/Titano.App/App.xaml.cs | 67 +- src/Titano.App/DesignTime/SampleData.cs | 343 ++++++++ .../Infrastructure/AppEnvironment.cs | 33 +- src/Titano.App/Infrastructure/AppServices.cs | 136 +++ src/Titano.App/Infrastructure/AppSettings.cs | 118 ++- src/Titano.App/Infrastructure/ArchiveSetup.cs | 104 +++ .../Infrastructure/DiagnosticsBundle.cs | 147 ++++ src/Titano.App/Infrastructure/Formatting.cs | 25 + src/Titano.App/Infrastructure/IAppDialogs.cs | 39 + src/Titano.App/Infrastructure/ProductLinks.cs | 10 +- src/Titano.App/Infrastructure/ShellActions.cs | 25 +- src/Titano.App/Infrastructure/UiLanguage.cs | 33 + src/Titano.App/Interop/FileDialogs.cs | 192 +++++ src/Titano.App/Jobs/JobListModel.cs | 164 ++++ src/Titano.App/Jobs/JobQueue.cs | 106 +++ src/Titano.App/Jobs/JobRowViewModel.cs | 133 +++ src/Titano.App/Jobs/JobText.cs | 68 ++ src/Titano.App/Jobs/JobUpdateBuffer.cs | 143 ++++ src/Titano.App/Library/FilterOption.cs | 10 + src/Titano.App/Library/LibraryFilter.cs | 65 ++ src/Titano.App/Library/LibraryPager.cs | 102 +++ src/Titano.App/Library/SequenceItem.cs | 179 ++++ src/Titano.App/Library/ThumbnailCache.cs | 152 ++++ src/Titano.App/Library/ThumbnailLoading.cs | 52 ++ src/Titano.App/Library/ThumbnailService.cs | 192 +++++ src/Titano.App/Sections/AboutView.xaml | 61 +- src/Titano.App/Sections/AboutViewModel.cs | 149 ++++ src/Titano.App/Sections/ArchiveViewModel.cs | 9 + src/Titano.App/Sections/ImportViewModel.cs | 9 + src/Titano.App/Sections/JobsView.xaml | 164 +++- src/Titano.App/Sections/JobsView.xaml.cs | 7 + src/Titano.App/Sections/JobsViewModel.cs | 379 +++++++++ src/Titano.App/Sections/LibraryView.xaml | 248 +++++- src/Titano.App/Sections/LibraryView.xaml.cs | 7 + src/Titano.App/Sections/LibraryViewModel.cs | 630 ++++++++++++++ src/Titano.App/Sections/Sections.cs | 164 ---- src/Titano.App/Sections/SequenceViewModel.cs | 12 + src/Titano.App/Sections/ServerView.xaml | 117 ++- src/Titano.App/Sections/ServerView.xaml.cs | 12 + src/Titano.App/Sections/ServerViewModel.cs | 209 +++++ src/Titano.App/Sections/SettingsView.xaml | 386 +++++++-- src/Titano.App/Sections/SettingsView.xaml.cs | 14 - src/Titano.App/Sections/SettingsViewModel.cs | 803 ++++++++++++++++++ src/Titano.App/Sections/WelcomeView.xaml | 115 +++ src/Titano.App/Sections/WelcomeView.xaml.cs | 8 + src/Titano.App/Sections/WelcomeViewModel.cs | 231 +++++ src/Titano.App/Server/ConnectFlow.cs | 298 +++++++ src/Titano.App/Server/ServerApi.cs | 143 ++++ src/Titano.App/Server/ServerSession.cs | 238 ++++++ src/Titano.App/Settings/EditableField.cs | 116 +++ src/Titano.App/Settings/EncoderInventory.cs | 205 +++++ src/Titano.App/Settings/LanguageCatalog.cs | 62 ++ src/Titano.App/Settings/NamingPreview.cs | 82 ++ src/Titano.App/Settings/SettingsRows.cs | 120 +++ src/Titano.App/Shell/AppDialogs.cs | 27 + src/Titano.App/Shell/AppResources.cs | 19 + src/Titano.App/Shell/AppStyles.xaml | 233 +++++ src/Titano.App/Shell/ConfirmDialog.xaml | 22 + src/Titano.App/Shell/ConfirmDialog.xaml.cs | 29 + src/Titano.App/Shell/EditBehavior.cs | 65 ++ src/Titano.App/Shell/LoginDialog.xaml | 34 + src/Titano.App/Shell/LoginDialog.xaml.cs | 61 ++ src/Titano.App/Shell/MainWindow.xaml | 20 +- src/Titano.App/Shell/MainWindow.xaml.cs | 15 +- src/Titano.App/Shell/ScreenCapture.cs | 148 +++- src/Titano.App/Shell/ShellViewModel.cs | 109 ++- src/Titano.Ui/Controls/JobBar.cs | 6 +- src/Titano.Ui/Themes/Controls.xaml | 4 +- .../About/UpdateCheckTests.cs | 74 ++ .../Jobs/JobListModelTests.cs | 187 ++++ .../Jobs/JobUpdateBufferTests.cs | 106 +++ .../Library/LibraryPagerTests.cs | 180 ++++ .../Library/ThumbnailCacheTests.cs | 164 ++++ .../Server/ConnectFlowTests.cs | 238 ++++++ .../Settings/SettingsLogicTests.cs | 156 ++++ 94 files changed, 10130 insertions(+), 374 deletions(-) create mode 100644 src/Titano.App/About/UpdateCheck.cs create mode 100644 src/Titano.App/DesignTime/SampleData.cs create mode 100644 src/Titano.App/Infrastructure/AppServices.cs create mode 100644 src/Titano.App/Infrastructure/ArchiveSetup.cs create mode 100644 src/Titano.App/Infrastructure/DiagnosticsBundle.cs create mode 100644 src/Titano.App/Infrastructure/IAppDialogs.cs create mode 100644 src/Titano.App/Infrastructure/UiLanguage.cs create mode 100644 src/Titano.App/Interop/FileDialogs.cs create mode 100644 src/Titano.App/Jobs/JobListModel.cs create mode 100644 src/Titano.App/Jobs/JobQueue.cs create mode 100644 src/Titano.App/Jobs/JobRowViewModel.cs create mode 100644 src/Titano.App/Jobs/JobText.cs create mode 100644 src/Titano.App/Jobs/JobUpdateBuffer.cs create mode 100644 src/Titano.App/Library/FilterOption.cs create mode 100644 src/Titano.App/Library/LibraryFilter.cs create mode 100644 src/Titano.App/Library/LibraryPager.cs create mode 100644 src/Titano.App/Library/SequenceItem.cs create mode 100644 src/Titano.App/Library/ThumbnailCache.cs create mode 100644 src/Titano.App/Library/ThumbnailLoading.cs create mode 100644 src/Titano.App/Library/ThumbnailService.cs create mode 100644 src/Titano.App/Sections/AboutViewModel.cs create mode 100644 src/Titano.App/Sections/ArchiveViewModel.cs create mode 100644 src/Titano.App/Sections/ImportViewModel.cs create mode 100644 src/Titano.App/Sections/JobsViewModel.cs create mode 100644 src/Titano.App/Sections/LibraryViewModel.cs delete mode 100644 src/Titano.App/Sections/Sections.cs create mode 100644 src/Titano.App/Sections/SequenceViewModel.cs create mode 100644 src/Titano.App/Sections/ServerViewModel.cs create mode 100644 src/Titano.App/Sections/SettingsViewModel.cs create mode 100644 src/Titano.App/Sections/WelcomeView.xaml create mode 100644 src/Titano.App/Sections/WelcomeView.xaml.cs create mode 100644 src/Titano.App/Sections/WelcomeViewModel.cs create mode 100644 src/Titano.App/Server/ConnectFlow.cs create mode 100644 src/Titano.App/Server/ServerApi.cs create mode 100644 src/Titano.App/Server/ServerSession.cs create mode 100644 src/Titano.App/Settings/EditableField.cs create mode 100644 src/Titano.App/Settings/EncoderInventory.cs create mode 100644 src/Titano.App/Settings/LanguageCatalog.cs create mode 100644 src/Titano.App/Settings/NamingPreview.cs create mode 100644 src/Titano.App/Settings/SettingsRows.cs create mode 100644 src/Titano.App/Shell/AppDialogs.cs create mode 100644 src/Titano.App/Shell/AppResources.cs create mode 100644 src/Titano.App/Shell/AppStyles.xaml create mode 100644 src/Titano.App/Shell/ConfirmDialog.xaml create mode 100644 src/Titano.App/Shell/ConfirmDialog.xaml.cs create mode 100644 src/Titano.App/Shell/EditBehavior.cs create mode 100644 src/Titano.App/Shell/LoginDialog.xaml create mode 100644 src/Titano.App/Shell/LoginDialog.xaml.cs create mode 100644 tests/Titano.App.Tests/About/UpdateCheckTests.cs create mode 100644 tests/Titano.App.Tests/Jobs/JobListModelTests.cs create mode 100644 tests/Titano.App.Tests/Jobs/JobUpdateBufferTests.cs create mode 100644 tests/Titano.App.Tests/Library/LibraryPagerTests.cs create mode 100644 tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs create mode 100644 tests/Titano.App.Tests/Server/ConnectFlowTests.cs create mode 100644 tests/Titano.App.Tests/Settings/SettingsLogicTests.cs diff --git a/i18n/en/About.resx b/i18n/en/About.resx index a9d2a50d..ce8aea99 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -4,11 +4,25 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Build Data + Diagnostics bundle + Licence + View licence + Machine translated Data folder Releases + Suggest a fix Runtime System Third-party code None + Translation + Titano {0} available + Check for updates + Checking… + Up to date + Download + Check failed + Updates diff --git a/i18n/en/Common.resx b/i18n/en/Common.resx index 5b7c5adf..bcf09a3a 100644 --- a/i18n/en/Common.resx +++ b/i18n/en/Common.resx @@ -12,4 +12,5 @@ n/a Open Open logs + {0} % diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 702ea76f..2c90ab45 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -4,5 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Enter a whole number from {0} to {1}. + Enter a folder. + This is not a valid folder path. + This path is a file, not a folder. + The drive of this folder is not available. + Enter a full path that starts with a drive or a network share. + Enter a server address such as nas.local:8443 or https://titano.example.com. + This file does not contain Titano settings. + The template is empty. + Empty token at position {1}: write a name between the braces. + File names cannot contain a slash; put folders in the folder template. + The format after the colon does not suit its token. + Names would repeat: add the frame number, the time or the original name. + The brace opened at position {1} is never closed. + Unknown token “{0}” at position {1}. + The closing brace at position {1} has no opening one; double it for a literal brace. Something went wrong. diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index 9be7175a..a165f36d 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -4,5 +4,63 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cancel + Folder + Move up + Open + Pause + Remove + Resume + Retry + Show + {0} left + Clear done + Kind + Left + Progress + Speed + State + Target + Where + {0} / {1} No jobs yet + All · {0} + Done · {0} + Failed · {0} + Queued · {0} + Running · {0} + History keeps {0} day + History keeps {0} days + Adopt folder + Deep analysis + Duplicates + Import + Light analysis + Maintenance + Move archive + Orphans + Proxies + Rebuild index + Render + Scan + Thumbnails + Upload + Verify + after {0} + next + No log lines yet + Pause all + Rendering settings + Search target or kind + {0} fps + {0}/s + cancelled + done + failed + paused + queued + running + {0} · {1} + this PC + Workers {0} / {1} diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx index 7db63837..8d365087 100644 --- a/i18n/en/Library.resx +++ b/i18n/en/Library.resx @@ -4,8 +4,67 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analyse + Clear selection + Export list + Folder + Open + Proxies + Verify + Adopt a folder + Clear filters + Camera + Date + Folder + Frames + Interval + Sequence + Size + Span + State + Tags No sequences yet + Adopt a folder Connect to a server Import a card Open an archive + List exported + Show + Export the list to + All cameras + Any status + All tags + All years + Camera + Status + Analysed + Without proxies + Not analysed + Not verified + With proxies + Verified + With warnings + Tags + Year + {0} s + No sequences match the filters + {0} queued · {1} + Rescan + Search title, camera, tag + {0:N0} selected + {0:N0} selected + Sort + Most frames + Newest first + Oldest first + Largest first + Title + Analysed + Analysing + Proxies + Remote + Synced + View + Grid + List diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index b9ba718d..24a55d5c 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -4,5 +4,49 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + nas.local:8443invariant + Certificate + Forget + Keep + Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.long + Server certificate + TLS {0} trusted {1} + Connect + Disconnect Not connected to a server + Wrong user name or password.long + The server certificate changed; confirm it and sign in again.long + The connection failed; the log has the details.long + That is not a valid server address.long + That address is not a Titano Server.long + The session expired; sign in again.long + The server does not answer; check the address and the network.long + The certificate was not trusted, so nothing was sent.long + Servers found + Account + Server + Status + {0} ms + Cancel + Password + Sign in + Sign in + User + {0} of {1} + {0} used + Offer this PC as render node + Admin + Editor + Uploader + Viewer + Sign out + Connected + Connecting… + Disconnected + Not connected + Trust + Cancel + {0} uses a certificate Titano does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.long + Trust this server? + v{0} diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx index bd1f5673..1604e694 100644 --- a/i18n/en/Settings.resx +++ b/i18n/en/Settings.resx @@ -4,7 +4,31 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Database + Index backed up + Back up now Data folder + Diagnostics + Diagnostics bundle saved + Save the diagnostics bundle to + Export bundle + Logs + Portable mode + Off + On + File names + Folders + {0} free + Full size + Choose the archive folder + Preview + Proxy size + Archive folder + Back to Auto + Choose folder + Export… + Settings exported + Export the settings to Check on start Language Theme @@ -12,6 +36,12 @@ Light System Updates + Usage counts + Send anonymous counts + Import… + Settings imported + Titano settings + Import settings Advanced Analysis Archive @@ -21,5 +51,60 @@ Licence Rendering Server + Storage Updates + Auto · {0} + Low priority while editing + Codec + Encoder + Max + Self-test + 10-bit + of {0} logical cores + {0} (built in) + {0} (hardware) + {0} (software) + {0} encoder + {0} encoders + Encoders on this PC + failed + {0} GB + Hardware encoding + of {0} GB installed + Memory budget + no limit + Parallelism + {0} fps · ok + Prefer hardware + Hardware for previews only + Quality profile + Balanced + Best + Fast + Re-detect + Run self-test + Software only + 10-bit + testing… + Reset section + Search settings + Trusted certificates + Default server + None + Render node + Clear + Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.long + Clear the cache? + {0} freed + Cache folder + Keep + Cache limit + GB + Titano did not create this folder, so nothing was deleted.long + Choose the cache folder + Thumbnails in memory + thumbnails + {0} used · {1} free + {0} used + Latest version diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index 80a2fb84..a2ff72aa 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -5,6 +5,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Titanoinvariant + Ready Ready · {0} jobs queued About Archive @@ -17,9 +18,23 @@ Connected to "{0}" {0:N0} job {0:N0} jobs + No archive Not connected {0:N0} photo {0:N0} photos {0:N0} sequence {0:N0} sequences + Adopt an existing folder + Change… + Choose… + Help improve Titano with anonymous usage countslong + Continue + Found + Create a local archive + {0} · {1} free + Choose where the archive lives + Where should your time-lapses live?long + Connect to a server + {0} on this network · {1} + Welcome to Titano diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index fcb3a77b..7ca6cbe4 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -4,14 +4,90 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Ask the public releases page for a newer version · a few seconds + Zip the logs and an environment report into a folder you choose; settings and passwords are not included + Open the release page in the browser + Open the licence in the browser Open the folder with database, settings and logs Open the public releases page in the browser + Every language but English is machine-translated; propose a better wording on the public issue tracker + Titano uses no third-party code: everything beyond .NET and Windows is written in-house Dismiss Open the folder with the log files Return to the advisor's value + Stop this job; Retry continues later from its last checkpoint + Hide finished jobs from the list; they stay in the history + Every job + Finished jobs + Stopped with an error or cancelled + Waiting for a worker + Working now or paused + Show the folder in Explorer + Hide the log + Finished jobs older than this are removed when Titano starts + Raise the priority: it runs before jobs of lower priority + Open what this job worked on + Pause at the next checkpoint; Resume continues from there + Pause every running job; the queue keeps its order + Hold this job in the queue until you resume it + Remove from the queue; the job is cancelled + Parallelism, hardware preference, memory budget + Put the job back in the queue; it continues from its checkpoint + Run again from the last checkpoint + Filter by target or kind as you type + Open what this job worked on to see the problem + Show the last lines of the log + Cancelled; Retry continues from the last checkpoint + Finished; the run time follows the dot + Stopped with an error; Retry continues from the last checkpoint + Paused; Resume continues from the checkpoint + Waiting for a worker on this PC + Working now + Jobs running on this PC out of the job engine's workers + Index photos you already have, in place; choose their top folder + Deep analysis of every frame · runs as a job in the background + Deep analysis of the selected sequences · runs as one job + Show only one camera + Click selects · Ctrl+click adds · double-click opens · move over the picture to scrub + Show every sequence again + Deselect every sequence Work with the archive of a Titano Server + Save the selected rows as CSV in a folder you choose + Show the sequence folder in Explorer + Cards with thumbnails Copy and verify photos from a memory card + Table with sortable columns + Open in the sequence editor · Enter Use an existing archive folder on this PC or the network + Build JPEG proxies for fast editing · runs as a job + Build proxies of the selected sequences · runs as one job + Rescan the archive for changes · runs as a job + Click selects · double-click opens + Search titles, camera makes and models, and tags as you type + Add to the selection or remove from it + Show the file in Explorer + Order of the sequences + Sort by first capture; click again to reverse + Sort by number of frames, most first + Sort by size on disk, largest first + Sort by title, A to Z + Filter by analysis, proxies, verification or warnings + Analysed: exposure, flicker and motion are measured + An analysis job is running on this sequence + Some frames are missing or unreadable; open the sequence for details + No proxies yet; editing reads the originals + Not analysed yet + JPEG proxies built for fast editing + Lives on the server; this PC has proxies at most + Rendered once + Rendered {0:N0} times + The same on this PC and on the server + {0:N0} warning; open the sequence for details + {0:N0} warnings; open the sequence for details + Show only one tag + Re-read every file and compare its hash with the index · runs as a job + Verify the hashes of the selected sequences · runs as one job + Show only one year of first capture Version, diagnostics and links Scan, verify and maintain the archive · Ctrl+4 Import photos from a card or folder · Ctrl+2 @@ -20,13 +96,84 @@ Edit and render the open sequence · Ctrl+3 Connection, sync and render node · Ctrl+6 Preferences of this PC · Ctrl+, + Address of the Titano Server; https is assumed · Enter connects + Show the full fingerprint, or forget the trust + Fingerprint trusted on first use; a change blocks the connection and asks you again + Identify the server, confirm a new certificate, then sign in · Enter + Close the session and work with the local archive only; you stay signed in + Do not connect; nothing is sent to this server + SHA-256 fingerprint of the server certificate + Forget this certificate; the next connection asks again + Servers found on this network and used before + Keep trusting this certificate + Close without signing in · Esc + Sent only to this server; Titano keeps a session token, never the password + Your user name on the server + Space you use on the server out of your quota + Let the server send render jobs to this PC when it is idle; uses your GPU encoders + Admins manage users, the archive and the server + Editors import, edit and render; only admins manage users + Uploaders send photos; editing needs an editor + Viewers browse and download + Sign in; the token is stored encrypted for this Windows user · Enter + Sign out; the token is removed from this PC + Connection to the server + Trust this certificate for this server and continue to sign in + Use this address + Graphics adapter and Media Foundation encoders found + Free space on the archive drive + Root of the local archive; files are not moved · Enter applies, Esc reverts + Lower the job priority while Titano is in front so the interface stays fluid + Copy the index to the backups folder; the newest three are kept · a few seconds + Choose the archive folder + Choose the cache folder; a fast SSD helps + Where frames spill and thumbnails are kept; a fast SSD helps · Enter applies, Esc reverts + Largest size of the disk cache in GB · Enter applies, Esc reverts + Space the cache uses and free space on its drive Look for a new release when Titano starts · no data is sent + Delete the cache contents now + Delete spilled frames and cached thumbnails; asks first Database, settings, logs and caches of this PC + Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts + Zip the logs and an environment report into a folder you choose + Save every setting as JSON, without the session token + File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts + Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts + Load settings from a JSON file; the session and the window layout stay as they are + Keep the cache as it is Language of the interface · applies immediately + Daily log files, kept for 14 days + Frames stay in memory up to this budget, then spill to the cache folder + Auto: a quarter of installed memory + Back to Auto: a quarter of installed memory Open the data folder in Explorer + Portable mode, logs, diagnostics, database backup + Archive folder, naming templates, proxy size + Language, theme, usage counts + Quality profile, memory budget, parallelism, encoders + Default server, render node, trusted certificates + Cache folder, thumbnails in memory, cache limit + Update check on start + Worker threads for decoding and processing · Enter applies, Esc reverts + Auto: cores minus four so the interface stays responsive + Back to Auto: cores minus four + On when portable.txt sits next to Titano.exe: all data stays in its data folder + Use a hardware encoder when one supports the preset; software otherwise + First three names of a sample import with these templates + Hardware for previews, software for archive presets + Long edge of the JPEG proxies built for new sequences + Balanced suits most work; Best doubles sampling and never spills; Fast is for previews + List the encoders again after a driver or codec install + Return every control of this section to its default + Find a setting by name + Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute + Speed on the synthetic 1280×720 test clip + Always the Microsoft software H.264 encoder; slower, identical everywhere Dark interface (default) Light interface Follow the Windows app mode + Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies + Send a daily anonymous count of versions and languages in use; nothing else, off by default Install in Program Files for every account · asks for administrator approval Return to the options without changing anything Choose the installation folder @@ -53,6 +200,7 @@ Replace the installed version in place · your data is kept Collapse navigation to icons Show navigation names + Pause the job shown; it continues from its checkpoint when resumed Stop the current job · it can be resumed later Add a folder to watch Pick files, a folder or a card @@ -91,6 +239,14 @@ The folder cannot be reached; it is checked again every {0} · click to change or remove Network share; polled every {0} because change notifications are unreliable on SMB · click to change or remove Check the folder at this interval + Index photos you already have, without moving them + Choose another folder for the archive + Choose the folder to adopt + Start with the highlighted choice · Enter + Announced on this network a moment ago + Interface language; you can change it later in Settings + Creates the folder layout and the index here; you can move it later + Sign in to a Titano Server on your network or on the internet Close Maximize Minimize diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx index 3f3261ff..2370ca1e 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -4,11 +4,25 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Build Dati + Pacchetto diagnostico + Licenza + Leggi la licenza + Traduzione automatica Cartella dati Versioni + Suggerisci una correzione Runtime Sistema Codice di terzi Nessuno + Traduzione + Titano {0} disponibile + Cerca aggiornamenti + Verifica in corso… + Aggiornato + Scarica + Verifica non riuscita + Aggiornamenti diff --git a/i18n/it/Common.it.resx b/i18n/it/Common.it.resx index 24f3494c..8794e75b 100644 --- a/i18n/it/Common.it.resx +++ b/i18n/it/Common.it.resx @@ -12,4 +12,5 @@ n/d Apri Apri log + {0}% diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index cc83b7f7..44442694 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -4,5 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Inserisci un numero intero da {0} a {1}. + Inserisci una cartella. + Questo non è un percorso di cartella valido. + Questo percorso è un file, non una cartella. + L'unità di questa cartella non è disponibile. + Inserisci un percorso completo che inizi con un'unità o una condivisione di rete. + Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com. + Questo file non contiene impostazioni di Titano. + Il modello è vuoto. + Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe. + I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle. + Il formato dopo i due punti non è adatto al suo segnaposto. + I nomi si ripeterebbero: aggiungi il numero del fotogramma, l'ora o il nome originale. + La parentesi graffa aperta alla posizione {1} non viene mai chiusa. + Segnaposto sconosciuto «{0}» alla posizione {1}. + La parentesi graffa chiusa alla posizione {1} non ha un'apertura; raddoppiala per una graffa letterale. Si è verificato un problema. diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 2495adbd..29507c5b 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -4,5 +4,63 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Annulla + Cartella + Anticipa + Apri + Pausa + Rimuovi + Riprendi + Riprova + Mostra + {0} rimanenti + Rimuovi concluse + Tipo + Rimanente + Avanzamento + Velocità + Stato + Oggetto + Dove + {0} / {1} Nessuna attività + Tutte · {0} + Concluse · {0} + Non riuscite · {0} + In coda · {0} + In corso · {0} + Cronologia di {0} giorno + Cronologia di {0} giorni + Adozione cartella + Analisi approfondita + Duplicati + Importazione + Analisi rapida + Manutenzione + Spostamento archivio + File orfani + Proxy + Ricostruzione indice + Rendering + Scansione + Miniature + Caricamento + Verifica + dopo {0} + prossima + Ancora nessuna riga di log + Sospendi tutte + Impostazioni di rendering + Cerca oggetto o tipo + {0} fps + {0}/s + annullata + conclusa + non riuscita + in pausa + in coda + in corso + {0} · {1} + questo PC + Processi {0} / {1} diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx index 11ad6451..cbf7ca1a 100644 --- a/i18n/it/Library.it.resx +++ b/i18n/it/Library.it.resx @@ -4,8 +4,67 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analizza + Deseleziona tutto + Esporta elenco + Cartella + Apri + Proxy + Verifica + Adotta una cartella + Azzera i filtri + Fotocamera + Data + Cartella + Fotogrammi + Intervallo + Sequenza + Dimensione + Durata + Stato + Tag Nessuna sequenza + Adotta una cartella Connetti a un server Importa una scheda Apri un archivio + Elenco esportato + Mostra + Esporta l'elenco in + Tutte le fotocamere + Qualsiasi stato + Tutti i tag + Tutti gli anni + Fotocamera + Stato + Analizzate + Senza proxy + Non analizzate + Non verificate + Con proxy + Verificate + Con avvisi + Tag + Anno + {0} s + Nessuna sequenza corrisponde + {0} in coda · {1} + Ripeti scansione + Cerca titolo, fotocamera, tag + {0:N0} selezionata + {0:N0} selezionate + Ordina + Più fotogrammi + Più recenti + Meno recenti + Più grandi + Titolo + Analizzata + In analisi + Proxy + Remota + Sincronizzata + Vista + Griglia + Elenco diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index d80ac2f7..8fdb24f3 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -4,5 +4,48 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Certificato + Dimentica + Mantieni + Titano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo. + Certificato del server + TLS {0} attendibile dal {1} + Connetti + Disconnetti Non connesso a un server + Nome utente o password errati. + Il certificato del server è cambiato; confermalo e accedi di nuovo. + La connessione non è riuscita; i dettagli sono nel log. + Questo non è un indirizzo di server valido. + Questo indirizzo non è un Titano Server. + La sessione è scaduta; accedi di nuovo. + Il server non risponde; controlla l'indirizzo e la rete. + Il certificato non è stato accettato, quindi non è stato inviato nulla. + Server trovati + Account + Server + Stato + {0} ms + Annulla + Password + Accedi + Accedi + Utente + {0} di {1} + {0} usati + Offri questo PC per il rendering + Amministratore + Editor + Caricatore + Visualizzatore + Esci + Connesso + Connessione… + Disconnesso + Non connesso + Considera attendibile + Annulla + {0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile. + Ti fidi di questo server? + v{0} diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx index bcfe6714..198c180c 100644 --- a/i18n/it/Settings.it.resx +++ b/i18n/it/Settings.it.resx @@ -4,7 +4,31 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Database + Copia dell'indice salvata + Salva una copia Cartella dati + Diagnostica + Pacchetto diagnostico salvato + Salva il pacchetto in + Esporta pacchetto + Log + Modalità portatile + Disattivata + Attiva + Nomi dei file + Cartelle + {0} liberi + Dimensione piena + Scegli la cartella dell'archivio + Anteprima + Dimensione proxy + Cartella archivio + Torna ad Auto + Scegli cartella + Esporta… + Impostazioni esportate + Esporta le impostazioni in Controlla all'avvio Lingua Tema @@ -12,6 +36,12 @@ Chiaro Sistema Aggiornamenti + Statistiche d'uso + Invia conteggi anonimi + Importa… + Impostazioni importate + Impostazioni di Titano + Importa impostazioni Avanzate Analisi Archivio @@ -21,5 +51,60 @@ Licenza Rendering Server + Spazio su disco Aggiornamenti + Auto · {0} + Priorità bassa in modifica + Codec + Encoder + Massimo + Autotest + 10 bit + di {0} core logici + {0} (integrato) + {0} (hardware) + {0} (software) + {0} encoder + {0} encoder + Encoder su questo PC + non riuscito + {0} GB + Codifica hardware + di {0} GB installati + Memoria disponibile + nessun limite + Parallelismo + {0} fps · ok + Preferisci hardware + Hardware solo per anteprime + Profilo di qualità + Bilanciato + Massima qualità + Veloce + Rileva di nuovo + Esegui autotest + Solo software + 10 bit + in prova… + Ripristina sezione + Cerca impostazioni + Certificati attendibili + Server predefinito + Nessuno + Nodo di rendering + Svuota + I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti. + Svuotare la cache? + {0} liberati + Cartella cache + Mantieni + Limite della cache + GB + Questa cartella non è stata creata da Titano, quindi non è stato eliminato nulla. + Scegli la cartella della cache + Miniature in memoria + miniature + {0} usati · {1} liberi + {0} usati + Ultima versione diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 471272fb..6da87848 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -4,6 +4,7 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Pronto Pronto · {0} attività in coda Informazioni Archivio @@ -16,9 +17,23 @@ Connesso a «{0}» {0:N0} attività {0:N0} attività + Nessun archivio Non connesso {0:N0} foto {0:N0} foto {0:N0} sequenza {0:N0} sequenze + Adotta una cartella esistente + Cambia… + Scegli… + Aiuta a migliorare Titano con conteggi d'uso anonimi + Continua + Trovato + Crea un archivio locale + {0} · {1} liberi + Scegli dove tenere l'archivio + Dove vuoi conservare i tuoi time-lapse? + Connettiti a un server + {0} in questa rete · {1} + Benvenuto in Titano diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 039162d1..c81ad08f 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -4,14 +4,90 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi + Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse + Apre la pagina della versione nel browser + Apre la licenza nel browser Apri la cartella con database, impostazioni e log Apri la pagina pubblica delle versioni nel browser + Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico + Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente Chiudi Apri la cartella dei file di log Torna al valore consigliato + Ferma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresa + Nasconde le attività concluse dall'elenco; restano nella cronologia + Tutte le attività + Attività concluse + Fermate per un errore o annullate + In attesa di un processo libero + In esecuzione o in pausa + Mostra la cartella in Esplora file + Nasconde il log + Le attività concluse più vecchie vengono rimosse all'avvio di Titano + Alza la priorità: verrà eseguita prima delle attività a priorità più bassa + Apre l'oggetto di questa attività + Mette in pausa al prossimo punto di ripresa; Riprendi continua da lì + Mette in pausa tutte le attività in corso; la coda mantiene il suo ordine + Trattiene l'attività in coda finché non la riprendi + Rimuove dalla coda; l'attività viene annullata + Parallelismo, preferenza hardware, memoria disponibile + Rimette l'attività in coda; riparte dal suo punto di ripresa + Esegue di nuovo dall'ultimo punto di ripresa + Filtra per oggetto o tipo mentre scrivi + Apre l'oggetto dell'attività per vedere il problema + Mostra le ultime righe del log + Annullata; Riprova continua dall'ultimo punto di ripresa + Conclusa; dopo il punto c'è la durata + Fermata per un errore; Riprova continua dall'ultimo punto di ripresa + In pausa; Riprendi continua dal punto di ripresa + In attesa di un processo libero su questo PC + In esecuzione + Attività in esecuzione su questo PC rispetto ai processi disponibili + Indicizza le foto che hai già, dove si trovano; scegli la loro cartella principale + Analisi approfondita di ogni fotogramma · viene eseguita come attività in background + Analisi approfondita delle sequenze selezionate · un'unica attività + Mostra una sola fotocamera + Clic seleziona · Ctrl+clic aggiunge · doppio clic apre · scorri sull'immagine per sfogliare + Mostra di nuovo tutte le sequenze + Deseleziona tutte le sequenze Lavora con l'archivio di un Titano Server + Salva le righe selezionate come CSV in una cartella a tua scelta + Mostra la cartella della sequenza in Esplora file + Schede con miniature Copia e verifica le foto da una scheda di memoria + Tabella con colonne ordinabili + Apre nell'editor della sequenza · Invio Usa una cartella archivio esistente su questo PC o in rete + Crea proxy JPEG per una modifica veloce · viene eseguita come attività + Crea i proxy delle sequenze selezionate · un'unica attività + Ripete la scansione dell'archivio per trovare modifiche · viene eseguita come attività + Clic seleziona · doppio clic apre + Cerca titoli, marche e modelli di fotocamera e tag mentre scrivi + Aggiunge alla selezione o la toglie + Mostra il file in Esplora file + Ordine delle sequenze + Ordina per primo scatto; fai clic di nuovo per invertire + Ordina per numero di fotogrammi, dal più alto + Ordina per spazio su disco, dalla più grande + Ordina per titolo, dalla A alla Z + Filtra per analisi, proxy, verifica o avvisi + Analizzata: esposizione, flicker e movimento sono misurati + Un'attività di analisi è in corso su questa sequenza + Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli + Ancora nessun proxy; la modifica legge gli originali + Non ancora analizzata + Proxy JPEG pronti per una modifica veloce + Si trova sul server; questo PC ne ha al massimo i proxy + Esportata una volta + Esportata {0:N0} volte + Uguale su questo PC e sul server + {0:N0} avviso; apri la sequenza per i dettagli + {0:N0} avvisi; apri la sequenza per i dettagli + Mostra un solo tag + Rilegge ogni file e ne confronta l'hash con l'indice · viene eseguita come attività + Verifica gli hash delle sequenze selezionate · un'unica attività + Mostra un solo anno del primo scatto Versione, diagnostica e collegamenti Scansiona, verifica e gestisci l'archivio · Ctrl+4 Importa foto da una scheda o una cartella · Ctrl+2 @@ -20,13 +96,84 @@ Modifica e renderizza la sequenza aperta · Ctrl+3 Connessione, sincronizzazione e nodo di rendering · Ctrl+6 Preferenze di questo PC · Ctrl+, + Indirizzo del Titano Server; si presume https · Invio per connettersi + Mostra l'impronta completa o revoca la fiducia + Impronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo + Identifica il server, conferma un certificato nuovo e poi accedi · Invio + Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato + Non connetterti; a questo server non viene inviato nulla + Impronta SHA-256 del certificato del server + Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo + Server trovati in questa rete e usati in precedenza + Continua a considerare attendibile questo certificato + Chiude senza accedere · Esc + Inviata solo a questo server; Titano conserva un token di sessione, mai la password + Il tuo nome utente sul server + Spazio che usi sul server rispetto alla tua quota + Permette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPU + Gli amministratori gestiscono utenti, archivio e server + Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti + I caricatori inviano foto; per modificare serve un editor + I visualizzatori sfogliano e scaricano + Accedi; il token viene salvato cifrato per questo utente di Windows · Invio + Esci; il token viene rimosso da questo PC + Connessione al server + Considera attendibile questo certificato per questo server e prosegui con l'accesso + Usa questo indirizzo + Scheda grafica ed encoder Media Foundation trovati + Spazio libero sull'unità dell'archivio + Radice dell'archivio locale; i file non vengono spostati · Invio applica, Esc annulla + Abbassa la priorità delle attività mentre Titano è in primo piano, così l'interfaccia resta fluida + Copia l'indice nella cartella dei backup; vengono conservate le tre copie più recenti · pochi secondi + Scegli la cartella dell'archivio + Scegli la cartella della cache; un SSD veloce aiuta + Dove vanno i fotogrammi temporanei e le miniature; un SSD veloce aiuta · Invio applica, Esc annulla + Dimensione massima della cache su disco in GB · Invio applica, Esc annulla + Spazio usato dalla cache e spazio libero sulla sua unità Cerca una nuova versione all'avvio di Titano · nessun dato viene inviato + Elimina adesso il contenuto della cache + Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma Database, impostazioni, log e cache di questo PC + Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla + Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta + Salva tutte le impostazioni in JSON, senza il token di sessione + Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla + Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla + Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate + Lascia la cache com'è Lingua dell'interfaccia · si applica subito + File di log giornalieri, conservati per 14 giorni + I fotogrammi restano in memoria fino a questo limite, poi passano nella cartella della cache + Auto: un quarto della memoria installata + Torna ad Auto: un quarto della memoria installata Apri la cartella dati in Esplora file + Modalità portatile, log, diagnostica, backup del database + Cartella dell'archivio, modelli dei nomi, dimensione dei proxy + Lingua, tema, statistiche d'uso + Profilo di qualità, memoria, parallelismo, encoder + Server predefinito, nodo di rendering, certificati attendibili + Cartella della cache, miniature in memoria, limite della cache + Controllo degli aggiornamenti all'avvio + Thread di lavoro per decodifica ed elaborazione · Invio applica, Esc annulla + Auto: core meno quattro, così l'interfaccia resta reattiva + Torna ad Auto: core meno quattro + Attiva quando portable.txt si trova accanto a Titano.exe: tutti i dati restano nella sua cartella data + Usa un encoder hardware quando supporta il preset; altrimenti il software + I primi tre nomi di un'importazione di esempio con questi modelli + Hardware per le anteprime, software per i preset d'archivio + Lato lungo dei proxy JPEG creati per le nuove sequenze + Bilanciato va bene quasi sempre; Massima qualità raddoppia il campionamento e non usa la cache su disco; Veloce è per le anteprime + Elenca di nuovo gli encoder dopo l'installazione di un driver o di un codec + Riporta ogni controllo di questa sezione al valore predefinito + Trova un'impostazione per nome + Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto + Velocità sulla clip di prova sintetica 1280×720 + Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque Interfaccia scura (predefinita) Interfaccia chiara Segui la modalità app di Windows + Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica + Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore Torna alle opzioni senza modificare nulla Scegli la cartella di installazione @@ -53,6 +200,7 @@ Sostituisci la versione installata · i tuoi dati restano Riduci la navigazione alle icone Mostra i nomi della navigazione + Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa Ferma l'attività in corso · potrai riprenderla Aggiungi una cartella da controllare Scegli file, una cartella o una scheda @@ -91,6 +239,14 @@ La cartella non è raggiungibile; viene ricontrollata ogni {0} · fai clic per modificare o rimuovere Condivisione di rete; controllata ogni {0} perché le notifiche di modifica non sono affidabili su SMB · fai clic per modificare o rimuovere Controlla la cartella con questo intervallo + Indicizza le foto che hai già, senza spostarle + Scegli un'altra cartella per l'archivio + Scegli la cartella da adottare + Inizia con la scelta evidenziata · Invio + Annunciato in questa rete poco fa + Lingua dell'interfaccia; puoi cambiarla più tardi nelle Impostazioni + Crea qui la struttura delle cartelle e l'indice; puoi spostarlo in seguito + Accedi a un Titano Server nella tua rete o su internet Chiudi Ingrandisci Riduci a icona diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs new file mode 100644 index 00000000..8434cb88 --- /dev/null +++ b/src/Titano.App/About/UpdateCheck.cs @@ -0,0 +1,76 @@ +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; + +namespace Titano.App.About; + +/// The newest public release (BRIEF §18). +public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl); + +/// +/// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the +/// latest release, ignores drafts and pre-releases, and compares its tag with the running version. +/// +public static class UpdateCheck +{ + /// "v1.2.3", "1.2.3", "v1.2.3-beta.1" → 1.2.3; null for anything else. + public static Version? ParseVersion(string? tag) + { + if (string.IsNullOrWhiteSpace(tag)) return null; + var text = tag.Trim(); + if (text.StartsWith('v') || text.StartsWith('V')) text = text[1..]; + var end = text.IndexOfAny(['-', '+', ' ']); + if (end >= 0) text = text[..end]; + if (!Version.TryParse(text, out var version)) return null; + // Normalise to three parts so 1.2 equals 1.2.0. + return new Version(version.Major, version.Minor, Math.Max(0, version.Build)); + } + + /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + public static ReleaseInfo? Parse(string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; + if (Flag(root, "draft") || Flag(root, "prerelease")) return null; + var tag = root.TryGetProperty("tag_name", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null; + var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null; + var version = ParseVersion(tag); + if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null; + return new ReleaseInfo(version, tag, url); + } + + /// True when is newer than (build/revision ignored). + public static bool IsNewer(ReleaseInfo release, Version running) => + release.Version > new Version(running.Major, running.Minor, Math.Max(0, running.Build)); + + /// The running version from an informational version such as "0.1.0" or "0.1.0+abc". + public static Version RunningVersion(string informationalVersion) => ParseVersion(informationalVersion) ?? new Version(0, 0, 0); + + /// Asks the releases API for the latest release; null when there is none (404) or it cannot be read. + /// The request failed. + public static async Task FetchAsync(HttpClient http, string apiUrl, string userAgentVersion, CancellationToken ct) + { + using var request = new HttpRequestMessage(HttpMethod.Get, apiUrl); + request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion)); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); + using var response = await http.SendAsync(request, ct).ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + try + { + return Parse(json); + } + catch (JsonException) + { + return null; + } + } + + private static bool Flag(JsonElement root, string name) => + root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True; + + /// "0.2.0" for display. + public static string Display(Version version) => version.ToString(Math.Clamp(version.Build < 0 ? 2 : 3, 2, 3)); +} diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 90c39120..e9900ac1 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -1,37 +1,45 @@ -using System.Globalization; using System.Windows; using System.Windows.Threading; +using Titano.App.DesignTime; using Titano.App.Infrastructure; using Titano.App.Shell; using Titano.Core.Diagnostics; -using Titano.Core.Localization; using Titano.Ui.Mvvm; using Titano.Ui.Theming; namespace Titano.App; +/// +/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window, +/// then the index and the job engine () off the UI thread. --capture <dir> +/// renders every screen with synthetic data in a throw-away data folder and exits. +/// public partial class App : Application { private FileLogSink? _log; public AppEnvironment Environment { get; private set; } = null!; public AppSettings Settings { get; private set; } = null!; + public AppServices Services { get; private set; } = null!; public static new App Current => (App)Application.Current; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); - Environment = AppEnvironment.Detect(); + var captureIndex = Array.IndexOf(e.Args, "--capture"); + var capture = captureIndex >= 0; + // Capture never reads or writes the user's data folder. + Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect(); _log = new FileLogSink(Environment.LogDirectory, "titano"); - var capture = Array.IndexOf(e.Args, "--capture") >= 0; // Capture runs in CI: mirror the log to stderr so failures are visible in the job output. Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log); - Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}"); + Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}"); - Settings = AppSettings.Load(Environment.SettingsPath); - ApplyLanguage(Settings.Language); - ThemeManager.Initialize(this, Settings.Theme); + Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath); + UiLanguage.Apply(Settings.Language); + ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme); + AppResources.Merge(this); DispatcherUnhandledException += OnUnhandledException; AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception); @@ -41,30 +49,37 @@ public partial class App : Application args.SetObserved(); }; - var shell = new ShellViewModel(Settings); + var dialogs = new AppDialogs(); + Services = new AppServices(Environment, Settings, SaveSettings, dialogs); + SampleData? sample = capture ? SampleData.Configure(Services) : null; + var shell = new ShellViewModel(Services); AsyncRelayCommand.Failed += ex => shell.ReportError(ex); var window = new MainWindow(shell); + dialogs.Owner = window; MainWindow = window; - var captureIndex = Array.IndexOf(e.Args, "--capture"); if (capture) { var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots"; - ScreenCapture.Run(window, shell, dir); + _ = ScreenCapture.RunAsync(window, shell, sample!, dir); return; } window.Show(); + _ = StartAsync(shell); } - /// Switches the UI language at run time (BRIEF §16) and remembers the choice. - public void ApplyLanguage(string? code) + /// Opens the index and the job engine after the window is visible, then fills the screens. + private async Task StartAsync(ShellViewModel shell) { - var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code)); - CultureInfo.DefaultThreadCurrentUICulture = culture; - CultureInfo.CurrentUICulture = culture; - Loc.SetCulture(culture); - foreach (Window w in Windows) - w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + try + { + await Services.OpenAsync(Environment.DatabasePath); + await shell.StartAsync(); + } + catch (Exception ex) + { + shell.ReportError(ex); + } } public void SaveSettings() @@ -73,7 +88,7 @@ public partial class App : Application { Settings.Save(Environment.SettingsPath); } - catch (System.IO.IOException ex) + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) { Log.Warning("app", "Settings not saved", ex); } @@ -82,8 +97,20 @@ public partial class App : Application protected override void OnExit(ExitEventArgs e) { SaveSettings(); + if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose(); + try + { + // Data and engine code continue on the thread pool, so waiting here cannot deadlock the dispatcher. + if (Services is not null && !Services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10))) + Log.Warning("app", "Services did not stop within 10 s"); + } + catch (AggregateException ex) + { + Log.Warning("app", "Services stopped with an error", ex); + } Log.Info("app", "Titano exiting"); _log?.Dispose(); + if (Environment.IsCapture) Environment.DeleteCaptureData(); base.OnExit(e); } diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs new file mode 100644 index 00000000..105b4f1a --- /dev/null +++ b/src/Titano.App/DesignTime/SampleData.cs @@ -0,0 +1,343 @@ +using System.IO; +using System.Net; +using Titano.App.About; +using Titano.App.Infrastructure; +using Titano.App.Server; +using Titano.App.Settings; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Core.Video; +using Titano.Data; +using Titano.Protocol; +using Titano.Protocol.Client; + +namespace Titano.App.DesignTime; + +/// +/// Synthetic content for --capture screenshots and the screen smoke tests ONLY: a temporary SQLite index +/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW +/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the +/// capture environment's temporary folder; nothing touches the network or the user's data. +/// +public sealed class SampleData +{ + public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE"; + + private readonly AppServices _services; + private TitanoDatabase? _db; + + private SampleData(AppServices services) => _services = services; + + /// Points the services at fakes (server, encoders, update check) for an empty first-run state. + public static SampleData Configure(AppServices services) + { + if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment."); + var settings = services.Settings; + services.Server.Dispose(); + services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector()); + services.Encoders = new SampleEncoders(); + services.CheckForUpdateAsync = _ => Task.FromResult(null); + return new SampleData(services); + } + + /// Opens the empty temporary index (first run: no archive, nothing indexed). + public async Task OpenEmptyAsync() + { + _db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath)); + await _services.AttachAsync(_db, startEngine: false); + } + + /// Fills the index with sample sequences, frames and jobs, and saves a signed-in server session. + public async Task FillAsync() + { + var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first."); + var settings = _services.Settings; + var root = Path.Combine(_services.Environment.DataDirectory, "archive"); + Directory.CreateDirectory(root); + var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) }; + await db.Archives.UpsertAsync(archive); + + var sequences = Sequences(archive.Id).ToList(); + foreach (var (sequence, colours, raw) in sequences) + { + await db.Sequences.UpsertAsync(sequence); + await db.Frames.BulkInsertAsync(WriteFrames(root, sequence, colours, raw)); + } + await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]); + await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]); + + foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job); + + settings.LastArchivePath = @"D:\TitanoArchive"; + settings.ServerUrl = "https://nas.local:8443"; + settings.ServerUsername = "alberto"; + settings.ProtectedToken = "sample-token"; + settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }]; + settings.RecentServers = ["https://nas.local:8443"]; + settings.RenderNodeOptIn = true; + settings.FirstRunCompleted = true; + } + + private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId) + { + var now = new DateTime(2026, 9, 28, 18, 2, 11); + (Sequence, string[], bool) Make(string? title, string folder, string make, string model, int frames, TimeSpan span, double interval, int daysAgo, + SequenceStatus status, string[] colours, int renders = 0, int warnings = 0, SequenceOrigin origin = SequenceOrigin.Local, + SyncState sync = SyncState.LocalOnly, bool raw = false) + { + var start = now.AddDays(-daysAgo); + return (new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archiveId, + Title = title, + Folder = folder, + CameraMake = make, + CameraModel = model, + FirstCapture = start, + LastCapture = start + span, + FrameCount = frames, + MedianInterval = interval, + TotalBytes = frames * 24_000_000L, + Status = status, + RenderedCount = renders, + WarningCount = warnings, + Origin = origin, + SyncState = sync, + UpdatedAt = DateTimeOffset.UtcNow, + }, colours, raw); + } + + const SequenceStatus Analysed = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep; + const SequenceStatus Full = Analysed | SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt | SequenceStatus.Verified; + yield return Make("Harbour sunset", "2026/2026-09-28 Canon EOS R5", "Canon", "Canon EOS R5", 3_600, TimeSpan.FromHours(2), 2, 0, Full, + ["#2A2F6B", "#B8452F", "#F0A04B", "#2B2B33"], renders: 2, sync: SyncState.InSync, raw: true); + yield return Make("Comet over the ridge", "2026/2026-08-13 GoPro HERO8 Black", "GoPro", "HERO8 Black", 1_005, new TimeSpan(5, 34, 0), 20, 46, Full, + ["#050914", "#0F1D3A", "#1E3A2F"], warnings: 1); + yield return Make(null, "2026/2026-09-27 Sony ILCE-7M4", "SONY", "ILCE-7M4", 2_140, new TimeSpan(1, 11, 0), 2, 1, Analysed, + ["#4A7FB5", "#A9C9E6", "#6F7D6A"]); + yield return Make("Aurora, Tromsø", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_860, new TimeSpan(4, 8, 0), 8, 220, Full, + ["#0C2A3A", "#1AA08C", "#0B1A26"], sync: SyncState.InSync); + yield return Make("Construction cam · week 38", "2026/2026-09-14 Brinno TLC2020", "Brinno", "TLC2020", 8_920, TimeSpan.FromDays(7), 60, 14, + SequenceStatus.None, ["#7C8AA0", "#C9CFD6", "#4C5058"], origin: SequenceOrigin.Server, sync: SyncState.RemoteOnly); + yield return Make("Milan skyline dusk", "2026/2026-06-03 Apple iPhone 16 Pro", "Apple", "iPhone 16 Pro", 2_400, new TimeSpan(1, 20, 0), 2, 117, Full, + ["#1B2B4A", "#D67A4E", "#3A2A2A"], renders: 1); + yield return Make("Clouds over the Langhe", "2026/2026-05-11 Canon EOS R5", "Canon", "Canon EOS R5", 1_320, TimeSpan.FromMinutes(44), 2, 140, + SequenceStatus.None, ["#3B6FA6", "#E6EEF5", "#5C7A52"]); + yield return Make("Star trails, Colle del Nivolet", "2025/2025-08-02 Sony ILCE-7M4", "SONY", "ILCE-7M4", 640, new TimeSpan(5, 20, 0), 30, 422, Full, + ["#08101C", "#142A4A", "#0D0F14"], renders: 3); + yield return Make("Fog lifting, Asti", "2025/2025-11-21 DJI Osmo Action 5 Pro", "DJI", "Osmo Action 5 Pro", 980, new TimeSpan(1, 38, 0), 6, 311, + Analysed, ["#6A8FB0", "#F2E6D0", "#7A6A55"]); + yield return Make("Holy grail · Monviso", "2025/2025-07-14 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_720, new TimeSpan(3, 2, 0), 6, 441, Full, + ["#2C1F4D", "#C2455A", "#F5A524", "#26262C"], renders: 1, sync: SyncState.InSync); + for (var i = 0; i < 26; i++) + { + var shade = 40 + i * 6; + yield return Make($"Rooftop · day {i + 1}", $"2025/2025-03-{i + 1:00} Canon EOS R6", "Canon", "Canon EOS R6", 1_200 + i * 37, TimeSpan.FromHours(9), 30, + 480 + i, i % 3 == 0 ? Analysed : Full, [$"#{shade:X2}5A8C", "#C9D6E2", "#3D4A3A"]); + } + } + + /// Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview. + private static IEnumerable WriteFrames(string root, Sequence sequence, string[] colours, bool raw) + { + var folder = Path.Combine(root, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(folder); + var count = sequence.Title?.StartsWith("Rooftop", StringComparison.Ordinal) == true ? 1 : 3; + var frames = new List(count); + for (var i = 0; i < count; i++) + { + var jpeg = Gradient(colours, 320, 180, i / 3.0); + var name = $"{sequence.FirstCapture:yyyy-MM-dd}_{i + 1:0000}.{(raw ? "CR2" : "JPG")}"; + long? previewOffset = null; + long? previewLength = null; + var bytes = jpeg; + if (raw) + { + // A fake RAW: a header the decoders cannot read, the JPEG preview, then trailing data. + var header = new byte[4096]; + "II*\0"u8.CopyTo(header); + bytes = [.. header, .. jpeg, .. new byte[2048]]; + previewOffset = header.Length; + previewLength = jpeg.Length; + } + File.WriteAllBytes(Path.Combine(folder, name), bytes); + frames.Add(new Frame + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + Index = i, + RelativePath = sequence.Folder + "/" + name, + FileName = name, + Size = bytes.Length, + CapturedAt = sequence.FirstCapture!.Value.AddSeconds(i * (sequence.MedianInterval ?? 2)), + TimestampSource = TimestampSource.ExifOriginal, + Width = 320, + Height = 180, + Format = raw ? ImageFileFormat.Cr2 : ImageFileFormat.Jpeg, + PreviewOffset = previewOffset, + PreviewLength = previewLength, + ExposureTime = 1.0 / 250, + FNumber = 8, + Iso = 100, + }); + } + return frames; + } + + /// A vertical gradient through the given sRGB colours with a sun disc that moves with . + private static byte[] Gradient(string[] colours, int width, int height, double phase) + { + using var image = new ImageBuffer(width, height, 3, clear: false); + var stops = colours.Select(Parse).ToArray(); + var sunX = width * (0.3 + 0.4 * phase); + var sunY = height * (0.55 - 0.1 * phase); + for (var y = 0; y < height; y++) + { + var t = y / (double)(height - 1) * (stops.Length - 1); + var k = Math.Min((int)t, stops.Length - 2); + var f = t - k; + for (var x = 0; x < width; x++) + { + var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY)); + var sun = Math.Clamp(1 - d / 14, 0, 1); + for (var c = 0; c < 3; c++) + { + var value = stops[k][c] * (1 - f) + stops[k + 1][c] * f; + image.Plane(c)[y * width + x] = (float)(value + sun * (1.0 - value) * 0.9); + } + } + } + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85 }); + + static double[] Parse(string hex) + { + var rgb = Convert.FromHexString(hex.TrimStart('#')); + return [Linear(rgb[0]), Linear(rgb[1]), Linear(rgb[2])]; + } + + static double Linear(byte v) + { + var s = v / 255.0; + return s <= 0.04045 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4); + } + } + + private IEnumerable Jobs(IReadOnlyList s, Guid archiveId) + { + var now = DateTimeOffset.UtcNow; + var here = _services.WorkerId; + Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null, + TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null, + JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + TargetIds = target is null ? [archiveId] : [target.Id], + TargetLabel = label, + State = state, + Priority = priority, + ProgressDone = done, + ProgressTotal = total, + ItemsPerSecond = rate, + Eta = eta, + NodeId = state == JobState.Queued ? null : node ?? here, + Error = error, + LogTail = log, + Attempts = state == JobState.Queued ? 0 : 1, + Created = now - (createdAgo ?? startedAgo ?? TimeSpan.FromMinutes(1)), + Started = startedAgo is { } ago ? now - ago : null, + Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null, + }; + + yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2), + startedAgo: TimeSpan.FromMinutes(3.4), log: + "10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" + + "10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" + + "10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" + + "10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget"); + yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1)); + yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8)); + yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12)); + yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30)); + yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43), + error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW"); + yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70), + runFor: new TimeSpan(0, 2, 41), node: "studio-pc"); + yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110), + runFor: new TimeSpan(0, 11, 52)); + yield return Make(JobKind.Thumbs, s[2], s[2].DisplayTitle, JobState.Done, 2_140, 2_140, 2_300, startedAgo: TimeSpan.FromMinutes(108), runFor: TimeSpan.FromSeconds(1)); + } + + /// A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts. + private sealed class SampleServerApiFactory : IServerApiFactory + { + public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints); + } + + private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection trusted) : IServerApi + { + private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false, + new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow); + + public Uri BaseAddress { get; } = baseAddress; + + public string? Token { get; set; } + + public async Task GetInfoAsync(CancellationToken ct) + { + await Task.Delay(14, ct); + if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint); + return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0)); + } + + public Task LoginAsync(string username, string password, CancellationToken ct) + { + Token = "sample-token"; + return Task.FromResult(new LoginResponse(Token, User, false, DateTimeOffset.UtcNow.AddDays(30))); + } + + public Task MeAsync(CancellationToken ct) => + Token == "sample-token" ? Task.FromResult(User) : throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in")); + + public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask; + + public void Dispose() + { + } + } + + /// No encryption: the capture environment is thrown away. + private sealed class PlainTokenProtector : ITokenProtector + { + public string Protect(string token) => token; + + public string? Unprotect(string protectedToken) => protectedToken; + } + + /// The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds. + private sealed class SampleEncoders : IEncoderInventory + { + public string? Adapter() => "NVIDIA GeForce RTX 4070"; + + public IReadOnlyList Detect() => + [ + new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc), + new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264), + new("AV1", "NVIDIA AV1 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Av1), + new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264), + new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg), + new("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null), + ]; + + public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(row.Codec switch + { + "HEVC" => new SelfTestResult(true, 142, null), + "AV1" => new SelfTestResult(true, 96, null), + "H.264" when row.Hardware => new SelfTestResult(true, 188, null), + "H.264" => new SelfTestResult(true, 21, null), + _ => new SelfTestResult(true, 64, null), + }); + } +} diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs index 5b0d9db2..349f91bd 100644 --- a/src/Titano.App/Infrastructure/AppEnvironment.cs +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -8,10 +8,11 @@ namespace Titano.App.Infrastructure; /// public sealed class AppEnvironment { - private AppEnvironment(string dataDirectory, bool portable) + private AppEnvironment(string dataDirectory, bool portable, bool isCapture) { DataDirectory = dataDirectory; IsPortable = portable; + IsCapture = isCapture; Directory.CreateDirectory(DataDirectory); Directory.CreateDirectory(LogDirectory); Directory.CreateDirectory(CacheDirectory); @@ -19,8 +20,13 @@ public sealed class AppEnvironment public string DataDirectory { get; } public bool IsPortable { get; } + + /// A throw-away environment for --capture: nothing of the user's data is read or written. + public bool IsCapture { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string CacheDirectory => Path.Combine(DataDirectory, "cache"); + public string BackupDirectory => Path.Combine(DataDirectory, "backups"); public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); @@ -28,8 +34,29 @@ public sealed class AppEnvironment { var exeDir = AppContext.BaseDirectory; if (File.Exists(Path.Combine(exeDir, "portable.txt"))) - return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true); + return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false); var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - return new AppEnvironment(Path.Combine(local, "Titano"), portable: false); + return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false); + } + + /// A fresh temporary data folder for screenshots and smoke tests; delete it with . + public static AppEnvironment ForCapture() => + new(Path.Combine(Path.GetTempPath(), "titano-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true); + + /// Removes the temporary data folder of a capture environment (never a real one). + public void DeleteCaptureData() + { + if (!IsCapture) return; + try + { + Directory.Delete(DataDirectory, recursive: true); + } + catch (IOException) + { + // Files still open (log, database) are left to the OS temp cleanup. + } + catch (UnauthorizedAccessException) + { + } } } diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs new file mode 100644 index 00000000..7e000a70 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -0,0 +1,136 @@ +using System.Net.Http; +using System.Reflection; +using Titano.App.About; +using Titano.App.Jobs; +using Titano.App.Library; +using Titano.App.Server; +using Titano.App.Settings; +using Titano.Core.Diagnostics; +using Titano.Data; +using Titano.Data.Jobs; + +namespace Titano.App.Infrastructure; + +/// +/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one +/// of this PC with the handlers of , thumbnails, the server +/// session, the encoder inventory, the update check and the archive setup. Started after the window shows, stopped +/// when the app exits. +/// +/// +/// Integration points (one place each): +/// +/// — register the archive handlers (scan, rebuild, verify, adopt, …) and the +/// render handler here. +/// — replace with the archive engine's +/// implementation (it receives the first-run choices: create a local archive, adopt a folder). +/// +/// +public sealed class AppServices : IAsyncDisposable +{ + private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); + + public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs) + { + Environment = environment; + Settings = settings; + SaveSettingsAction = saveSettings; + Dialogs = dialogs; + ArchiveSetup = new LocalArchiveSetup(settings, saveSettings); + Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); + Encoders = new MediaFoundationInventory(); + CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); + } + + public AppEnvironment Environment { get; } + public AppSettings Settings { get; } + public IAppDialogs Dialogs { get; } + + private Action SaveSettingsAction { get; } + + /// First-run archive actions; replaced by the integrator with the archive engine's implementation. + public IArchiveSetup ArchiveSetup { get; set; } + + public ServerSession Server { get; set; } + + public IEncoderInventory Encoders { get; set; } + + /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). + public Func> CheckForUpdateAsync { get; set; } + + /// The index; null until succeeded. + public TitanoDatabase? Database { get; private set; } + + public JobEngine? Engine { get; private set; } + + public IJobQueue? Jobs { get; private set; } + + public ThumbnailService? Thumbnails { get; private set; } + + /// Why the index could not be opened; null when it is open. + public Exception? OpenError { get; private set; } + + /// Node id of this PC's workers. + public string WorkerId { get; init; } = System.Environment.MachineName; + + /// "0.1.0" (informational version). + public static string VersionText { get; } = + typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + /// + /// The job handlers of this PC's engine — the single registration list. The integrator adds the archive + /// handlers and the render handler here; a kind without a handler stays queued (it is never claimed here). + /// + public static IReadOnlyList CreateJobHandlers(AppServices services) => + [ + ]; + + public void SaveSettings() => SaveSettingsAction(); + + /// Opens (or creates) the index at , migrates it and starts the job engine. + public async Task OpenAsync(string databasePath, CancellationToken ct = default) + { + try + { + Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct); + Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}"); + } + catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException) + { + OpenError = ex; + Log.Error("app", "The index could not be opened", ex); + return; + } + await StartJobsAsync(Database, startEngine: true, ct); + Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems); + } + + /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped. + public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default) + { + Database = database; + await StartJobsAsync(database, startEngine, ct); + Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems); + } + + public async ValueTask DisposeAsync() + { + (Jobs as IDisposable)?.Dispose(); + if (Engine is not null) await Engine.DisposeAsync(); + Thumbnails?.Dispose(); + Server.Dispose(); + if (Database is not null) await Database.DisposeAsync(); + } + + private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct) + { + var handlers = CreateJobHandlers(this); + var kinds = handlers.Select(h => h.Kind).Distinct().ToArray(); + Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds }); + // With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job. + var started = startEngine && handlers.Count > 0; + if (started) await Engine.StartAsync(ct); + Jobs = new EngineJobQueue(database, Engine, started); + Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued"); + } +} diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs index 9022de83..59385ce1 100644 --- a/src/Titano.App/Infrastructure/AppSettings.cs +++ b/src/Titano.App/Infrastructure/AppSettings.cs @@ -2,21 +2,119 @@ using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Titano.Core.IO; +using Titano.Core.Naming; +using Titano.Data.Repositories; using Titano.Ui.Theming; namespace Titano.App.Infrastructure; -/// Per-user preferences needed before the database opens (language, theme, window layout). +/// Library presentation (BRIEF §12.2). +public enum LibraryLayout +{ + Grid, + List, +} + +/// Rendering quality profile (Settings › Rendering). +public enum QualityProfile +{ + Best, + Balanced, + Fast, +} + +/// Which encoders a render may use (Settings › Rendering). +public enum HardwarePreference +{ + PreferHardware, + SoftwareOnly, + HardwareForPreviews, +} + +/// A server certificate the user trusted on first use (BRIEF §12.7). +public sealed class TrustedCertificate +{ + public string Fingerprint { get; set; } = string.Empty; + public string? Server { get; set; } + public DateTimeOffset TrustedAt { get; set; } +} + +/// +/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in +/// settings.json next to the database and written atomically, because language and theme apply before the +/// database opens. +/// public sealed class AppSettings { + public const int DefaultThumbnailMemoryItems = 2_000; + public const int DefaultCacheLimitGb = 20; + + // ---- General ---- public string? Language { get; set; } public AppTheme Theme { get; set; } = AppTheme.Dark; public bool RailCollapsed { get; set; } - public bool CheckForUpdates { get; set; } = true; public bool AnonymousUsageCounts { get; set; } - public string? LastArchivePath { get; set; } public WindowPlacement? Window { get; set; } + /// The first-run choice (local archive, adopted folder or server) was made. + public bool FirstRunCompleted { get; set; } + + // ---- Updates ---- + public bool CheckForUpdates { get; set; } = true; + + // ---- Archive ---- + /// Root of the local archive; null until the first-run choice or Settings › Archive sets it. + public string? LastArchivePath { get; set; } + + public string FolderTemplate { get; set; } = TemplateDefaults.Folder; + public string FileTemplate { get; set; } = TemplateDefaults.File; + + /// Proxy long edge for new archives; 0 = full size. + public int ProxyLongEdge { get; set; } = 1920; + + // ---- Library ---- + public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid; + public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest; + + // ---- Rendering ---- + public QualityProfile Quality { get; set; } = QualityProfile.Balanced; + + /// Frame memory budget in GB; null = Auto (a quarter of installed memory). + public int? MemoryBudgetGb { get; set; } + + /// Worker threads; null = Auto (cores minus four, at least one). + public int? Parallelism { get; set; } + + public bool BackgroundPriority { get; set; } = true; + public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware; + + // ---- Storage ---- + /// Cache (spill frames, thumbnails); null = cache under the data folder. + public string? CacheFolder { get; set; } + + /// Decoded thumbnails kept in memory. + public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems; + + /// Upper bound of the disk cache in GB. + public int CacheLimitGb { get; set; } = DefaultCacheLimitGb; + + // ---- Server ---- + public string? ServerUrl { get; set; } + public string? ServerUsername { get; set; } + + /// The session token, encrypted for this Windows user with DPAPI (Base64). + public string? ProtectedToken { get; set; } + + public List TrustedCertificates { get; set; } = []; + public List RecentServers { get; set; } = []; + + /// Let the server send render jobs to this PC (BRIEF §14.7). + public bool RenderNodeOptIn { get; set; } + + // ---- Jobs ---- + /// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history). + public DateTimeOffset? JobsClearedAt { get; set; } + public sealed class WindowPlacement { public double Left { get; set; } @@ -30,8 +128,7 @@ public sealed class AppSettings { try { - if (File.Exists(path)) - return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings(); + if (File.Exists(path)) return Parse(File.ReadAllText(path)) ?? new AppSettings(); } catch (JsonException) { @@ -43,7 +140,16 @@ public sealed class AppSettings return new AppSettings(); } - public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings)); + /// Reads settings JSON (Settings › Import); null when the text is not a settings object. + /// The text is not valid JSON. + public static AppSettings? Parse(string json) => JsonSerializer.Deserialize(json, AppSettingsJson.Default.AppSettings); + + public string ToJson() => JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings); + + public void Save(string path) => AtomicFile.WriteAllText(path, ToJson()); + + /// A deep copy (JSON round trip), used for import and reset. + public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings(); } [JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)] diff --git a/src/Titano.App/Infrastructure/ArchiveSetup.cs b/src/Titano.App/Infrastructure/ArchiveSetup.cs new file mode 100644 index 00000000..92975647 --- /dev/null +++ b/src/Titano.App/Infrastructure/ArchiveSetup.cs @@ -0,0 +1,104 @@ +using System.IO; +using Titano.Core.Diagnostics; + +namespace Titano.App.Infrastructure; + +/// +/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The +/// integrator replaces with an implementation backed by the archive engine (folder +/// layout, index, adopt job); see . +/// +public interface IArchiveSetup +{ + /// Creates (or opens) the local archive rooted at . + Task CreateAsync(string root, CancellationToken cancellationToken = default); + + /// Indexes the photos under in place, or opens a previous Titano archive there. + Task AdoptAsync(string folder, CancellationToken cancellationToken = default); +} + +/// Until the archive engine is connected: remembers the chosen root in the settings and nothing else. +public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup +{ + public Task CreateAsync(string root, CancellationToken cancellationToken = default) + { + Remember(root); + Log.Info("archive", $"Local archive root set to {root}"); + return Task.CompletedTask; + } + + public Task AdoptAsync(string folder, CancellationToken cancellationToken = default) + { + Remember(folder); + Log.Info("archive", $"Adopted folder recorded: {folder}"); + return Task.CompletedTask; + } + + private void Remember(string path) + { + settings.LastArchivePath = Path.GetFullPath(path); + save(); + } +} + +/// Archive roots offered by default and their free space. +public static class ArchiveLocations +{ + public const string DefaultFolderName = "TitanoArchive"; + + /// "<fixed drive with the most free space>\TitanoArchive". + public static string SuggestRoot() + { + try + { + var best = DriveInfo.GetDrives() + .Where(d => d.DriveType == DriveType.Fixed && d.IsReady) + .OrderByDescending(d => d.AvailableFreeSpace) + .FirstOrDefault(); + if (best is not null) return Path.Combine(best.RootDirectory.FullName, DefaultFolderName); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DefaultFolderName); + } + + /// Free bytes on the volume of ; null when unknown. + public static long? FreeSpace(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return null; + try + { + var root = Path.GetPathRoot(Path.GetFullPath(path)); + if (string.IsNullOrEmpty(root)) return null; + var drive = new DriveInfo(root); + return drive.IsReady ? drive.AvailableFreeSpace : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return null; + } + } + + /// The problem of an archive root as a localized sentence; null when it can be used. + public static string? Validate(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return Core.Localization.Loc.L("Errors.Path.Empty"); + try + { + if (!Path.IsPathFullyQualified(path)) return Core.Localization.Loc.L("Errors.Path.NotAbsolute"); + var full = Path.GetFullPath(path); + if (File.Exists(full)) return Core.Localization.Loc.L("Errors.Path.IsFile"); + var root = Path.GetPathRoot(full); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return Core.Localization.Loc.L("Errors.Path.NoDrive"); + return null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return Core.Localization.Loc.L("Errors.Path.Invalid"); + } + } +} diff --git a/src/Titano.App/Infrastructure/DiagnosticsBundle.cs b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs new file mode 100644 index 00000000..1bdb5217 --- /dev/null +++ b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs @@ -0,0 +1,147 @@ +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Text; + +namespace Titano.App.Infrastructure; + +/// +/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report +/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included. +/// +public static class DiagnosticsBundle +{ + /// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into and returns its path. + public static Task CreateAsync(AppEnvironment environment, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) => + Task.Run(() => + { + var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip"); + var temp = path + ".tmp"; + using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create)) + { + var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal); + using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false))) + { + writer.Write(Report(environment, extraLines)); + } + if (Directory.Exists(environment.LogDirectory)) + { + foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal)) + { + ct.ThrowIfCancellationRequested(); + var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal); + // The current log is open for writing: share the handle instead of copying the file. + using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var target = entry.Open(); + source.CopyTo(target); + } + } + } + File.Move(temp, path, overwrite: true); + return path; + }, ct); + + /// Plain-text environment report. + public static string Report(AppEnvironment environment, IEnumerable? extraLines = null) + { + var sb = new StringBuilder(); + sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})"); + if (extraLines is not null) + { + foreach (var line in extraLines) sb.AppendLine(line); + } + return sb.ToString(); + } +} + +/// +/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Titano created +/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them. +/// +public static class CacheStore +{ + public const string MarkerFile = ".titano-cache"; + + /// The cache folder in effect. + public static string Folder(AppEnvironment environment, AppSettings settings) => + string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!; + + /// Creates the folder (if needed) and marks it as Titano's. + public static void Prepare(string folder) + { + Directory.CreateDirectory(folder); + var marker = Path.Combine(folder, MarkerFile); + if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time."); + } + + /// True when is a Titano cache folder (safe to empty). + public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile)); + + /// Total bytes of the files in the cache (0 when missing). + public static long Size(string folder) + { + if (!Directory.Exists(folder)) return 0; + long total = 0; + var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length; + return total; + } + + /// Deletes everything inside an owned cache folder except the marker; returns the bytes freed. + /// The folder is not a Titano cache folder. + public static long Clear(string folder) + { + if (!Directory.Exists(folder)) return 0; + if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano cache folder: " + folder); + long freed = 0; + var root = new DirectoryInfo(folder); + foreach (var file in root.EnumerateFiles()) + { + if (file.Name == MarkerFile) continue; + freed += TryDelete(file); + } + foreach (var directory in root.EnumerateDirectories()) + { + if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue; + var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file); + try + { + directory.Delete(recursive: true); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + return freed; + } + + private static long TryDelete(FileInfo file) + { + try + { + var length = file.Length; + file.Delete(); + return length; + } + catch (IOException) + { + return 0; // in use (a render spilling right now) + } + catch (UnauthorizedAccessException) + { + return 0; + } + } +} diff --git a/src/Titano.App/Infrastructure/Formatting.cs b/src/Titano.App/Infrastructure/Formatting.cs index 5a3c2ab8..18c48b23 100644 --- a/src/Titano.App/Infrastructure/Formatting.cs +++ b/src/Titano.App/Infrastructure/Formatting.cs @@ -26,9 +26,34 @@ public static class Formatting /// Compact duration: "2 h 00 m", "5 min", "40 s". public static string Duration(TimeSpan t) { + if (t < TimeSpan.Zero) t = TimeSpan.Zero; if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours); if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture)); if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes)); return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds)); } + + /// Clock-style elapsed time for finished jobs: "2:41", "1:02:41". + public static string Elapsed(TimeSpan t) + { + if (t < TimeSpan.Zero) t = TimeSpan.Zero; + return t.TotalHours >= 1 + ? ((int)t.TotalHours).ToString(Loc.Culture) + ":" + t.Minutes.ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture) + : ((int)t.TotalMinutes).ToString(Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture); + } + + /// 0.62 → "62 %". + public static string Percent(double fraction) => Loc.L("Common.Percent", Math.Round(Math.Clamp(fraction, 0, 1) * 100).ToString("0", Loc.Culture)); + + /// Items per second with one decimal below 100: "11.3", "118". + public static string Rate(double perSecond) => perSecond.ToString(perSecond < 100 ? "0.#" : "N0", Loc.Culture); + + /// Local time of day in the culture's short format ("09:12"). + public static string TimeOfDay(DateTimeOffset at) => at.ToLocalTime().ToString("t", Loc.Culture); + + /// Calendar date in the culture's short format. + public static string Date(DateTimeOffset at) => at.ToLocalTime().ToString("d", Loc.Culture); + + /// Camera wall-clock date in the culture's short format. + public static string Date(DateTime wallClock) => wallClock.ToString("d", Loc.Culture); } diff --git a/src/Titano.App/Infrastructure/IAppDialogs.cs b/src/Titano.App/Infrastructure/IAppDialogs.cs new file mode 100644 index 00000000..892964e2 --- /dev/null +++ b/src/Titano.App/Infrastructure/IAppDialogs.cs @@ -0,0 +1,39 @@ +namespace Titano.App.Infrastructure; + +/// Texts of a confirmation dialog (DESIGN §4: two buttons, safe action left and default). +public sealed record ConfirmRequest +{ + public required string Heading { get; init; } + public required string Message { get; init; } + + /// Monospaced detail (certificate fingerprint); null hides it. + public string? Detail { get; init; } + + public string? DetailToolTip { get; init; } + public required string SafeText { get; init; } + public required string SafeToolTip { get; init; } + public required string ActionText { get; init; } + public required string ActionToolTip { get; init; } + + /// Warning-outlined action (never a primary) for data-destroying choices. + public bool IsDestructive { get; init; } +} + +/// Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login). +public interface IAppDialogs +{ + /// A folder chosen in the shell's folder picker; null when cancelled. + string? PickFolder(string title, string? initialFolder = null); + + /// A JSON file chosen in the shell's Open dialog; null when cancelled. + string? PickJsonFile(string title); + + /// True when the user chose the action. + bool Confirm(ConfirmRequest request); + + /// + /// The login form. receives user and password and returns null on success or the + /// error sentence to show; the form stays open until it succeeds or the user cancels. True when signed in. + /// + bool SignIn(string server, string? username, Func> signIn); +} diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs index abdef10a..bcccb637 100644 --- a/src/Titano.App/Infrastructure/ProductLinks.cs +++ b/src/Titano.App/Infrastructure/ProductLinks.cs @@ -8,7 +8,15 @@ public static class ProductLinks .OfType() .FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases"; - public static string Releases => $"https://github.com/{ReleasesRepository}/releases"; + public static string Repository => $"https://github.com/{ReleasesRepository}"; + + public static string Releases => $"{Repository}/releases"; public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest"; + + /// The licence (EULA) published with the releases (BRIEF §12.9). + public static string Licence => $"{Repository}/blob/HEAD/LICENSE.md"; + + /// Where translations are reviewed by the community (BRIEF §16). + public static string Issues => $"{Repository}/issues"; } diff --git a/src/Titano.App/Infrastructure/ShellActions.cs b/src/Titano.App/Infrastructure/ShellActions.cs index ba546bb5..ef09d422 100644 --- a/src/Titano.App/Infrastructure/ShellActions.cs +++ b/src/Titano.App/Infrastructure/ShellActions.cs @@ -1,20 +1,31 @@ -using System.Diagnostics; using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Windows.Shell; namespace Titano.App.Infrastructure; -/// The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder. +/// The only shell launches the product performs (BRIEF §8.6): open a web or Store link, reveal a folder or file. public static class ShellActions { public static void OpenUrl(string url) { - if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return; - Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + if (!ShellLauncher.IsAllowedUrl(url)) return; + try + { + if (!ShellLauncher.OpenUrl(url)) Log.Warning("shell", $"The shell could not open {url}"); + } + catch (Exception ex) when (ex is ArgumentException or System.ComponentModel.Win32Exception) + { + Log.Warning("shell", $"The shell could not open {url}", ex); + } } - public static void OpenFolder(string path) + /// Opens a folder in Explorer, or shows a file selected in its folder. + public static void Reveal(string path) { - if (!Directory.Exists(path)) return; - Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" }); + if (string.IsNullOrWhiteSpace(path) || !(Directory.Exists(path) || File.Exists(path))) return; + if (!ShellLauncher.RevealInExplorer(path)) Log.Warning("shell", $"Explorer could not show {path}"); } + + public static void OpenFolder(string path) => Reveal(path); } diff --git a/src/Titano.App/Infrastructure/UiLanguage.cs b/src/Titano.App/Infrastructure/UiLanguage.cs new file mode 100644 index 00000000..e2a5f783 --- /dev/null +++ b/src/Titano.App/Infrastructure/UiLanguage.cs @@ -0,0 +1,33 @@ +using System.Globalization; +using System.Windows; +using Titano.Core.Localization; + +namespace Titano.App.Infrastructure; + +/// Switches the UI language at run time without restart (BRIEF §16), mirroring right-to-left languages. +public static class UiLanguage +{ + /// Applies (or the OS language when null) and returns the culture in use. + public static CultureInfo Apply(string? code) + { + CultureInfo requested; + try + { + requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code); + } + catch (CultureNotFoundException) + { + requested = CultureInfo.CurrentUICulture; + } + var culture = Languages.BestMatch(requested); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + if (Application.Current is { } app) + { + foreach (Window window in app.Windows) + window.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + } + return culture; + } +} diff --git a/src/Titano.App/Interop/FileDialogs.cs b/src/Titano.App/Interop/FileDialogs.cs new file mode 100644 index 00000000..9f8e75de --- /dev/null +++ b/src/Titano.App/Interop/FileDialogs.cs @@ -0,0 +1,192 @@ +using System.Runtime.InteropServices; + +namespace Titano.App.Interop; + +/// A filter of the Open dialog: display name and patterns such as *.jpg;*.cr2. +public readonly record struct FileFilter(string Name, string Patterns); + +/// +/// The shell's Open dialog through IFileOpenDialog COM (no WinForms): one or several files, or one folder +/// (which also picks a card root such as E:\). Same wrapper as the uploader's (kept per program so neither +/// depends on the other). +/// +public static class FileDialogs +{ + private const uint FosPickFolders = 0x20; + private const uint FosForceFileSystem = 0x40; + private const uint FosAllowMultiSelect = 0x200; + private const uint FosPathMustExist = 0x800; + private const uint FosFileMustExist = 0x1000; + private const uint SigdnFileSysPath = 0x80058000; + private const int ErrorCancelled = unchecked((int)0x800704C7); + + /// Selected files; empty when cancelled. + public static IReadOnlyList PickFiles(IntPtr owner, string title, IReadOnlyList filters) => + Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters); + + /// One selected file; null when cancelled. + public static string? PickFile(IntPtr owner, string title, IReadOnlyList filters) => + Show(owner, title, FosFileMustExist, filters).FirstOrDefault(); + + /// Selected folder; null when cancelled. + public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault(); + + private static List Show(IntPtr owner, string title, uint options, IReadOnlyList filters) + { + var dialog = (IFileOpenDialog)new FileOpenDialogClass(); + try + { + dialog.GetOptions(out var current); + dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist); + dialog.SetTitle(title); + if (filters.Count > 0) + { + var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray(); + dialog.SetFileTypes((uint)specs.Length, specs); + dialog.SetFileTypeIndex(1); + } + var hr = dialog.Show(owner); + if (hr == ErrorCancelled) return []; + Marshal.ThrowExceptionForHR(hr); + + dialog.GetResults(out var items); + try + { + items.GetCount(out var count); + var paths = new List((int)count); + for (uint i = 0; i < count; i++) + { + items.GetItemAt(i, out var item); + try + { + item.GetDisplayName(SigdnFileSysPath, out var path); + paths.Add(path); + } + finally + { + Marshal.ReleaseComObject(item); + } + } + return paths; + } + finally + { + Marshal.ReleaseComObject(items); + } + } + finally + { + Marshal.ReleaseComObject(dialog); + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct FilterSpec + { + [MarshalAs(UnmanagedType.LPWStr)] + public string Name; + + [MarshalAs(UnmanagedType.LPWStr)] + public string Spec; + } + + [ComImport] + [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] + private class FileOpenDialogClass; + + // Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order. + [ComImport] + [Guid("d57c7288-d4ad-4768-be02-9d969532d960")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFileOpenDialog + { + [PreserveSig] + int Show(IntPtr owner); + + void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters); + + void SetFileTypeIndex(uint index); + + void GetFileTypeIndex(out uint index); + + void Advise(IntPtr events, out uint cookie); + + void Unadvise(uint cookie); + + void SetOptions(uint options); + + void GetOptions(out uint options); + + void SetDefaultFolder(IShellItem item); + + void SetFolder(IShellItem item); + + void GetFolder(out IShellItem item); + + void GetCurrentSelection(out IShellItem item); + + void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); + + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); + + void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); + + void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text); + + void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); + + void GetResult(out IShellItem item); + + void AddPlace(IShellItem item, int placement); + + void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension); + + void Close(int hr); + + void SetClientGuid(ref Guid guid); + + void ClearClientData(); + + void SetFilter(IntPtr filter); + + void GetResults(out IShellItemArray items); + + void GetSelectedItems(out IShellItemArray items); + } + + [ComImport] + [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetParent(out IShellItem parent); + + void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name); + + void GetAttributes(uint mask, out uint attributes); + + void Compare(IShellItem other, uint hint, out int order); + } + + [ComImport] + [Guid("b63ea76d-1f85-456f-a19c-48159efa858b")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItemArray + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetPropertyStore(int flags, ref Guid iid, out IntPtr store); + + void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list); + + void GetAttributes(int flags, uint mask, out uint attributes); + + void GetCount(out uint count); + + void GetItemAt(uint index, out IShellItem item); + + void EnumItems(out IntPtr items); + } +} diff --git a/src/Titano.App/Jobs/JobListModel.cs b/src/Titano.App/Jobs/JobListModel.cs new file mode 100644 index 00000000..cd72b0c8 --- /dev/null +++ b/src/Titano.App/Jobs/JobListModel.cs @@ -0,0 +1,164 @@ +using Titano.Core.Model; +using Titano.Data.Jobs; + +namespace Titano.App.Jobs; + +/// Filter chips of the Jobs screen (BRIEF §12.6). +public enum JobFilter +{ + All, + Running, + Queued, + Done, + Failed, +} + +/// One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs. +public sealed class JobEntry(Job job) +{ + public Job Job { get; internal set; } = job; + + /// Latest progress event of the running job; null once it stops. + public JobProgressInfo? Live { get; internal set; } + + /// of the last update. + internal long Stamp { get; set; } + + public Guid Id => Job.Id; + public JobState State => Job.State; + public long Done => Live?.Done ?? Job.ProgressDone; + public long Total => Live?.Total ?? Job.ProgressTotal; + public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond; + public TimeSpan? Eta => Live?.Eta ?? Job.Eta; + public string? Message => Live?.Message; + + /// 0…1, or null while the total is unknown. + public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null; + + public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled; +} + +/// +/// The job list behind the Jobs screen and the job bar: merges stored snapshots (, +/// repository pages) with live progress (), keeps queue order and answers the +/// filters. WPF-free and not thread-safe; feed it on the UI thread (through ). +/// +public sealed class JobListModel +{ + private readonly Dictionary _entries = []; + + private long _stamp; + + public int Count => _entries.Count; + + public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id); + + /// + /// Change counter. Read it before requesting a page from the database and pass it to , + /// so a page that was read before an event cannot overwrite the newer state the event brought. + /// + public long Stamp => _stamp; + + /// Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed. + public bool Apply(Job job) => Store(job, ++_stamp); + + /// Inserts a snapshot read from the database; skipped when an event updated the job after . + public bool ApplyLoaded(Job job, long readAt) + { + if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false; + return Store(job, readAt); + } + + private bool Store(Job job, long stamp) + { + if (!_entries.TryGetValue(job.Id, out var entry)) + { + _entries[job.Id] = new JobEntry(job) { Stamp = stamp }; + return true; + } + entry.Stamp = Math.Max(entry.Stamp, stamp); + if (entry.Job == job) return false; + entry.Job = job; + if (job.State != JobState.Running) entry.Live = null; + return true; + } + + /// Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed. + public bool Apply(JobProgressInfo progress) + { + if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false; + if (entry.Live == progress) return false; + entry.Live = progress; + return true; + } + + /// Removes jobs no longer present (e.g. purged history). + public bool Remove(Guid id) => _entries.Remove(id); + + /// + /// Display order: running (oldest start first), paused, queued in the order workers claim them (priority, then + /// age), then the history, newest finish first. Finished jobs before are hidden. + /// + public IReadOnlyList Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null) + { + var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim(); + return _entries.Values + .Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text))) + .OrderBy(Group) + .ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0) + .ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks) + .ThenBy(e => e.Job.Created) + .ThenBy(e => e.Id) + .ToList(); + } + + /// Jobs per filter chip (after "Clear done"). + public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) => + _entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore)); + + /// 1-based place of a queued job in the order workers claim jobs; 0 when it is not queued. + public int QueuePosition(Guid id) + { + if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0; + return _entries.Values.Count(e => e.State == JobState.Queued && ClaimsBefore(e.Job, entry.Job)) + 1; + } + + /// The job the job bar mirrors: the running job with the most recent progress, else the first running one. + public JobEntry? Current => + _entries.Values.Where(e => e.State == JobState.Running) + .OrderByDescending(e => e.Live is not null) + .ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks) + .FirstOrDefault(); + + public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running); + + public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued); + + /// Same order as JobRepository.ClaimNextAsync: priority descending, then creation time and id. + public static bool ClaimsBefore(Job a, Job b) => + a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0; + + private static int Group(JobEntry e) => e.State switch + { + JobState.Running => 0, + JobState.Paused => 1, + JobState.Queued => 2, + _ => 3, + }; + + private static bool Matches(JobEntry e, JobFilter filter) => filter switch + { + JobFilter.Running => e.State is JobState.Running or JobState.Paused, + JobFilter.Queued => e.State == JobState.Queued, + JobFilter.Done => e.State == JobState.Done, + JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled, + _ => true, + }; + + private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) => + clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore; + + private static bool MatchesText(JobEntry e, string text) => + (e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false) + || JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase); +} diff --git a/src/Titano.App/Jobs/JobQueue.cs b/src/Titano.App/Jobs/JobQueue.cs new file mode 100644 index 00000000..dbc587d1 --- /dev/null +++ b/src/Titano.App/Jobs/JobQueue.cs @@ -0,0 +1,106 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Jobs; +using Titano.Data.Repositories; + +namespace Titano.App.Jobs; + +/// What the Jobs screen, the job bar and the Library need from the job system. +public interface IJobQueue +{ + /// A job changed state (any thread). + event Action? JobChanged; + + /// Progress of a running job (any thread, high frequency). + event Action? Progress; + + /// Node id stamped on jobs run by this PC. + string WorkerId { get; } + + /// Concurrent workers of the local engine; 0 when it runs no handler yet. + int Workers { get; } + + /// Kinds this PC can run. + IReadOnlyCollection Kinds { get; } + + Task> ListAsync(string? cursor, int limit, CancellationToken ct = default); + + Task GetAsync(Guid id, CancellationToken ct = default); + + Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default); + + Task PauseAsync(Guid id); + + /// Resumes a paused job, or retries a failed or cancelled one from its checkpoint. + Task ResumeAsync(Guid id); + + /// Cancels a running or queued job. + Task CancelAsync(Guid id); + + /// Moves a queued job ahead of lower-priority jobs (one priority level up). + Task RaisePriorityAsync(Guid id); +} + +/// over the local and the job table. +public sealed class EngineJobQueue : IJobQueue, IDisposable +{ + private readonly TitanoDatabase _db; + private readonly JobEngine _engine; + private readonly bool _started; + + public EngineJobQueue(TitanoDatabase db, JobEngine engine, bool started) + { + _db = db; + _engine = engine; + _started = started; + _engine.JobChanged += OnJobChanged; + _engine.Progress += OnProgress; + } + + public event Action? JobChanged; + + public event Action? Progress; + + public string WorkerId => _engine.Options.WorkerId; + + public int Workers => _started ? _engine.Options.Workers : 0; + + public IReadOnlyCollection Kinds => _engine.Options.Kinds ?? []; + + public Task> ListAsync(string? cursor, int limit, CancellationToken ct = default) => _db.Jobs.ListAsync(null, limit, cursor, ct); + + public Task GetAsync(Guid id, CancellationToken ct = default) => _db.Jobs.GetAsync(id, ct); + + public Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) => + _engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct); + + public Task PauseAsync(Guid id) => _engine.PauseAsync(id); + + public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id); + + public Task CancelAsync(Guid id) => _engine.CancelAsync(id); + + public async Task RaisePriorityAsync(Guid id) + { + // JobRepository has no priority update yet; one guarded statement keeps it atomic (queued jobs only). + var session = await _db.Database.OpenAsync(CancellationToken.None); + await using (session) + { + await session.ExecuteAsync( + $"UPDATE jobs SET priority = priority + 1 WHERE id = $1 AND state = {(int)JobState.Queued} AND priority < {(int)JobPriority.User}", + [id], CancellationToken.None); + } + if (await _db.Jobs.GetAsync(id) is { } job) JobChanged?.Invoke(job); + _engine.Wake(); + } + + public void Dispose() + { + _engine.JobChanged -= OnJobChanged; + _engine.Progress -= OnProgress; + } + + private void OnJobChanged(Job job) => JobChanged?.Invoke(job); + + private void OnProgress(JobProgressInfo progress) => Progress?.Invoke(progress); +} diff --git a/src/Titano.App/Jobs/JobRowViewModel.cs b/src/Titano.App/Jobs/JobRowViewModel.cs new file mode 100644 index 00000000..7aed3470 --- /dev/null +++ b/src/Titano.App/Jobs/JobRowViewModel.cs @@ -0,0 +1,133 @@ +using System.Windows.Input; +using Titano.App.Infrastructure; +using Titano.App.Sections; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Ui.Controls; +using Titano.Ui.Mvvm; + +namespace Titano.App.Jobs; + +/// A row action: label, tooltip and command (26-px row buttons, DESIGN §4 tables). +public sealed record JobAction(string Text, string ToolTip, ICommand Command, bool IsDestructive = false); + +/// One row of the Jobs table (Jobs.html): kind, target, progress, speed, left, where, state, actions, log. +public sealed class JobRowViewModel : ObservableObject +{ + private readonly JobActions _actions; + private JobEntry _entry; + private int _queuePosition; + private bool _isExpanded; + private string? _logTail; + + internal JobRowViewModel(JobEntry entry, int queuePosition, JobActions actions) + { + _entry = entry; + _queuePosition = queuePosition; + _actions = actions; + ToggleLogCommand = new RelayCommand(() => IsExpanded = !IsExpanded); + } + + public JobEntry Entry => _entry; + public Guid Id => _entry.Id; + public Job Job => _entry.Job; + + public string Kind => JobText.Kind(_entry.Job.Kind); + + public string Target => _entry.Job.TargetLabel ?? string.Empty; + + /// Progress 0…1 (0 while unknown). + public double Progress => _entry.State == JobState.Done ? 1 : _entry.Fraction ?? 0; + + /// "62 %", "—" while queued or unknown. + public string PercentText => _entry.State == JobState.Done ? Formatting.Percent(1) : _entry.Fraction is { } f && _entry.State != JobState.Queued ? Formatting.Percent(f) : "—"; + + public string SpeedText => _entry.State is JobState.Running or JobState.Done ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—"; + + public string LeftText => Blank(JobText.Left(_entry, _queuePosition)); + + public string WhereText => _entry.State == JobState.Queued ? Loc.L("Jobs.Where.ThisPc") : Blank(JobText.Where(_entry.Job.NodeId, _actions.WorkerId)); + + public string StateText => JobText.State(_entry); + + /// Glyph and colour of the state (paired with the word, never colour alone). + public StatusKind StateKind => _entry.State switch + { + JobState.Running => StatusKind.Running, + JobState.Queued => StatusKind.Queued, + JobState.Paused => StatusKind.Paused, + JobState.Done => StatusKind.Done, + JobState.Failed => StatusKind.Failed, + _ => StatusKind.Offline, + }; + + /// The error of a failed job, or the state explanation. + public string StateToolTip => _entry.Job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _entry.State); + + /// Muted text for rows that are not doing anything (queued, history), as in the mockup. + public bool IsDimmed => _entry.State is JobState.Queued or JobState.Done or JobState.Cancelled; + + public bool IsFailed => _entry.State == JobState.Failed; + public bool IsDone => _entry.State == JobState.Done; + + public IReadOnlyList Actions => _actions.For(_entry); + + public ICommand ToggleLogCommand { get; } + + public bool IsExpanded + { + get => _isExpanded; + set + { + if (!Set(ref _isExpanded, value)) return; + OnPropertyChanged(nameof(ToggleToolTip)); + if (value) _ = _actions.LoadLogAsync(this); + } + } + + public string ToggleToolTip => Loc.L(_isExpanded ? "Tooltips.Jobs.HideLog" : "Tooltips.Jobs.ShowLog"); + + /// The last lines of the job log, plus the live message while it runs. + public string LogText + { + get + { + var tail = _logTail ?? _entry.Job.LogTail ?? string.Empty; + if (_entry.State == JobState.Running && _entry.Message is { Length: > 0 } message && !tail.EndsWith(message, StringComparison.Ordinal)) + tail = tail.Length == 0 ? message : tail + "\n" + message; + return tail.Length == 0 ? Loc.L("Jobs.Log.Empty") : tail; + } + } + + internal void SetLog(string? logTail) + { + _logTail = logTail; + OnPropertyChanged(nameof(LogText)); + } + + /// Refreshes the row from the model; returns true when it changed position-relevant data. + internal void Update(JobEntry entry, int queuePosition) + { + var stateChanged = entry.State != _entry.State; + _entry = entry; + _queuePosition = queuePosition; + if (stateChanged) + { + _logTail = null; + OnAllPropertiesChanged(); + if (_isExpanded) _ = _actions.LoadLogAsync(this); + return; + } + OnPropertyChanged(nameof(Progress)); + OnPropertyChanged(nameof(PercentText)); + OnPropertyChanged(nameof(SpeedText)); + OnPropertyChanged(nameof(LeftText)); + OnPropertyChanged(nameof(WhereText)); + OnPropertyChanged(nameof(StateText)); + if (_isExpanded) OnPropertyChanged(nameof(LogText)); + } + + internal void Refresh() => OnAllPropertiesChanged(); + + private static string Blank(string text) => text.Length == 0 ? "—" : text; +} diff --git a/src/Titano.App/Jobs/JobText.cs b/src/Titano.App/Jobs/JobText.cs new file mode 100644 index 00000000..4bec41c4 --- /dev/null +++ b/src/Titano.App/Jobs/JobText.cs @@ -0,0 +1,68 @@ +using Titano.App.Infrastructure; +using Titano.Core.Localization; +using Titano.Core.Model; + +namespace Titano.App.Jobs; + +/// Localized texts of jobs: kind, speed, time left, place in the queue, state (Jobs screen and job bar). +public static class JobText +{ + /// "Render", "Deep analysis", … + public static string Kind(JobKind kind) => Loc.L("Jobs.Kind." + kind); + + /// True for jobs whose items are frames, so their speed reads in fps. + public static bool CountsFrames(JobKind kind) => + kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Verify; + + /// "11.3 fps" for frame jobs, "41/s" otherwise; empty when unknown. + public static string Speed(JobKind kind, double? perSecond) => + perSecond is > 0 and var rate + ? Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate)) + : string.Empty; + + /// "1,240 / 3,600"; empty while the total is unknown. + public static string Counter(long done, long total) => + total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty; + + /// + /// The "Left" column: time left while running, "after n" while queued, the finish time of the history. + /// + public static string Left(JobEntry entry, int queuePosition) => entry.State switch + { + JobState.Running => entry.Eta is { } eta ? Formatting.Duration(eta) : string.Empty, + JobState.Queued => queuePosition > 1 ? Loc.L("Jobs.Left.After", queuePosition - 1) : Loc.L("Jobs.Left.Next"), + _ when entry.Job.Finished is { } finished => Formatting.TimeOfDay(finished), + _ => string.Empty, + }; + + /// State word, with the run time for done jobs ("done · 2:41"). + public static string State(JobEntry entry) + { + var word = Loc.L("Jobs.State." + entry.State); + return entry.State == JobState.Done && entry.Job is { Started: { } started, Finished: { } finished } + ? Loc.L("Jobs.State.WithDetail", word, Formatting.Elapsed(finished - started)) + : word; + } + + /// Where the job runs: "this PC" for this machine's workers, the node name otherwise. + public static string Where(string? nodeId, string localWorkerId) + { + if (string.IsNullOrEmpty(nodeId)) return string.Empty; + var hash = nodeId.IndexOf('#', StringComparison.Ordinal); + var name = hash < 0 ? nodeId : nodeId[..hash]; + return name.Equals(localWorkerId, StringComparison.OrdinalIgnoreCase) ? Loc.L("Jobs.Where.ThisPc") : name; + } + + /// + /// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left". + /// + public static string Bar(JobEntry entry) + { + var parts = new List(5) { Kind(entry.Job.Kind) }; + if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!); + if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter); + if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); + if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta))); + return string.Join(" · ", parts); + } +} diff --git a/src/Titano.App/Jobs/JobUpdateBuffer.cs b/src/Titano.App/Jobs/JobUpdateBuffer.cs new file mode 100644 index 00000000..a5b471a5 --- /dev/null +++ b/src/Titano.App/Jobs/JobUpdateBuffer.cs @@ -0,0 +1,143 @@ +using Titano.Core.Model; +using Titano.Data.Jobs; + +namespace Titano.App.Jobs; + +/// +/// Collects job events from worker threads and hands them to the UI in batches: per job only the newest snapshot +/// and the newest progress survive, so a handler reporting thousands of times per second costs the UI one update per +/// flush. Thread-safe. +/// +public sealed class JobUpdateBuffer +{ + private readonly Lock _gate = new(); + private Dictionary _jobs = []; + private Dictionary _progress = []; + private long _posted; + + /// Events accepted since creation (diagnostics, tests). + public long Posted => Interlocked.Read(ref _posted); + + /// Records a state change; true when the buffer was empty (the caller schedules a flush). + public bool Post(Job job) + { + lock (_gate) + { + var wasEmpty = IsEmptyLocked; + _jobs[job.Id] = job; + // A newer snapshot supersedes progress reported before it. + _progress.Remove(job.Id); + _posted++; + return wasEmpty; + } + } + + /// Records progress; true when the buffer was empty (the caller schedules a flush). + public bool Post(JobProgressInfo progress) + { + lock (_gate) + { + var wasEmpty = IsEmptyLocked; + _progress[progress.JobId] = progress; + _posted++; + return wasEmpty; + } + } + + public bool IsEmpty + { + get + { + lock (_gate) return IsEmptyLocked; + } + } + + /// Takes everything collected since the last drain (snapshots first, then progress). + public (IReadOnlyCollection Jobs, IReadOnlyCollection Progress) Drain() + { + lock (_gate) + { + var jobs = _jobs; + var progress = _progress; + _jobs = []; + _progress = []; + return (jobs.Values, progress.Values); + } + } + + private bool IsEmptyLocked => _jobs.Count == 0 && _progress.Count == 0; +} + +/// +/// Runs an action on a synchronization context at most once per interval, however often it is signalled from any +/// thread: the first signal after a flush schedules the next flush for interval after the previous one +/// (the job list refreshes at about 10 Hz). +/// +public sealed class CoalescingThrottle : IDisposable +{ + private readonly TimeSpan _interval; + private readonly SynchronizationContext? _context; + private readonly Action _flush; + private readonly Func _now; + private readonly Timer _timer; + private readonly Lock _gate = new(); + private long _lastFlush = long.MinValue; + private bool _scheduled; + private bool _disposed; + + /// Minimum time between two flushes. + /// Where runs (the UI); null runs it on the timer thread. + /// The batched work. + /// Milliseconds clock for tests; defaults to the high-resolution . + public CoalescingThrottle(TimeSpan interval, SynchronizationContext? context, Action flush, Func? clock = null) + { + _interval = interval; + _context = context; + _flush = flush; + _now = clock ?? (() => System.Diagnostics.Stopwatch.GetTimestamp() * 1000 / System.Diagnostics.Stopwatch.Frequency); + _timer = new Timer(_ => Dispatch(), null, Timeout.Infinite, Timeout.Infinite); + } + + /// Flushes performed (tests). + public int Flushes { get; private set; } + + /// Asks for a flush; coalesced with every other signal until it runs. + public void Signal() + { + lock (_gate) + { + if (_scheduled || _disposed) return; + _scheduled = true; + var wait = _lastFlush == long.MinValue ? 0 : (long)_interval.TotalMilliseconds - (_now() - _lastFlush); + if (wait <= 0) wait = 0; + _timer.Change(wait, Timeout.Infinite); + } + } + + public void Dispose() + { + lock (_gate) + { + _disposed = true; + _timer.Dispose(); + } + } + + private void Dispatch() + { + if (_context is null) Run(); + else _context.Post(_ => Run(), null); + } + + private void Run() + { + lock (_gate) + { + if (_disposed) return; + _scheduled = false; + _lastFlush = _now(); + Flushes++; + } + _flush(); + } +} diff --git a/src/Titano.App/Library/FilterOption.cs b/src/Titano.App/Library/FilterOption.cs new file mode 100644 index 00000000..81c0425d --- /dev/null +++ b/src/Titano.App/Library/FilterOption.cs @@ -0,0 +1,10 @@ +namespace Titano.App.Library; + +/// +/// One entry of a toolbar dropdown: in the open list, in the closed box +/// (the filter's name while nothing is chosen, e.g. "Year", the chosen value otherwise). +/// +public sealed record FilterOption(T Value, string Label, string BoxText, bool IsAny = false) +{ + public override string ToString() => Label; +} diff --git a/src/Titano.App/Library/LibraryFilter.cs b/src/Titano.App/Library/LibraryFilter.cs new file mode 100644 index 00000000..c0d64493 --- /dev/null +++ b/src/Titano.App/Library/LibraryFilter.cs @@ -0,0 +1,65 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; + +namespace Titano.App.Library; + +/// Status choices of the Library toolbar; each maps onto status flags the index can filter on. +public enum StatusFilter +{ + Any, + Analysed, + NotAnalysed, + Proxies, + NoProxies, + Verified, + NotVerified, + Warnings, +} + +/// Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it. +public sealed record LibraryFilter +{ + public string? Text { get; init; } + public int? Year { get; init; } + public string? Camera { get; init; } + public StatusFilter Status { get; init; } + public string? Tag { get; init; } + public SequenceSort Sort { get; init; } = SequenceSort.Newest; + + /// No filter narrows the list (the sort may differ): an empty result means an empty library. + public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null; + + /// The same sort without filters ("Clear filters"). + public LibraryFilter Cleared() => new() { Sort = Sort }; + + /// The repository query for one page. + public SequenceQuery ToQuery(int limit, string? cursor) + { + var (with, without) = Flags(Status); + return new SequenceQuery + { + Text = string.IsNullOrWhiteSpace(Text) ? null : Text.Trim(), + Year = Year, + Camera = Camera, + Tag = Tag, + WithStatus = with, + WithoutStatus = without, + Sort = Sort, + Limit = limit, + Cursor = cursor, + }; + } + + /// Flags that must be set and clear for a status choice. + public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch + { + StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None), + StatusFilter.NotAnalysed => (SequenceStatus.None, SequenceStatus.AnalyzedLight), + StatusFilter.Proxies => (SequenceStatus.ProxiesBuilt, SequenceStatus.None), + StatusFilter.NoProxies => (SequenceStatus.None, SequenceStatus.ProxiesBuilt), + StatusFilter.Verified => (SequenceStatus.Verified, SequenceStatus.None), + StatusFilter.NotVerified => (SequenceStatus.None, SequenceStatus.Verified), + StatusFilter.Warnings => (SequenceStatus.HasWarnings, SequenceStatus.None), + _ => (SequenceStatus.None, SequenceStatus.None), + }; +} diff --git a/src/Titano.App/Library/LibraryPager.cs b/src/Titano.App/Library/LibraryPager.cs new file mode 100644 index 00000000..7995f47c --- /dev/null +++ b/src/Titano.App/Library/LibraryPager.cs @@ -0,0 +1,102 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; + +namespace Titano.App.Library; + +/// A page of the Library list. pages replace the list, the others append to it. +public sealed record LibraryPage(int Generation, IReadOnlyList Items, bool IsFirst, bool HasMore); + +/// +/// Keyset paging of the Library (BRIEF §5: pagination on (first_capture, id)): the first page after a filter +/// change, then the next page whenever the view scrolls near the end. A filter change cancels the page in flight +/// and every result of an older filter is dropped, so stale rows never reach the list. Not thread-safe: call from +/// one thread (the UI). +/// +public sealed class LibraryPager(Func>> fetch, int pageSize = LibraryPager.DefaultPageSize) +{ + public const int DefaultPageSize = 200; + + private CancellationTokenSource _cancellation = new(); + private Task>? _pending; + private string? _cursor; + + public int PageSize { get; } = Math.Clamp(pageSize, 1, 1000); + + public LibraryFilter Filter { get; private set; } = new(); + + /// Incremented by every ; pages carry the generation they belong to. + public int Generation { get; private set; } + + /// More rows exist after the loaded ones. + public bool HasMore { get; private set; } + + public bool IsLoading => _pending is not null; + + /// Rows delivered for the current filter. + public int Loaded { get; private set; } + + /// Starts over with ; null when a newer reset superseded this one. + public Task ResetAsync(LibraryFilter filter) + { + _cancellation.Cancel(); + _cancellation.Dispose(); + _cancellation = new CancellationTokenSource(); + _pending = null; + Generation++; + Filter = filter; + _cursor = null; + Loaded = 0; + HasMore = true; + return LoadAsync(first: true); + } + + /// The next page; null when everything is loaded, a page is already loading, or the filter changed meanwhile. + public Task LoadMoreAsync() + { + if (_pending is not null || !HasMore || Generation == 0) return Task.FromResult(null); + return LoadAsync(first: false); + } + + /// Stops the page in flight (screen closed). + public void Cancel() + { + _cancellation.Cancel(); + _pending = null; + } + + private async Task LoadAsync(bool first) + { + var generation = Generation; + var cancellation = _cancellation; + var pending = fetch(Filter.ToQuery(PageSize, _cursor), cancellation.Token); + _pending = pending; + Page page; + try + { + page = await pending; + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + return null; + } + catch (Exception) when (generation != Generation) + { + return null; + } + catch + { + // A failing page stops the scroll-driven loading until the next reset instead of retrying on every scroll. + HasMore = false; + throw; + } + finally + { + if (ReferenceEquals(_pending, pending)) _pending = null; + } + if (generation != Generation || cancellation.IsCancellationRequested) return null; + _cursor = page.NextCursor; + HasMore = page.NextCursor is not null; + Loaded += page.Items.Count; + return new LibraryPage(generation, page.Items, first, HasMore); + } +} diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs new file mode 100644 index 00000000..f1ed8d64 --- /dev/null +++ b/src/Titano.App/Library/SequenceItem.cs @@ -0,0 +1,179 @@ +using System.Windows.Media; +using Titano.App.Infrastructure; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Naming; +using Titano.Ui.Controls; +using Titano.Ui.Mvvm; +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// One sequence of the Library grid and list (BRIEF §12.2). +public sealed class SequenceItem : ObservableObject +{ + private readonly ThumbnailService? _thumbnails; + private Sequence _sequence; + private ImageSource? _thumbnail; + private IThumbnailSource? _scrub; + private CancellationTokenSource? _loading; + private int _requestedWidth; + private bool _isSelected; + private bool _isAnalysing; + + public SequenceItem(Sequence sequence, ThumbnailService? thumbnails) + { + _sequence = sequence; + _thumbnails = thumbnails; + } + + public Sequence Sequence => _sequence; + public Guid Id => _sequence.Id; + + /// User title or "{date} {camera}". + public string Title => _sequence.DisplayTitle; + + /// "Canon EOS R5" (brand not repeated). + public string Camera => PathTemplate.CameraName(_sequence.CameraMake, _sequence.CameraModel); + + /// Card line: count · camera · span. + public string Subtitle => string.Join(" · ", new[] { FramesText, Camera, SpanText }.Where(s => s.Length > 0)); + + public string FramesText => Formatting.Count(_sequence.FrameCount); + + /// First capture date (camera clock). + public string DateText => _sequence.FirstCapture is { } first ? Formatting.Date(first) : string.Empty; + + /// Time from first to last capture. + public string SpanText => _sequence is { FirstCapture: { } a, LastCapture: { } b } && b > a ? Formatting.Duration(b - a) : string.Empty; + + public string IntervalText => _sequence.MedianInterval is > 0 and var s ? Loc.L("Library.Interval", s.ToString(s < 10 ? "0.#" : "0", Loc.Culture)) : string.Empty; + + public string SizeText => Formatting.Bytes(_sequence.TotalBytes); + + public string TagsText => string.Join(", ", _sequence.Tags); + + /// Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone). + public IReadOnlyList Statuses => BuildStatuses(_sequence, _isAnalysing); + + /// The single most relevant status for the list's State column. + public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing) + ?? Statuses[0]; + + public ImageSource? Thumbnail + { + get => _thumbnail; + private set => Set(ref _thumbnail, value); + } + + /// Frames for hover scrubbing; created on first use. + public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence); + + public bool IsSelected + { + get => _isSelected; + set => Set(ref _isSelected, value); + } + + /// An analysis job runs on this sequence ("◐ Analysing"). + public bool IsAnalysing + { + get => _isAnalysing; + set + { + if (Set(ref _isAnalysing, value)) RaiseStatuses(); + } + } + + /// Replaces the row with a fresher copy of the same sequence. + public void Update(Sequence sequence) + { + var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount; + _sequence = sequence; + if (heroChanged) + { + _scrub = null; + if (_requestedWidth > 0) RequestThumbnail(_requestedWidth, force: true); + } + OnAllPropertiesChanged(); + } + + /// The card or row became visible: load the hero thumbnail (once per width). + public void RequestThumbnail(int pixelWidth, bool force = false) + { + if (_thumbnails is null || pixelWidth <= 0) return; + if (!force && _thumbnail is not null && pixelWidth <= _requestedWidth) return; + if (!force && _loading is not null && pixelWidth <= _requestedWidth) return; + _requestedWidth = pixelWidth; + _loading?.Cancel(); + var cancellation = new CancellationTokenSource(); + _loading = cancellation; + _ = LoadAsync(pixelWidth, cancellation); + } + + /// The card left the screen (recycled): stop its load. + public void ReleaseThumbnail() + { + _loading?.Cancel(); + _loading = null; + if (_thumbnail is null) _requestedWidth = 0; + } + + private async Task LoadAsync(int pixelWidth, CancellationTokenSource cancellation) + { + try + { + var image = await _thumbnails!.HeroAsync(_sequence, pixelWidth, cancellation.Token); + if (!cancellation.IsCancellationRequested) Thumbnail = image; + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + Log.Warning("library", $"Thumbnail of {_sequence.Id} failed", ex); + } + finally + { + if (ReferenceEquals(_loading, cancellation)) _loading = null; + cancellation.Dispose(); + } + } + + private void RaiseStatuses() + { + OnPropertyChanged(nameof(Statuses)); + OnPropertyChanged(nameof(PrimaryStatus)); + } + + /// Card status row: analysed, proxies, renders, sync, warnings (Main.html). + public static IReadOnlyList BuildStatuses(Sequence s, bool analysing) + { + var list = new List(5); + if (analysing) list.Add(new CardStatus(StatusKind.Analysing, Loc.L("Library.Status.Analysing"), Loc.L("Tooltips.Library.Status.Analysing"))); + else if ((s.Status & SequenceStatus.AnalyzedLight) != 0) list.Add(new CardStatus(StatusKind.Analysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.Analysed"))); + else list.Add(new CardStatus(StatusKind.NotAnalysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.NotAnalysed"))); + + if (s.Origin == SequenceOrigin.Server && s.SyncState == SyncState.RemoteOnly) + { + list.Add(new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.Remote"))); + } + else + { + list.Add((s.Status & SequenceStatus.ProxiesBuilt) != 0 + ? new CardStatus(StatusKind.Proxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.Proxies")) + : new CardStatus(StatusKind.NoProxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.NoProxies"))); + } + + if (s.RenderedCount > 0) + list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount))); + if (s.SyncState == SyncState.InSync) + list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced"))); + if ((s.Status & SequenceStatus.HasErrors) != 0) + list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors"))); + else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0) + list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount)))); + return list; + } +} diff --git a/src/Titano.App/Library/ThumbnailCache.cs b/src/Titano.App/Library/ThumbnailCache.cs new file mode 100644 index 00000000..e6030b9d --- /dev/null +++ b/src/Titano.App/Library/ThumbnailCache.cs @@ -0,0 +1,152 @@ +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// +/// Decoded thumbnails in a least-recently-used cache, with loads shared between requests for the same key. A load +/// runs off the calling thread, at most maxConcurrentLoads at once; it is cancelled as soon as every request +/// waiting for it is cancelled (the card scrolled away), so the decoder never works for rows nobody sees. Results, +/// including "no thumbnail" (null), are cached; failures are not. +/// +public sealed class ThumbnailCache : IDisposable + where TKey : notnull + where TImage : class +{ + private readonly LruCache _cache; + private readonly Dictionary _loading = []; + private readonly Func> _load; + private readonly SemaphoreSlim _slots; + private readonly Lock _gate = new(); + + public ThumbnailCache(int capacity, Func> load, int maxConcurrentLoads = 4) + { + ArgumentOutOfRangeException.ThrowIfLessThan(maxConcurrentLoads, 1); + _cache = new LruCache(capacity); + _load = load; + _slots = new SemaphoreSlim(maxConcurrentLoads, maxConcurrentLoads); + } + + /// Cached entries. + public int Count + { + get + { + lock (_gate) return _cache.Count; + } + } + + /// Maximum cached entries; lowering it evicts the least recently used at once. + public int Capacity + { + get + { + lock (_gate) return _cache.Capacity; + } + set + { + lock (_gate) _cache.Capacity = value; + } + } + + /// Loads started and not yet finished or cancelled. + public int PendingLoads + { + get + { + lock (_gate) return _loading.Count; + } + } + + /// The cached image without loading; true also for a cached "no thumbnail". + public bool TryGet(TKey key, out TImage? image) + { + lock (_gate) return _cache.TryGet(key, out image); + } + + /// The image for , from the cache or a (shared) load. + /// was cancelled. + public async Task GetAsync(TKey key, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Load load; + lock (_gate) + { + if (_cache.TryGet(key, out var cached)) return cached; + if (!_loading.TryGetValue(key, out load!)) + { + load = new Load(); + _loading[key] = load; + load.Task = Task.Run(() => RunAsync(key, load), CancellationToken.None); + } + load.Waiters++; + } + try + { + return await load.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + lock (_gate) + { + if (--load.Waiters == 0 && !load.Task.IsCompleted) + { + load.Cancellation.Cancel(); + if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key); + } + } + throw; + } + } + + /// Forgets every cached image (loads in flight complete normally). + public void Clear() + { + lock (_gate) _cache.Clear(); + } + + public void Dispose() + { + lock (_gate) + { + foreach (var load in _loading.Values) load.Cancellation.Cancel(); + _loading.Clear(); + _cache.Clear(); + } + } + + private async Task RunAsync(TKey key, Load load) + { + var token = load.Cancellation.Token; + try + { + await _slots.WaitAsync(token).ConfigureAwait(false); + try + { + var image = await _load(key, token).ConfigureAwait(false); + lock (_gate) + { + if (!token.IsCancellationRequested) _cache.Set(key, image); + } + return image; + } + finally + { + _slots.Release(); + } + } + finally + { + lock (_gate) + { + if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key); + } + } + } + + private sealed class Load + { + public CancellationTokenSource Cancellation { get; } = new(); + public Task Task { get; set; } = null!; + public int Waiters { get; set; } + } +} diff --git a/src/Titano.App/Library/ThumbnailLoading.cs b/src/Titano.App/Library/ThumbnailLoading.cs new file mode 100644 index 00000000..828849dd --- /dev/null +++ b/src/Titano.App/Library/ThumbnailLoading.cs @@ -0,0 +1,52 @@ +using System.Windows; +using System.Windows.Media; + +namespace Titano.App.Library; + +/// +/// Attached behaviour of the card template: requests the hero thumbnail when a card shows a sequence and cancels +/// it when the card is recycled for another sequence or leaves the tree (scrolled away). +/// +public static class ThumbnailLoading +{ + /// Width of the thumbnail in device-independent pixels; 0 disables loading. + public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached( + "Width", typeof(double), typeof(ThumbnailLoading), new PropertyMetadata(0.0, OnWidthChanged)); + + public static double GetWidth(DependencyObject d) => (double)d.GetValue(WidthProperty); + + public static void SetWidth(DependencyObject d, double value) => d.SetValue(WidthProperty, value); + + private static void OnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is not FrameworkElement element) return; + element.DataContextChanged -= OnDataContextChanged; + element.Loaded -= OnLoaded; + element.Unloaded -= OnUnloaded; + if ((double)e.NewValue <= 0) return; + element.DataContextChanged += OnDataContextChanged; + element.Loaded += OnLoaded; + element.Unloaded += OnUnloaded; + Request(element); + } + + private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + { + if (e.OldValue is SequenceItem old) old.ReleaseThumbnail(); + Request((FrameworkElement)sender); + } + + private static void OnLoaded(object sender, RoutedEventArgs e) => Request((FrameworkElement)sender); + + private static void OnUnloaded(object sender, RoutedEventArgs e) + { + if (((FrameworkElement)sender).DataContext is SequenceItem item) item.ReleaseThumbnail(); + } + + private static void Request(FrameworkElement element) + { + if (element.DataContext is not SequenceItem item || !element.IsLoaded) return; + var scale = VisualTreeHelper.GetDpi(element).DpiScaleX; + item.RequestThumbnail((int)Math.Ceiling(GetWidth(element) * scale)); + } +} diff --git a/src/Titano.App/Library/ThumbnailService.cs b/src/Titano.App/Library/ThumbnailService.cs new file mode 100644 index 00000000..439650c9 --- /dev/null +++ b/src/Titano.App/Library/ThumbnailService.cs @@ -0,0 +1,192 @@ +using System.Collections.Concurrent; +using System.IO; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Titano.Core.Diagnostics; +using Titano.Core.Model; +using Titano.Data; +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// A thumbnail request: one frame at a width bucket (so nearby sizes share a decode). +public readonly record struct ThumbnailKey(Guid FrameId, int Width); + +/// +/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the +/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright, +/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away. +/// +public sealed class ThumbnailService : IDisposable +{ + /// Embedded previews larger than this are not read (a damaged index would make us read gigabytes). + private const long MaxPreviewBytes = 64L << 20; + + private const int WidthStep = 64; + + private readonly TitanoDatabase _db; + private readonly ThumbnailCache _cache; + private readonly ConcurrentDictionary _archiveRoots = new(); + private readonly ConcurrentDictionary _firstFrames = new(); + + public ThumbnailService(TitanoDatabase db, int capacity) + { + _db = db; + _cache = new ThumbnailCache(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6)); + } + + public int Count => _cache.Count; + + /// Decodes in flight (capture waits for them). + public int PendingLoads => _cache.PendingLoads; + + /// Maximum thumbnails kept in memory (Settings › Storage). + public int Capacity + { + get => _cache.Capacity; + set => _cache.Capacity = Math.Max(16, value); + } + + /// The hero thumbnail of a sequence: its hero frame, or the first frame. + public async Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct) + { + var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false); + return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null; + } + + /// A frame of a sequence by index (hover scrubbing). + public async Task FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct) + { + var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false); + return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false); + } + + /// Hover-scrub frames of a sequence, sampled to at most positions. + public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions); + + /// Drops decoded thumbnails (Settings › Storage › Clear). + public void Clear() + { + _cache.Clear(); + _archiveRoots.Clear(); + _firstFrames.Clear(); + } + + public void Dispose() => _cache.Dispose(); + + private static ThumbnailKey Key(Guid frameId, int pixelWidth) => + new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048)); + + private async Task FirstFrameAsync(Guid sequenceId, CancellationToken ct) + { + if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached; + var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false); + var id = frames.Count > 0 ? frames[0].Id : (Guid?)null; + _firstFrames[sequenceId] = id; + return id; + } + + private async Task ArchiveRootAsync(Guid sequenceId, CancellationToken ct) + { + var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false); + if (sequence is null) return null; + if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root; + root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath; + _archiveRoots[sequence.ArchiveId] = root; + return root; + } + + private async Task LoadAsync(ThumbnailKey key, CancellationToken ct) + { + var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false); + if (frame is null) return null; + var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false); + if (root is null) return null; + var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar)); + ct.ThrowIfCancellationRequested(); + try + { + return Decode(path, frame, key.Width, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException) + { + Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}"); + return null; + } + } + + /// The embedded preview when the index knows it, otherwise the original, decoded at . + internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct) + { + if (!File.Exists(path)) return null; + if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length) + { + var bytes = new byte[length]; + using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess)) + { + if (offset + length <= file.Length) + { + file.Seek(offset, SeekOrigin.Begin); + file.ReadExactly(bytes); + ct.ThrowIfCancellationRequested(); + try + { + using var memory = new MemoryStream(bytes, writable: false); + return DecodeStream(memory, frame.Orientation, width); + } + catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException) + { + // A broken preview falls through to the original. + } + } + } + } + ct.ThrowIfCancellationRequested(); + using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan); + return DecodeStream(original, frame.Orientation, width); + } + + /// WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread. + internal static BitmapSource DecodeStream(Stream stream, int orientation, int width) + { + var turned = orientation is 5 or 6 or 7 or 8; + var image = new BitmapImage(); + image.BeginInit(); + image.CacheOption = BitmapCacheOption.OnLoad; + image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; + if (turned) image.DecodePixelHeight = width; + else image.DecodePixelWidth = width; + image.StreamSource = stream; + image.EndInit(); + BitmapSource result = image; + if (orientation is > 1 and <= 8) + { + var transform = new TransformGroup(); + if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1)); + var angle = orientation switch + { + 3 or 4 => 180, + 5 or 6 => 90, + 7 or 8 => 270, + _ => 0, + }; + if (angle != 0) transform.Children.Add(new RotateTransform(angle)); + result = new TransformedBitmap(image, transform); + } + result.Freeze(); + return result; + } + + /// Evenly spaced frames of one sequence for hover scrubbing. + private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource + { + public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions); + + public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken) + { + if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false); + var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1)); + return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index adaa0d17..30236370 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -3,19 +3,21 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui" xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"> + - + - + - + + - + @@ -23,20 +25,47 @@ + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +