using Titano.Core.Codecs.Jpeg; namespace Titano.Core.Imaging.Thumbnails; /// A decoded thumbnail ready for display: interleaved 8-bit sRGB RGB. public sealed class Thumbnail(int width, int height, byte[] rgb) { public int Width { get; } = width; public int Height { get; } = height; /// Width × height × 3 bytes, sRGB-encoded, top-down. public byte[] Rgb { get; } = rgb; /// Memory charged against a budget. public long ByteSize => Rgb.Length + 64; /// Decodes a thumbnail JPEG (gray is expanded to RGB). /// The JPEG is malformed. public static Thumbnail FromJpeg(ReadOnlySpan jpeg) { var image = JpegDecoder.Decode(jpeg); var pixels = image.Pixels8 ?? throw new InvalidDataException("Thumbnail: not an 8-bit JPEG"); if (image.Components == 3) return new Thumbnail(image.Width, image.Height, pixels); var rgb = new byte[pixels.Length * 3]; for (var i = 0; i < pixels.Length; i++) rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = pixels[i]; return new Thumbnail(image.Width, image.Height, rgb); } } /// /// In-memory LRU of decoded thumbnails under a byte budget (BRIEF §8.5). Thread-safe; concurrent requests for the same /// key share one load (), so a scrolling UI never decodes a thumbnail twice. /// public sealed class ThumbnailCache where TKey : notnull { private readonly Lock _gate = new(); private readonly Dictionary> _map = []; private readonly LinkedList<(TKey Key, Thumbnail Value)> _lru = new(); private readonly Dictionary> _loading = []; private long _bytes; /// Upper bound on the bytes held (a thumbnail larger than the budget is never cached). public ThumbnailCache(long byteBudget) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(byteBudget); Budget = byteBudget; } public long Budget { get; } public long Bytes { get { lock (_gate) return _bytes; } } public int Count { get { lock (_gate) return _map.Count; } } /// Returns a cached thumbnail and marks it most recently used. public bool TryGet(TKey key, out Thumbnail thumbnail) { lock (_gate) { if (_map.TryGetValue(key, out var node)) { _lru.Remove(node); _lru.AddFirst(node); thumbnail = node.Value.Value; return true; } } thumbnail = null!; return false; } /// Adds or replaces a thumbnail, evicting least recently used ones to stay within the budget. public void Set(TKey key, Thumbnail thumbnail) { ArgumentNullException.ThrowIfNull(thumbnail); lock (_gate) { RemoveLocked(key); if (thumbnail.ByteSize > Budget) return; _map[key] = _lru.AddFirst((key, thumbnail)); _bytes += thumbnail.ByteSize; while (_bytes > Budget && _lru.Last is { } last) { RemoveLocked(last.Value.Key); } } } public bool Remove(TKey key) { lock (_gate) return RemoveLocked(key); } public void Clear() { lock (_gate) { _map.Clear(); _lru.Clear(); _bytes = 0; } } /// Cached thumbnail, or the result of (cached when not null). Concurrent calls for /// the same key await the same load; each caller's only cancels its own wait. public async Task GetOrLoadAsync(TKey key, Func> loader, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(loader); if (TryGet(key, out var hit)) return hit; Task task; lock (_gate) { if (!_loading.TryGetValue(key, out task!)) { task = LoadAsync(key, loader); _loading[key] = task; } } return await task.WaitAsync(cancellationToken).ConfigureAwait(false); } private async Task LoadAsync(TKey key, Func> loader) { try { await Task.Yield(); var value = await loader(key, CancellationToken.None).ConfigureAwait(false); if (value is not null) Set(key, value); return value; } finally { lock (_gate) _loading.Remove(key); } } private bool RemoveLocked(TKey key) { if (!_map.Remove(key, out var node)) return false; _lru.Remove(node); _bytes -= node.Value.Value.ByteSize; return true; } }