Febe deve leggere e scrivere JPEG senza SkiaSharp né altri componenti esterni (decisione del 18 novembre 2026), quindi il codec è scritto dalla specifica ITU-T T.81. Lettore (JpegDecoder): sequenziale di base ed esteso, progressivo (selezione spettrale e approssimazioni successive), senza perdita (predittori 1-7), ognuno con Huffman e con codifica aritmetica; 8 e 12 bit (senza perdita da 2 a 16); qualunque campionamento, ripristino, DNL; grigio, YCbCr, RGB, CMYK e YCCK con il segmento Adobe. IDCT esatta e crominanza con il filtro triangolare. EXIF, ICC a pezzi, XMP e commenti; l'orientamento EXIF va in ImageMetadata.Orientation (anche per PNG) e non si applica ai pixel. I file gerarchici e quelli a 2 componenti si rifiutano come formato non letto; i dati troncati dentro una scansione sono un file danneggiato. Scrittore (JpegEncoder): sequenziale di base, qualità 1-100 sulle tabelle dell'allegato K, 4:2:0, 4:4:4 e grigio, intervallo di ripristino, EXIF, ICC, XMP e commenti. Prove: contro le letture di SkiaSharp i JPEG dell'insieme di riferimento stanno fra 59 e 67 dB di PSNR per canale, scarto massimo 3 (soglia 40 dB e 0,1% di pixel oltre 16). Un codificatore di prova scrive gli stessi coefficienti in progressivo, aritmetico, 12 bit, con ripristino, scansioni separate e DNL, e il lettore deve ridarli identici; senza perdita si confronta campione per campione. Più andata e ritorno dello scrittore, file danneggiati e mutazioni casuali con seme fisso. La facciata ImageDecoder ora legge i JPEG. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
354 lines
13 KiB
C#
354 lines
13 KiB
C#
using Febe.Core.Codecs.Images;
|
||
|
||
namespace Febe.Tests.Imaging;
|
||
|
||
/// <summary>
|
||
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
|
||
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
|
||
/// </summary>
|
||
[TestClass]
|
||
public sealed class JpegMalformedTests
|
||
{
|
||
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
|
||
|
||
private static byte[] Baseline(int width = 37, int height = 21, int restart = 0) =>
|
||
JpegEncoder.Encode(TestImages.Gradient(width, height, 3), new JpegEncoderOptions { Quality = 80, RestartInterval = restart });
|
||
|
||
[TestMethod]
|
||
public void ABaselineFileCutInsideItsScanIsDamaged()
|
||
{
|
||
foreach (var restart in new[] { 0, 2 })
|
||
{
|
||
var file = Baseline(restart: restart);
|
||
// Identify needs the headers up to the frame, not the scan.
|
||
var sof = SegmentOffset(file, 0xC0);
|
||
var frameEnd = sof + 2 + ((file[sof + 2] << 8) | file[sof + 3]);
|
||
using var whole = JpegDecoder.Decode(file);
|
||
for (var length = 0; length < file.Length - 2; length++)
|
||
{
|
||
var cut = file[..length];
|
||
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte");
|
||
if (length < frameEnd)
|
||
{
|
||
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Identify(cut), $"Identify, {length} byte");
|
||
}
|
||
}
|
||
|
||
// Only the EOI missing: complete scans are accepted.
|
||
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
|
||
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
|
||
}
|
||
}
|
||
|
||
[TestMethod]
|
||
public void BytesAfterTheEndAreIgnored()
|
||
{
|
||
var file = Baseline();
|
||
using var whole = JpegDecoder.Decode(file);
|
||
var random = new Random(5);
|
||
var tail = new byte[300];
|
||
random.NextBytes(tail);
|
||
byte[] longer = [.. file, .. tail];
|
||
using var withTail = JpegDecoder.Decode(longer);
|
||
ImageAssert.AreEqual(whole, withTail, "byte dopo EOI");
|
||
}
|
||
|
||
[TestMethod]
|
||
public void FillBytesAndGarbageBetweenSegmentsAreSkipped()
|
||
{
|
||
var file = Baseline();
|
||
using var whole = JpegDecoder.Decode(file);
|
||
var dqt = SegmentOffset(file, 0xDB);
|
||
|
||
// T.81 B.1.1.2: any marker may be preceded by fill bytes 0xFF.
|
||
byte[] padded = [.. file[..dqt], 0xFF, 0xFF, 0xFF, .. file[dqt..]];
|
||
using var filled = JpegDecoder.Decode(padded);
|
||
ImageAssert.AreEqual(whole, filled, "byte di riempimento");
|
||
}
|
||
|
||
[TestMethod]
|
||
public void WithoutDhtTheAnnexKTablesAreUsed()
|
||
{
|
||
// Motion JPEG frames omit DHT and rely on the tables of Annex K, which are the ones our encoder writes.
|
||
var file = Baseline();
|
||
using var whole = JpegDecoder.Decode(file);
|
||
var stripped = RemoveSegments(file, 0xC4);
|
||
Assert.IsLessThan(file.Length, stripped.Length);
|
||
using var decoded = JpegDecoder.Decode(stripped);
|
||
ImageAssert.AreEqual(whole, decoded, "senza DHT");
|
||
}
|
||
|
||
[TestMethod]
|
||
public void HierarchicalAndTwoComponentFilesAreNotSupported()
|
||
{
|
||
var file = Baseline();
|
||
foreach (var marker in new byte[] { 0xC5, 0xC6, 0xC7, 0xCD, 0xCE, 0xCF })
|
||
{
|
||
var changed = file.ToArray();
|
||
changed[SegmentOffset(file, 0xC0) + 1] = marker;
|
||
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(changed), $"SOF 0x{marker:X2}");
|
||
}
|
||
|
||
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||
var samples = new int[16 * 16];
|
||
var two = JpegEncoder.TransformPlanes(16, 16, 8, [(1, 1, 1, 0, samples), (2, 1, 1, 0, samples)], [fine], 0xC1);
|
||
var twoFile = JpegTestEncoder.Write(two, new JpegTestOptions());
|
||
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(twoFile));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void DamagedHeadersAreRefused()
|
||
{
|
||
var file = Baseline();
|
||
var sof = SegmentOffset(file, 0xC0);
|
||
var sos = SegmentOffset(file, 0xDA);
|
||
|
||
// Width 0.
|
||
var zeroWidth = file.ToArray();
|
||
zeroWidth[sof + 7] = 0;
|
||
zeroWidth[sof + 8] = 0;
|
||
AssertDamaged(zeroWidth, "larghezza 0");
|
||
|
||
// Height 0 and no DNL segment after the first scan.
|
||
var zeroHeight = file.ToArray();
|
||
zeroHeight[sof + 5] = 0;
|
||
zeroHeight[sof + 6] = 0;
|
||
AssertDamaged(zeroHeight, "altezza 0 senza DNL");
|
||
|
||
// Precision 7.
|
||
var precision = file.ToArray();
|
||
precision[sof + 4] = 7;
|
||
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(precision), "precisione 7");
|
||
|
||
// Sampling factor 0 and 5.
|
||
foreach (var factor in new byte[] { 0x01, 0x10, 0x51, 0x15 })
|
||
{
|
||
var sampling = file.ToArray();
|
||
sampling[sof + 11] = factor;
|
||
AssertDamaged(sampling, $"campionamento 0x{factor:X2}");
|
||
}
|
||
|
||
// A scan naming a component the frame does not have.
|
||
var unknown = file.ToArray();
|
||
unknown[sos + 5] = 99;
|
||
AssertDamaged(unknown, "componente sconosciuto");
|
||
|
||
// A scan referring to a Huffman table that was never defined (slot 3).
|
||
var table = file.ToArray();
|
||
table[sos + 6] = 0x33;
|
||
AssertDamaged(table, "tabella di Huffman assente");
|
||
|
||
// No quantization table.
|
||
AssertDamaged(RemoveSegments(file, 0xDB), "senza DQT");
|
||
|
||
// A Huffman table with more codes than its lengths allow (two codes of length 1, then more).
|
||
var dht = SegmentOffset(file, 0xC4);
|
||
var badTable = file.ToArray();
|
||
badTable[dht + 5] = 3;
|
||
AssertDamaged(badTable, "tabella di Huffman impossibile");
|
||
|
||
// A segment length that runs past the end.
|
||
var longSegment = file.ToArray();
|
||
longSegment[sof + 2] = 0xFF;
|
||
AssertDamaged(longSegment, "segmento oltre la fine");
|
||
|
||
// No SOI, no frame, no scan.
|
||
AssertDamaged(file[2..], "senza SOI");
|
||
AssertDamaged([0xFF, 0xD8, 0xFF, 0xD9], "solo SOI ed EOI");
|
||
AssertDamaged(file[..sos], "senza scansioni");
|
||
}
|
||
|
||
[TestMethod]
|
||
public void TheLimitsAreEnforcedBeforeDecoding()
|
||
{
|
||
var file = Baseline(200, 150);
|
||
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 }));
|
||
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 }));
|
||
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWorkingBytes = 40_000 }));
|
||
|
||
// A header claiming 65535 × 65535 is refused at once, not after allocating.
|
||
var huge = file.ToArray();
|
||
var sof = SegmentOffset(file, 0xC0);
|
||
huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
|
||
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(huge, Small));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void AnIccProfileWithAMissingChunkIsDropped()
|
||
{
|
||
var icc = new byte[140_000];
|
||
new Random(8).NextBytes(icc);
|
||
var file = JpegEncoder.Encode(TestImages.Gradient(10, 10, 1), new JpegEncoderOptions { IccProfile = icc });
|
||
CollectionAssert.AreEqual(icc, JpegDecoder.Identify(file).Metadata.IccProfile);
|
||
|
||
// Remove the second of three APP2 chunks.
|
||
var second = SegmentOffsets(file, 0xE2)[1];
|
||
var length = (file[second + 2] << 8) | file[second + 3];
|
||
byte[] missing = [.. file[..second], .. file[(second + 2 + length)..]];
|
||
Assert.IsNull(JpegDecoder.Identify(missing).Metadata.IccProfile);
|
||
using var image = JpegDecoder.Decode(missing);
|
||
Assert.AreEqual(10, image.Width);
|
||
}
|
||
|
||
[TestMethod]
|
||
public void OtherFormatsAreNotJpeg()
|
||
{
|
||
var png = ReferenceImages.Of(ReferenceFormat.Png).First().ReadInput();
|
||
Assert.IsFalse(JpegDecoder.IsJpeg(png));
|
||
Assert.IsFalse(JpegDecoder.IsJpeg([0xFF, 0xD8]));
|
||
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(png));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void ChangedBytesInEveryCodingNeverBreakTheDecoder()
|
||
{
|
||
using var image = TestImages.Gradient(45, 30, 6);
|
||
var coefficients = JpegEncoder.Transform(image, new JpegEncoderOptions { Quality = 75 });
|
||
var lossless = new List<(int Id, int H, int V, int[] Samples)>
|
||
{
|
||
(1, 2, 2, Enumerable.Range(0, 45 * 30).Select(i => i % 251).ToArray()),
|
||
(2, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 13).ToArray()),
|
||
(3, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 7).ToArray()),
|
||
};
|
||
var files = new (string Name, byte[] File)[]
|
||
{
|
||
("progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Progressive = true, RestartInterval = 3 })),
|
||
("aritmetico", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 4 })),
|
||
("aritmetico progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true })),
|
||
("DNL", JpegTestEncoder.Write(coefficients, new JpegTestOptions { HeightInDnl = true })),
|
||
("senza perdita", JpegTestEncoder.WriteLossless(45, 30, 8, lossless, 4, 0, new JpegTestOptions { RestartInterval = 7 })),
|
||
("senza perdita aritmetico", JpegTestEncoder.WriteLossless(45, 30, 12, lossless, 7, 1, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic })),
|
||
};
|
||
|
||
var random = new Random(2026);
|
||
foreach (var (name, file) in files)
|
||
{
|
||
using (JpegDecoder.Decode(file, Small))
|
||
{
|
||
}
|
||
|
||
for (var i = 0; i < 150; i++)
|
||
{
|
||
var mutated = Mutate(file, random);
|
||
TryDecode(mutated, $"{name}, modifica {i}");
|
||
}
|
||
|
||
// Every cut of the file, as the network would leave it.
|
||
for (var length = 0; length < file.Length; length += 1 + (file.Length / 200))
|
||
{
|
||
TryDecode(file[..length], $"{name}, {length} byte");
|
||
}
|
||
}
|
||
}
|
||
|
||
private static void TryDecode(byte[] bytes, string what)
|
||
{
|
||
try
|
||
{
|
||
using var decoded = JpegDecoder.Decode(bytes, Small);
|
||
Assert.IsGreaterThan(0, decoded.Width, what);
|
||
}
|
||
catch (ImageDecodeException)
|
||
{
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||
}
|
||
|
||
try
|
||
{
|
||
JpegDecoder.Identify(bytes, Small);
|
||
}
|
||
catch (ImageDecodeException)
|
||
{
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||
}
|
||
}
|
||
|
||
private static byte[] Mutate(byte[] original, Random random)
|
||
{
|
||
var bytes = original.ToArray();
|
||
switch (random.Next(3))
|
||
{
|
||
case 0:
|
||
for (var k = random.Next(1, 9); k > 0; k--)
|
||
{
|
||
bytes[random.Next(2, bytes.Length)] = (byte)random.Next(256);
|
||
}
|
||
|
||
return bytes;
|
||
|
||
case 1:
|
||
// Headers: the first segments hold the tables and the frame.
|
||
bytes[random.Next(2, Math.Min(bytes.Length, 700))] = (byte)(random.Next(3) switch { 0 => 0, 1 => 0xFF, _ => random.Next(256) });
|
||
return bytes;
|
||
|
||
default:
|
||
var start = random.Next(2, bytes.Length);
|
||
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
|
||
for (var k = 0; k < length; k++)
|
||
{
|
||
bytes[start + k] ^= 0x5A;
|
||
}
|
||
|
||
return bytes;
|
||
}
|
||
}
|
||
|
||
private static void AssertDamaged(byte[] file, string what)
|
||
{
|
||
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
|
||
Assert.IsNotInstanceOfType<ImageLimitException>(error, what);
|
||
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what);
|
||
}
|
||
|
||
/// <summary>Offset of the first marker segment of type <paramref name="marker"/> (the 0xFF byte).</summary>
|
||
private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0];
|
||
|
||
private static List<int> SegmentOffsets(byte[] file, int marker)
|
||
{
|
||
var found = new List<int>();
|
||
var pos = 2;
|
||
while (pos + 4 <= file.Length && file[pos] == 0xFF)
|
||
{
|
||
if (file[pos + 1] == marker)
|
||
{
|
||
found.Add(pos);
|
||
}
|
||
|
||
if (file[pos + 1] == 0xDA)
|
||
{
|
||
break;
|
||
}
|
||
|
||
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
|
||
}
|
||
|
||
return found;
|
||
}
|
||
|
||
private static byte[] RemoveSegments(byte[] file, int marker)
|
||
{
|
||
var result = new List<byte>(file.Length);
|
||
result.AddRange(file.AsSpan(0, 2));
|
||
var pos = 2;
|
||
while (file[pos + 1] != 0xDA)
|
||
{
|
||
var length = 2 + ((file[pos + 2] << 8) | file[pos + 3]);
|
||
if (file[pos + 1] != marker)
|
||
{
|
||
result.AddRange(file.AsSpan(pos, length));
|
||
}
|
||
|
||
pos += length;
|
||
}
|
||
|
||
result.AddRange(file.AsSpan(pos));
|
||
return [.. result];
|
||
}
|
||
}
|