Unione di funzione/decoder-h264 in funzione/decoder-hevc (catena della 0.3.0)

Il ramo HEVC era partito da b23632f; la catena porta qui documenti e regole,
S4b, i codec di casa (C1) e il resto dell'H.264 (campi, Extended, alta
profondità, MVC, SVC, lettori ASF/FLV/MPEG). Le due serie restano intere:
- VideoFrameDecoder sceglie H.264 o HEVC come nel ramo HEVC; dell'H.264 prende
  la sola vista di base dell'MVC e i piani a 16 bit, passati al convertitore
  comune YuvToRgb (anche 4:2:2, 4:4:4 e 4:0:0) al posto del suo.
- Le foto HEIC passano dalla facciata dei codec di C1: HeifImageDecoder
  trasforma l'HeifImage in RgbaImage senza copia e irot/imir nell'orientamento,
  così ImageDecoding, miniature e impronte le trattano come le altre foto; la
  dimensione di un HEIC grande si legge dai soli box.
- decisioni.md tiene tutte le righe dei due lati (prima quelle della catena).
- Prove: entrambe le copie dei flussi di conformità H.264 e H.265 e delle
  immagini di riferimento; nei file rovinati entrano sia HEVC sia WMV/FLV/MPEG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 11:34:18 +01:00
commit 14920afebf
420 files changed
+39437 -2446

No files matched your search

+42
View File
@@ -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);
}
}
+188 -152
View File
@@ -1,12 +1,12 @@
using Febe.Core.Codecs.Heif;
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. HEIC/HEIF photos, which SkiaSharp does not read, go
/// through the decoder written in house (<see cref="HeifDecoder"/>).
/// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP and HEIC through
/// <see cref="HeifDecoder"/>), applying the EXIF orientation (photos from phones; for HEIC its <c>irot</c>/<c>imir</c>)
/// 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
{
@@ -16,185 +16,221 @@ 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, AVIF, 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;
}
if (HeifDecoder.Looks(data.AsSpan()))
{
return DecodeHeif(data);
}
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, the JPEG processes it leaves out) and for a picture over the limits: those are not
/// damaged, Febe just has no picture of them. HEIC is never said damaged: its decoder does not tell a damaged file
/// from a HEIF it does not handle (AV1 or JPEG pictures, an unknown essential property), so a HEIC without a
/// picture only gets the neutral tile.
/// </summary>
internal static bool IsDamaged(ReadOnlyMemory<byte> data)
{
var format = data.IsEmpty ? ImageFormat.Unknown : ImageFormatSniffer.Detect(data.Span);
if (format == ImageFormat.Heif || !ImageDecoder.CanDecode(format))
{
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; HEIC only its boxes (<see cref="HeifDecoder.ReadInfo"/>), never its pictures.
/// </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);
if (stream.CanSeek)
if (!stream.CanSeek)
{
var start = stream.Position;
Span<byte> head = stackalloc byte[64];
var read = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
stream.Position = start;
if (HeifDecoder.Looks(head[..read]))
{
try
{
return HeifDecoder.ReadInfo(stream).DisplaySize;
}
catch (HeifException)
{
return null;
}
}
return ReadAll(stream) is { } all ? ReadSize(all) : null;
}
using var codec = SKCodec.Create(stream);
if (codec is 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);
}
if (remaining <= HeaderBytes)
{
return ReadSize(ReadAll(stream));
}
var start = stream.Position;
var data = new byte[HeaderBytes];
stream.ReadExactly(data);
if (ImageFormatSniffer.Detect(data) == ImageFormat.Heif)
{
// A HEIC keeps its boxes at the start and its pictures after them: the boxes alone give the size.
stream.Position = start;
try
{
return HeifDecoder.ReadInfo(stream).DisplaySize;
}
catch (HeifException)
{
return null;
}
}
if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp))
{
// 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);
}
/// <summary>
/// A HEIC/HEIF photo, which SkiaSharp does not decode: the decoder written in house (<see cref="HeifDecoder"/>), at
/// full size, turned upright by its <c>irot</c>/<c>imir</c> properties; null when it cannot be decoded.
/// </summary>
private static SKBitmap? DecodeHeif(SKData data)
{
HeifImage image;
try
{
using var stream = data.AsStream();
var info = HeifDecoder.ReadInfo(stream);
if ((long)info.Width * info.Height > MaxDecodedPixels)
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)
{
return null;
}
stream.Position = 0;
image = HeifDecoder.Decode(stream);
}
catch (HeifException)
{
return null;
var bytes = new byte[remaining];
stream.ReadExactly(bytes);
return bytes;
}
var bitmap = new SKBitmap(new SKImageInfo(image.Width, image.Height, SKColorType.Rgba8888, image.HasAlpha ? SKAlphaType.Unpremul : SKAlphaType.Premul));
System.Runtime.InteropServices.Marshal.Copy(image.Pixels, 0, bitmap.GetPixels(), image.Pixels.Length);
if (image.HasAlpha)
using var copy = new MemoryStream();
var buffer = new byte[81920];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// The other paths give premultiplied pixels: the same here.
var premultiplied = new SKBitmap(new SKImageInfo(image.Width, image.Height, SKColorType.Rgba8888, SKAlphaType.Premul));
using (var canvas = new SKCanvas(premultiplied))
if (copy.Length + read > MaxFileBytes)
{
canvas.Clear(SKColors.Transparent);
canvas.DrawBitmap(bitmap, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
return null;
}
bitmap.Dispose();
bitmap = premultiplied;
copy.Write(buffer, 0, read);
}
return Orient(bitmap, (SKEncodedOrigin)image.Orientation);
}
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)
{
return full;
}
var best = full;
foreach (var scale in new[] { 0.5f, 0.25f, 0.125f })
{
var scaled = codec.GetScaledDimensions(scale);
if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min)
{
break;
}
best = scaled;
}
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)
{
return source;
}
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();
}
}
+4 -4
View File
@@ -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)
+4 -6
View File
@@ -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;
}
}
}
+48 -42
View File
@@ -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++)
+57 -62
View File
@@ -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);
}
}
}
+46 -5
View File
@@ -402,7 +402,8 @@ public sealed class VideoFrameDecoder
}
else
{
avc = new H264Decoder { Wanted = _ => wanted() };
// Of an MVC stream only the base view: it is the 2D video, and the other views would add frames.
avc = new H264Decoder { Wanted = _ => wanted(), DecodeAllViews = false };
avc.FrameDecoded += frame => found(new Frame(frame, null));
lengthSize = video.AnnexB ? 0 : avc.ConfigureAvcC(video.AvcConfiguration);
}
@@ -562,7 +563,8 @@ public sealed class VideoFrameDecoder
}
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
private static double[] Grid(Frame frame) => frame.Hevc is { } h ? Grid(Planes(h)) : Grid(Planes(frame.Avc!));
private static double[] Grid(Frame frame) =>
frame.Hevc is { } h ? Grid(Planes(h)) : frame.Avc!.BytesPerSample == 2 ? Grid(WidePlanes(frame.Avc)) : Grid(Planes(frame.Avc));
/// <summary>
/// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
@@ -619,8 +621,45 @@ public sealed class VideoFrameDecoder
return grid;
}
private static YuvPlanes<byte> Planes(H264Frame frame) =>
new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, 1, 1, false, 8, 8);
/// <summary>
/// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0
/// chroma planes (<see cref="H264Frame"/>), which the conversion does not read.
/// </summary>
private static YuvPlanes<byte> Planes(H264Frame frame)
{
var (sx, sy) = ChromaShifts(frame.ChromaFormat);
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
/// <summary>
/// The planes of an H.264 frame above 8 bits (two bytes a sample, little-endian), as 16-bit values: copied once,
/// for the few frames a thumbnail or a stillness check decodes.
/// </summary>
private static YuvPlanes<ushort> WidePlanes(H264Frame frame)
{
static ushort[] Wide(byte[] plane)
{
var values = new ushort[plane.Length / 2];
for (var i = 0; i < values.Length; i++)
{
values[i] = BinaryPrimitives.ReadUInt16LittleEndian(plane.AsSpan(2 * i));
}
return values;
}
var (sx, sy) = ChromaShifts(frame.ChromaFormat);
return new(Wide(frame.Y), Wide(frame.Cb), Wide(frame.Cr), frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0,
frame.BitDepthLuma, frame.BitDepthChroma);
}
/// <summary>Chroma subsampling of chroma_format_idc (0, monochrome, as 4:2:0: the planes H.264 gives it are that size).</summary>
private static (int X, int Y) ChromaShifts(int chromaFormat) => chromaFormat switch
{
0 or 1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
private static YuvPlanes<ushort> Planes(H265Frame frame)
{
@@ -641,7 +680,9 @@ public sealed class VideoFrameDecoder
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) =>
ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
frame.BytesPerSample == 2
? ToImage(WidePlanes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide)
: ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
/// <summary>
/// An HEVC frame in RGB, as <see cref="ToImage(H264Frame, int, int)"/>: any chroma format (4:0:0 in grey) and bit