Codec di casa al posto di SkiaSharp (C1, passo 5)

SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies escono da
Directory.Packages.props e da ogni progetto, per la regola «niente
componenti esterni». Tutto ciò che leggeva, ridimensionava o disegnava
immagini con Skia ora usa codice scritto in casa sulla BCL:

- ImageResampler: Lanczos3 separabile o media per area, alfa
  premoltiplicata, luce lineare facoltativa; ImageGray per l'impronta.
- Il lettore JPEG decodifica ridotto a 1/2, 1/4, 1/8; le miniature
  chiedono almeno il doppio del lato lungo, così l'ultimo passo resta a
  Lanczos e la miniatura resta uguale alla lettura intera.
- ImageOrientation applica l'EXIF in un punto solo (miniature, impronte,
  anteprime, dimensioni mostrate).
- ImageConverter cambia formato fra JPEG, PNG e WebP portando EXIF, ICC,
  XMP e testi, con l'etichetta d'orientamento e i pixel non ruotati;
  PngEncoder scrive anche i testi (tEXt o iTXt).
- Febe.Core.Drawing: rasterizzatore con antialiasing (tracciati,
  riempimenti, tratti, gradienti) per icona, immagini dimostrative,
  riquadro neutro dei video, foto del sito di prova e prove. Febe.ico
  rigenerata.
- ThumbnailStore legge anche i BMP a 24 bit, come quelli del decoder
  video del ramo funzione/decoder-h264.

Le impronte salvate restano confrontabili (390 su 393 campioni identiche,
le altre a distanza 2, soglia 6): nessun ricalcolo. Un PNG o JPEG
troncato ora non ha miniatura né impronta. Documenti, elenco dei
componenti della pagina «Informazioni» e decisioni aggiornati; nuove
prove per ridimensionamento, orientamento, lettura ridotta, conversione
con metadati, testi PNG e rasterizzatore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 16:02:03 +01:00
1 parent b4383a6110
commit d6a6a68496
47 files changed
+3391 -562

No files matched your search

@@ -0,0 +1,220 @@
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>Options of <see cref="ImageConverter"/>.</summary>
public sealed record ImageConversionOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static ImageConversionOptions Default { get; } = new();
/// <summary>Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026).</summary>
public int JpegQuality { get; init; } = 92;
/// <summary>Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible.</summary>
public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444;
/// <summary>What transparent areas become in a JPEG target, which has no alpha.</summary>
public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White;
/// <summary>Limits of the decoding of the source.</summary>
public ImageLimits Limits { get; init; } = ImageLimits.Default;
}
/// <summary>What <see cref="ImageConverter.Convert"/> made.</summary>
/// <param name="Data">The converted file.</param>
/// <param name="Source">The format of the source.</param>
/// <param name="Target">The format written.</param>
/// <param name="Width">Width as stored (the orientation is not applied: the tag is copied).</param>
/// <param name="Height">Height as stored.</param>
/// <param name="Lossy">Whether pixels may differ from the source's (a JPEG target).</param>
/// <param name="Metadata">The metadata written.</param>
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
public sealed record ImageConversionResult(
byte[] Data,
ImageFormat Source,
ImageFormat Target,
int Width,
int Height,
bool Lossy,
ImageMetadata Metadata,
IReadOnlyList<string> NotCarried);
/// <summary>
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP losslessly, JPEG at
/// the quality of the options. The EXIF block (dates, camera, the orientation tag), the ICC profile and the XMP
/// packet are copied as they are; the pixels stay as stored, not turned by the orientation, which the copied tag
/// still describes. Texts go where the target can hold them: PNG text chunks, JPEG comments; WebP has none, and
/// what cannot be carried is listed in <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first
/// frame only, and say so.
/// </summary>
public static class ImageConverter
{
/// <summary>The formats a conversion can write.</summary>
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
public static ImageConversionResult Convert(ReadOnlyMemory<byte> source, ImageFormat target, ImageConversionOptions? options = null)
{
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
using var image = ImageDecoder.Decode(source, out var info, options.Limits, pooled: true);
var notCarried = new List<string>();
if (info.FrameCount > 1)
{
notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}");
}
var metadata = info.Metadata;
var exif = metadata.Exif;
var icc = metadata.IccProfile;
var xmp = metadata.Xmp;
var texts = metadata.Texts;
byte[] data;
switch (target)
{
case ImageFormat.Png:
data = PngEncoder.Encode(image, new PngEncoderOptions
{
Exif = exif,
IccProfile = icc,
IccProfileName = ValidIccName(metadata.IccProfileName) ?? PngEncoderOptions.Default.IccProfileName,
Xmp = xmp,
Texts = PngTexts(texts, notCarried),
});
break;
case ImageFormat.WebP:
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
{
throw new ImageLimitException($"Un'immagine WebP non supera {WebPEncoder.MaxDimension} pixel per lato ({image.Width}×{image.Height}).");
}
if (texts.Count > 0)
{
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
}
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
break;
default:
{
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
{
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
exif = null;
}
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
{
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
xmp = null;
}
var comments = new List<string>();
foreach (var text in texts)
{
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
}
if (!image.IsOpaque())
{
ImageBackground.Flatten(image, options.JpegBackground);
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
}
data = JpegEncoder.Encode(image, new JpegEncoderOptions
{
Quality = options.JpegQuality,
Subsampling = options.JpegSubsampling,
Exif = exif,
IccProfile = icc,
Xmp = xmp,
Comments = comments,
});
break;
}
}
var written = new ImageMetadata
{
Exif = exif,
Orientation = metadata.Orientation,
IccProfile = icc,
IccProfileName = metadata.IccProfileName,
Xmp = xmp,
Texts = target == ImageFormat.WebP ? [] : texts,
};
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, target == ImageFormat.Jpeg, written, notCarried);
}
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
private const int JpegMaxSegmentPayload = 65533;
private static string? ValidIccName(string? name)
{
if (string.IsNullOrEmpty(name) || name.Length > 79)
{
return null;
}
foreach (var c in name)
{
if (c < 32 || c > 255 || (c > 126 && c < 161))
{
return null;
}
}
return name.Trim().Length == name.Length ? name : null;
}
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
{
var result = new List<ImageText>(texts.Count);
foreach (var text in texts)
{
var keyword = text.Keyword.Length == 0 ? "Comment" : text.Keyword;
if (!PngEncoder.IsValidKeyword(keyword))
{
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
continue;
}
result.Add(text with { Keyword = keyword });
}
return result;
}
}
/// <summary>Composites an image over a plain colour.</summary>
public static class ImageBackground
{
/// <summary>Every pixel of <paramref name="image"/> seen over <paramref name="background"/>, opaque, in place.</summary>
public static void Flatten(RgbaImage image, Drawing.Color background)
{
ArgumentNullException.ThrowIfNull(image);
var pixels = image.Pixels;
for (var i = 0; i < pixels.Length; i += 4)
{
int a = pixels[i + 3];
if (a == 255)
{
continue;
}
var keep = 255 - a;
pixels[i] = (byte)(((pixels[i] * a) + (background.R * keep) + 127) / 255);
pixels[i + 1] = (byte)(((pixels[i + 1] * a) + (background.G * keep) + 127) / 255);
pixels[i + 2] = (byte)(((pixels[i + 2] * a) + (background.B * keep) + 127) / 255);
pixels[i + 3] = 255;
}
}
}
@@ -38,6 +38,53 @@ public static class ImageDecoder
var other => throw NotSupported(other),
};
/// <summary>Decodes an image to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
{
switch (ImageFormatSniffer.Detect(data.Span))
{
case ImageFormat.Png:
return PngDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.Jpeg:
return JpegDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.Gif:
return GifDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.Bmp:
return BmpDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.WebP:
return WebPDecoder.Decode(data, out info, limits, pooled);
case var other:
throw NotSupported(other);
}
}
/// <summary>
/// Decodes an image no smaller than <paramref name="minLongSide"/> on its long side where the format allows a
/// cheaper reduced decode (JPEG: a half, a quarter or an eighth, the smallest that keeps that side), at full size
/// otherwise; with what <see cref="Identify"/> returns (the full size). The result may still need resizing.
/// </summary>
public static RgbaImage DecodeAtLeast(ReadOnlyMemory<byte> data, int minLongSide, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(minLongSide);
if (ImageFormatSniffer.Detect(data.Span) != ImageFormat.Jpeg)
{
return Decode(data, out info, limits, pooled);
}
var header = JpegDecoder.Identify(data, limits);
var longSide = Math.Max(header.Width, header.Height);
var reduction = 0;
while (reduction < 3 && ((longSide + (2 << reduction) - 1) >> (reduction + 1)) >= minLongSide)
{
reduction++;
}
return JpegDecoder.DecodeReduced(data, reduction, out info, limits, pooled);
}
private static ImageFormatNotSupportedException NotSupported(ImageFormat format) =>
format == ImageFormat.Unknown
? new ImageFormatNotSupportedException("Formato d'immagine non riconosciuto.")
+33
View File
@@ -0,0 +1,33 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Grey levels of RGBA pixels.</summary>
public static class ImageGray
{
/// <summary>
/// The grey level 0-255 of each pixel of an RGBA row seen over white, with the weights of ITU-R BT.601
/// (0.299 R + 0.587 G + 0.114 B): a transparent pixel is white, a half-transparent one halfway to white.
/// </summary>
public static void LumaOverWhite(ReadOnlySpan<byte> rgba, Span<double> output)
{
if (output.Length * 4 > rgba.Length)
{
throw new ArgumentException("The row has fewer pixels than the output.", nameof(rgba));
}
for (var x = 0; x < output.Length; x++)
{
var i = x * 4;
int a = rgba[i + 3];
if (a == 255)
{
output[x] = (0.299 * rgba[i]) + (0.587 * rgba[i + 1]) + (0.114 * rgba[i + 2]);
continue;
}
// Over white each channel becomes c·α + 255·(1 − α), with α = a / 255.
var alpha = a / 255.0;
var white = 255 - a;
output[x] = (0.299 * ((rgba[i] * alpha) + white)) + (0.587 * ((rgba[i + 1] * alpha) + white)) + (0.114 * ((rgba[i + 2] * alpha) + white));
}
}
}
@@ -0,0 +1,70 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The eight EXIF orientations (TIFF 6.0, tag 0x0112): how the stored pixels must be turned to be shown upright.
/// 1 upright; 2 mirrored left-right; 3 turned 180°; 4 mirrored top-bottom; 5 mirrored along the main diagonal
/// (transposed); 6 to be turned 90° clockwise; 7 mirrored along the other diagonal; 8 to be turned 90° anticlockwise.
/// The decoders report the orientation and never apply it: only what Febe shows (thumbnails, previews, the perceptual
/// hash) is turned; files and conversions keep the stored pixels and the tag.
/// </summary>
public static class ImageOrientation
{
/// <summary>Whether the orientation swaps width and height (5-8).</summary>
public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8;
/// <summary>The size of an image as shown, from its stored size.</summary>
public static (int Width, int Height) ShownSize(int width, int height, int orientation) =>
SwapsAxes(orientation) ? (height, width) : (width, height);
/// <summary>
/// The image turned upright. Returns <paramref name="stored"/> itself for orientation 1 (or any value outside
/// 1-8); otherwise a new image (pooled when asked), and <paramref name="stored"/> is left as it is.
/// </summary>
public static RgbaImage Apply(RgbaImage stored, int orientation, bool pooled = false)
{
ArgumentNullException.ThrowIfNull(stored);
if (orientation is < 2 or > 8)
{
return stored;
}
var w = stored.Width;
var h = stored.Height;
var (ow, oh) = ShownSize(w, h, orientation);
var result = pooled ? RgbaImage.Rent(ow, oh) : new RgbaImage(ow, oh);
var source = stored.Pixels;
var target = result.Pixels;
var sourceStride = w * 4;
// For every target pixel (x, y) the stored pixel it shows: sx = x0 + x·dxx + y·dxy, sy = y0 + x·dyx + y·dyy.
var (x0, dxx, dxy, y0, dyx, dyy) = orientation switch
{
2 => (w - 1, -1, 0, 0, 0, 1),
3 => (w - 1, -1, 0, h - 1, 0, -1),
4 => (0, 1, 0, h - 1, 0, -1),
5 => (0, 0, 1, 0, 1, 0),
6 => (0, 0, 1, h - 1, -1, 0),
7 => (w - 1, 0, -1, h - 1, -1, 0),
_ => (w - 1, 0, -1, 0, 1, 0), // 8
};
var step = (dyx * sourceStride) + (dxx * 4);
for (var y = 0; y < oh; y++)
{
var sx = x0 + (y * dxy);
var sy = y0 + (y * dyy);
var s = (sy * sourceStride) + (sx * 4);
var row = target.Slice(y * ow * 4, ow * 4);
for (var x = 0; x < row.Length; x += 4)
{
row[x] = source[s];
row[x + 1] = source[s + 1];
row[x + 2] = source[s + 2];
row[x + 3] = source[s + 3];
s += step;
}
}
return result;
}
}
@@ -0,0 +1,433 @@
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Febe.Core.Codecs.Images;
/// <summary>The filter <see cref="ImageResampler"/> weighs the source pixels with.</summary>
public enum ResampleFilter
{
/// <summary>
/// The Lanczos window of three lobes, sinc(x) sinc(x/3) for |x| &lt; 3: sharp, with a faint ring along hard edges.
/// When reducing, the window is stretched by the reduction so that every source pixel counts (no aliasing).
/// </summary>
Lanczos3,
/// <summary>
/// Area averaging when reducing: each target pixel is the mean of the source area it covers, partial pixels
/// weighted by the fraction covered. Enlarging falls back to linear interpolation.
/// </summary>
Area,
}
/// <summary>Options of <see cref="ImageResampler"/>.</summary>
public sealed record ResampleOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static ResampleOptions Default { get; } = new();
public ResampleFilter Filter { get; init; } = ResampleFilter.Lanczos3;
/// <summary>
/// Average the light rather than the stored values: sRGB samples are turned into linear light before filtering and
/// back afterwards. Off by default, as other programs resize (thin bright lines on dark keep more of their weight
/// when on).
/// </summary>
public bool LinearLight { get; init; }
}
/// <summary>
/// Changes the size of an image with a separable filter: every row is filtered horizontally into a short ring of
/// floating-point rows, and each target row is a weighted sum of the ring's rows. Memory is the target image plus
/// a few rows, whatever the size of the source. Images with transparency are filtered with premultiplied alpha, so
/// the colour under transparent pixels does not bleed into the visible ones.
/// </summary>
public static class ImageResampler
{
/// <summary><paramref name="source"/> resized to <paramref name="width"/> × <paramref name="height"/>.</summary>
public static RgbaImage Resize(RgbaImage source, int width, int height, ResampleOptions? options = null, bool pooled = false)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
options ??= ResampleOptions.Default;
var target = pooled ? RgbaImage.Rent(width, height) : new RgbaImage(width, height);
try
{
if (width == source.Width && height == source.Height)
{
source.Pixels.CopyTo(target.Pixels);
return target;
}
Run(source, target, options);
return target;
}
catch
{
target.Dispose();
throw;
}
}
/// <summary>
/// The size that fits <paramref name="width"/> × <paramref name="height"/> inside a square of
/// <paramref name="longSide"/>, keeping the proportions (rounded, at least 1); the same size when it already fits.
/// </summary>
public static (int Width, int Height) FitWithin(int width, int height, int longSide)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(longSide);
var scale = Math.Min(1.0, (double)longSide / Math.Max(width, height));
return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
}
private static void Run(RgbaImage source, RgbaImage target, ResampleOptions options)
{
var premultiply = !source.IsOpaque();
var linear = options.LinearLight;
var horizontal = Weights.Build(source.Width, target.Width, options.Filter);
var vertical = Weights.Build(source.Height, target.Height, options.Filter);
var sw = source.Width;
var dw = target.Width;
var capacity = Math.Min(vertical.MaxTaps + 1, source.Height);
var pool = ArrayPool<Vector4>.Shared;
var input = pool.Rent(sw);
var accumulator = pool.Rent(dw);
var ring = new Vector4[capacity][];
var ringRow = new int[capacity];
try
{
for (var i = 0; i < capacity; i++)
{
ring[i] = pool.Rent(dw);
ringRow[i] = -1;
}
var toFloat = linear ? Tables.SrgbToLinear : Tables.Identity;
for (var y = 0; y < target.Height; y++)
{
var start = vertical.Start[y];
var count = vertical.Count[y];
var acc = accumulator.AsSpan(0, dw);
acc.Clear();
for (var k = 0; k < count; k++)
{
var sy = start + k;
var slot = sy % capacity;
if (ringRow[slot] != sy)
{
LoadRow(source.GetRow(sy), input.AsSpan(0, sw), toFloat, premultiply);
FilterRow(input.AsSpan(0, sw), ring[slot].AsSpan(0, dw), horizontal);
ringRow[slot] = sy;
}
var weight = vertical.Values[(y * vertical.MaxTaps) + k];
if (weight != 0)
{
AddScaled(acc, ring[slot].AsSpan(0, dw), weight);
}
}
StoreRow(acc, target.GetRow(y), linear, premultiply);
}
}
finally
{
pool.Return(input);
pool.Return(accumulator);
foreach (var row in ring)
{
if (row is not null)
{
pool.Return(row);
}
}
}
}
private static void LoadRow(ReadOnlySpan<byte> row, Span<Vector4> output, float[] toFloat, bool premultiply)
{
for (var x = 0; x < output.Length; x++)
{
var i = x * 4;
var a = row[i + 3] * (1f / 255f);
var value = new Vector4(toFloat[row[i]], toFloat[row[i + 1]], toFloat[row[i + 2]], a);
if (premultiply)
{
value = new Vector4(value.X * a, value.Y * a, value.Z * a, a);
}
output[x] = value;
}
}
private static void FilterRow(ReadOnlySpan<Vector4> input, Span<Vector4> output, Weights weights)
{
var taps = weights.MaxTaps;
var values = weights.Values;
for (var x = 0; x < output.Length; x++)
{
var start = weights.Start[x];
var count = weights.Count[x];
var w = values.AsSpan(x * taps, count);
var src = input.Slice(start, count);
var sum = Vector4.Zero;
for (var k = 0; k < w.Length; k++)
{
sum += src[k] * w[k];
}
output[x] = sum;
}
}
private static void AddScaled(Span<Vector4> accumulator, ReadOnlySpan<Vector4> row, float weight)
{
var acc = MemoryMarshal.Cast<Vector4, float>(accumulator);
var add = MemoryMarshal.Cast<Vector4, float>(row);
var i = 0;
if (Vector.IsHardwareAccelerated && acc.Length >= Vector<float>.Count)
{
var w = new Vector<float>(weight);
var accVectors = MemoryMarshal.Cast<float, Vector<float>>(acc);
var addVectors = MemoryMarshal.Cast<float, Vector<float>>(add);
for (var v = 0; v < accVectors.Length; v++)
{
accVectors[v] += addVectors[v] * w;
}
i = accVectors.Length * Vector<float>.Count;
}
for (; i < acc.Length; i++)
{
acc[i] += add[i] * weight;
}
}
private static void StoreRow(ReadOnlySpan<Vector4> row, Span<byte> output, bool linear, bool premultiplied)
{
for (var x = 0; x < row.Length; x++)
{
var v = row[x];
var a = Math.Clamp(v.W, 0f, 1f);
var o = x * 4;
if (premultiplied)
{
if (v.W <= 0f)
{
output[o] = 0;
output[o + 1] = 0;
output[o + 2] = 0;
output[o + 3] = 0;
continue;
}
// Divided by the alpha as filtered, before clamping: the ratio of colour to alpha is what was averaged,
// and Lanczos overshooting at a hard edge must not tint the colour.
var inverse = 1f / v.W;
v = new Vector4(v.X * inverse, v.Y * inverse, v.Z * inverse, a);
}
output[o] = ToByte(v.X, linear);
output[o + 1] = ToByte(v.Y, linear);
output[o + 2] = ToByte(v.Z, linear);
output[o + 3] = (byte)((a * 255f) + 0.5f);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte ToByte(float value, bool linear)
{
if (linear)
{
var index = (int)((value * (Tables.LinearSteps - 1)) + 0.5f);
return Tables.LinearToSrgb[Math.Clamp(index, 0, Tables.LinearSteps - 1)];
}
var v = (int)(value + 0.5f);
return (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
}
/// <summary>
/// The weights of one direction: for each target index the first source index, how many follow and their
/// weights (summing to 1), <see cref="MaxTaps"/> slots per target index. Source indices outside the image are
/// folded onto the nearest edge pixel.
/// </summary>
private sealed class Weights
{
private Weights(int[] start, int[] count, float[] values, int maxTaps)
{
Start = start;
Count = count;
Values = values;
MaxTaps = maxTaps;
}
public int[] Start { get; }
public int[] Count { get; }
public float[] Values { get; }
public int MaxTaps { get; }
public static Weights Build(int sourceLength, int targetLength, ResampleFilter filter)
{
var scale = (double)sourceLength / targetLength;
var stretch = Math.Max(1.0, scale);
var area = filter == ResampleFilter.Area;
double radius = area ? (scale > 1 ? 0.5 * scale : 1.0) : 3.0 * stretch;
var maxTaps = Math.Min(sourceLength, (int)Math.Ceiling(2 * radius) + 2);
var start = new int[targetLength];
var count = new int[targetLength];
var values = new float[targetLength * maxTaps];
Span<double> raw = maxTaps <= 1024 ? stackalloc double[maxTaps] : new double[maxTaps];
for (var t = 0; t < targetLength; t++)
{
var centre = ((t + 0.5) * scale) - 0.5;
var first = (int)Math.Floor(centre - radius) + 1;
var last = (int)Math.Ceiling(centre + radius) - 1;
if (area && scale > 1)
{
// Exact coverage of [t·scale, (t+1)·scale) by the source cells.
var from = t * scale;
var to = from + scale;
first = (int)Math.Floor(from);
last = Math.Min(sourceLength - 1, (int)Math.Ceiling(to) - 1);
}
var lo = Math.Max(first, 0);
var hi = Math.Min(last, sourceLength - 1);
if (hi < lo)
{
lo = hi = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
}
var n = hi - lo + 1;
if (n > maxTaps)
{
// Only at the far edges of a very small source; keep the taps nearest the centre.
var middle = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
lo = Math.Clamp(middle - (maxTaps / 2), 0, sourceLength - maxTaps);
hi = lo + maxTaps - 1;
n = maxTaps;
}
raw[..n].Clear();
double sum = 0;
for (var s = first; s <= last; s++)
{
double weight;
if (area && scale > 1)
{
var from = t * scale;
weight = Math.Min(from + scale, s + 1) - Math.Max(from, s);
}
else if (area)
{
weight = Math.Max(0, 1 - Math.Abs(s - centre));
}
else
{
weight = Lanczos3((s - centre) / stretch);
}
if (weight == 0)
{
continue;
}
var index = Math.Clamp(s, lo, hi) - lo;
raw[index] += weight;
sum += weight;
}
if (sum == 0)
{
raw[Math.Clamp((int)Math.Round(centre), lo, hi) - lo] = 1;
sum = 1;
}
start[t] = lo;
count[t] = n;
var row = values.AsSpan(t * maxTaps, maxTaps);
for (var i = 0; i < n; i++)
{
row[i] = (float)(raw[i] / sum);
}
}
return new Weights(start, count, values, maxTaps);
}
private static double Lanczos3(double x)
{
x = Math.Abs(x);
if (x < 1e-9)
{
return 1;
}
if (x >= 3)
{
return 0;
}
var px = Math.PI * x;
return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
}
}
/// <summary>Conversions between 8-bit sRGB and linear light (IEC 61966-2-1).</summary>
internal static class Tables
{
public const int LinearSteps = 4096;
public static readonly float[] Identity = BuildIdentity();
public static readonly float[] SrgbToLinear = BuildToLinear();
public static readonly byte[] LinearToSrgb = BuildToSrgb();
private static float[] BuildIdentity()
{
var table = new float[256];
for (var i = 0; i < table.Length; i++)
{
table[i] = i;
}
return table;
}
private static float[] BuildToLinear()
{
var table = new float[256];
for (var i = 0; i < table.Length; i++)
{
var c = i / 255.0;
table[i] = (float)(c <= 0.04045 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4));
}
return table;
}
private static byte[] BuildToSrgb()
{
var table = new byte[LinearSteps];
for (var i = 0; i < table.Length; i++)
{
var l = i / (double)(LinearSteps - 1);
var c = l <= 0.0031308 ? l * 12.92 : (1.055 * Math.Pow(l, 1 / 2.4)) - 0.055;
table[i] = (byte)Math.Clamp((int)Math.Round(c * 255), 0, 255);
}
return table;
}
}
}
+44
View File
@@ -73,6 +73,50 @@ internal static class JpegDct
}
}
/// <summary>
/// Like <see cref="Inverse"/>, but writes the block reduced by 2^<paramref name="shift"/> (1 to 3) in each
/// direction: every output sample is the rounded mean of a square of the full block's samples. At an eighth that
/// mean is the DC term alone (S00 / 8 plus the level shift: the AC basis functions sum to zero over the block), so
/// no transform is computed.
/// </summary>
public static void InverseReduced(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit, int shift)
{
var max = precision == 12 ? 4095 : 255;
if (shift >= 3)
{
var level = precision == 12 ? 2048 : 128;
var value = (int)Math.Floor((block[0] * quantization[0] / 8.0) + level + 0.5);
value = Math.Clamp(value, 0, max);
output[0] = precision == 12 ? to8Bit[value] : (byte)value;
return;
}
Span<byte> full = stackalloc byte[64];
Inverse(block, quantization, full, 8, precision, to8Bit);
var n = 8 >> shift;
var side = 1 << shift;
var area = side * side;
var half = area >> 1;
for (var y = 0; y < n; y++)
{
var o = output.Slice(y * stride, n);
for (var x = 0; x < n; x++)
{
var sum = 0;
for (var dy = 0; dy < side; dy++)
{
var row = full.Slice((((y * side) + dy) * 8) + (x * side), side);
for (var dx = 0; dx < side; dx++)
{
sum += row[dx];
}
}
o[x] = (byte)((sum + half) / area);
}
}
}
/// <summary>
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
/// not yet quantized.
@@ -49,6 +49,23 @@ public static class JpegDecoder
return image;
}
/// <summary>
/// Decodes a JPEG reduced by 2^<paramref name="reduction"/> in each direction (0 full size, 1 half, 2 quarter,
/// 3 eighth; sizes rounded up), with what <see cref="Identify"/> returns (the full size): each 8×8 block gives the
/// means of its squares of samples, which saves memory and, at an eighth, the whole inverse transform. Lossless
/// files are always decoded at full size: check the size of the result.
/// </summary>
public static RgbaImage DecodeReduced(ReadOnlyMemory<byte> data, int reduction, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
{
ArgumentOutOfRangeException.ThrowIfNegative(reduction);
ArgumentOutOfRangeException.ThrowIfGreaterThan(reduction, 3);
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true) { ScaleShift = reduction };
file.Run();
var image = file.Render(pooled);
info = file.ToInfo();
return image;
}
/// <summary>
/// The quantized DCT coefficients of every block of a DCT-based JPEG, as they stand after the last scan, with the
/// frame parameters: what tests compare between encodings of the same image (sequential, progressive, restart).
@@ -66,7 +66,7 @@ internal sealed partial class JpegFile
DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], 1, 63, 0, block, zigzag);
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
{
JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
TransformBlock(c, plane, block, bx, by, to8);
}
break;
@@ -92,7 +92,7 @@ internal sealed partial class JpegFile
DecodeSequential(ref reader, dcTables[ci]!, acTables[ci]!, ref c.DcPredictor, block, zigzag);
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
{
JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
TransformBlock(c, plane, block, bx, by, to8);
}
break;
+14 -11
View File
@@ -46,17 +46,19 @@ internal sealed partial class JpegFile
public RgbaImage Render(bool pooled)
{
var image = RgbaImage.Create(Width, Height, _limits, pooled);
var width = OutputWidth;
var height = OutputHeight;
var image = RgbaImage.Create(width, height, _limits, pooled);
var buffers = new byte[Components.Length][];
try
{
for (var i = 0; i < buffers.Length; i++)
{
buffers[i] = ArrayPool<byte>.Shared.Rent(Width + 1);
buffers[i] = ArrayPool<byte>.Shared.Rent(width + 1);
}
var model = Colors;
for (var y = 0; y < Height; y++)
for (var y = 0; y < height; y++)
{
var output = image.GetRow(y);
var c0 = UpsampleRow(Components[0], y, buffers[0]);
@@ -103,7 +105,7 @@ internal sealed partial class JpegFile
}
/// <summary>
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="Width"/> samples. A ratio
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="OutputWidth"/> samples. A ratio
/// of 2 to the largest sampling factor uses the triangular ("fancy") filter of the JFIF siting: each output sample
/// weighs 3/4 the nearest input sample and 1/4 the next one, the edges repeating; other ratios repeat samples.
/// </summary>
@@ -111,22 +113,23 @@ internal sealed partial class JpegFile
{
var plane = c.Plane!;
var stride = c.PlaneStride;
var width = Width;
var width = OutputWidth;
if (c.H == MaxH && c.V == MaxV)
{
return plane.AsSpan(y * stride, width);
}
var output = buffer.AsSpan(0, width);
var lastX = c.Width - 1;
var lastY = c.Height - 1;
var componentWidth = Reduce(c.Width);
var lastX = componentWidth - 1;
var lastY = Reduce(c.Height) - 1;
var integral = MaxH % c.H == 0 && MaxV % c.V == 0;
var hr = MaxH / c.H;
var vr = MaxV / c.V;
if (!integral || hr > 2 || vr > 2)
{
var sy = Math.Min((int)((long)y * c.V / MaxV), lastY);
var row = plane.AsSpan(sy * stride, c.Width);
var row = plane.AsSpan(sy * stride, componentWidth);
for (var x = 0; x < width; x++)
{
output[x] = row[Math.Min((int)((long)x * c.H / MaxH), lastX)];
@@ -138,7 +141,7 @@ internal sealed partial class JpegFile
if (vr == 1)
{
// hr == 2.
var row = plane.AsSpan(y * stride, c.Width);
var row = plane.AsSpan(y * stride, componentWidth);
for (var i = 0; i <= lastX; i++)
{
var three = row[i] * 3;
@@ -155,8 +158,8 @@ internal sealed partial class JpegFile
var cy = y >> 1;
var farY = (y & 1) == 0 ? Math.Max(cy - 1, 0) : Math.Min(cy + 1, lastY);
var near = plane.AsSpan(cy * stride, c.Width);
var far = plane.AsSpan(farY * stride, c.Width);
var near = plane.AsSpan(cy * stride, componentWidth);
var far = plane.AsSpan(farY * stride, componentWidth);
if (hr == 1)
{
var bias = (y & 1) == 0 ? 1 : 2;
+46 -5
View File
@@ -79,6 +79,7 @@ internal sealed partial class JpegFile : IDisposable
private bool _allocated;
private bool _pooledArrays;
private int _scaleShift;
private int _scanCount;
private int _sosEnd;
@@ -119,6 +120,25 @@ internal sealed partial class JpegFile : IDisposable
public JpegComponent[] Components { get; private set; } = [];
/// <summary>
/// The reduction of a DCT image decoded to samples, as a power of two (0 full size, 1 half, 2 quarter, 3 eighth):
/// each 8×8 block gives (8 &gt;&gt; shift)² samples, the means of its squares of samples (only its DC term at an
/// eighth). Set before <see cref="Run"/>; a lossless file is always decoded at full size.
/// </summary>
public int ScaleShift
{
get => _scaleShift;
set => _scaleShift = Math.Clamp(value, 0, 3);
}
/// <summary>Width of the decoded image: <see cref="Width"/> reduced by <see cref="ScaleShift"/>, rounded up.</summary>
public int OutputWidth => Reduce(Width);
/// <summary>Height of the decoded image: <see cref="Height"/> reduced by <see cref="ScaleShift"/>, rounded up.</summary>
public int OutputHeight => Reduce(Height);
private int Reduce(int length) => (length + (1 << _scaleShift) - 1) >> _scaleShift;
public int MaxH { get; private set; }
public int MaxV { get; private set; }
@@ -767,14 +787,19 @@ internal sealed partial class JpegFile : IDisposable
private void Allocate()
{
_limits.CheckSize(Width, Height);
if (Lossless || _mode != Mode.Pixels)
{
_scaleShift = 0;
}
_limits.CheckSize(OutputWidth, OutputHeight);
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
long bytes = 0;
foreach (var c in Components)
{
var unit = Lossless ? 1 : 8;
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
bytes += samples;
bytes += samples >> (2 * _scaleShift);
if (keepCoefficients && !Lossless)
{
bytes += samples * 2;
@@ -792,11 +817,12 @@ internal sealed partial class JpegFile : IDisposable
foreach (var c in Components)
{
var unit = Lossless ? 1 : 8;
c.PlaneStride = c.PaddedUnitsWide * unit;
var planeUnit = unit >> _scaleShift;
c.PlaneStride = c.PaddedUnitsWide * planeUnit;
var samples = c.PlaneStride * c.PaddedUnitsHigh * unit;
if (_mode == Mode.Pixels)
{
c.Plane = ArrayPool<byte>.Shared.Rent(samples);
c.Plane = ArrayPool<byte>.Shared.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit);
}
if (Lossless)
@@ -984,11 +1010,26 @@ internal sealed partial class JpegFile : IDisposable
for (var bx = 0; bx < c.UnitsWide; bx++)
{
var block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64);
JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8);
TransformBlock(c, plane, block, bx, by, to8);
}
}
}
/// <summary>The samples of one block into the plane of its component, at the scale of <see cref="ScaleShift"/>.</summary>
private void TransformBlock(JpegComponent c, byte[] plane, ReadOnlySpan<short> block, int bx, int by, ReadOnlySpan<byte> to8)
{
var n = 8 >> _scaleShift;
var output = plane.AsSpan((by * n * c.PlaneStride) + (bx * n));
if (_scaleShift == 0)
{
JpegDct.Inverse(block, c.Quantization, output, c.PlaneStride, Precision, to8);
}
else
{
JpegDct.InverseReduced(block, c.Quantization, output, c.PlaneStride, Precision, to8, _scaleShift);
}
}
/// <summary>12-bit samples to 8 bits, rounded.</summary>
private static class Twelve
{
+73
View File
@@ -59,6 +59,12 @@ public sealed record PngEncoderOptions
/// <summary>XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».</summary>
public string? Xmp { get; init; }
/// <summary>
/// Texts to write, in order, after the pixels: a tEXt chunk when keyword and text are Latin-1 and there is no
/// language, an uncompressed iTXt chunk otherwise. Keywords: 1 to 79 printable Latin-1 characters.
/// </summary>
public IReadOnlyList<ImageText> Texts { get; init; } = [];
}
/// <summary>
@@ -85,6 +91,13 @@ public static class PngEncoder
options ??= PngEncoderOptions.Default;
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
var iccName = options.IccProfile is null ? null : IccName(options.IccProfileName);
foreach (var text in options.Texts)
{
if (!IsValidKeyword(text.Keyword))
{
throw new ArgumentException($"«{text.Keyword}» is not a valid PNG keyword.", nameof(options));
}
}
var alpha = options.ColorMode switch
{
@@ -143,6 +156,11 @@ public static class PngEncoder
idat.Complete();
}
foreach (var text in options.Texts)
{
WriteText(output, text);
}
WriteChunk(output, "IEND"u8, []);
}
@@ -295,6 +313,61 @@ public static class PngEncoder
return span.ToArray();
}
/// <summary>Whether <paramref name="keyword"/> can name a PNG text chunk: 1-79 printable Latin-1, no outer or double spaces.</summary>
public static bool IsValidKeyword(string keyword)
{
if (string.IsNullOrEmpty(keyword) || keyword.Length > 79 || keyword[0] == ' ' || keyword[^1] == ' ' || keyword.Contains(" ", StringComparison.Ordinal))
{
return false;
}
foreach (var c in keyword)
{
if (c is < ' ' or (> '~' and < '¡') or > 'ÿ')
{
return false;
}
}
return true;
}
private static void WriteText(Stream output, ImageText text)
{
using var payload = new MemoryStream();
payload.Write(Encoding.Latin1.GetBytes(text.Keyword));
payload.WriteByte(0);
var latin1 = text.Language.Length == 0 && text.TranslatedKeyword.Length == 0 && IsLatin1(text.Text);
if (latin1)
{
payload.Write(Encoding.Latin1.GetBytes(text.Text));
WriteChunk(output, "tEXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
return;
}
payload.WriteByte(0); // not compressed
payload.WriteByte(0); // method
payload.Write(Encoding.ASCII.GetBytes(text.Language));
payload.WriteByte(0);
payload.Write(Encoding.UTF8.GetBytes(text.TranslatedKeyword));
payload.WriteByte(0);
payload.Write(Encoding.UTF8.GetBytes(text.Text));
WriteChunk(output, "iTXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
}
private static bool IsLatin1(string text)
{
foreach (var c in text)
{
if (c > '\u00FF' || c == '\0')
{
return false;
}
}
return true;
}
private static byte[] IccName(string name)
{
if (name.Length is < 1 or > 79 || name[0] == ' ' || name[^1] == ' ')