merge: RAW/DNG decoding, managed decoder provider, frame window and thumbnails

# Conflicts:
#	src/Titano.Tools/Program.cs
This commit is contained in:
Claude committed 2026-10-02 12:32:14 +00:00
commit 9ee2d482b6
40 files changed
+8350

No files matched your search

@@ -0,0 +1,100 @@
using System.Globalization;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
namespace Titano.Tools.Commands;
/// <summary>
/// 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.
/// </summary>
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<int> 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 <folder> [--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<string, int[]>(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<string> { $"{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}");
}
}
}
@@ -0,0 +1,147 @@
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text.Json;
namespace Titano.Tools.Commands;
/// <summary>
/// Fetches the CC0 RAW samples listed in <c>tests/fixtures/manifest.json</c> into <c>tests/fixtures/external</c> (BRIEF
/// §20.2): interrupted downloads resume from their <c>.part</c> file with an HTTP range request, every file is verified
/// against its SHA-256, and verified files are skipped. An entry whose <c>sha256</c> is null gets the hash of its first
/// download recorded in <c>external/recorded-hashes.json</c> (later runs verify against it) and printed so it can be
/// copied into the manifest.
/// </summary>
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<int> 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<Dictionary<string, string>>(await File.ReadAllTextAsync(recordedPath)) ?? []
: [];
var newlyRecorded = new List<string>();
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<Entry> 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<Entry>();
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;
}
/// <summary>Downloads into <c>target.part</c>, resuming from its length with a range request, then renames it.</summary>
private static async Task<string> 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<string> 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));
}
}
+2
View File
@@ -10,6 +10,8 @@ var commands = new ICommand[]
new ChangelogCommand(),
new PackInstallerCommand(),
new SelfTestCommand(),
new DiagnoseCommand(),
new FixturesCommand(),
};
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")