Unione di funzione/codec-immagini in funzione/decoder-h264 (catena della 0.3.0)
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>
This commit is contained in:
commit
8bcc86e496
279 files changed
+25617
-816
No files matched your search
@@ -0,0 +1,42 @@
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a photo truncated or
|
||||
/// damaged, downloaded or imported, is refused and said so. It has no thumbnail (the neutral tile) and no perceptual
|
||||
/// hash, so it is never a probable duplicate; its SHA-256 still counts. The file stays in the library (rule 12): this
|
||||
/// class only looks, it never deletes, replaces or downloads again.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The check decodes the picture, so it is meant for a single file at a time (the viewer) and only for photos that
|
||||
/// have no thumbnail: a photo with a thumbnail was decoded when it was stored.
|
||||
/// </remarks>
|
||||
public static class DamagedImage
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or
|
||||
/// truncated; false for a photo that decodes, for a format Febe does not read (HEIC, an unknown one) and for a
|
||||
/// picture too large to decode.
|
||||
/// </summary>
|
||||
public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk, read once; false when it cannot be read or is
|
||||
/// larger than <see cref="ImageDecoding.MaxFileBytes"/>.
|
||||
/// </summary>
|
||||
public static bool IsFileDamaged(string path)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
byte[]? data;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
data = ImageDecoding.ReadAll(stream);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return data is not null && ImageDecoding.IsDamaged(data);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it,
|
||||
/// decoding directly at a reduced size to save memory and time.
|
||||
/// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP), applying the
|
||||
/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is
|
||||
/// enough, which saves memory and time.
|
||||
/// </summary>
|
||||
internal static class ImageDecoding
|
||||
{
|
||||
@@ -14,118 +15,203 @@ internal static class ImageDecoding
|
||||
/// </summary>
|
||||
public const long MaxDecodedPixels = 100_000_000;
|
||||
|
||||
/// <summary>Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it).</summary>
|
||||
public const long MaxFileBytes = 512L * 1024 * 1024;
|
||||
|
||||
private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels };
|
||||
|
||||
/// <summary>
|
||||
/// Decodes an image upright, as premultiplied RGBA. When <paramref name="minLongSide"/> is given the codec may
|
||||
/// decode at a lower resolution, but never below that long side (unless the image is smaller).
|
||||
/// Returns null when the content is not a decodable image.
|
||||
/// Decodes an image upright, as straight RGBA. When <paramref name="minLongSide"/> is given the codec may decode
|
||||
/// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the
|
||||
/// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large).
|
||||
/// </summary>
|
||||
public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null)
|
||||
public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
using var data = SKData.Create(stream);
|
||||
if (data is null || data.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var codec = SKCodec.Create(data);
|
||||
if (codec is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var size = ChooseDecodeSize(codec, minLongSide);
|
||||
if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
|
||||
var decoded = new SKBitmap(info);
|
||||
var result = codec.GetPixels(info, decoded.GetPixels());
|
||||
if (result is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
|
||||
{
|
||||
decoded.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
return Orient(decoded, codec.EncodedOrigin);
|
||||
return ReadAll(stream) is { } data ? DecodeUpright(data, minLongSide) : null;
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="DecodeUpright(Stream, int?)"/>, from bytes already in memory.</summary>
|
||||
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide = null) => DecodeUpright(data, minLongSide, out _);
|
||||
|
||||
/// <summary>
|
||||
/// Like <see cref="DecodeUpright(ReadOnlyMemory{byte}, int?)"/>, and also gives what <see cref="ReadSize(ReadOnlyMemory{byte})"/>
|
||||
/// would (the full size as shown, even when the picture comes back reduced or not at all), from the same bytes.
|
||||
/// </summary>
|
||||
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide, out (int Width, int Height)? shownSize)
|
||||
{
|
||||
shownSize = null;
|
||||
if (data.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
RgbaImage? stored = null;
|
||||
try
|
||||
{
|
||||
ImageInfo info;
|
||||
stored = minLongSide is { } min && min > 0
|
||||
? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true)
|
||||
: ImageDecoder.Decode(data, out info, Limits, pooled: true);
|
||||
shownSize = ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||
var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true);
|
||||
if (!ReferenceEquals(upright, stored))
|
||||
{
|
||||
stored.Dispose();
|
||||
}
|
||||
|
||||
stored = null;
|
||||
return upright;
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
// A damaged, truncated or too large picture can still tell its size from its headers.
|
||||
shownSize ??= ReadSize(data);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
stored?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="data"/> is in a format Febe decodes but cannot be decoded because it is damaged or
|
||||
/// truncated (spec §8.4, «File danneggiato o incompleto»). False for a picture that decodes, for what Febe does not
|
||||
/// read (unknown formats, HEIC, the JPEG processes it leaves out) and for a picture over the limits: those are not
|
||||
/// damaged, Febe just has no picture of them.
|
||||
/// </summary>
|
||||
internal static bool IsDamaged(ReadOnlyMemory<byte> data)
|
||||
{
|
||||
if (data.IsEmpty || !ImageDecoder.CanDecode(ImageFormatSniffer.Detect(data.Span)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// A reduced JPEG decode still reads every scan to its end, so it finds a cut as the full decode does.
|
||||
using var image = ImageDecoder.DecodeAtLeast(data, DamageCheckSide, out _, Limits, pooled: true);
|
||||
return false;
|
||||
}
|
||||
catch (ImageLimitException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (ImageFormatNotSupportedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The smallest long side <see cref="IsDamaged"/> lets a JPEG be decoded at: the cheapest reduction.</summary>
|
||||
private const int DamageCheckSide = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Bytes read first by <see cref="ReadSize(Stream)"/> for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is
|
||||
/// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP
|
||||
/// are always read whole.
|
||||
/// </summary>
|
||||
internal const int HeaderBytes = 256 * 1024;
|
||||
|
||||
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
|
||||
public static (int Width, int Height)? ReadSize(Stream stream)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
using var codec = SKCodec.Create(stream);
|
||||
if (codec is null)
|
||||
if (!stream.CanSeek)
|
||||
{
|
||||
return ReadAll(stream) is { } all ? ReadSize(all) : null;
|
||||
}
|
||||
|
||||
var remaining = stream.Length - stream.Position;
|
||||
if (remaining <= 0 || remaining > MaxFileBytes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var (w, h) = (codec.Info.Width, codec.Info.Height);
|
||||
return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
|
||||
}
|
||||
|
||||
private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
|
||||
{
|
||||
var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
|
||||
if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min)
|
||||
if (remaining <= HeaderBytes)
|
||||
{
|
||||
return full;
|
||||
return ReadSize(ReadAll(stream));
|
||||
}
|
||||
|
||||
var best = full;
|
||||
foreach (var scale in new[] { 0.5f, 0.25f, 0.125f })
|
||||
var data = new byte[HeaderBytes];
|
||||
stream.ReadExactly(data);
|
||||
if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp))
|
||||
{
|
||||
var scaled = codec.GetScaledDimensions(scale);
|
||||
if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min)
|
||||
// PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs
|
||||
// past the data: neither can be identified from a prefix.
|
||||
Array.Resize(ref data, (int)remaining);
|
||||
stream.ReadExactly(data.AsSpan(HeaderBytes));
|
||||
return ReadSize(data);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var info = ImageDecoder.Identify(data, Limits);
|
||||
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
// The headers go on past the prefix (or the file is damaged): read the rest and look again.
|
||||
}
|
||||
|
||||
Array.Resize(ref data, (int)remaining);
|
||||
stream.ReadExactly(data.AsSpan(HeaderBytes));
|
||||
return ReadSize(data);
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="ReadSize(Stream)"/>, from bytes already in memory.</summary>
|
||||
public static (int Width, int Height)? ReadSize(ReadOnlyMemory<byte> data)
|
||||
{
|
||||
if (data.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var info = ImageDecoder.Identify(data, Limits);
|
||||
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The rest of <paramref name="stream"/>, or null when it is empty or over <see cref="MaxFileBytes"/>.</summary>
|
||||
internal static byte[]? ReadAll(Stream stream)
|
||||
{
|
||||
if (stream.CanSeek)
|
||||
{
|
||||
var remaining = stream.Length - stream.Position;
|
||||
if (remaining <= 0 || remaining > MaxFileBytes)
|
||||
{
|
||||
break;
|
||||
return null;
|
||||
}
|
||||
|
||||
best = scaled;
|
||||
var bytes = new byte[remaining];
|
||||
stream.ReadExactly(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool SwapsAxes(SKEncodedOrigin origin) =>
|
||||
origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom;
|
||||
|
||||
private static SKBitmap Orient(SKBitmap source, SKEncodedOrigin origin)
|
||||
{
|
||||
if (origin is SKEncodedOrigin.TopLeft or SKEncodedOrigin.Default)
|
||||
using var copy = new MemoryStream();
|
||||
var buffer = new byte[81920];
|
||||
int read;
|
||||
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
return source;
|
||||
if (copy.Length + read > MaxFileBytes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
copy.Write(buffer, 0, read);
|
||||
}
|
||||
|
||||
float w = source.Width, h = source.Height;
|
||||
var swap = SwapsAxes(origin);
|
||||
var outW = swap ? source.Height : source.Width;
|
||||
var outH = swap ? source.Width : source.Height;
|
||||
|
||||
// Each matrix maps a source pixel (x, y) to its upright position.
|
||||
var matrix = origin switch
|
||||
{
|
||||
SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1),
|
||||
SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1),
|
||||
SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1),
|
||||
SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1),
|
||||
_ => SKMatrix.Identity,
|
||||
};
|
||||
|
||||
var upright = new SKBitmap(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||||
using (var canvas = new SKCanvas(upright))
|
||||
{
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
canvas.SetMatrix(in matrix);
|
||||
canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
|
||||
}
|
||||
|
||||
source.Dispose();
|
||||
return upright;
|
||||
return copy.Length == 0 ? null : copy.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -278,11 +278,11 @@ public sealed class LibraryIngest(
|
||||
{
|
||||
try
|
||||
{
|
||||
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
|
||||
await using var stream = File.OpenRead(saved.FullPath);
|
||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
||||
// One read of the file gives both the perceptual hash and the size as shown.
|
||||
(hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath);
|
||||
if (size is { } shown)
|
||||
{
|
||||
(width, height) = size;
|
||||
(width, height) = shown;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
|
||||
@@ -445,13 +445,11 @@ public sealed class LibraryRebuilder(
|
||||
{
|
||||
if (!isVideo)
|
||||
{
|
||||
phash = PerceptualHash.ComputeFromFile(path);
|
||||
await using (var stream = File.OpenRead(path))
|
||||
// One read of the file gives both the perceptual hash and the size as shown.
|
||||
(phash, var size) = PerceptualHash.ComputeWithSizeFromFile(path);
|
||||
if (size is { } shown)
|
||||
{
|
||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
||||
{
|
||||
(width, height) = size;
|
||||
}
|
||||
(width, height) = shown;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Numerics;
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
@@ -38,6 +38,9 @@ public static class PerceptualHash
|
||||
private const int Size = 32;
|
||||
private const int Low = 8;
|
||||
|
||||
/// <summary>A JPEG is decoded reduced, but never below this long side.</summary>
|
||||
private const int MinDecodedSide = 256;
|
||||
|
||||
private static readonly double[,] Cosines = BuildCosines();
|
||||
|
||||
/// <summary>Hamming distance between two hashes (0–64).</summary>
|
||||
@@ -50,8 +53,8 @@ public static class PerceptualHash
|
||||
public static ulong? Compute(Stream encodedImage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(encodedImage);
|
||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
|
||||
return bitmap is null ? null : Compute(bitmap);
|
||||
using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide);
|
||||
return image is null ? null : Compute(image);
|
||||
}
|
||||
|
||||
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
|
||||
@@ -61,17 +64,33 @@ public static class PerceptualHash
|
||||
return Compute(stream);
|
||||
}
|
||||
|
||||
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
|
||||
internal static ulong Compute(SKBitmap bitmap)
|
||||
/// <summary>
|
||||
/// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had
|
||||
/// (a damaged file may still give its size).
|
||||
/// </summary>
|
||||
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory<byte> encodedImage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bitmap);
|
||||
using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul
|
||||
? null
|
||||
: bitmap.Copy(SKColorType.Rgba8888);
|
||||
var source = rgba ?? bitmap;
|
||||
var grey = Luminance(source);
|
||||
var small = AreaResample(grey, source.Width, source.Height, Size, Size);
|
||||
return HashOf(small);
|
||||
using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size);
|
||||
return (image is null ? null : Compute(image), size);
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="ComputeWithSize(ReadOnlyMemory{byte})"/> for a file, read once.</summary>
|
||||
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path)
|
||||
{
|
||||
byte[]? data;
|
||||
using (var stream = File.OpenRead(path))
|
||||
{
|
||||
data = ImageDecoding.ReadAll(stream);
|
||||
}
|
||||
|
||||
return data is null ? (null, null) : ComputeWithSize(data);
|
||||
}
|
||||
|
||||
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
|
||||
internal static ulong Compute(RgbaImage image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
return HashOf(AreaResample(image, Size, Size));
|
||||
}
|
||||
|
||||
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
|
||||
@@ -123,50 +142,37 @@ public static class PerceptualHash
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
|
||||
private static double[] Luminance(SKBitmap bitmap)
|
||||
/// <summary>
|
||||
/// The grey levels (0–255, over white: <see cref="ImageGray.LumaOverWhite"/>) of an image reduced to dw × dh by area
|
||||
/// averaging, one source row at a time (memory: one row and dw × source height values).
|
||||
/// </summary>
|
||||
internal static double[] AreaResample(RgbaImage image, int dw, int dh)
|
||||
{
|
||||
var width = bitmap.Width;
|
||||
var height = bitmap.Height;
|
||||
var result = new double[width * height];
|
||||
var pixels = bitmap.GetPixelSpan();
|
||||
var rowBytes = bitmap.RowBytes;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = pixels.Slice(y * rowBytes, width * 4);
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var r = row[x * 4];
|
||||
var g = row[(x * 4) + 1];
|
||||
var b = row[(x * 4) + 2];
|
||||
var a = row[(x * 4) + 3];
|
||||
var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha)
|
||||
result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
|
||||
internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh)
|
||||
{
|
||||
var horizontal = new double[dw * sh];
|
||||
var sw = image.Width;
|
||||
var sh = image.Height;
|
||||
var xs = Weights(sw, dw);
|
||||
var horizontal = new double[dw * sh];
|
||||
var grey = new double[sw];
|
||||
for (var y = 0; y < sh; y++)
|
||||
{
|
||||
ImageGray.LumaOverWhite(image.GetRow(y), grey);
|
||||
for (var dx = 0; dx < dw; dx++)
|
||||
{
|
||||
double sum = 0;
|
||||
foreach (var (index, weight) in xs[dx])
|
||||
{
|
||||
sum += source[(y * sw) + index] * weight;
|
||||
sum += grey[index] * weight;
|
||||
}
|
||||
|
||||
horizontal[(y * dw) + dx] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
return Vertical(horizontal, sh, dw, dh);
|
||||
}
|
||||
|
||||
private static double[] Vertical(double[] horizontal, int sh, int dw, int dh)
|
||||
{
|
||||
var result = new double[dw * dh];
|
||||
var ys = Weights(sh, dh);
|
||||
for (var dy = 0; dy < dh; dy++)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Drawing;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
@@ -54,13 +55,14 @@ public sealed class ThumbnailStore
|
||||
return true;
|
||||
}
|
||||
|
||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
|
||||
if (bitmap is null)
|
||||
using var image = DecodeFor(encodedImage, LongSide);
|
||||
if (image is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
WriteJpeg(target, Render(bitmap, LongSide));
|
||||
using var thumbnail = Render(image, LongSide);
|
||||
WriteJpeg(target, thumbnail);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -94,26 +96,20 @@ public sealed class ThumbnailStore
|
||||
}
|
||||
|
||||
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 })
|
||||
using var tile = new RgbaImage(width, height);
|
||||
using (var canvas = new Canvas(tile))
|
||||
{
|
||||
canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
|
||||
}
|
||||
var background = new Color(0xE4, 0xE4, 0xE4);
|
||||
canvas.Clear(background);
|
||||
canvas.FillCircle(width / 2f, height / 2f, 34, new Color(0x9A, 0x9A, 0x9A));
|
||||
|
||||
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;
|
||||
// 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;
|
||||
SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
|
||||
canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
|
||||
canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background);
|
||||
}
|
||||
|
||||
using var image = surface.Snapshot();
|
||||
using var bitmap = SKBitmap.FromImage(image);
|
||||
WriteJpeg(path, bitmap.Copy());
|
||||
WriteJpeg(path, tile);
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -125,67 +121,66 @@ public sealed class ThumbnailStore
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
||||
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
|
||||
using var decoded = DecodeFor(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();
|
||||
return Jpeg(small);
|
||||
}
|
||||
|
||||
private static SKBitmap Render(SKBitmap source, int longSide)
|
||||
/// <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 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);
|
||||
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;
|
||||
}
|
||||
|
||||
private static void WriteJpeg(string target, SKBitmap bitmap)
|
||||
/// <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)
|
||||
{
|
||||
using (bitmap)
|
||||
var data = Jpeg(image);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
||||
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
||||
{
|
||||
file.Write(data);
|
||||
}
|
||||
|
||||
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.
|
||||
}
|
||||
File.Move(temp, target, overwrite: false);
|
||||
}
|
||||
finally
|
||||
catch (IOException) when (File.Exists(target))
|
||||
{
|
||||
if (File.Exists(temp))
|
||||
{
|
||||
File.Delete(temp);
|
||||
}
|
||||
// Created meanwhile by another task: same content.
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temp))
|
||||
{
|
||||
File.Delete(temp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user