Porta nel decodificatore H.264 le regole senza componenti esterni, la sessione S4b e i codec di immagini di casa (C1), così la richiesta di unione di questo ramo contiene già tutta la catena. Conflitti risolti tenendo le due parti: in decisioni.md tutte le righe, prima quelle della catena e poi quelle del decodificatore; in docker.md, processo.md e Sviluppo.md né ffmpeg (uscito con questo ramo) né SkiaSharp (uscito con C1), con l'eccezione «da fare» delle prove di conformità; nelle prove di Febe.Tests entrambe le cartelle di file copiati e, nelle prove delle miniature, sia i video sia le immagini di riferimento. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
6.8 KiB
C#
197 lines
6.8 KiB
C#
using Febe.Core.Codecs.Images;
|
||
using Febe.Core.Drawing;
|
||
|
||
namespace Febe.Core.Library;
|
||
|
||
/// <summary>
|
||
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under
|
||
/// <c>Dati/miniature</c>, 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 (<see cref="VideoFrameDecoder"/>); without either, the interface shows the neutral tile
|
||
/// (<see cref="NeutralVideoTile"/>).
|
||
/// </summary>
|
||
public sealed class ThumbnailStore
|
||
{
|
||
/// <summary>Long side of a thumbnail, in pixels.</summary>
|
||
public const int LongSide = 480;
|
||
|
||
/// <summary>JPEG quality of thumbnails.</summary>
|
||
public const int JpegQuality = 82;
|
||
|
||
/// <summary>File name of the neutral tile for videos without a cover.</summary>
|
||
public const string NeutralVideoTileName = "_video.jpg";
|
||
|
||
private readonly string _root;
|
||
|
||
public ThumbnailStore(string thumbnailsFolder)
|
||
{
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(thumbnailsFolder);
|
||
_root = Path.GetFullPath(thumbnailsFolder);
|
||
}
|
||
|
||
/// <summary>The thumbnails folder.</summary>
|
||
public string Root => _root;
|
||
|
||
/// <summary>Path of the thumbnail of a key (lowercase hex SHA-256).</summary>
|
||
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));
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Creates the thumbnail of an image file.</summary>
|
||
public bool CreateFromFile(string key, string imagePath)
|
||
{
|
||
using var stream = File.OpenRead(imagePath);
|
||
return Create(key, stream);
|
||
}
|
||
|
||
/// <summary>Removes a thumbnail (when no file of the library uses its key any more).</summary>
|
||
public bool Delete(string key)
|
||
{
|
||
var path = PathFor(key);
|
||
if (!File.Exists(path))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
File.Delete(path);
|
||
return true;
|
||
}
|
||
|
||
/// <summary>The neutral tile for videos without a cover, created on first use (grey, with a play sign).</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Decodes an image upright for a picture of <paramref name="longSide"/> 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.
|
||
/// </summary>
|
||
internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
|
||
ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
|
||
|
||
/// <summary>
|
||
/// The image reduced to <paramref name="longSide"/> 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.
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>The JPEG of a thumbnail: quality <see cref="JpegQuality"/>, chroma 4:2:0.</summary>
|
||
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));
|
||
}
|
||
}
|
||
}
|