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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 08:59:40 +00:00
1 parent def3fadb6e
commit 83a54fb57b
109 files changed
+7523

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
namespace Titano.Core.Branding;
public enum BrandVariant
{
/// <summary>Titano desktop client: plate, ring, sun.</summary>
App,
/// <summary>Titano Server: App mark plus the three-bar rack badge (≥ 48 px).</summary>
Server,
/// <summary>Titano Uploader: App mark plus the up-arrow badge (≥ 48 px).</summary>
Uploader,
/// <summary>White mark without plate, for the tray.</summary>
Mono,
}
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>Opacity of tick <paramref name="i"/> (0 = first clockwise from 12 o'clock).</summary>
public static double TickOpacity(int i) => Math.Round(0.14 + (1.0 - 0.14) * i / (TickCount - 1), 2);
/// <summary>Start and end angle of tick <paramref name="i"/> in degrees, clockwise from 12 o'clock.</summary>
public static (double Start, double End) TickAngles(int i)
{
var start = FirstTickStartDegrees + i * TickPitchDegrees;
return (start, start + TickSweepDegrees);
}
/// <summary>Renders the mark as straight-alpha RGBA8 (row-major, top-down).</summary>
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;
}
/// <summary>The master SVG for a variant (identical geometry to <see cref="Render"/>).</summary>
public static string ToSvg(BrandVariant variant)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
var sb = new System.Text.StringBuilder();
sb.Append("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" width=\"256\" height=\"256\">\n");
var ring = variant == BrandVariant.Mono ? "#ffffff" : Accent.Hex;
if (variant != BrandVariant.Mono) sb.Append("<rect x=\"0\" y=\"0\" width=\"256\" height=\"256\" rx=\"56\" fill=\"").Append(Plate.Hex).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, $"<path d=\"M{x0:0.0} {y0:0.0} A92 92 0 0 1 {x1:0.0} {y1:0.0}\" fill=\"none\" stroke=\"{ring}\" stroke-width=\"20\" stroke-linecap=\"round\" opacity=\"{TickOpacity(i):0.0#}\"/>\n");
}
sb.Append("<circle cx=\"152\" cy=\"104\" r=\"30\" fill=\"").Append(variant == BrandVariant.Mono ? "#ffffff" : Sun.Hex).Append("\"/>\n");
if (variant == BrandVariant.Server)
sb.Append("<circle cx=\"204\" cy=\"204\" r=\"40\" fill=\"#1a1a1e\" stroke=\"#4cc2ff\" stroke-width=\"6\"/><rect x=\"185\" y=\"188\" width=\"38\" height=\"12\" rx=\"4\" fill=\"#4cc2ff\"/><rect x=\"185\" y=\"208\" width=\"38\" height=\"12\" rx=\"4\" fill=\"#4cc2ff\"/>\n");
if (variant == BrandVariant.Uploader)
sb.Append("<circle cx=\"204\" cy=\"204\" r=\"40\" fill=\"#1a1a1e\" stroke=\"#f5a524\" stroke-width=\"6\"/><path d=\"M204 226v-40M188 202l16-16 16 16\" fill=\"none\" stroke=\"#f5a524\" stroke-width=\"8\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n");
sb.Append("</svg>\n");
return sb.ToString();
}
/// <summary>Point on the ring at <paramref name="degrees"/> clockwise from 12 o'clock.</summary>
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}";
}
}
+78
View File
@@ -0,0 +1,78 @@
using System.Buffers.Binary;
using Titano.Core.Codecs.Png;
namespace Titano.Core.Codecs.Ico;
/// <summary>
/// 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.
/// </summary>
public static class IcoWriter
{
/// <param name="images">Straight-alpha RGBA8 square images keyed by size.</param>
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<byte> 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<byte> 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;
}
}
+133
View File
@@ -0,0 +1,133 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
namespace Titano.Core.Codecs.Png;
/// <summary>PNG colour types written by <see cref="PngEncoder"/>.</summary>
public enum PngColorType : byte
{
Gray = 0,
Rgb = 2,
GrayAlpha = 4,
Rgba = 6,
}
/// <summary>PNG encoder (8/16-bit, gray/RGB with or without alpha), adaptive filtering, zlib via the BCL.</summary>
public static class PngEncoder
{
private static ReadOnlySpan<byte> Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
/// <summary>Encodes interleaved pixels. 16-bit samples are big-endian in <paramref name="pixels"/>.</summary>
public static byte[] Encode(ReadOnlySpan<byte> 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<byte> 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<byte> 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", []);
}
/// <summary>Filters every row (adaptive, minimum sum of absolute differences) and deflates the result.</summary>
public static byte[] Compress(ReadOnlySpan<byte> 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<byte> data)
{
Span<byte> 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<byte> 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;
}
}
+116
View File
@@ -0,0 +1,116 @@
using System.Globalization;
namespace Titano.Core.Diagnostics;
public enum LogLevel
{
Trace,
Debug,
Info,
Warning,
Error,
}
/// <summary>Destination for engine log events (file logger on desktop, ILogger bridge on the server).</summary>
public interface ILogSink
{
void Write(LogLevel level, string category, string message, Exception? exception);
}
/// <summary>Tiny engine-wide logger. Core code logs through it; hosts plug in a sink.</summary>
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);
}
}
}
/// <summary>Appends log lines to rotating files (one per day, kept for <c>retainDays</c>).</summary>
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();
}
}
+47
View File
@@ -0,0 +1,47 @@
namespace Titano.Core.Hashing;
/// <summary>CRC-32 (IEEE 802.3, reflected 0xEDB88320) as used by PNG, ZIP and gzip. Slicing-by-8.</summary>
public sealed class Crc32
{
private static readonly uint[] Table = BuildTable();
private uint _crc = 0xFFFFFFFFu;
public void Append(ReadOnlySpan<byte> data) => _crc = Update(_crc, data);
public uint GetCurrentHashAsUInt32() => ~_crc;
public void Reset() => _crc = 0xFFFFFFFFu;
public static uint Compute(ReadOnlySpan<byte> data) => ~Update(0xFFFFFFFFu, data);
private static uint Update(uint crc, ReadOnlySpan<byte> 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;
}
}
+81
View File
@@ -0,0 +1,81 @@
using System.Text;
namespace Titano.Core.IO;
/// <summary>
/// Crash-safe writes: content goes to a temporary sibling, is flushed to disk, then renamed over the
/// target (BRIEF §7 "temp → fsync → rename").
/// </summary>
public static class AtomicFile
{
public static void WriteAllBytes(string path, ReadOnlySpan<byte> 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));
/// <summary>Streams content produced by <paramref name="write"/> and commits it atomically.</summary>
public static async Task WriteAsync(string path, Func<Stream, CancellationToken, Task> 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;
}
}
/// <summary>Commits an already-written temporary file over <paramref name="path"/> after flushing it.</summary>
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)
{
}
}
}
+23
View File
@@ -0,0 +1,23 @@
namespace Titano.Core.IO;
/// <summary>Helpers for UNC and long paths on Windows network archives (BRIEF §7).</summary>
public static class LongPath
{
/// <summary>Adds the <c>\\?\</c> prefix on Windows when a path exceeds MAX_PATH.</summary>
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;
}
/// <summary>Relative path with forward slashes, as stored in sidecars and the database.</summary>
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));
}
+112
View File
@@ -0,0 +1,112 @@
namespace Titano.Core.Imaging;
/// <summary>How a frame's pixels were obtained (BRIEF §8.2). Logged per frame.</summary>
public enum DecodeTier
{
/// <summary>Full-resolution decode of the main image (in-house or WIC).</summary>
Native = 1,
/// <summary>Largest embedded JPEG preview; output resolution is capped to its size.</summary>
EmbeddedPreview = 2,
/// <summary>No decoder could produce pixels; the frame is excluded from renders.</summary>
Unavailable = 3,
}
public enum DecodePurpose
{
Thumbnail,
Analysis,
Proxy,
Render,
}
/// <summary>A request to decode one file.</summary>
/// <param name="Path">Absolute path of the source file.</param>
/// <param name="MaxLongEdge">Maximum long edge of the result in pixels; 0 = native size.</param>
/// <param name="Purpose">Lets providers trade quality for speed (e.g. bilinear demosaic for thumbnails).</param>
/// <param name="ApplyOrientation">Rotate/flip according to the Exif orientation.</param>
/// <param name="AllowPreview">Accept the embedded-preview tier when native decode is impossible.</param>
/// <param name="ForcePreview">Use the embedded preview even when native decode is possible (fast paths).</param>
public sealed record DecodeRequest(
string Path,
int MaxLongEdge = 0,
DecodePurpose Purpose = DecodePurpose.Render,
bool ApplyOrientation = true,
bool AllowPreview = true,
bool ForcePreview = false);
/// <summary>Decoded pixels plus how they were produced. Dispose to return the buffer to the pool.</summary>
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;
/// <summary>Short provider/decoder name for logs ("wic", "managed-jpeg", "managed-dng").</summary>
public string Decoder { get; } = decoder;
/// <summary>Dimensions of the full-resolution source (before scaling), oriented.</summary>
public int SourceWidth { get; } = sourceWidth;
public int SourceHeight { get; } = sourceHeight;
public void Dispose() => Pixels.Dispose();
}
/// <summary>A platform image decoder (WIC on Windows, managed codecs everywhere).</summary>
public interface IImageDecoderProvider
{
/// <summary>Short name for logs and the Settings › Formats table.</summary>
string Name { get; }
/// <summary>The best tier this provider can deliver for the format on this machine, or null.</summary>
DecodeTier? TierFor(ImageFileFormat format);
bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null;
/// <summary>Decodes or returns null when this provider cannot handle the specific file.</summary>
DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default);
}
/// <summary>Tries providers in priority order and applies the tier rules of BRIEF §8.2.</summary>
public sealed class ImageDecoder(IReadOnlyList<IImageDecoderProvider> providers)
{
public IReadOnlyList<IImageDecoderProvider> Providers { get; } = providers;
/// <summary>Best tier available for <paramref name="format"/> across all providers.</summary>
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;
}
/// <summary>Decodes with the first provider that succeeds; null means <see cref="DecodeTier.Unavailable"/>.</summary>
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
var format = ImageFormatInfo.FromPath(request.Path);
List<Exception>? 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;
}
}
+74
View File
@@ -0,0 +1,74 @@
using System.Buffers;
namespace Titano.Core.Imaging;
/// <summary>
/// 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 <see cref="ArrayPool{T}"/> and returned on <see cref="Dispose"/>.
/// </summary>
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<float>.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;
/// <summary>All planes, channel-major: plane c starts at <c>c * Width * Height</c>.</summary>
public Span<float> Data => Storage.AsSpan(0, PlaneLength * Channels);
public Span<float> Plane(int channel)
{
if ((uint)channel >= (uint)Channels) throw new ArgumentOutOfRangeException(nameof(channel));
return Storage.AsSpan(channel * PlaneLength, PlaneLength);
}
public Span<float> 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;
}
/// <summary>Underlying array (may be longer than the image). Exposed for SIMD kernels.</summary>
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);
}
/// <summary>Approximate managed memory held by the buffer, in bytes.</summary>
public long ByteSize => (long)PlaneLength * Channels * sizeof(float);
public void Dispose()
{
var data = Interlocked.Exchange(ref _data, null);
if (data is not null) ArrayPool<float>.Shared.Return(data);
}
}
+109
View File
@@ -0,0 +1,109 @@
namespace Titano.Core.Imaging;
/// <summary>Container/file formats recognised by signature and extension (BRIEF §8.1).</summary>
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,
}
/// <summary>Static facts about a format: family, extensions, whether it is a camera RAW.</summary>
public sealed record ImageFormatInfo(ImageFileFormat Format, ImageFamily Family, IReadOnlyList<string> 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<string, ImageFormatInfo> ByExtension =
All.SelectMany(i => i.Extensions.Select(e => (e, i))).ToDictionary(p => p.e, p => p.i, StringComparer.OrdinalIgnoreCase);
public static IReadOnlyList<ImageFormatInfo> 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;
/// <summary>Format implied by a file name's extension (signature sniffing lives in Metadata).</summary>
public static ImageFormatInfo FromPath(string path)
{
var ext = Path.GetExtension(path).TrimStart('.');
return ByExtension.TryGetValue(ext, out var info) ? info : Unknown;
}
/// <summary>True when the extension is one Titano imports as a photo.</summary>
public static bool IsSupportedExtension(string path) => FromPath(path).Format != ImageFileFormat.Unknown;
}
+39
View File
@@ -0,0 +1,39 @@
using System.Globalization;
namespace Titano.Core.Localization;
/// <summary>Languages shipped with Titano (BRIEF §16). English is the source.</summary>
public static class Languages
{
public static readonly IReadOnlyList<string> 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",
];
/// <summary>Languages whose UI layout is mirrored.</summary>
public static readonly IReadOnlySet<string> RightToLeft = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "ar", "he", "fa", "ur" };
/// <summary>The shipped language that best matches <paramref name="culture"/>, falling back to English.</summary>
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");
}
/// <summary>Native display name ("Italiano", "日本語").</summary>
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;
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.Resources;
namespace Titano.Core.Localization;
/// <summary>
/// Runtime string catalog. Keys are stable identifiers of the form <c>Area.Group.Name</c>; the first
/// segment selects the resource file <c>i18n/&lt;culture&gt;/&lt;Area&gt;.resx</c>. English is the source.
/// </summary>
public static class Loc
{
private const string BaseNamePrefix = "Titano.Core.i18n.";
private static readonly ConcurrentDictionary<string, ResourceManager> Managers = new(StringComparer.Ordinal);
private static CultureInfo _culture = CultureInfo.CurrentUICulture;
/// <summary>Raised after <see cref="SetCulture"/> so bound UI can refresh without restart.</summary>
public static event EventHandler? CultureChanged;
/// <summary>Raised once per missing key (used by tests and diagnostics).</summary>
public static event Action<string>? MissingKey;
public static CultureInfo Culture => _culture;
/// <summary>Text direction of the current culture.</summary>
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);
}
/// <summary>Returns the localized string for <paramref name="key"/> in the current culture.</summary>
public static string L(string key) => Get(key, _culture) ?? Missing(key);
/// <summary>Returns the localized composite format for <paramref name="key"/> filled with <paramref name="args"/>.</summary>
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);
}
/// <summary>
/// Plural-aware lookup: resolves <c>key.one</c>, <c>key.few</c>, <c>key.many</c> or <c>key.other</c>
/// using CLDR rules of the current language; <c>{0}</c> receives the count.
/// </summary>
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);
}
/// <summary>Looks a key up in a specific culture (falls back to parents and English); null when absent.</summary>
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;
}
}
/// <summary>Every key and English value of an area, for tooling and the web admin export.</summary>
public static IReadOnlyDictionary<string, string> GetArea(string area, CultureInfo culture)
{
var manager = Managers.GetOrAdd(area, static a => new ResourceManager(BaseNamePrefix + a, typeof(Loc).Assembly));
var result = new Dictionary<string, string>(StringComparer.Ordinal);
// Walk from invariant to specific so the most specific value wins.
var chain = new List<CultureInfo>();
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 + "⟧";
}
}
+103
View File
@@ -0,0 +1,103 @@
using System.Globalization;
namespace Titano.Core.Localization;
public enum PluralCategory
{
One,
Few,
Many,
Other,
}
/// <summary>
/// Minimal CLDR cardinal plural rules for the shipped languages (integers only, which is all the UI needs).
/// </summary>
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;
}
}
}
+71
View File
@@ -0,0 +1,71 @@
using Titano.Core.Imaging;
using Titano.Core.Model;
namespace Titano.Core.Metadata;
public enum PreviewKind
{
Thumbnail,
Preview,
FullSize,
}
/// <summary>An embedded JPEG inside a RAW/TIFF/HEIF/JPEG(MPF) container.</summary>
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);
/// <summary>Everything Titano reads from one photo's metadata (BRIEF §9). Never throws while parsing:
/// malformed input yields partial data plus <see cref="Warnings"/>.</summary>
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; }
/// <summary>Camera wall-clock time including sub-seconds (DateTimeKind.Unspecified).</summary>
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; }
/// <summary>Exif orientation 1–8.</summary>
public int Orientation { get; init; } = 1;
/// <summary>Dimensions of the main (largest) image as stored, before orientation.</summary>
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; }
/// <summary>Embedded JPEGs, largest first.</summary>
public IReadOnlyList<EmbeddedPreview> Previews { get; init; } = [];
public IReadOnlyList<string> Warnings { get; init; } = [];
/// <summary>Width/height after applying orientation 5–8 (90° rotations).</summary>
public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height);
public EmbeddedPreview? LargestPreview => Previews.Count > 0 ? Previews[0] : null;
}
+251
View File
@@ -0,0 +1,251 @@
using System.Buffers.Binary;
using System.Text;
namespace Titano.Core.Metadata.Tiff;
/// <summary>One IFD entry. Small values (≤ 4 bytes) are inline; larger ones live at <see cref="ValueOffset"/>.</summary>
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;
/// <summary>Absolute file position of the value bytes (inline values sit inside the entry).</summary>
public long ValuePosition(long tiffBase) => IsInline ? EntryPosition + 8 : tiffBase + ValueOffset;
}
/// <summary>An image file directory: its entries and the offset of the next IFD (0 = none).</summary>
public sealed class Ifd(long position, IReadOnlyDictionary<ushort, IfdEntry> entries, uint nextOffset)
{
public long Position { get; } = position;
public IReadOnlyDictionary<ushort, IfdEntry> Entries { get; } = entries;
public uint NextOffset { get; } = nextOffset;
public bool Has(ushort tag) => Entries.ContainsKey(tag);
}
/// <summary>
/// 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).
/// </summary>
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<string> _warnings = [];
private TiffReader(Stream stream, long tiffBase, bool littleEndian, uint firstIfdOffset)
{
_stream = stream;
Base = tiffBase;
LittleEndian = littleEndian;
FirstIfdOffset = firstIfdOffset;
}
/// <summary>Absolute position of the TIFF header ("II*\0"/"MM\0*"); IFD offsets are relative to it.</summary>
public long Base { get; }
public bool LittleEndian { get; }
public uint FirstIfdOffset { get; }
public IReadOnlyList<string> Warnings => _warnings;
public long StreamLength => _stream.Length;
/// <summary>Opens a TIFF header at <paramref name="tiffBase"/>; null when the bytes are not a TIFF header.
/// Accepts the ORF ("IIRO"/"IIRS") and RW2 ("IIU\0") header variants.</summary>
public static TiffReader? Open(Stream stream, long tiffBase = 0)
{
if (!stream.CanSeek || tiffBase < 0 || tiffBase + 8 > stream.Length) return null;
Span<byte> 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);
}
/// <summary>Creates a reader for an IFD structure without a header (e.g. maker notes) with a known byte order.</summary>
public static TiffReader ForEmbedded(Stream stream, long tiffBase, bool littleEndian) => new(stream, tiffBase, littleEndian, 0);
/// <summary>Reads the chain of top-level IFDs (IFD0, IFD1, …).</summary>
public IReadOnlyList<Ifd> ReadChain()
{
var list = new List<Ifd>();
var seen = new HashSet<long>();
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;
}
/// <summary>Reads one IFD at a base-relative offset; null if out of bounds or already visited.</summary>
public Ifd? ReadIfd(uint offset, HashSet<long>? 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<byte> 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<ushort, IfdEntry>(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);
}
/// <summary>Raw value bytes of an entry (bounded by <see cref="MaxValueBytes"/>); null when invalid.</summary>
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;
/// <summary>Integer values of BYTE/SHORT/LONG/IFD (and signed variants) entries.</summary>
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;
/// <summary>Numeric values of any numeric type as doubles (rationals divided; 0-denominator → NaN skipped as 0).</summary>
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;
}
/// <summary>ASCII/UTF-8 string value with trailing NULs and spaces trimmed; null when empty.</summary>
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;
}
/// <summary>Reads arbitrary bytes at a base-relative offset (bounds-checked).</summary>
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<byte> s) => LittleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(s) : BinaryPrimitives.ReadUInt16BigEndian(s);
public uint U32(ReadOnlySpan<byte> s) => LittleEndian ? BinaryPrimitives.ReadUInt32LittleEndian(s) : BinaryPrimitives.ReadUInt32BigEndian(s);
public ulong U64(ReadOnlySpan<byte> 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<byte> 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;
}
}
}
+126
View File
@@ -0,0 +1,126 @@
namespace Titano.Core.Metadata.Tiff;
/// <summary>Tag numbers used across TIFF, Exif, GPS and DNG.</summary>
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;
}
+32
View File
@@ -0,0 +1,32 @@
namespace Titano.Core.Metadata.Tiff;
/// <summary>TIFF 6.0 field types (plus IFD = 13).</summary>
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
{
/// <summary>Size in bytes of one value; 0 for unknown types.</summary>
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,
};
}
+238
View File
@@ -0,0 +1,238 @@
using Titano.Core.Imaging;
namespace Titano.Core.Model;
/// <summary>A rooted folder tree that holds originals, sidecars, proxies and exports (BRIEF §7).</summary>
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; }
/// <summary>Proxy long edge in pixels; 0 = full size, -1 = proxies disabled.</summary>
public int ProxyLongEdge { get; init; } = 1920;
}
/// <summary>One shoot: a folder of frames that becomes one project (BRIEF §5).</summary>
public sealed record Sequence
{
public required Guid Id { get; init; }
public required Guid ArchiveId { get; init; }
public string? Title { get; init; }
/// <summary>Folder relative to the archive root, forward slashes.</summary>
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; }
/// <summary>Median capture interval in seconds.</summary>
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<string> Tags { get; init; } = [];
public int Rating { get; init; }
public string? Notes { get; init; }
/// <summary>Render settings ("project") as JSON.</summary>
public string? SettingsJson { get; init; }
/// <summary>Compact analysis summary as JSON; the full report lives in <c>.titano/analysis.json</c>.</summary>
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; }
/// <summary>User title or "{date} {camera}".</summary>
public string DisplayTitle => !string.IsNullOrWhiteSpace(Title)
? Title!
: $"{FirstCapture:yyyy-MM-dd} {CameraModel}".Trim();
}
/// <summary>One photo of a sequence.</summary>
public sealed record Frame
{
public required Guid Id { get; init; }
public required Guid SequenceId { get; init; }
public required int Index { get; init; }
/// <summary>Path relative to the archive root, forward slashes.</summary>
public required string RelativePath { get; init; }
public required string FileName { get; init; }
public string? OriginalFileName { get; init; }
public long Size { get; init; }
/// <summary>Lower-case hex SHA-256 of the original file.</summary>
public string? Sha256 { get; init; }
/// <summary>Camera wall-clock time including sub-seconds (unspecified kind).</summary>
public DateTime? CapturedAt { get; init; }
/// <summary>UTC offset of <see cref="CapturedAt"/> when known, in minutes.</summary>
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; }
/// <summary>Mean log2 luminance once analysed.</summary>
public double? MeanLogLuminance { get; init; }
public double? ClipLow { get; init; }
public double? ClipHigh { get; init; }
public FrameFlags Flags { get; init; }
/// <summary>Exposure value at ISO 100: log2(N²/t) − log2(ISO/100).</summary>
public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0
? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso ?? 100) / 100.0)
: null;
}
/// <summary>An exported video or image sequence.</summary>
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; }
}
/// <summary>Any long operation: resumable, cancellable, logged (BRIEF §5, §14.6).</summary>
public sealed record Job
{
public required Guid Id { get; init; }
public required JobKind Kind { get; init; }
public IReadOnlyList<Guid> TargetIds { get; init; } = [];
/// <summary>Human-readable target ("Harbour sunset", "Archive · 2024").</summary>
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; }
/// <summary>Opaque resume cursor written at checkpoints.</summary>
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; }
}
/// <summary>A memory card known to this client (BRIEF §13).</summary>
public sealed record MediaCard
{
public required Guid Id { get; init; }
/// <summary><c>{volumeSerial}-{label}-{capacity}</c>.</summary>
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; }
}
+126
View File
@@ -0,0 +1,126 @@
namespace Titano.Core.Model;
/// <summary>Where a capture timestamp came from.</summary>
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,
};
}
@@ -0,0 +1,8 @@
namespace Titano.Core.Naming;
/// <summary>Default naming templates (BRIEF §7.1).</summary>
public static class TemplateDefaults
{
public const string Folder = "{year}/{date} {camera}";
public const string File = "{date}_{time}_{n:0000}";
}
+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Titano.Core</RootNamespace>
<TitanoEmbedI18n>true</TitanoEmbedI18n>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Titano.Core.Tests" />
<InternalsVisibleTo Include="Titano.Tools" />
</ItemGroup>
</Project>
+134
View File
@@ -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,
};
/// <summary>True for codecs every platform can produce without an OS encoder.</summary>
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",
};
}
/// <summary>What an encoder on this machine can do (shown in Settings › Rendering).</summary>
public sealed record EncoderCapability(
VideoCodec Codec,
string Name,
bool Hardware,
int MaxWidth,
int MaxHeight,
bool SupportsTenBit,
string? Vendor = null);
/// <summary>Complete parameters of one encode.</summary>
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;
/// <summary>Average bit rate in bits per second (VBR/CBR).</summary>
public long BitRate { get; init; }
/// <summary>0–100 quality for <see cref="RateControl.Quality"/>, JPEG/MJPEG and GIF.</summary>
public int Quality { get; init; } = 90;
/// <summary>Distance between key frames in frames; 0 = encoder default (≈ 1 s).</summary>
public int GopLength { get; init; }
public int BFrames { get; init; } = 2;
public bool PreferHardware { get; init; } = true;
/// <summary>Optional specific encoder name from <see cref="EncoderCapability.Name"/>.</summary>
public string? EncoderName { get; init; }
}
/// <summary>One open encode. Frames are linear-light buffers at the output size.</summary>
public interface IVideoEncoderSession : IDisposable
{
/// <summary>Encoder actually used ("NVIDIA NVENC H.264", "Managed MJPEG").</summary>
string EncoderName { get; }
bool IsHardware { get; }
/// <summary>Appends a frame shown for <paramref name="duration90k"/> ticks of a 90 kHz clock.</summary>
void WriteFrame(ImageBuffer frame, long duration90k);
/// <summary>Flushes and closes the output. Without it, <see cref="IDisposable.Dispose"/> deletes the partial file.</summary>
void Complete();
}
/// <summary>A family of encoders (Media Foundation on Windows, managed everywhere).</summary>
public interface IVideoEncoderProvider
{
string Name { get; }
IReadOnlyList<EncoderCapability> Capabilities { get; }
bool CanEncode(EncodeSettings settings);
IVideoEncoderSession Open(EncodeSettings settings);
}
+29
View File
@@ -0,0 +1,29 @@
using System.Globalization;
namespace Titano.Core.Video;
/// <summary>An exact frame rate such as 24000/1001.</summary>
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);
}
/// <summary>Duration of one frame in 90 kHz ticks (MP4 timescale used by Titano).</summary>
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);
}