using System.Collections.Concurrent;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data;
using Titano.Ui.Visuals;
namespace Titano.App.Library;
/// A thumbnail request: one frame at a width bucket (so nearby sizes share a decode).
public readonly record struct ThumbnailKey(Guid FrameId, int Width);
///
/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the
/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright,
/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away.
///
public sealed class ThumbnailService : ISequenceThumbnails, IDisposable
{
/// Embedded previews larger than this are not read (a damaged index would make us read gigabytes).
private const long MaxPreviewBytes = 64L << 20;
private const int WidthStep = 64;
private readonly TitanoDatabase _db;
private readonly ThumbnailCache _cache;
private readonly ConcurrentDictionary _archiveRoots = new();
private readonly ConcurrentDictionary _firstFrames = new();
private int _requests;
public ThumbnailService(TitanoDatabase db, int capacity)
{
_db = db;
_cache = new ThumbnailCache(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6));
}
public int Count => _cache.Count;
/// Thumbnail requests in flight, index lookups included (capture and tests wait for them).
public int PendingLoads => Math.Max(Volatile.Read(ref _requests), _cache.PendingLoads);
/// Maximum thumbnails kept in memory (Settings › Storage).
public int Capacity
{
get => _cache.Capacity;
set => _cache.Capacity = Math.Max(16, value);
}
/// The hero thumbnail of a sequence: its hero frame, or the first frame.
public async Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
{
Interlocked.Increment(ref _requests);
try
{
var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false);
return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null;
}
finally
{
Interlocked.Decrement(ref _requests);
}
}
/// A frame of a sequence by index (hover scrubbing).
public async Task FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
{
Interlocked.Increment(ref _requests);
try
{
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false);
return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false);
}
finally
{
Interlocked.Decrement(ref _requests);
}
}
/// Hover-scrub frames of a sequence, sampled to at most positions.
public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
IThumbnailSource? ISequenceThumbnails.ScrubSource(Sequence sequence) => ScrubSource(sequence);
/// Drops decoded thumbnails (Settings › Storage › Clear).
public void Clear()
{
_cache.Clear();
_archiveRoots.Clear();
_firstFrames.Clear();
}
public void Dispose() => _cache.Dispose();
private static ThumbnailKey Key(Guid frameId, int pixelWidth) =>
new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048));
private async Task FirstFrameAsync(Guid sequenceId, CancellationToken ct)
{
if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached;
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false);
var id = frames.Count > 0 ? frames[0].Id : (Guid?)null;
_firstFrames[sequenceId] = id;
return id;
}
private async Task ArchiveRootAsync(Guid sequenceId, CancellationToken ct)
{
var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
if (sequence is null) return null;
if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root;
root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath;
_archiveRoots[sequence.ArchiveId] = root;
return root;
}
private async Task LoadAsync(ThumbnailKey key, CancellationToken ct)
{
var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false);
if (frame is null) return null;
var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false);
if (root is null) return null;
var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar));
ct.ThrowIfCancellationRequested();
try
{
return Decode(path, frame, key.Width, ct);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException)
{
Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}");
return null;
}
}
/// The embedded preview when the index knows it, otherwise the original, decoded at .
internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct)
{
if (!File.Exists(path)) return null;
if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length)
{
var bytes = new byte[length];
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess))
{
if (offset + length <= file.Length)
{
file.Seek(offset, SeekOrigin.Begin);
file.ReadExactly(bytes);
ct.ThrowIfCancellationRequested();
try
{
using var memory = new MemoryStream(bytes, writable: false);
return DecodeStream(memory, frame.Orientation, width);
}
catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException)
{
// A broken preview falls through to the original.
}
}
}
}
ct.ThrowIfCancellationRequested();
using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan);
return DecodeStream(original, frame.Orientation, width);
}
/// WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread.
internal static BitmapSource DecodeStream(Stream stream, int orientation, int width)
{
var turned = orientation is 5 or 6 or 7 or 8;
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
if (turned) image.DecodePixelHeight = width;
else image.DecodePixelWidth = width;
image.StreamSource = stream;
image.EndInit();
BitmapSource result = image;
if (orientation is > 1 and <= 8)
{
var transform = new TransformGroup();
if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1));
var angle = orientation switch
{
3 or 4 => 180,
5 or 6 => 90,
7 or 8 => 270,
_ => 0,
};
if (angle != 0) transform.Children.Add(new RotateTransform(angle));
result = new TransformedBitmap(image, transform);
}
result.Freeze();
return result;
}
/// Evenly spaced frames of one sequence for hover scrubbing.
private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource
{
public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions);
public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
{
if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false);
var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1));
return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false);
}
}
}