refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,84 @@
using System.Text.Json;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Metadata;
using Chronos.Testing;
namespace Chronos.Core.Tests.Decoding;
/// <summary>Real camera files from tests/fixtures/manifest.json (fetched by <c>Chronos.Tools fixtures</c>); 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.</summary>
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 Chronos.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);
}
/// <summary>Pearson correlation of sRGB-encoded luminance after resizing both to a common 64-pixel-wide grid.</summary>
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));
}
}
@@ -0,0 +1,67 @@
using Chronos.Core.Imaging;
using Chronos.Testing;
using static Chronos.Core.Tests.Decoding.FrameWindowTests;
namespace Chronos.Core.Tests.Decoding;
/// <summary>
/// <see cref="FrameWindow"/> cancellation (BRIEF §20.4 cancellation gate). Unobserved task exceptions are counted
/// process-wide, so the class is serial: a faulted task another test left behind would otherwise be blamed on it.
/// </summary>
[Serial]
public sealed class FrameWindowIsolationTests(TestContext context)
{
[Test]
[Timeout(10_000)]
public async Task CancellationLeavesNoSpillFileAndNoUnobservedErrors()
{
// Faulted tasks the earlier tests left for the finalizer are reported now, before this test starts counting.
GC.Collect();
GC.WaitForPendingFinalizers();
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<OperationCanceledException>(async () => await pending);
}
finally
{
await window.DisposeAsync();
}
Assert.FileMissing(spill!);
Assert.Equal(0, source.Live());
await Assert.ThrowsAsync<OperationCanceledException>(async () => await window.GetAsync(1));
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
TaskScheduler.UnobservedTaskException -= OnUnobserved;
}
Assert.Equal(0, unobserved);
}
}
@@ -0,0 +1,146 @@
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Decoding;
/// <summary><see cref="FrameWindow"/>: memory bound independent of sequence length, spill round trip, read-ahead and
/// deterministic disposal (BRIEF §8.4, §20.4 memory gate; the cancellation gate is in <see cref="FrameWindowIsolationTests"/>).</summary>
public sealed class FrameWindowTests(TestContext context)
{
private const int Size = 64;
internal const long FrameBytes = Size * Size * 3 * sizeof(float);
/// <summary>Synthetic loader whose frames encode their index; records every buffer it hands out.</summary>
internal sealed class Source
{
private readonly List<ImageBuffer> _made = [];
public int Loads;
public TimeSpan Delay;
public async ValueTask<ImageBuffer> 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;
}
/// <summary>Loader-made buffers not yet disposed (independent of the window's own counters).</summary>
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]);
}
/// <summary>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.</summary>
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]
public async Task LoaderFailuresSurfaceAndCanBeRetried()
{
var attempts = 0;
async ValueTask<ImageBuffer> 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<InvalidDataException>(async () => await window.GetAsync(2));
using var retried = await window.GetAsync(2);
Assert.Equal(2f, retried.Image[0, 0, 0]);
}
}
@@ -0,0 +1,394 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Core.Tests.Raw;
using Chronos.Testing;
using static Chronos.Core.Tests.Raw.NativeRawWriters;
namespace Chronos.Core.Tests.Decoding;
/// <summary>Tier selection (native → embedded preview → unavailable), decoder chains and <see cref="DecodeRequest"/> fast paths.</summary>
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}");
}
}
}
[Test]
public void TheChainProbesEachFileForItsTier()
{
var server = DecoderFactory.CreateServer();
// JPEG, PNG and TIFF decode natively whatever they hold: the probe does not even open them.
Assert.Equal(DecodeTier.Native, server.Probe(Path.Combine(_dir, "absent.jpg"), ImageFileFormat.Jpeg).Tier);
var supported = server.Probe(Write("IMG_5.CR2", Cr2File("Canon EOS 5D Mark III")), ImageFileFormat.Cr2);
Assert.Equal((DecodeTier.Native, "managed-cr2"), (supported.Tier, supported.Decoder));
// An unsupported body decodes only through its 64×48 preview, rotated like the main image (orientation 6).
var preview = server.Probe(Write("IMG_6.CR2", Cr2File("Canon EOS R99", orientation: 6)), ImageFileFormat.Cr2);
Assert.Equal((DecodeTier.EmbeddedPreview, 48, 64), (preview.Tier, preview.Width, preview.Height));
Assert.Contains("no colour matrix", preview.Reason);
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 unknownBody = System.Text.Encoding.Latin1.GetBytes(System.Text.Encoding.Latin1.GetString(nef).Replace("NIKON D850", "NIKON Z99X"));
var none = server.Probe(Write("DSC_7.NEF", unknownBody), ImageFileFormat.Nef);
Assert.Equal(DecodeTier.Unavailable, none.Tier);
Assert.Contains("no embedded preview", none.Reason);
// A Windows-like provider native for CR3 answers from its codec list, before the managed preview tier.
var client = DecoderFactory.CreateClient(new FakeProvider());
var cr3 = client.Probe(Path.Combine(_dir, "absent.cr3"), ImageFileFormat.Cr3);
Assert.Equal((DecodeTier.Native, "fake"), (cr3.Tier, cr3.Decoder));
Assert.Equal(DecodeTier.Unavailable, client.Probe(Write("y.webp", Fixtures.WebP()), ImageFileFormat.WebP).Tier);
}
[Test]
public void GoProRawDecodesThroughTheJpegBesideIt()
{
var gpr = Write("GOPR0001.GPR", Gpr(previewWidth: 64, previewHeight: 48));
var server = DecoderFactory.CreateServer();
// Alone, a GPR (VC-5, out of scope) shows its embedded preview.
using (var alone = server.Decode(new DecodeRequest(gpr)))
Assert.Equal(("managed-preview", 64), (alone!.Decoder, alone.Pixels.Width));
Write("GOPR0001.JPG", JpegFile(160, 120, 1));
using (var withJpeg = server.Decode(new DecodeRequest(gpr)))
{
Assert.Equal((DecodeTier.EmbeddedPreview, "managed-sidecar"), (withJpeg!.Tier, withJpeg.Decoder));
Assert.Equal((160, 120, 160, 120), (withJpeg.Pixels.Width, withJpeg.Pixels.Height, withJpeg.SourceWidth, withJpeg.SourceHeight));
}
using (var scaled = server.Decode(new DecodeRequest(gpr, MaxLongEdge: 40, Purpose: DecodePurpose.Thumbnail)))
Assert.Equal(40, scaled!.Pixels.Width);
var probe = new ManagedDecoderProvider().Probe(gpr);
Assert.Equal((DecodeTier.EmbeddedPreview, "managed-sidecar", 160, 120), (probe.Tier, probe.Decoder, probe.Width, probe.Height));
// A companion smaller than the embedded preview is not the better source.
var big = Write("GOPR0002.GPR", Gpr(previewWidth: 320, previewHeight: 240));
Write("GOPR0002.JPG", JpegFile(160, 120, 1));
using (var preview = server.Decode(new DecodeRequest(big)))
Assert.Equal(("managed-preview", 320), (preview!.Decoder, preview.Pixels.Width));
Assert.Equal("managed-preview", new ManagedDecoderProvider().Probe(big).Decoder);
}
[Test]
public void GoProRawDecodesThroughItsJpegWhereTheImportKeptIt()
{
// An import splits sessions per format: the JPEG lives in another sequence folder, under its imported name.
var gpr = Write("GOPR0003.GPR", Gpr(previewWidth: 64, previewHeight: 48));
var elsewhere = Path.Combine(context.CreateTempDirectory("jpeg-sequence"), "2026-09-28_0003.JPG");
File.WriteAllBytes(elsewhere, JpegFile(160, 120, 1));
var server = DecoderFactory.CreateServer();
using (var decoded = server.Decode(new DecodeRequest(gpr, Companion: elsewhere)))
Assert.Equal(("managed-sidecar", 160, 120), (decoded!.Decoder, decoded.SourceWidth, decoded.SourceHeight));
var probe = server.Probe(gpr, ImageFileFormat.Gpr, elsewhere);
Assert.Equal((DecodeTier.EmbeddedPreview, "managed-sidecar", 160, 120), (probe.Tier, probe.Decoder, probe.Width, probe.Height));
// A JPEG that is gone (deleted since) leaves the embedded preview; other formats ignore the companion.
var gone = Path.Combine(_dir, "gone.JPG");
using (var preview = server.Decode(new DecodeRequest(gpr, Companion: gone)))
Assert.Equal(("managed-preview", 64), (preview!.Decoder, preview.Pixels.Width));
Assert.Equal("managed-preview", server.Probe(gpr, ImageFileFormat.Gpr, gone).Decoder);
var jpeg = Write("plain.jpg", JpegFile(64, 48, 1));
using (var plain = server.Decode(new DecodeRequest(jpeg, Companion: elsewhere)))
Assert.Equal(("managed-jpeg", 64), (plain!.Decoder, plain.SourceWidth));
}
[Test]
public void AFileNoProviderCouldReadIsAReadErrorNotAnUndecodableFile()
{
var path = Write("locked.jpg", JpegFile(64, 48, 1));
// Every provider failed to read the file (locked by another program, a network read failed): nothing is known
// about its content, so the caller gets the read error instead of "nothing decodes it".
var unreadable = new ImageDecoder([new ScriptedProvider("a", _ => throw new IOException("sharing violation"))]);
Assert.Throws<IOException>(() => unreadable.Decode(new DecodeRequest(path)));
// One provider read it and found nothing, another could not read it: still unproven.
var mixed = new ImageDecoder([new ScriptedProvider("a", _ => null), new ScriptedProvider("b", _ => throw new IOException("short read"))]);
Assert.Throws<IOException>(() => mixed.Decode(new DecodeRequest(path)));
// A provider that produces pixels wins over one that could not read the file.
var recovered = new ImageDecoder([new ScriptedProvider("a", _ => throw new IOException("busy")), new ManagedDecoderProvider()]);
using (var image = recovered.Decode(new DecodeRequest(path)))
Assert.Equal("managed-jpeg", image!.Decoder);
// Providers that read the file and found it malformed prove it undecodable.
var damaged = new ImageDecoder([new ScriptedProvider("a", _ => throw new InvalidDataException("bad marker"))]);
Assert.Null(damaged.Decode(new DecodeRequest(path)));
Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(Write("garbage.jpg", new byte[3000]))));
Assert.Throws<FileNotFoundException>(() => DecoderFactory.CreateServer().Decode(new DecodeRequest(Path.Combine(_dir, "vanished.jpg"))));
}
/// <summary>
/// The owner's archive (R4, owner review 1): GoPro DNGs converted by Lightroom or DNG Converter carry a full-size JPEG
/// preview in IFD0 and a lossless or lossy raw image in a SubIFD. They are DNGs, developed natively; only a VC-5 raw
/// image (or the .gpr extension) makes a GPR.
/// </summary>
[Test]
public void AGoProDngIsGprOnlyWhenItsRawImageIsVc5()
{
using var scene = SyntheticRaw.Smooth(W, H);
var converted = Write("GOPR0100.dng", SyntheticDng.Write(scene, new DngSpec { Make = "GoPro", RawInSubIfd = true, PreviewJpeg = JpegFile(W, H, 1) }));
Assert.Equal(ImageFileFormat.Dng, Signature(converted));
using (var decoded = DecoderFactory.CreateServer().Decode(new DecodeRequest(converted)))
Assert.Equal((DecodeTier.Native, "managed-dng"), (decoded!.Tier, decoded.Decoder));
var vc5 = new IfdSpec().Long(TiffTags.NewSubfileType, 0).Long(TiffTags.ImageWidth, 64).Long(TiffTags.ImageLength, 48)
.Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 9).Short(TiffTags.PhotometricInterpretation, 32803);
var gpr = Write("GOPR0101.dng", TiffFile.Build(Fixtures.Ifd0("GoPro", "HERO8 Black", 1).Bytes(TiffTags.DngVersion, 1, 4, 0, 0).Child(TiffTags.SubIfds, vc5)));
Assert.Equal(ImageFileFormat.Gpr, Signature(gpr));
var renamed = Write("GOPR0102.GPR", File.ReadAllBytes(converted));
Assert.Equal(ImageFileFormat.Gpr, Signature(renamed));
}
private static ImageFileFormat Signature(string path)
{
using var stream = File.OpenRead(path);
return ImageSignature.Detect(stream, path);
}
[Test]
public void APreferredPreviewIsTakenByChoiceOnlyWhenItIsLargeEnough()
{
using var scene = SyntheticRaw.Smooth(W, H);
var dng = Write("preview.dng", SyntheticDng.Write(scene, new DngSpec { RawInSubIfd = true, PreviewJpeg = JpegFile(W, H, 1) }));
var server = DecoderFactory.CreateServer();
// Analysis size within the preview: the preview, marked as taken by choice (the frame still decodes natively).
using (var quick = server.Decode(new DecodeRequest(dng, MaxLongEdge: 48, Purpose: DecodePurpose.Analysis, PreferPreview: true)))
{
Assert.Equal((DecodeTier.EmbeddedPreview, "managed-preview", true), (quick!.Tier, quick.Decoder, quick.ByChoice));
Assert.Equal(48, quick.Pixels.Width);
}
// Larger than the preview, or no size limit: developed.
using (var native = server.Decode(new DecodeRequest(dng, MaxLongEdge: 4 * W, Purpose: DecodePurpose.Analysis, PreferPreview: true)))
Assert.Equal((DecodeTier.Native, "managed-dng", false), (native!.Tier, native.Decoder, native.ByChoice));
using (var whole = server.Decode(new DecodeRequest(dng, PreferPreview: true)))
Assert.Equal((DecodeTier.Native, false), (whole!.Tier, whole.ByChoice));
// Renders never prefer the preview.
using (var render = server.Decode(new DecodeRequest(dng, MaxLongEdge: 48)))
Assert.Equal((DecodeTier.Native, "managed-dng", false), (render!.Tier, render.Decoder, render.ByChoice));
}
/// <summary>A GoPro GPR as far as Chronos reads it: a DNG made by "GoPro" whose only decodable image is a YCbCr JPEG preview.</summary>
private static byte[] Gpr(int previewWidth, int previewHeight)
{
var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1)
.Long(TiffTags.ImageWidth, (uint)previewWidth).Long(TiffTags.ImageLength, (uint)previewHeight)
.Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 7)
.Short(TiffTags.PhotometricInterpretation, 6).Strip(JpegFile(previewWidth, previewHeight, 1));
var ifd0 = Fixtures.Ifd0("GoPro", "HERO8 Black", 1)
.Bytes(TiffTags.DngVersion, 1, 4, 0, 0)
.Child(TiffTags.SubIfds, preview);
return TiffFile.Build(ifd0);
}
/// <summary>A Windows-like provider claiming native support for everything but declining every file.</summary>
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;
}
}
/// <summary>A JPEG provider whose decode does what the test says (return nothing, or throw).</summary>
private sealed class ScriptedProvider(string name, Func<DecodeRequest, DecodedImage?> decode) : IImageDecoderProvider
{
public string Name => name;
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Jpeg ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => decode(request);
}
}
@@ -0,0 +1,61 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Thumbnails;
using Chronos.Testing;
namespace Chronos.Core.Tests.Decoding;
/// <summary><see cref="ThumbnailCache{TKey}"/>: LRU eviction within a byte budget and coalesced loads.</summary>
public sealed class ThumbnailTests
{
/// <summary>Small distinct JPEGs (cheap to make in bulk).</summary>
private static byte[] Jpeg(int seed)
{
using var image = new ImageBuffer(40, 30);
for (var y = 0; y < 30; y++)
{
for (var x = 0; x < 40; 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 JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80 });
}
[Test]
public async Task CacheEvictsLeastRecentlyUsedAndCoalescesLoads()
{
var cache = new ThumbnailCache<int>(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<Thumbnail?> Loader(int key, CancellationToken ct)
{
Interlocked.Increment(ref loads);
await gate.Task;
return Thumbnail.FromJpeg(Jpeg(key));
}
var large = new ThumbnailCache<int>(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 _));
}
}