feat(imaging): thumbs.pack, thumbnail LRU cache and proxy builder
ThumbnailPack appends self-describing CRC-checked JPEG entries (320 px, q80) and index records; a two-slot header flips to each new index, so crashes and truncation lose only the damaged tail, and compaction rewrites live entries through AtomicFile. Reads are positional and run concurrently with the writer. ThumbnailCache is a byte-budget LRU that coalesces concurrent loads. ProxyBuilder decodes at the policy long edge with orientation applied and writes JPEG q92 with the source Exif (capture time kept, orientation reset). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
4 files changed
+994
No files matched your search
@@ -0,0 +1,156 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>A decoded thumbnail ready for display: interleaved 8-bit sRGB RGB.</summary>
|
||||
public sealed class Thumbnail(int width, int height, byte[] rgb)
|
||||
{
|
||||
public int Width { get; } = width;
|
||||
public int Height { get; } = height;
|
||||
|
||||
/// <summary>Width × height × 3 bytes, sRGB-encoded, top-down.</summary>
|
||||
public byte[] Rgb { get; } = rgb;
|
||||
|
||||
/// <summary>Memory charged against a <see cref="ThumbnailCache{TKey}"/> budget.</summary>
|
||||
public long ByteSize => Rgb.Length + 64;
|
||||
|
||||
/// <summary>Decodes a thumbnail JPEG (gray is expanded to RGB).</summary>
|
||||
/// <exception cref="InvalidDataException">The JPEG is malformed.</exception>
|
||||
public static Thumbnail FromJpeg(ReadOnlySpan<byte> jpeg)
|
||||
{
|
||||
var image = JpegDecoder.Decode(jpeg);
|
||||
var pixels = image.Pixels8 ?? throw new InvalidDataException("Thumbnail: not an 8-bit JPEG");
|
||||
if (image.Components == 3) return new Thumbnail(image.Width, image.Height, pixels);
|
||||
var rgb = new byte[pixels.Length * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = pixels[i];
|
||||
return new Thumbnail(image.Width, image.Height, rgb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In-memory LRU of decoded thumbnails under a byte budget (BRIEF §8.5). Thread-safe; concurrent requests for the same
|
||||
/// key share one load (<see cref="GetOrLoadAsync"/>), so a scrolling UI never decodes a thumbnail twice.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailCache<TKey> where TKey : notnull
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<TKey, LinkedListNode<(TKey Key, Thumbnail Value)>> _map = [];
|
||||
private readonly LinkedList<(TKey Key, Thumbnail Value)> _lru = new();
|
||||
private readonly Dictionary<TKey, Task<Thumbnail?>> _loading = [];
|
||||
private long _bytes;
|
||||
|
||||
/// <param name="byteBudget">Upper bound on the bytes held (a thumbnail larger than the budget is never cached).</param>
|
||||
public ThumbnailCache(long byteBudget)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(byteBudget);
|
||||
Budget = byteBudget;
|
||||
}
|
||||
|
||||
public long Budget { get; }
|
||||
|
||||
public long Bytes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _map.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns a cached thumbnail and marks it most recently used.</summary>
|
||||
public bool TryGet(TKey key, out Thumbnail thumbnail)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
thumbnail = node.Value.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
thumbnail = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Adds or replaces a thumbnail, evicting least recently used ones to stay within the budget.</summary>
|
||||
public void Set(TKey key, Thumbnail thumbnail)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(thumbnail);
|
||||
lock (_gate)
|
||||
{
|
||||
RemoveLocked(key);
|
||||
if (thumbnail.ByteSize > Budget) return;
|
||||
_map[key] = _lru.AddFirst((key, thumbnail));
|
||||
_bytes += thumbnail.ByteSize;
|
||||
while (_bytes > Budget && _lru.Last is { } last)
|
||||
{
|
||||
RemoveLocked(last.Value.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(TKey key)
|
||||
{
|
||||
lock (_gate) return RemoveLocked(key);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_map.Clear();
|
||||
_lru.Clear();
|
||||
_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cached thumbnail, or the result of <paramref name="loader"/> (cached when not null). Concurrent calls for
|
||||
/// the same key await the same load; each caller's <paramref name="cancellationToken"/> only cancels its own wait.</summary>
|
||||
public async Task<Thumbnail?> GetOrLoadAsync(TKey key, Func<TKey, CancellationToken, Task<Thumbnail?>> loader, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(loader);
|
||||
if (TryGet(key, out var hit)) return hit;
|
||||
Task<Thumbnail?> task;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_loading.TryGetValue(key, out task!))
|
||||
{
|
||||
task = LoadAsync(key, loader);
|
||||
_loading[key] = task;
|
||||
}
|
||||
}
|
||||
return await task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<Thumbnail?> LoadAsync(TKey key, Func<TKey, CancellationToken, Task<Thumbnail?>> loader)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Yield();
|
||||
var value = await loader(key, CancellationToken.None).ConfigureAwait(false);
|
||||
if (value is not null) Set(key, value);
|
||||
return value;
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoveLocked(TKey key)
|
||||
{
|
||||
if (!_map.Remove(key, out var node)) return false;
|
||||
_lru.Remove(node);
|
||||
_bytes -= node.Value.Value.ByteSize;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user