using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (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. /// [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(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte"); if (length < frameEnd) { Assert.Throws(() => JpegDecoder.Identify(cut), $"Identify, {length} byte"); } } // Only the EOI missing: incomplete all the same (spec §3), though its size is still read. var withoutEoi = file[..^2]; var error = Assert.Throws(() => JpegDecoder.Decode(withoutEoi), $"senza EOI, ripristino {restart}"); StringAssert.Contains(error.Message, "EOI"); Assert.AreEqual((whole.Width, whole.Height), (JpegDecoder.Identify(withoutEoi).Width, JpegDecoder.Identify(withoutEoi).Height)); } } [TestMethod] public void AFileCutAfterItsHeadersFailsAtTheFirstMcuRow() { // Headers of 8192×8192 (64 megapixels, within the default limits) and not one byte of the scan. The reader // gives zero bits past the end, which are valid codes of the Annex K tables, so before the check per MCU row // the decoder went through all 262,144 MCUs (seconds of IDCT) before failing; now it stops after one row. foreach (var lossless in new[] { false, true }) { var file = lossless ? JpegTestEncoder.WriteLossless(16, 16, 8, [(1, 1, 1, new int[256])], 1, 0, new JpegTestOptions()) : Baseline(16, 16); var sof = SegmentOffset(file, lossless ? 0xC3 : 0xC0); var sos = SegmentOffset(file, 0xDA); var headers = file[..(sos + 2 + ((file[sos + 2] << 8) | file[sos + 3]))]; headers[sof + 5] = headers[sof + 7] = 0x20; headers[sof + 6] = headers[sof + 8] = 0x00; var clock = System.Diagnostics.Stopwatch.StartNew(); var error = Assert.Throws(() => JpegDecoder.Decode(headers), lossless ? "senza perdita" : "base"); clock.Stop(); StringAssert.Contains(error.Message, "troncato"); // Planes of 64 MB are still allocated; decoding every MCU took several seconds even in Release. Assert.IsLessThan(2000, clock.ElapsedMilliseconds, $"{(lossless ? "senza perdita" : "base")}: {clock.ElapsedMilliseconds} ms"); } } [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(() => 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(() => 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(() => 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; the total stays that of the segment's values, so // the error is the oversubscription itself and not a truncated segment. var dht = SegmentOffset(file, 0xC4); var badTable = file.ToArray(); // The luminance DC table counts 0,1,5,1,1,...: three codes of length 1, none of length 2, three of length 3. badTable[dht + 5] = 3; badTable[dht + 6] = 0; badTable[dht + 7] = 3; AssertOversubscribed(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 OversubscribedHuffmanTablesAreRefusedAtEveryLength() { // One code of each length below L leaves room for two codes of length L; three overflow it. The symbols // match the counts, so only the oversubscription can be at fault. Lengths up to 9 used to index past the // lookup table and threw ArgumentOutOfRangeException. for (var length = 1; length <= 16; length++) { var counts = new byte[16]; for (var shorter = 1; shorter < length; shorter++) { counts[shorter - 1] = 1; } counts[length - 1] = 3; Assert.IsTrue(Oversubscribed(counts), $"lunghezza {length}"); var values = new byte[length + 2]; for (var i = 0; i < values.Length; i++) { values[i] = (byte)i; } var error = Assert.ThrowsExactly(() => JpegHuffmanTable.Build(counts, values), $"lunghezza {length}"); StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", $"lunghezza {length}"); // Two codes of length L fill the code space exactly and are valid. counts[length - 1] = 2; _ = JpegHuffmanTable.Build(counts, values.AsSpan(0, length + 1)); } // Three codes of length 1 (the case of the review) and a full table that is still valid. var three = new byte[16]; three[0] = 3; Assert.ThrowsExactly(() => JpegHuffmanTable.Build(three, [0, 1, 2])); var full = new byte[16]; full[0] = 1; full[1] = 2; _ = JpegHuffmanTable.Build(full, [0, 1, 2]); } private static bool Oversubscribed(byte[] counts) { long code = 0; for (var length = 1; length <= 16; length++) { code += counts[length - 1]; if (code > 1L << length) { return true; } code <<= 1; } return false; } [TestMethod] public void TheLimitsAreEnforcedBeforeDecoding() { var file = Baseline(200, 150); Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 })); Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 })); Assert.ThrowsExactly(() => 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(() => 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(() => 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(() => JpegDecoder.Decode(file), what); Assert.IsNotInstanceOfType(error, what); Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what); } private static void AssertOversubscribed(byte[] file, string what) { var error = Assert.ThrowsExactly(() => JpegDecoder.Decode(file), what); StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", what); } /// Offset of the first marker segment of type (the 0xFF byte). private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0]; private static List SegmentOffsets(byte[] file, int marker) { var found = new List(); 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(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]; } }