using Febe.Core.Codecs.Images;
using Febe.Core.Drawing;
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 image = DecodeFor(encodedImage, LongSide);
if (image is null)
{
return false;
}
using var thumbnail = Render(image, LongSide);
WriteJpeg(target, thumbnail);
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 tile = new RgbaImage(width, height);
using (var canvas = new Canvas(tile))
{
var background = new Color(0xE4, 0xE4, 0xE4);
canvas.Clear(background);
canvas.FillCircle(width / 2f, height / 2f, 34, new Color(0x9A, 0x9A, 0x9A));
// The play sign: a triangle pointing right, a little right of the centre to look centred.
var cx = (width / 2f) + 4;
var cy = height / 2f;
canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background);
}
WriteJpeg(path, tile);
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 = DecodeFor(source, longSide);
if (decoded is null)
{
return null;
}
using var small = Render(decoded, longSide);
return Jpeg(small);
}
///
/// Decodes an image upright for a picture of pixels. A JPEG may be shrunk while decoding,
/// but only down to twice that size: the last step is left to Lanczos, since the codec's 8 × 8 block averages would
/// show at almost 1:1. Null when the content cannot be decoded.
///
internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
///
/// The image reduced to on its long side (Lanczos, never enlarged) and seen over white,
/// since JPEG has no alpha. Always a new pooled image, which the caller disposes.
///
internal static RgbaImage Render(RgbaImage source, int longSide)
{
var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, longSide);
var result = ImageResampler.Resize(source, width, height, pooled: true);
ImageBackground.Flatten(result, Color.White);
return result;
}
/// The JPEG of a thumbnail: quality , chroma 4:2:0.
internal static byte[] Jpeg(RgbaImage image) =>
JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = JpegQuality, Subsampling = JpegSubsampling.Ratio420 });
private static void WriteJpeg(string target, RgbaImage image)
{
var data = Jpeg(image);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
try
{
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
{
file.Write(data);
}
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));
}
}
}