using SkiaSharp;
namespace Febe.Core.Library;
///
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under
/// Dati/miniature, in 256 shard folders named after the first two hex digits of the key. The key is the
/// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a
/// frame (); without either, the interface shows the neutral tile
/// ().
///
public sealed class ThumbnailStore
{
/// Long side of a thumbnail, in pixels.
public const int LongSide = 480;
/// JPEG quality of thumbnails.
public const int JpegQuality = 82;
/// File name of the neutral tile for videos without a cover.
public const string NeutralVideoTileName = "_video.jpg";
private readonly string _root;
public ThumbnailStore(string thumbnailsFolder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(thumbnailsFolder);
_root = Path.GetFullPath(thumbnailsFolder);
}
/// The thumbnails folder.
public string Root => _root;
/// Path of the thumbnail of a key (lowercase hex SHA-256).
public string PathFor(string key)
{
ValidateKey(key);
var k = key.ToLowerInvariant();
return Path.Combine(_root, k[..2], k + ".jpg");
}
public bool Exists(string key) => File.Exists(PathFor(key));
///
/// Creates the thumbnail of an encoded image (photo, or video cover). Does nothing when it already exists.
/// Returns false when the content cannot be decoded.
///
public bool Create(string key, Stream encodedImage)
{
ArgumentNullException.ThrowIfNull(encodedImage);
var target = PathFor(key);
if (File.Exists(target))
{
return true;
}
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
if (bitmap is null)
{
return false;
}
WriteJpeg(target, Render(bitmap, LongSide));
return true;
}
/// Creates the thumbnail of an image file.
public bool CreateFromFile(string key, string imagePath)
{
using var stream = File.OpenRead(imagePath);
return Create(key, stream);
}
/// Removes a thumbnail (when no file of the library uses its key any more).
public bool Delete(string key)
{
var path = PathFor(key);
if (!File.Exists(path))
{
return false;
}
File.Delete(path);
return true;
}
/// The neutral tile for videos without a cover, created on first use (grey, with a play sign).
public string NeutralVideoTile()
{
var path = Path.Combine(_root, NeutralVideoTileName);
if (File.Exists(path))
{
return path;
}
const int width = 270, height = LongSide; // 9:16, like stories and reels
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
var canvas = surface.Canvas;
canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4));
using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill })
{
canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
}
using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill })
{
// A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp.
var cx = width / 2f + 4;
var cy = height / 2f;
SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
}
using var image = surface.Snapshot();
using var bitmap = SKBitmap.FromImage(image);
WriteJpeg(path, bitmap.Copy());
return path;
}
///
/// Re-encodes an image to a small JPEG in memory (issue #37, photos of the profile search: never on disk). Returns
/// null when the content is not a decodable image.
///
public static byte[]? EncodeSmallJpeg(Stream source, int longSide)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
if (decoded is null)
{
return null;
}
using var small = Render(decoded, longSide);
using var pixmap = small.PeekPixels();
if (pixmap is null)
{
return null;
}
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
return data?.ToArray();
}
private static SKBitmap Render(SKBitmap source, int longSide)
{
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
var width = Math.Max(1, (int)Math.Round(source.Width * scale));
var height = Math.Max(1, (int)Math.Round(source.Height * scale));
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white
using var image = SKImage.FromBitmap(source);
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
return result;
}
private static void WriteJpeg(string target, SKBitmap bitmap)
{
using (bitmap)
{
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
try
{
using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel."))
using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality))
?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita."))
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
{
data.SaveTo(file);
}
try
{
File.Move(temp, target, overwrite: false);
}
catch (IOException) when (File.Exists(target))
{
// Created meanwhile by another task: same content.
}
}
finally
{
if (File.Exists(temp))
{
File.Delete(temp);
}
}
}
}
private static void ValidateKey(string key)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
if (key.Length < 8 || !key.All(Uri.IsHexDigit))
{
throw new ArgumentException("La chiave di una miniatura è uno SHA-256 in esadecimale.", nameof(key));
}
}
}