From 6c78b2fdd8ab8312492b01922a01f650e9031f0d Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 22:00:42 +0100 Subject: [PATCH 01/22] fix(images): mask a PNG colour key to the bit depth before writing it The PNG specification stores a grey or RGB tRNS key as 16-bit words whatever the depth and requires a decoder to mask the bits above the depth to 0. The loader rescaled the raw word, so a valid PNG with stray high bits got a Mask entry above 2^BitsPerComponent - 1, which ISO 32000-2 8.9.6.4 forbids, and readers painted the pixel the PNG marks transparent. Mask first, then rescale. Only a PNG whose key has bits above the depth changes output. The audit's pin is replaced by its accept test and the three inputs join the colour-key kinds. --- CHANGELOG.md | 10 ++++++ src/VellumPdf.Kernel/Images/PngImageLoader.cs | 5 +++ .../ConformanceAuditG4Tests.Images.cs | 33 +++++++------------ 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5d1137a1..1c376a14d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -810,6 +810,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **A PNG colour key is masked to the bit depth before it is written (#768).** The PNG + specification stores a grey or RGB `tRNS` key as 16-bit words whatever the depth and has a + decoder mask the bits above the depth to 0. `PngImageLoader` rescaled the raw word, so a valid + PNG whose key held stray high bits was written with a `Mask` entry above + 2^BitsPerComponent - 1, which ISO 32000-2, 8.9.6.4, forbids, and a reader then painted the pixel + the PNG marks transparent. The word is now masked to the depth first. **Deliberate output + change:** the `Mask` array of a PNG whose `tRNS` word has bits above the depth (for example grey + 8-bit with `01 10`, now `[16 16]`); a PNG whose key bits above the depth are zero, a 16-bit PNG + and a PNG with no key write the same bytes as before. + - **A text with U+FEFF no longer gets a ToUnicode value that PDF/A-2u, PDF/A-2a and PDF/UA-1 forbid (#752).** ISO 19005-2, 6.2.11.7.2, and ISO 14289-1, 7.21.7, allow no ToUnicode value of U+0000, U+FEFF or U+FFFE, and veraPDF failed rules 6.2.11.7.2-2 and 7.21.7-2 on a Kernel or Layout diff --git a/src/VellumPdf.Kernel/Images/PngImageLoader.cs b/src/VellumPdf.Kernel/Images/PngImageLoader.cs index f3e51b895..fc26e9960 100644 --- a/src/VellumPdf.Kernel/Images/PngImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/PngImageLoader.cs @@ -462,6 +462,11 @@ private static PdfImageXObject BuildXObject( // • sub-byte greyscale (1/2/4-bit): linearly scaled to 0-255 like UnpackSubByte. // • native 8-bit: the low byte is the exact sample. var raw16 = (int)((transparencyBytes[c * 2] << 8) | transparencyBytes[c * 2 + 1]); + // Below 16 bits only the low bitDepth bits of the word count and a decoder + // masks the rest to 0 (PNG 3rd edition, tRNS). A key written unmasked can fall + // outside 0 to 2^BitsPerComponent - 1, which ISO 32000-2 8.9.6.4 forbids. + if (bitDepth < 16) + raw16 &= (1 << bitDepth) - 1; int maskVal; if (bitsPerComponent == 16) maskVal = raw16; diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 975534845..ce745f24f 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -70,6 +70,10 @@ private static Dictionary BuildKinds() new("png-grey-key8", Png(2, 1, 8, 0, [0x10, 0x80], 2, null, [0, 0x10]), 2, 1, "DeviceGray", 8, "FlateDecode", "1080", Mask: [16, 16]), new("png-grey-key4", Png(2, 1, 4, 0, [0x5A], 1, null, [0, 5]), 2, 1, "DeviceGray", 8, "FlateDecode", "55AA", Mask: [85, 85]), new("png-rgb-key8", Png(2, 1, 8, 2, [255, 0, 0, 0, 255, 0], 6, null, [0, 255, 0, 0, 0, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00", Mask: [255, 255, 0, 0, 0, 0]), + // A tRNS word with bits above the depth: the key is the word masked to the depth. + new("png-grey-key8-stray-bits", Png(2, 1, 8, 0, [0x10, 0x80], 2, null, [0x01, 0x10]), 2, 1, "DeviceGray", 8, "FlateDecode", "1080", Mask: [16, 16]), + new("png-grey-key4-stray-bits", Png(2, 1, 4, 0, [0x5A], 1, null, [0x00, 0x15]), 2, 1, "DeviceGray", 8, "FlateDecode", "55AA", Mask: [85, 85]), + new("png-rgb-key8-stray-bits", Png(2, 1, 8, 2, [255, 0, 0, 0, 255, 0], 6, null, [0x01, 0xFF, 0, 0, 0, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00", Mask: [255, 255, 0, 0, 0, 0]), // JPEG passes through; the frame header decides the colour space. new("jpeg-grey", Jpeg(4, 2, 1), 4, 2, "DeviceGray", 8, "DCTDecode"), @@ -932,36 +936,23 @@ public void Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused public static TheoryData StrayBitKeyNames() => new() { "grey8", "grey4", "rgb8" }; - private static (Kind Kind, int[] Written, int[] Needed) StrayBitKey(string name) => name switch + private static (Kind Kind, int[] Needed) StrayBitKey(string name) => name switch { // PNG 3rd edition, tRNS: for depths below 16 decoders mask the unused high bits to 0 before using the value. - "grey8" => (new Kind("png-key-stray-grey8", Png(2, 1, 8, 0, [0x10, 0x80], 2, null, [0x01, 0x10]), 2, 1, "DeviceGray", - 8, "FlateDecode", "1080"), [272, 272], [16, 16]), - "grey4" => (new Kind("png-key-stray-grey4", Png(2, 1, 4, 0, [0x5A], 1, null, [0x00, 0x15]), 2, 1, "DeviceGray", - 8, "FlateDecode", "55AA"), [357, 357], [85, 85]), - _ => (new Kind("png-key-stray-rgb8", Png(2, 1, 8, 2, [255, 0, 0, 0, 255, 0], 6, null, [0x01, 0xFF, 0, 0, 0, 0]), 2, 1, - "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), [511, 511, 0, 0, 0, 0], [255, 255, 0, 0, 0, 0]), + "grey8" => (KindTable["png-grey-key8-stray-bits"], [16, 16]), + "grey4" => (KindTable["png-grey-key4-stray-bits"], [85, 85]), + _ => (KindTable["png-rgb-key8-stray-bits"], [255, 255, 0, 0, 0, 0]), }; [Theory] [MemberData(nameof(StrayBitKeyNames))] - public void Iso32000_1_8_9_6_4_PinsTodayAPngKeyWithBitsAboveTheDepthIsWrittenOutsideTheSampleRange(string name) - { - var (kind, written, _) = StrayBitKey(name); - var image = Written(ImageFile(PdfConformance.PdfA2b, kind)); - var values = Assert.IsType(image.Dict.Get(N("Mask"))).Items().Select(v => (int)Num(v)).ToArray(); - Assert.Equal(written, values); - Assert.Contains(values, v => v > 255); - } - - [Theory(Skip = "Gap #768: a PNG whose tRNS holds bits above the bit depth (a valid file) is written with a colour key " + - "outside 0 to 2^BitsPerComponent - 1, which ISO 32000-1 and -2, 8.9.6.4, forbid; PNG says decoders mask those bits.")] - [MemberData(nameof(StrayBitKeyNames))] public void Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten(string name) { - var (kind, _, needed) = StrayBitKey(name); + var (kind, needed) = StrayBitKey(name); var image = Written(ImageFile(PdfConformance.PdfA2b, kind)); - Assert.Equal(needed, Assert.IsType(image.Dict.Get(N("Mask"))).Items().Select(v => (int)Num(v)).ToArray()); + var values = Assert.IsType(image.Dict.Get(N("Mask"))).Items().Select(v => (int)Num(v)).ToArray(); + Assert.Equal(needed, values); + Assert.All(values, v => Assert.InRange(v, 0, (1 << kind.Bpc!.Value) - 1)); } [Fact] From 910887e3976c68873d41513b71687d908cff5529 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 22:06:43 +0100 Subject: [PATCH 02/22] fix(images): write a black Matte for an associated-alpha TIFF ExtraSamples 1 means the colour samples are already multiplied by alpha, which is the pre-blending of ISO 32000-2 11.6.5.2 with a black matte. A soft-mask image with no Matte says its data are not pre-blended, so readers multiplied twice and the image came out darker than the source. Write /Matte [0 0 0] on the soft mask and keep the samples as stored: exact, where un-multiplying in the loader would round at 8 bits. Only an RGBA TIFF with ExtraSamples 1 and non-opaque alpha changes output. --- CHANGELOG.md | 11 +++++ .../Images/TiffImageLoader.cs | 33 +++++++++---- .../ConformanceAuditG4Tests.Images.cs | 48 +++++++++++++------ 3 files changed, 69 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c376a14d..7043db727 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -810,6 +810,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **A TIFF with associated alpha is written with a black Matte on its soft mask (#764).** TIFF + 6.0 says `ExtraSamples` 1 holds colour samples already multiplied by alpha, which is the + pre-blending of ISO 32000-2, 11.6.5.2, with a black matte, and a soft-mask image with no + `Matte` says its image data are not pre-blended. `TiffImageLoader` read the tag and dropped it, + so a reader composited the multiplied samples a second time and the image came out darker than + the source. The soft mask now carries `/Matte [0 0 0]` and the samples are written as they were. + **Deliberate output change:** the soft-mask dictionary of an RGBA TIFF whose `ExtraSamples` is 1 + and whose alpha is not 255 everywhere (8-bit, and 16-bit under either `ImageBitDepth`); a TIFF + with `ExtraSamples` 2 or none, and one whose alpha is opaque throughout, write the same bytes as + before. + - **A PNG colour key is masked to the bit depth before it is written (#768).** The PNG specification stores a grey or RGB `tRNS` key as 16-bit words whatever the depth and has a decoder mask the bits above the depth to 0. `PngImageLoader` rescaled the raw word, so a valid diff --git a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs index 475f62143..45c736516 100644 --- a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs @@ -116,10 +116,13 @@ private static byte[] BuildBitReverseLookup() /// this loader does not read is neither honoured nor refused, so the file loads and what /// comes back is a different image, with nothing reported. Orientation is ignored, /// so a rotated or flipped source arrives in storage order. Only the first IFD is walked, - /// so later pages are absent. ExtraSamples is read and then discarded, so - /// pre-multiplied alpha is emitted as a plain soft mask with no /Matte and - /// composites wrong (#534). Read the directory yourself if you did not produce the + /// so later pages are absent. Read the directory yourself if you did not produce the /// file. + /// ExtraSamples is read for one decision: the value 1 (associated alpha, colour + /// samples already multiplied by alpha) writes /Matte [0 0 0] on the soft mask, the + /// black matte that formula implies, and leaves the samples as they are. Any other value, or + /// none, writes the soft mask with no Matte, as a straight alpha. A 4-sample RGB file + /// whose alpha is 255 everywhere has no soft mask and so no Matte. /// A ColorMap the loader cannot use is refused with /// . The tag is read whenever the directory carries it, under /// every compression, so a negative offset on a tag with a nonzero count and an offset that @@ -604,7 +607,7 @@ public static PdfImageXObject Load(byte[] tiff, ImageLoadOptions options) return photometric switch { 0 or 1 => BuildGreyscale(rawBuffer, width, height, photometric == 0, bitsPerSample, options), - 2 => BuildRgb(rawBuffer, width, height, hasAlpha, bitsPerSample, options), + 2 => BuildRgb(rawBuffer, width, height, hasAlpha, extraSamples == 1, bitsPerSample, options), 3 => BuildPalette(rawBuffer, width, height, colorMap!), _ => throw new NotSupportedException( $"TIFF PhotometricInterpretation={photometric} is not supported.") @@ -838,7 +841,7 @@ private static PdfImageXObject BuildGreyscale( } private static PdfImageXObject BuildRgb( - byte[] raw, int width, int height, bool hasAlpha, + byte[] raw, int width, int height, bool hasAlpha, bool associatedAlpha, int bitsPerSample, ImageLoadOptions options) { var pixelCount = width * height; @@ -885,7 +888,7 @@ private static PdfImageXObject BuildRgb( var rgb8 = Downsample16(rgb16); PdfStream? sMask8 = null; if (hasAlpha && hasNonOpaqueAlpha) - sMask8 = new PdfStream(Downsample16(alpha16!)); + sMask8 = WithBlackMatte(new PdfStream(Downsample16(alpha16!)), associatedAlpha); else if (hasAlpha && !hasNonOpaqueAlpha) sMask8 = null; return new PdfImageXObject(width, height, rgb8, PdfName.FlateDecode, ImageColorSpace.DeviceRgb, 8, sMask8, 8); @@ -894,7 +897,7 @@ private static PdfImageXObject BuildRgb( { PdfStream? sMask16 = null; if (hasAlpha && hasNonOpaqueAlpha) - sMask16 = new PdfStream(alpha16!); + sMask16 = WithBlackMatte(new PdfStream(alpha16!), associatedAlpha); return new PdfImageXObject(width, height, rgb16, PdfName.FlateDecode, ImageColorSpace.DeviceRgb, 16, sMask16, 16); } } @@ -915,10 +918,24 @@ private static PdfImageXObject BuildRgb( alphaOut[i] = a; if (a != 255) hasNonOpaque = true; } - PdfStream? sMask = hasNonOpaque ? new PdfStream(alphaOut) : null; + PdfStream? sMask = hasNonOpaque ? WithBlackMatte(new PdfStream(alphaOut), associatedAlpha) : null; return new PdfImageXObject(width, height, rgbOut, PdfName.FlateDecode, ImageColorSpace.DeviceRgb, 8, sMask); } + /// + /// Marks a soft mask as the alpha of colour samples already multiplied by it. TIFF 6.0 says + /// ExtraSamples 1 holds pre-multiplied colour, which is the pre-blending formula of ISO 32000-2, + /// 11.6.5.2, with a black matte; without Matte (Table 144) the data are not pre-blended, + /// so a reader would composite the multiplied samples a second time. The matte is three zeros, + /// one per component of DeviceRGB. + /// + private static PdfStream WithBlackMatte(PdfStream sMask, bool associatedAlpha) + { + if (associatedAlpha) + sMask.Dictionary.Set(new PdfName("Matte"), new PdfArray([new PdfInteger(0), new PdfInteger(0), new PdfInteger(0)])); + return sMask; + } + private static PdfImageXObject BuildPalette( byte[] raw, int width, int height, ushort[] colorMap) { diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index ce745f24f..750b1cf87 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -679,21 +679,6 @@ [.. BaseTags(2, 1, 8, 2, 4), Short(338, 1)], [128, 0, 0, 128, 0, 128, 0, 255]); [Fact] - public void Iso32000_1_11_6_5_3_PinsTodayAnAssociatedAlphaTiffIsWrittenAsStraightAlphaWithNoMatte() - { - // ExtraSamples 1 says each colour sample is already multiplied by the alpha, so 128 at alpha 128 is a - // full red. The file keeps 128 and gives the alpha as a soft mask with no Matte. - var image = Written(ImageFile(PdfConformance.None, new Kind("tiff-associated", AssociatedAlphaTiff(), 2, 1, - "DeviceRGB", 8, "FlateDecode"))); - Assert.Equal("800000" + "008000", Convert.ToHexString(image.Decoded)); - var mask = Assert.IsType(image.SoftMask); - Assert.Equal("80FF", Convert.ToHexString(mask.Decoded)); - Assert.Null(mask.Dict.Get(N("Matte"))); - } - - [Fact(Skip = "Gap #764: TiffImageLoader reads ExtraSamples and discards it, so a pre-multiplied alpha is " + - "written as a plain soft mask with no Matte. ISO 32000-1, 11.6.5.3, Table 146: when Matte is absent the " + - "image data shall not be preblended; the image composites darker than the source.")] public void Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack() { var image = Written(ImageFile(PdfConformance.None, new Kind("tiff-associated", AssociatedAlphaTiff(), 2, 1, @@ -703,6 +688,39 @@ public void Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack() var matte = Assert.IsType(image.SoftMask!.Dict.Get(N("Matte"))); Assert.Equal([0.0, 0.0, 0.0], matte.Items().Select(Num).ToArray()); Assert.Equal("800000" + "008000", Convert.ToHexString(image.Decoded)); + Assert.Equal("80FF", Convert.ToHexString(image.SoftMask.Decoded)); + } + + [Theory] + [InlineData(ImageBitDepth.Preserve)] + [InlineData(ImageBitDepth.ReduceToEight)] + public void Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth(ImageBitDepth depth) + { + // The matte is a colour component value, so it does not depend on the depth the alpha is written at. + var tiff = Tiff(false, [.. BaseTags(1, 1, 16, 2, 4), Short(338, 1)], + [0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00]); + var loaded = TiffImageLoader.Load(tiff, new ImageLoadOptions { BitDepth = depth }); + var sMask = Assert.IsType(loaded.SMask); + var matte = Assert.IsType(sMask.Dictionary.Get(N("Matte"))); + Assert.Equal([0.0, 0.0, 0.0], matte.Items().Select(Num).ToArray()); + } + + [Theory] + [InlineData(2)] + [InlineData(0)] + public void Iso32000_1_11_6_5_3_AnUnassociatedOrUnspecifiedAlphaTiffHasNoMatte(int extraSamples) + { + // ExtraSamples 2 is straight alpha and 0 says nothing, so the samples are not pre-blended. + var tiff = Tiff(true, [.. BaseTags(2, 1, 8, 2, 4), Short(338, (uint)extraSamples)], [255, 0, 0, 128, 0, 255, 0, 255]); + var sMask = Assert.IsType(TiffImageLoader.Load(tiff).SMask); + Assert.Null(sMask.Dictionary.Get(N("Matte"))); + } + + [Fact] + public void Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWithOpaqueAlphaHasNoSoftMaskAndNoMatte() + { + var tiff = Tiff(true, [.. BaseTags(2, 1, 8, 2, 4), Short(338, 1)], [255, 0, 0, 255, 0, 255, 0, 255]); + Assert.Null(TiffImageLoader.Load(tiff).SMask); } [Fact] From 358c85b0323bf9b9e0b0ec62b60f350ef301c6ed Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 22:10:52 +0100 Subject: [PATCH 03/22] fix(images): refuse a JPEG 2000 codestream that sets the Part 2 Rsiz bit ISO 32000-2 7.4.9 limits the data of an image XObject to the JPX baseline set of features. The loader read the SIZ marker for size, channel count and depth but never its Rsiz field, so a codestream declaring Part 2 capabilities was wrapped and written. Read Rsiz from a bare codestream and from the jp2c box of a JP2 file, and refuse bit 15 with InvalidDataException. The text that defines the baseline set is not held here, so only that bit is checked, and the doc says so. A codestream behind a JP2 header that does not start with SOC and SIZ stays unexamined, as before. --- CHANGELOG.md | 9 ++++ src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 54 ++++++++++++++++++- .../ConformanceAuditG4Tests.Images.cs | 45 +++++++++++----- 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7043db727..59ae62fa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -810,6 +810,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, + 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and + `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so a codestream with bit 15 set + was wrapped and written. `Load` now throws `InvalidDataException` naming `Rsiz` for such a + codestream, bare or inside a JP2 file. ISO/IEC 15444, which defines the baseline set, is not + held here, so only that one bit is checked and a codestream that uses another feature outside the + set still passes through. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 15 set; + every other codestream writes the same bytes as before. + - **A TIFF with associated alpha is written with a black Matte on its soft mask (#764).** TIFF 6.0 says `ExtraSamples` 1 holds colour samples already multiplied by alpha, which is the pre-blending of ISO 32000-2, 11.6.5.2, with a black matte, and a soft-mask image with no diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 3725b82c7..46499504a 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -64,6 +64,10 @@ public static class JpxImageLoader private const ushort MarkerSOC = 0xFF4F; // JPEG 2000 SIZ marker (image and tile size). private const ushort MarkerSIZ = 0xFF51; + // Bit 15 of the SIZ marker's Rsiz field, the bit that marks a codestream using capabilities + // beyond JPEG 2000 Part 1. ISO/IEC 15444 is not held in this repository, so this bit is the + // only part of Rsiz the loader reads; the other Rsiz values are not examined. + private const int RsizPart2Bit = 0x8000; // colr enumColourspace values (ISO 15444-1 Table I.11). private const int ColrEnumSRgb = 16; @@ -79,8 +83,20 @@ public static class JpxImageLoader /// A with /Filter /JPXDecode. /// /// Thrown when the data is malformed, truncated, or its dimensions exceed - /// . + /// , or when the codestream's Rsiz has the Part 2 + /// capabilities bit (0x8000) set. /// + /// + /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws + /// naming the Rsiz value when bit 15 of the SIZ marker's + /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the + /// JPX baseline set of features. The bit is read + /// from a bare codestream and from the jp2c box of a JP2 file whose codestream starts with + /// SOC and SIZ. This loader checks only that bit: the text that defines the baseline set is + /// ISO/IEC 15444, which is not checked here, so a codestream that sets no Part 2 bit but still uses + /// a feature outside the baseline set passes through. Do not pass a codestream you have not + /// checked against the baseline set; this loader does not decode it. + /// public static PdfImageXObject Load(byte[] jpx) => Load(jpx, ImageLoadOptions.Default); @@ -99,13 +115,18 @@ public static PdfImageXObject Load(byte[] jpx) /// A with /Filter /JPXDecode. /// /// Thrown when the data is malformed, truncated, or its dimensions exceed - /// . + /// , or when the codestream's Rsiz has the Part 2 + /// capabilities bit (0x8000) set. /// /// /// Thrown when requests . /// Full JPEG 2000 decode (DWT + EBCOT + MQ arithmetic) is not yet supported; use /// instead. /// + /// + /// A codestream whose Rsiz has the Part 2 bit set is refused, as for + /// , which also says what is and is not checked. + /// public static PdfImageXObject Load(byte[] jpx, ImageLoadOptions options) { ArgumentNullException.ThrowIfNull(jpx); @@ -219,6 +240,12 @@ private static PdfImageXObject LoadJp2(byte[] data) if (jp2cBoxStart < 0) throw new InvalidDataException("JP2 file contains no contiguous codestream (jp2c) box."); + // The dimensions normally come from jp2h, so the codestream's SIZ is not parsed. Read its + // Rsiz where SOC and SIZ stand where they must, and leave a codestream that does not + // alone: this loader has never examined the codestream behind a usable jp2h. + if (TryReadRsiz(data, jp2cPayloadOffset, jp2cPayloadLength, out var jp2cRsiz)) + RefuseOutsideBaseline(jp2cRsiz); + // If jp2h was missing or did not yield dimensions, parse from the codestream's SIZ. if (width == 0 || height == 0) { @@ -470,6 +497,27 @@ private static (int width, int height, int components, int bpc) throw new InvalidDataException("JPEG 2000 codestream: SIZ marker not found."); } + private static void RefuseOutsideBaseline(int rsiz) + { + if ((rsiz & RsizPart2Bit) != 0) + throw new InvalidDataException( + $"JPEG 2000 codestream: Rsiz 0x{rsiz:X4} has the Part 2 capabilities bit (0x8000) set. " + + "A PDF image XObject is limited to the JPX baseline set of features (ISO 32000-2, 7.4.9)."); + } + + // Reads Rsiz when the codestream at offset is SOC followed at once by a SIZ segment long enough + // to hold it; false when it is not, so the caller leaves such a codestream unexamined. + private static bool TryReadRsiz(byte[] data, int offset, int length, out int rsiz) + { + rsiz = 0; + // SOC(2) SIZ(2) Lsiz(2) Rsiz(2) + if (length < 8 || data[offset] != 0xFF || data[offset + 1] != 0x4F || + data[offset + 2] != 0xFF || data[offset + 3] != 0x51) + return false; + rsiz = ReadUInt16Be(data, offset + 6); + return true; + } + /// /// Parses the SIZ marker segment payload at /// (i.e. points to the 2-byte Lsiz length field). @@ -499,6 +547,8 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // Field offsets relative to pos (the Lsiz field): // +0 Lsiz(2), +2 Rsiz(2), +4 Xsiz(4), +8 Ysiz(4), +12 XOsiz(4), +16 YOsiz(4) // +20 XTsiz(4), +24 YTsiz(4), +28 XTOsiz(4), +32 YTOsiz(4), +36 Csiz(2) + RefuseOutsideBaseline(ReadUInt16Be(data, pos + 2)); + var xsiz = (int)ReadUInt32Be(data, pos + 4); var ysiz = (int)ReadUInt32Be(data, pos + 8); var xosiz = (int)ReadUInt32Be(data, pos + 12); diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 750b1cf87..697be1569 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -930,24 +930,41 @@ public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefus } [Fact] - public void Iso32000_2_7_4_9_PinsTodayAPartTwoCodestreamIsPassedThrough() + public void Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused() { - // Rsiz with the Part 2 bit (0x8000) says the codestream uses extensions outside the baseline set that 7.4.9 - // limits PDF to. The loader reads no Rsiz, so the codestream is wrapped as it is. Whether the Part 2 bit puts it outside the - // baseline set is defined in ISO/IEC 15444-2, which is not held, so this pins the bytes and nothing more. - var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-part2", JpxCodestream(16, 16, 3, 7, 0x8000), 16, 16, - "DeviceRGB", 8, "JPXDecode"))); - Assert.Equal("JPXDecode", image.Name("Filter")); - var codestream = Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload; - Assert.Equal([0x80, 0x00], codestream[6..8]); + // Rsiz with the Part 2 bit (0x8000). Whether that bit puts a codestream outside the baseline set is defined in + // ISO/IEC 15444, which is not held, so the loader refuses on the bit and on nothing else. + var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000))); + Assert.Contains("0x8000", e.Message); } - [Fact(Skip = "Gap #770: JpxImageLoader reads no Rsiz, so a codestream that uses Part 2 extensions is wrapped and " + - "written. ISO 32000-1 and -2, 7.4.9: data used in PDF image XObjects shall be limited to the JPX baseline set of " + - "features.")] - public void Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused() + [Theory] + [InlineData(0x8000)] + [InlineData(0x8001)] + [InlineData(0xC000)] + public void Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File(int rsiz) { - Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000))); + var codestream = JpxCodestream(16, 16, 3, 7, rsiz); + Assert.Throws(() => JpxImageLoader.Load(codestream)); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(codestream, 3, 16))); + Assert.Throws(() => LayoutImage.FromBytes(codestream)); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(0x4000)] + [InlineData(0x7FFF)] + public void Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte(int rsiz) + { + var codestream = JpxCodestream(16, 16, 3, 7, rsiz); + var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-rsiz", codestream, 16, 16, "DeviceRGB", 8, + "JPXDecode"))); + Assert.Equal(codestream, Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload); + var jp2 = Written(ImageFile(PdfConformance.None, new Kind("jp2-rsiz", Jp2File(codestream, 3, 16), 16, 16, + "DeviceRGB", 8, "JPXDecode"))); + Assert.Equal(codestream, Jp2Boxes(jp2.Raw).Single(b => b.Type == "jp2c").Payload); } // ── PNG tRNS: only the low bits of a colour key count when the depth is below 16 ───────────── From 5df8405346ecb4f31dc8639701ceb0d80bca82e3 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 22:29:10 +0100 Subject: [PATCH 04/22] fix(images): refuse JPEG and JPEG 2000 frames the filters cannot carry JpegImageLoader wrote /DeviceRGB for every component count other than 1 and 4 and accepted every frame type and precision. JpxImageLoader wrote a device name from the channel count whatever the colr box said, and Table 87 says a ColorSpace that is present replaces the colour specification in the JPEG 2000 data. JPEG: refuse a component count other than 1, 3 or 4, a precision other than 8 and a frame type other than SOF0 to SOF2, which also covers a JPEG strip of a TIFF. JPEG 2000: refuse a bare codestream, or a JP2 file with no jp2h box, of a channel count other than 1, 3 or 4, and a JP2 file whose only colour specification is CIEJab; leave ColorSpace out when the colr boxes name no sRGB, greyscale or CMYK space (ICC, sYCC and the other enumerated spaces). A JP2 file of two channels beside a greyscale colr box, and one with a bpcc box, still pass through: ISO 32000-2 7.4.9 allows channels of different depths, so those are invalid only under PDF/A and wait for a ruling. Every other JPEG and JP2 file keeps its bytes. --- CHANGELOG.md | 20 ++ .../Images/JpegImageLoader.cs | 38 ++- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 118 ++++++-- .../Images/PdfImageXObject.cs | 13 +- .../Images/TiffImageLoader.cs | 3 + src/VellumPdf.Layout/Elements/LayoutImage.cs | 16 +- .../ConformanceAuditG4Tests.Images.cs | 281 ++++++++++-------- 7 files changed, 335 insertions(+), 154 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59ae62fa0..601678d1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -810,6 +810,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **JPEG and JPEG 2000 data that DCTDecode and JPXDecode cannot carry is refused, and a JP2 colour + specification is no longer overridden by a device name (#763).** `JpegImageLoader` chose + `/DeviceRGB` for every component count other than 1 and 4 and accepted every frame type and + precision, and `JpxImageLoader` wrote a device name from the channel count whatever the `colr` + box said. ISO 32000-2, 7.4.8, gives DCTDecode data one, three or four components of a byte + each, and 7.4.9 says a `ColorSpace` that is present replaces the colour specification in the + JPEG 2000 data and that the colour channels shall match its components. `Load` now throws + `InvalidDataException` for a JPEG frame with a component count other than 1, 3 or 4, a + precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a + JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` + box, of a channel count other than 1, 3 or 4, and for a JP2 file whose only colour + specification is enumerated colour space 19 (CIEJab), which 7.4.9 excludes. A JP2 file whose + colour specifications include no sRGB, greyscale or CMYK space (an ICC profile, sYCC, or + another enumerated space) is written with no `ColorSpace`, so the file's own specification + decides. **Deliberate output changes and new refusals:** those inputs; every other JPEG + (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file with an sRGB, greyscale or CMYK + `colr` box or no readable one writes the same bytes as before. A JP2 file of two channels + beside a greyscale `colr` box, and one whose channels have different depths, still pass + through unchanged. + - **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so a codestream with bit 15 set diff --git a/src/VellumPdf.Kernel/Images/JpegImageLoader.cs b/src/VellumPdf.Kernel/Images/JpegImageLoader.cs index 70d520a4f..91f6a9f72 100644 --- a/src/VellumPdf.Kernel/Images/JpegImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpegImageLoader.cs @@ -17,12 +17,25 @@ public static class JpegImageLoader /// /// /// The bytes do not begin with the SOI marker, or no usable frame header can be read from - /// them: absent, truncated, or behind a segment whose declared length does not fit. + /// them: absent, truncated, or behind a segment whose declared length does not fit. Or the + /// frame header declares a frame type other than SOF0, SOF1 or SOF2, a precision other than 8 + /// bits, or a component count other than 1, 3 or 4. /// /// /// This loader decodes nothing. The bytes are embedded verbatim as DCTDecode data and only /// the frame header is read. A file this accepts is therefore not necessarily a file a reader /// can render: corruption past the header passes straight into the document. + /// A frame header that DCTDecode data cannot have is refused. The call throws + /// naming the value for a start-of-frame marker other than + /// SOF0 (baseline), SOF1 (extended sequential) or SOF2 (progressive), that is SOF3 (lossless), + /// SOF5 to SOF7 (differential), SOF9 to SOF11 (arithmetic) and SOF13 to SOF15; for a precision + /// other than 8 bits, because DCTDecode delivers 8-bit samples; and for a component count other + /// than 1, 3 or 4, because the colour space written is chosen from that count and no device + /// space has another. Only the first start-of-frame header is read, and the checks run in that + /// order. The same applies to a JPEG strip of a TIFF read by . + /// Do not pass a JPEG whose frame type, precision or component count you have not read: + /// such a file is refused here, and was written as DCTDecode data under /DeviceRGB or the + /// colour space of its count by earlier versions. /// The 100,000,000-pixel limit is not checked for a JPEG. A file carrying nothing but a /// frame header saying 65535 by 65535 returns an image of 4,294,836,225 pixels, where /// refuses the same declaration. Nothing allocates a raster, @@ -42,11 +55,31 @@ public static PdfImageXObject Load(byte[] jpegBytes) { 1 => ImageColorSpace.DeviceGray, 4 => ImageColorSpace.DeviceCmyk, - _ => ImageColorSpace.DeviceRgb, + _ => ImageColorSpace.DeviceRgb, // 3: ReadSof refuses every other count }; return new PdfImageXObject(width, height, jpegBytes, PdfName.DCTDecode, cs, 8); } + // The three refusals of a frame DCTDecode data cannot be. ISO 32000-2, 7.4.8, describes the data + // as JPEG baseline format of one, three or four components, each a byte; 8.9.5 (BitsPerComponent) + // says DCTDecode always delivers 8-bit samples. SOF0 to SOF2 are the frames this loader keeps: + // baseline, extended sequential and progressive, all Huffman coded. + private static void RefuseFrame(byte marker, int precision, int components) + { + if (marker > 0xC2) + throw new InvalidDataException( + $"JPEG frame type SOF{marker - 0xC0} (marker 0xFF{marker:X2}) is not accepted: only SOF0, SOF1 " + + "and SOF2 frames are written as DCTDecode data (ISO 32000-2, 7.4.8)."); + if (precision != 8) + throw new InvalidDataException( + $"JPEG frame precision {precision} is not accepted: DCTDecode data has 8-bit samples " + + "(ISO 32000-2, 7.4.8 and 8.9.5)."); + if (components is not (1 or 3 or 4)) + throw new InvalidDataException( + $"JPEG frame has {components} components: DCTDecode data has one, three or four " + + "(ISO 32000-2, 7.4.8)."); + } + private static (int width, int height, int components) ReadSof(byte[] data) { // Validate the SOI (Start Of Image) marker before scanning. @@ -87,6 +120,7 @@ private static (int width, int height, int components) ReadSof(byte[] data) var h = (data[i + 3] << 8) | data[i + 4]; var w = (data[i + 5] << 8) | data[i + 6]; var c = data[i + 7]; + RefuseFrame(marker, data[i + 2], c); return (w, h, c); } i += length; diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 46499504a..af69cfb09 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -37,14 +37,31 @@ namespace VellumPdf.Images; /// No JPEG 2000 decode-to-raster is performed in this release — /// throws . /// -/// Colour space inference (Csiz/NC component count): +/// Colour space (/ColorSpace of the image dictionary). ISO 32000-2, 7.4.9, +/// says a ColorSpace that is present replaces the colour specification in the JPEG 2000 +/// data, so this loader writes one only where it is the same colour space. /// -/// 1 componentDeviceGray -/// 3 componentsDeviceRGB (refined to sRGB when the colr enumerated method = 16) -/// 4 componentsDeviceCMYK +/// A bare codestream, or a JP2 file with no jp2h box1, 3 or +/// 4 channels give DeviceGray, DeviceRGB or DeviceCMYK and a colr box +/// naming that space. Any other channel count is refused. +/// A JP2 file with an enumerated colr of sRGB (16), greyscale (17) or CMYK +/// (12) among its colour specificationsthe last enumerated value decides when +/// it is 16 (DeviceRGB) or 17 (DeviceGray); otherwise the channel count: 1 gives +/// DeviceGray, 4 gives DeviceCMYK and any other count gives +/// DeviceRGB. +/// A JP2 file with no colr box the loader can readthe +/// channel count chooses, as above. +/// A JP2 file with only other colour specifications: an ICC profile, or an +/// enumerated space such as sYCC (18)ColorSpace is left out, so the +/// colour specification in the file decides. +/// A JP2 file whose only colour specifications are enumerated colour space 19 +/// (CIEJab)refused, because ISO 32000-2, 7.4.9, excludes CIEJab and there is +/// nothing else to use. /// -/// ICC and indexed colour spaces from JP2 colr boxes are not yet handled; -/// component-count inference is used as a fallback. +/// An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile is +/// not read or checked. Indexed colour spaces are not handled. A JP2 file whose channels have +/// different bit depths (a bpcc box), or whose ihdr counts two channels beside a +/// greyscale colr, is passed through under the colour space above. /// public static class JpxImageLoader { @@ -72,6 +89,8 @@ public static class JpxImageLoader // colr enumColourspace values (ISO 15444-1 Table I.11). private const int ColrEnumSRgb = 16; private const int ColrEnumGreyscale = 17; + private const int ColrEnumCmyk = 12; + private const int ColrEnumCieJab = 19; /// /// Loads JPEG 2000 data using default options (passthrough, no raster decode). @@ -84,10 +103,19 @@ public static class JpxImageLoader /// /// Thrown when the data is malformed, truncated, or its dimensions exceed /// , or when the codestream's Rsiz has the Part 2 - /// capabilities bit (0x8000) set. + /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h + /// box, with a channel count other than 1, 3 or 4, and for a JP2 file whose only colour + /// specifications are enumerated colour space 19 (CIEJab). /// /// - /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws + /// A channel count that no device colour space has is refused for a bare codestream + /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a + /// colr box it writes, and ISO 32000-2, 7.4.9, says the colour channels shall match the + /// components of the colour space. A JP2 file whose only colour specification is CIEJab is + /// refused: neither a device name nor an absent ColorSpace would be valid for it. One + /// that also has an ICC profile, or another enumerated space, is written with no + /// ColorSpace. The class summary lists what is written for each colour specification. + /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws /// naming the Rsiz value when bit 15 of the SIZ marker's /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the /// JPX baseline set of features. The bit is read @@ -95,7 +123,7 @@ public static class JpxImageLoader /// SOC and SIZ. This loader checks only that bit: the text that defines the baseline set is /// ISO/IEC 15444, which is not checked here, so a codestream that sets no Part 2 bit but still uses /// a feature outside the baseline set passes through. Do not pass a codestream you have not - /// checked against the baseline set; this loader does not decode it. + /// checked against the baseline set; this loader does not decode it. /// public static PdfImageXObject Load(byte[] jpx) => Load(jpx, ImageLoadOptions.Default); @@ -116,7 +144,9 @@ public static PdfImageXObject Load(byte[] jpx) /// /// Thrown when the data is malformed, truncated, or its dimensions exceed /// , or when the codestream's Rsiz has the Part 2 - /// capabilities bit (0x8000) set. + /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h + /// box, with a channel count other than 1, 3 or 4, and for a JP2 file whose only colour + /// specifications are enumerated colour space 19 (CIEJab). /// /// /// Thrown when requests . @@ -169,6 +199,7 @@ private static PdfImageXObject LoadRawCodestream(byte[] data) var (width, height, components, bpc) = ParseSizFromCodestream(data, offset: 0); ImageLimits.ValidateDimensions("JPEG 2000", width, height); + RefuseUnmatchableChannelCount(components); var enumCs = EnumCsForComponents(components); var cs = InferColorSpace(components, enumCs); @@ -187,6 +218,7 @@ private static PdfImageXObject LoadJp2(byte[] data) { int width = 0, height = 0, nc = 0, bpc = 8; int? colrEnum = null; + var colr = new ColrSurvey(); // Box byte ranges captured for verbatim re-emission. The first occurrence of each // wins (a baseline JP2 has exactly one of each; capturing the first is correct for // the primary image in the unusual multi-codestream case). @@ -219,7 +251,7 @@ private static PdfImageXObject LoadJp2(byte[] data) jp2hBoxStart = pos; jp2hBoxTotal = boxTotalLength; ParseJp2Header(data, boxPayloadOffset, boxPayloadLength, - ref width, ref height, ref nc, ref bpc, ref colrEnum); + ref width, ref height, ref nc, ref bpc, ref colrEnum, colr); } break; @@ -261,7 +293,7 @@ private static PdfImageXObject LoadJp2(byte[] data) ImageLimits.ValidateDimensions("JPEG 2000 (JP2)", width, height); - var cs = InferColorSpace(nc, colrEnum); + var cs = ColorSpaceOf(nc, colrEnum, colr); var jp2cBox = data[jp2cBoxStart..(jp2cBoxStart + jp2cBoxTotal)]; byte[] jp2; @@ -281,7 +313,8 @@ private static PdfImageXObject LoadJp2(byte[] data) else { // jp2h absent (malformed source): synthesise one from the SIZ-derived geometry so the - // result is still conformant. + // result is still conformant. Its colr box names a device space, as for a bare codestream. + RefuseUnmatchableChannelCount(nc); jp2 = BuildMinimalJp2(width, height, nc, bpc, colrEnum ?? EnumCsForComponents(nc), jp2cBox); } @@ -362,7 +395,7 @@ private static (uint boxType, int boxPayloadOffset, int boxPayloadLength, int bo private static void ParseJp2Header( byte[] data, int offset, int length, - ref int width, ref int height, ref int nc, ref int bpc, ref int? colrEnum) + ref int width, ref int height, ref int nc, ref int bpc, ref int? colrEnum, ColrSurvey colr) { var end = offset + length; var pos = offset; @@ -415,7 +448,7 @@ private static void ParseJp2Header( break; case BoxTypeColr: - TryParseColr(data, subPayloadOffset, subPayloadLength, ref colrEnum); + TryParseColr(data, subPayloadOffset, subPayloadLength, ref colrEnum, colr); break; } @@ -441,7 +474,7 @@ private static void ParseIhdr( } // colr payload: METH(1) PREC(1) APPROX(1) [EnumCS(4) if METH=1] [ICCProfile if METH=2]. - private static void TryParseColr(byte[] data, int offset, int length, ref int? colrEnum) + private static void TryParseColr(byte[] data, int offset, int length, ref int? colrEnum, ColrSurvey colr) { if (length < 3) return; // malformed but non-fatal for colour space purposes @@ -451,9 +484,21 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c { // Enumerated colour space method: 4-byte enum value follows METH/PREC/APPROX. colrEnum = (int)ReadUInt32Be(data, offset + 3); + colr.Enumerated.Add(colrEnum.Value); + } + else if (meth is 2 or 3) + { + // METH 2 and 3 carry an ICC profile. The profile is not read or checked, only its presence. + colr.HasIccProfile = true; } - // METH=2 (ICC profile) and METH=3 (any-ICC/palette) are not yet handled; - // component-count inference is used as a fallback in those cases. + } + + // What the colr boxes of a JP2 file hold: every enumerated colour space in file order, and whether + // any box carries an ICC profile. colrEnum above keeps the last enumerated value, as it always has. + private sealed class ColrSurvey + { + public List Enumerated { get; } = []; + public bool HasIccProfile { get; set; } } // ── SIZ marker parsing ──────────────────────────────────────────────────── @@ -583,6 +628,43 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // ── Colour space inference ──────────────────────────────────────────────── + // The /ColorSpace of an image from a JP2 file, or null to leave it out so the colour specification + // in the JPEG 2000 data decides (ISO 32000-2, 7.4.9, Table 87: a ColorSpace that is present + // replaces that specification). + // - A device space among the enumerated ones (12, 16, 17): the name this loader has always + // chosen, from the last enumerated value or the channel count. + // - No device space, and an ICC profile or an enumerated space such as sYCC: left out. A device + // name would make a reader take the samples as device samples. + // - Only CIEJab (19): refused, since neither a name nor the colr box gives a colour space a + // PDF file may use. + // - No usable colr box: the channel count decides, as before. + private static ImageColorSpace? ColorSpaceOf(int components, int? colrEnum, ColrSurvey colr) + { + if (colr.Enumerated.Exists(e => e is ColrEnumCmyk or ColrEnumSRgb or ColrEnumGreyscale)) + return InferColorSpace(components, colrEnum); + if (colr.HasIccProfile) + return null; + if (colr.Enumerated.Count == 0) + return InferColorSpace(components, colrEnum); + if (colr.Enumerated.TrueForAll(e => e == ColrEnumCieJab)) + throw new InvalidDataException( + "JP2 file: its only colour specification is enumerated colour space 19 (CIEJab), which " + + "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); + return null; + } + + // A bare codestream, or a JP2 file with no jp2h box, is described to PDF by a colr box this loader + // writes, which names sRGB, greyscale or CMYK from the channel count. Two channels, or five or + // more, have no such space. + private static void RefuseUnmatchableChannelCount(int components) + { + if (components is not (1 or 3 or 4)) + throw new InvalidDataException( + $"JPEG 2000 data has {components} channels and no colour specification of its own: " + + "only 1 (greyscale), 3 (sRGB) or 4 (CMYK) channels can be described as a PDF colour " + + "space (ISO 32000-2, 7.4.9)."); + } + private static ImageColorSpace InferColorSpace(int components, int? colrEnum) { // Prefer enumerated colour space from the colr box when available. diff --git a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs index b406a9bbd..894c7ccef 100644 --- a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs +++ b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs @@ -19,7 +19,9 @@ public sealed class PdfImageXObject private readonly byte[] _streamData; private readonly PdfName _filter; - private readonly ImageColorSpace _colorSpace; + // Null leaves /ColorSpace out; only a JPXDecode image may, because its colour specification is then + // read from the JPEG 2000 data (ISO 32000-2, 7.4.9). + private readonly ImageColorSpace? _colorSpace; private readonly int _bitsPerComponent; private readonly PdfStream? _sMask; private readonly int _sMaskBitsPerComponent; @@ -36,7 +38,7 @@ public sealed class PdfImageXObject internal PdfImageXObject( int width, int height, byte[] streamData, PdfName filter, - ImageColorSpace colorSpace, int bitsPerComponent, PdfStream? sMask = null, + ImageColorSpace? colorSpace, int bitsPerComponent, PdfStream? sMask = null, int sMaskBitsPerComponent = 8, PdfDictionary? decodeParms = null, byte[]? jbig2Globals = null, PdfArray? colorKeyMask = null) { @@ -135,8 +137,9 @@ private void SetImageDict( d.Set(PdfName.Type, new PdfName("XObject")) .Set(PdfName.Subtype, new PdfName("Image")) .Set(new PdfName("Width"), new PdfInteger(Width)) - .Set(new PdfName("Height"), new PdfInteger(Height)) - .Set(new PdfName("ColorSpace"), ColorSpaceName()); + .Set(new PdfName("Height"), new PdfInteger(Height)); + if (_colorSpace is { } colorSpace) + d.Set(new PdfName("ColorSpace"), ColorSpaceName(colorSpace)); // /BitsPerComponent: required for every filter except JPXDecode, where the value comes // from the JPEG 2000 codestream and the entry is optional (ISO 32000-1 §7.4.9). JPEG 2000 @@ -164,7 +167,7 @@ private void SetImageDict( d.Set(new PdfName("Mask"), _colorKeyMask); } - private PdfObject ColorSpaceName() => _colorSpace switch + private static PdfObject ColorSpaceName(ImageColorSpace colorSpace) => colorSpace switch { ImageColorSpace.DeviceGray => new PdfName("DeviceGray"), ImageColorSpace.DeviceRgb => new PdfName("DeviceRGB"), diff --git a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs index 45c736516..eea7346bf 100644 --- a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs @@ -145,6 +145,9 @@ private static byte[] BuildBitReverseLookup() /// LZW stream decodes to more bytes than it occupies: a short LZW strip under a large header /// allocates memory sized from the header before it is refused, and a PackBits strip that /// decodes to less than the image needs loads with the rest zero-filled (#536). + /// A strip compressed with new-style JPEG (Compression 7) is read by + /// , so it is refused with for + /// the frame type, precision or component count that loader refuses. /// The limit is not checked for a JPEG strip. A strip compressed with new-style JPEG /// (Compression 7) is handed to and passed through /// as DCTDecode data, so the returned size is the one in the JPEG frame header. It is checked diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index a7a0b34de..6d3645d88 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -304,6 +304,16 @@ public LayoutImage(PdfImageXObject image) /// exception type and message, and the loader's documentation is where to read it. A JPEG is /// passed through as /DCTDecode, never decoded or re-encoded. The format is read from /// the data, not from a file name. + /// JPEG and JPEG 2000 data that cannot be written as a valid image is refused with + /// , the exception of the loader that reads it. For a JPEG + /// (or a JPEG strip of a TIFF) the refused set is a frame type other than SOF0, SOF1 and SOF2, + /// a precision other than 8 bits, and a component count other than 1, 3 and 4 + /// (). For JPEG 2000 it is a codestream whose + /// Rsiz sets the Part 2 bit, a bare codestream or a JP2 file with no jp2h box + /// whose channel count is not 1, 3 or 4, and a JP2 file whose only colour specification is + /// CIEJab (). A JP2 file with an ICC profile or an + /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; + /// it is written with no /ColorSpace, so the colour specification in the file decides. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 /// and Group 4 data carries no header and needs its width, height and coding parameters. Load @@ -439,7 +449,8 @@ public static LayoutImage FromBytes(byte[] data, GifLoadOptions options) /// /// The file cannot be opened or read. /// - /// The file is larger than the bound, begins with no known signature, or the loader refuses it. + /// The file is larger than the bound, begins with no known signature, or the loader refuses it, + /// including the JPEG and JPEG 2000 data that lists. /// /// As for . public static LayoutImage FromFile(string path) => @@ -558,7 +569,8 @@ public static LayoutImage FromFile(string path, GifLoadOptions options) /// The stream throws it, for a stream that is disposed but still reports CanRead. /// /// - /// The stream is larger than the bound, begins with no known signature, or the loader refuses it. + /// The stream is larger than the bound, begins with no known signature, or the loader refuses it, + /// including the JPEG and JPEG 2000 data that lists. /// /// /// As for , or the stream throws it, for instance from a diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 697be1569..c6d7cb128 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -362,51 +362,73 @@ public void Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsF Assert.Null(image.Dict.Get(N("DecodeParms"))); } - [Theory(Skip = "Gap #763: JpegImageLoader writes /DeviceRGB for a frame of 2 or 5 components. ISO 32000-1 and -2, " + - "8.9.3, infer the number of colour components from the colour space, so a reader takes three; ISO 32000-2, " + - "7.4.8, says DCTDecode data has one, three or four.")] + [Theory] + [InlineData(0)] [InlineData(2)] [InlineData(5)] + [InlineData(6)] public void Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused(int components) { - Assert.Throws(() => JpegImageLoader.Load(Jpeg(4, 2, components))); - } - - [Fact] - public void Iso32000_1_Table89_PinsTodayAJpegOfTwelveBitPrecisionIsWrittenAsEightBitDct() - { - // The frame header's precision byte is 12; the loader never reads it. Table 89 says DCTDecode always delivers - // 8-bit samples, and 7.4.8 that each component value occupies a byte. - var bytes = Jpeg(4, 2, 3); - bytes[3] = 0xC1; // SOF1, extended sequential DCT, which allows a precision of 12 - bytes[6] = 12; - var image = Written(ImageFile(PdfConformance.PdfA2b, new Kind("jpeg-12", bytes, 4, 2, "DeviceRGB", 8, "DCTDecode"))); - Assert.Equal(8, (int)image.Num("BitsPerComponent")); - Assert.Equal(bytes, image.Raw); - Assert.Empty(VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, new Kind("jpeg-12", bytes, 4, 2, "DeviceRGB", 8, - "DCTDecode")))); + var e = Assert.Throws(() => JpegImageLoader.Load(Jpeg(4, 2, components))); + Assert.Contains($"{components} components", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(Jpeg(4, 2, components))); } - [Fact(Skip = "Gap #763: JpegImageLoader never reads the frame's sample precision, so a 12-bit JPEG is written as " + - "/BitsPerComponent 8 DCTDecode, and Table 89 says DCTDecode always delivers 8-bit samples (ISO 32000-1 and -2).")] - public void Iso32000_1_Table89_AJpegOfAPrecisionOtherThanEightIsRefused() + [Theory] + [InlineData(0xC0, 12)] + [InlineData(0xC1, 12)] + [InlineData(0xC2, 12)] + [InlineData(0xC1, 16)] + [InlineData(0xC1, 4)] + public void Iso32000_1_Table89_AJpegOfAPrecisionOtherThanEightIsRefused(int marker, int precision) { var bytes = Jpeg(4, 2, 3); - bytes[3] = 0xC1; - bytes[6] = 12; - Assert.Throws(() => JpegImageLoader.Load(bytes)); + bytes[3] = (byte)marker; + bytes[6] = (byte)precision; + var e = Assert.Throws(() => JpegImageLoader.Load(bytes)); + Assert.Contains($"precision {precision}", e.Message); } - [Theory(Skip = "Gap #763: JpegImageLoader accepts every start-of-frame marker. ISO 32000-2, 7.4.8, describes " + - "DCTDecode as decoding baseline JPEG and the progressive extension; that sentence binds readers, and the row " + - "rests on it, not on a writer requirement. SOF3 (lossless) and SOF9 (arithmetic) are written as DCTDecode.")] + [Theory] [InlineData(0xC3)] + [InlineData(0xC5)] + [InlineData(0xC6)] + [InlineData(0xC7)] [InlineData(0xC9)] + [InlineData(0xCA)] + [InlineData(0xCB)] + [InlineData(0xCD)] + [InlineData(0xCE)] + [InlineData(0xCF)] public void Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode(int marker) { + // ISO 32000-2, 7.4.8, describes the filter as decoding the JPEG baseline format. SOF0 to SOF2 are kept + // (the next test and the progressive test); every other start-of-frame marker is refused. var bytes = Jpeg(4, 2, 3); bytes[3] = (byte)marker; - Assert.Throws(() => JpegImageLoader.Load(bytes)); + var e = Assert.Throws(() => JpegImageLoader.Load(bytes)); + Assert.Contains($"SOF{marker - 0xC0}", e.Message); + } + + [Theory] + [InlineData(0xC0, 1)] + [InlineData(0xC0, 3)] + [InlineData(0xC0, 4)] + [InlineData(0xC1, 1)] + [InlineData(0xC1, 3)] + [InlineData(0xC1, 4)] + [InlineData(0xC2, 1)] + [InlineData(0xC2, 3)] + [InlineData(0xC2, 4)] + public void Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte(int marker, + int components) + { + var bytes = Jpeg(4, 2, components); + bytes[3] = (byte)marker; + var space = components switch { 1 => "DeviceGray", 3 => "DeviceRGB", _ => "DeviceCMYK" }; + var image = Written(ImageFile(PdfConformance.PdfA2b, new Kind("jpeg-accepted", bytes, 4, 2, space, 8, "DCTDecode"))); + Assert.Equal(bytes, image.Raw); + Assert.Equal(space, image.Name("ColorSpace")); } [Fact] @@ -643,29 +665,6 @@ public void Iso32000_2_7_5_2_TheHeaderNamesAVersionThatHasEveryFeatureTheImagesU // ── Gaps found by this audit: the current output, and the output the clause needs ───────────── - [Theory] - [InlineData(2)] - [InlineData(5)] - public void Iso32000_2_7_4_8_PinsTodayAJpegOfAnotherComponentCountIsWrittenAsDeviceRgb(int components) - { - var image = Written(ImageFile(PdfConformance.None, new Kind("jpeg-n", Jpeg(4, 2, components), 4, 2, - "DeviceRGB", 8, "DCTDecode"))); - Assert.Equal("DeviceRGB", image.Name("ColorSpace")); - Assert.Equal("DCTDecode", image.Name("Filter")); - } - - [Theory] - [InlineData(0xC3)] - [InlineData(0xC9)] - public void Iso32000_2_7_4_8_PinsTodayAFrameTypeOtherThanBaselineOrProgressiveIsWrittenAsDctDecode(int marker) - { - var bytes = Jpeg(4, 2, 3); - bytes[3] = (byte)marker; - var image = Written(ImageFile(PdfConformance.None, new Kind("jpeg-sof", bytes, 4, 2, "DeviceRGB", 8, "DCTDecode"))); - Assert.Equal("DCTDecode", image.Name("Filter")); - Assert.Equal(bytes, image.Raw); - } - [Fact] public void Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt() { @@ -744,7 +743,8 @@ public void Tiff6_0_8_TheOrientationTagTurnsTheImageSoItsRowZeroIsOnTheSideTheTa // ── JPEG 2000: the colour specification of the file against the colour space of the dictionary ─── /// A JP2 file of whose colr box is METH 1 with the enumerated space. - private static byte[] Jp2File(byte[] codestream, int channels, int enumeratedColourSpace, byte[]? bpcc = null) + private static byte[] Jp2File(byte[] codestream, int channels, int? enumeratedColourSpace, byte[]? bpcc = null, + bool icc = false, int? extraEnumerated = null, bool noJp2h = false) { static byte[] BoxOf(string type, byte[] payload) { @@ -762,74 +762,103 @@ static byte[] BoxOf(string type, byte[] payload) ihdr[9] = (byte)channels; ihdr[10] = (byte)(bpcc is null ? 7 : 0xFF); ihdr[11] = 7; - var colr = new byte[7]; - colr[0] = 1; - System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(colr.AsSpan(3), enumeratedColourSpace); + static byte[] Enumerated(int value) + { + var colr = new byte[7]; + colr[0] = 1; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(colr.AsSpan(3), value); + return BoxOf("colr", colr); + } + + // The colour specifications in file order: the enumerated one, a second enumerated one, an ICC profile (METH 2; + // only its presence is read, so the profile bytes are zeros). + byte[] colours = + [ + .. enumeratedColourSpace is { } e ? Enumerated(e) : [], + .. extraEnumerated is { } x ? Enumerated(x) : [], + .. icc ? BoxOf("colr", [2, 0, 0, .. new byte[16]]) : [], + ]; byte[] depths = bpcc is null ? [] : BoxOf("bpcc", bpcc); + byte[] header = noJp2h ? [] : BoxOf("jp2h", [.. BoxOf("ihdr", ihdr), .. depths, .. colours]); return [ 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A, .. BoxOf("ftyp", [.. "jp2 "u8, 0, 0, 0, 0, .. "jp2 "u8]), - .. BoxOf("jp2h", [.. BoxOf("ihdr", ihdr), .. depths, .. BoxOf("colr", colr)]), + .. header, .. BoxOf("jp2c", codestream), ]; } - [Fact] - public void Iso32000_2_7_4_9_PinsTodayAJp2WithASyccColourSpecificationIsWrittenAsDeviceRgb() - { - // Enumerated colour space 18 is sYCC. The dictionary's ColorSpace, when present, replaces the file's colour - // specification (Table 87), so the YCC samples are read as RGB. - var bytes = Jp2File(JpxCodestream(16, 16, 3), 3, 18); - var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode"))); - Assert.Equal("DeviceRGB", image.Name("ColorSpace")); + [Theory] + [InlineData(18)] + [InlineData(20)] + [InlineData(22)] + [InlineData(24)] + public void Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName(int enumerated) + { + // Enumerated colour space 18 is sYCC; Table 87 says a ColorSpace that is present replaces the colour + // specification of the file, so ColorSpace is left out and the colr box decides. + var bytes = Jp2File(JpxCodestream(16, 16, 3), 3, enumerated); + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-other", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode"))); + Assert.Null(image.Dict.Get(N("ColorSpace"))); + Assert.Equal("JPXDecode", image.Name("Filter")); var colr = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Single(b => b.Type == "colr").Payload; - Assert.Equal(18, colr[6]); + Assert.Equal(enumerated, colr[6]); + Assert.Equal(JpxCodestream(16, 16, 3), Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload); } - [Fact(Skip = "Gap #763: JpxImageLoader writes a device colour space from the channel count and not from the colr " + - "box, so a JP2 file whose colour is sYCC is written as DeviceRGB, which replaces the file's own colour " + - "specification. ISO 32000-1 and -2, 7.4.9 (ColorSpace): the writer shall ensure the samples are consistent " + - "with the colour space used.")] - public void Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName() + [Fact] + public void Iso32000_2_7_4_9_AJp2OfSyccWithNoColorSpaceInTheDictionaryPassesVeraPdfUnderPdfA2b() { var bytes = Jp2File(JpxCodestream(16, 16, 3), 3, 18); - byte[] file; - try - { - file = ImageFile(PdfConformance.None, new Kind("jp2-sycc", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode")); - } - catch (Exception e) when (e is InvalidDataException or NotSupportedException) - { - return; - } - - // ColorSpace is left out, so the colr box decides. + var file = ImageFile(PdfConformance.PdfA2b, new Kind("jp2-sycc", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode")); Assert.Null(Written(file).Dict.Get(N("ColorSpace"))); + Assert.Empty(VeraFailures("2b", file)); + } + + [Theory] + [InlineData(16, "DeviceRGB", 3)] + [InlineData(17, "DeviceGray", 1)] + [InlineData(12, "DeviceCMYK", 4)] + public void Iso32000_2_7_4_9_AJp2OfADeviceColourSpaceKeepsItsDeviceName(int enumerated, string name, int channels) + { + var bytes = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated); + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-device", bytes, 16, 16, name, 8, "JPXDecode"))); + Assert.Equal(name, image.Name("ColorSpace")); } [Fact] - public void Iso32000_2_7_4_9_PinsTodayABareCodestreamOfTwoChannelsGetsAnSrgbColourSpecification() + public void Iso32000_2_7_4_9_AJp2WithAnIccProfileAndNoEnumeratedColourSpaceHasNoColorSpace() { - var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, - "DeviceRGB", 8, "JPXDecode"))); - var header = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload); - Assert.Equal(2, (header[0].Payload[8] << 8) | header[0].Payload[9]); - Assert.Equal(16, header[1].Payload[6]); - Assert.Equal("DeviceRGB", image.Name("ColorSpace")); - - // veraPDF's 6.2.8.3-1 fails the file under a PDF/A claim: the image has two colour channels. - var claimed = ImageFile(PdfConformance.PdfA2b, new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, "DeviceRGB", - 8, "JPXDecode")); - Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", claimed)); + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-icc", Jp2File(JpxCodestream(16, 16, 3), 3, null, + icc: true), 16, 16, "DeviceRGB", 8, "JPXDecode"))); + Assert.Null(image.Dict.Get(N("ColorSpace"))); } - [Fact(Skip = "Gap #763: JpxImageLoader wraps a bare codestream of two channels in a JP2 file whose colr box says " + - "sRGB and whose ihdr says two channels, and veraPDF fails the PDF/A-2b file on 6.2.8.3-1. ISO 32000-1 and -2, " + - "7.4.9: the number of channels shall match the colour space.")] - public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure() + [Fact] + public void Iso32000_2_7_4_9_AJp2WithAnEnumeratedDeviceSpaceAmongItsColourSpecificationsKeepsTheDeviceName() { - AssertRefusedOrAcceptedByVeraPdf(new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, "DeviceRGB", 8, "JPXDecode")); + // sRGB first and sYCC second: a device specification is present, so the name this loader has always + // written stays. + var bytes = Jp2File(JpxCodestream(16, 16, 3), 3, 16, extraEnumerated: 18); + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-two", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode"))); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); + } + + [Theory] + [InlineData(2)] + [InlineData(5)] + [InlineData(16)] + public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure(int channels) + { + // The loader describes a bare codestream to PDF by a colr box it writes, and no device space has two, five + // or sixteen channels, so it refuses. ISO 32000-2, 7.4.9: the colour channels shall match the components of + // the colour space. + var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, channels))); + Assert.Contains($"{channels} channels", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(JpxCodestream(16, 16, channels))); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(JpxCodestream(16, 16, channels), channels, + null, noJp2h: true))); } /// @@ -862,7 +891,7 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndF Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - [Fact(Skip = "Gap #763: a JP2 file of two channels is passed through with /ColorSpace /DeviceGray, and veraPDF " + + [Fact(Skip = "Gap #763, held for a ruling: a JP2 file of two channels is passed through with /ColorSpace /DeviceGray, and veraPDF " + "fails the PDF/A-2b file on 6.2.8.3-1. ISO 32000-1 and -2, 7.4.9: the number of channels shall match the " + "colour space. The test accepts a refusal or a file veraPDF passes, as #763 asks.")] public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure() @@ -881,7 +910,7 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsP Assert.Equal(["6.2.8.3-5"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - [Fact(Skip = "Gap #763: a JP2 file whose channels have depths of 8, 8 and 4 bits (ihdr 0xFF and a bpcc box) is passed " + + [Fact(Skip = "Gap #763, held for a ruling: a JP2 file whose channels have depths of 8, 8 and 4 bits (ihdr 0xFF and a bpcc box) is passed " + "through as /DeviceRGB with /BitsPerComponent 8, and veraPDF fails the PDF/A-2b file on 6.2.8.3-5. ISO 19005-2, " + "6.2.8.3: every channel has the same bit depth. The test accepts a refusal or a file veraPDF passes, as #763 asks.")] public void Iso19005_2_6_2_8_3_AJp2FileWithChannelsOfDifferentDepthsIsRefusedOrWrittenWithoutAVeraPdfFailure() @@ -894,39 +923,37 @@ public void Iso19005_2_6_2_8_3_AJp2FileWithChannelsOfDifferentDepthsIsRefusedOrW [7, 7, 3]), 16, 16, "DeviceRGB", 8, "JPXDecode"); [Fact] - public void Iso32000_2_7_4_9_PinsTodayAJp2WithACieJabColourSpecificationIsWrittenAsDeviceRgbAndVeraPdfDoesNotLook() + public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefusedOrBackedByAnIccProfile() { - // Enumerated colour space 19 is CIEJab, which 19005-2 6.2.8.3 forbids. With ColorSpace in the dictionary, - // veraPDF's rules 6.2.8.3-2 to -4 do not inspect the colr box (each begins hasColorSpace == true ||). + // Enumerated colour space 19 is CIEJab, which 7.4.9 of ISO 32000-2 excludes. With neither an ICC profile nor + // another specification the loader refuses; neither /DeviceRGB nor an absent ColorSpace would be valid. var kind = new Kind("jp2-cielab", Jp2File(JpxCodestream(16, 16, 3), 3, 19), 16, 16, "DeviceRGB", 8, "JPXDecode"); - var image = Written(ImageFile(PdfConformance.None, kind)); - Assert.Equal("DeviceRGB", image.Name("ColorSpace")); - var colr = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Single(b => b.Type == "colr").Payload; - Assert.Equal(19, colr[6]); - Assert.Empty(VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); + var e = Assert.Throws(() => ImageFile(PdfConformance.None, kind)); + Assert.Contains("CIEJab", e.Message); + Assert.Throws(() => ImageFile(PdfConformance.PdfA2b, kind)); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(JpxCodestream(16, 16, 3), 3, 19, + extraEnumerated: 19))); } - [Fact(Skip = "Gap #763: a JP2 file whose only colour specification is CIEJab (enumerated colour space 19) is written " + - "as /DeviceRGB. ISO 32000-2, 7.4.9, excludes CIEJab from the colour spaces a JPEG 2000 image in a PDF file may " + - "have; ISO 32000-1 allows it. Neither DeviceRGB nor an absent ColorSpace is valid, so the file is refused, or the " + - "output is backed by an ICC profile.")] - public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefusedOrBackedByAnIccProfile() + [Fact] + public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndHasNoColorSpace() { - var kind = new Kind("jp2-cielab", Jp2File(JpxCodestream(16, 16, 3), 3, 19), 16, 16, "DeviceRGB", 8, "JPXDecode"); - byte[] file; - try - { - file = ImageFile(PdfConformance.None, kind); - } - catch (InvalidDataException) - { - return; - } + var kind = new Kind("jp2-cielab-icc", Jp2File(JpxCodestream(16, 16, 3), 3, 19, icc: true), 16, 16, "DeviceRGB", 8, + "JPXDecode"); + var image = Written(ImageFile(PdfConformance.None, kind)); + Assert.Null(image.Dict.Get(N("ColorSpace"))); + var colours = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Where(b => b.Type == "colr") + .Select(b => (int)b.Payload[0]).ToArray(); + Assert.Equal([1, 2], colours); + } - var image = Written(file); + [Fact] + public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused() + { + // sYCC beside CIEJab is a usable specification, so the file is not CIEJab only. + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-cielab-sycc", Jp2File(JpxCodestream(16, 16, 3), 3, + 19, extraEnumerated: 18), 16, 16, "DeviceRGB", 8, "JPXDecode"))); Assert.Null(image.Dict.Get(N("ColorSpace"))); - var colr = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Single(b => b.Type == "colr").Payload; - Assert.Equal(2, colr[0]); } [Fact] From 2e5261686b9ad91bc16888b1f7e4f04123ad7a7d Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 23:00:02 +0100 Subject: [PATCH 05/22] feat(layout): report JP2 images that PDF/A-2 6.2.8.3 does not allow A JP2 file with a channel count other than 1, 3 or 4, or with channels of different bit depths, is valid under ISO 32000-2 7.4.9 and fails ISO 19005-2 6.2.8.3, so the Kernel loader keeps passing it through. The Layout save now reports each under a PDF/A-2b, 2u or 2a claim as the new error LayoutDiagnosticCode.JpxImageNotAllowedByPdfA (501), naming the image and the clause, so StrictDiagnostics refuses it. Without a claim, and under PDF/UA-1, nothing is reported. The loader records the ihdr channel count and whether the bpcc box gives different depths on the image, internally. The two audit accept tests become tests of the report and of the strict refusal; the pins of today's bytes stay. The loader docs carry the Do not pass. --- CHANGELOG.md | 15 ++- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 29 ++++- .../Images/PdfImageXObject.cs | 9 ++ src/VellumPdf.Layout/Elements/LayoutImage.cs | 5 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 19 +++ src/VellumPdf.Layout/PublicAPI.Unshipped.txt | 1 + .../Rendering/DocumentRenderer.Zones.cs | 1 + .../Rendering/ImageDiagnostics.cs | 44 +++++++ .../Rendering/LayoutDiagnosticSink.cs | 2 + .../Rendering/LayoutImageRenderer.cs | 1 + .../ConformanceAuditG4Tests.Images.cs | 110 +++++++++++++++--- 11 files changed, 213 insertions(+), 23 deletions(-) create mode 100644 src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index cd4f7dabe..9c646c3ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -865,11 +865,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). specification is enumerated colour space 19 (CIEJab), which 7.4.9 excludes. A JP2 file whose colour specifications include no sRGB, greyscale or CMYK space (an ICC profile, sYCC, or another enumerated space) is written with no `ColorSpace`, so the file's own specification - decides. **Deliberate output changes and new refusals:** those inputs; every other JPEG - (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file with an sRGB, greyscale or CMYK - `colr` box or no readable one writes the same bytes as before. A JP2 file of two channels - beside a greyscale `colr` box, and one whose channels have different depths, still pass - through unchanged. + decides, which includes a JP2 file with only an ICC profile. A JP2 file of two channels, or + with channels of different depths (a `bpcc` box), is valid under ISO 32000-2 and fails ISO + 19005-2, 6.2.8.3, so the loader still passes it through, and a Layout save under a PDF/A-2 + claim reports it as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error + that `StrictDiagnostics` refuses, naming the image and the clause; without a claim nothing + changes. **Deliberate output changes and new refusals:** those inputs, and the new diagnostic + under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every + JP2 file with an sRGB, greyscale or CMYK `colr` box or no readable one writes the same bytes + as before. - **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and @@ -900,6 +904,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). change:** the `Mask` array of a PNG whose `tRNS` word has bits above the depth (for example grey 8-bit with `01 10`, now `[16 16]`); a PNG whose key bits above the depth are zero, a 16-bit PNG and a PNG with no key write the same bytes as before. + - **A nested unordered list marker is no longer drawn as `?` in a Standard 14 font (#545).** The white bullet, U+25E6, is not in WinAnsiEncoding, so a Standard 14 font wrote it as `?` and recorded one `TextEncodingWarning` per marker. A marker is now the first of its level's diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index af69cfb09..73d20847d 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -59,9 +59,15 @@ namespace VellumPdf.Images; /// nothing else to use. /// /// An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile is -/// not read or checked. Indexed colour spaces are not handled. A JP2 file whose channels have -/// different bit depths (a bpcc box), or whose ihdr counts two channels beside a -/// greyscale colr, is passed through under the colour space above. +/// not read or checked. Indexed colour spaces are not handled. +/// A JP2 file with a channel count other than 1, 3 or 4, or with channels of different bit +/// depths (a bpcc box), is passed through. ISO 32000-2, 7.4.9, allows both, and +/// ISO 19005-2, 6.2.8.3, allows neither. This loader neither refuses nor reports them. A +/// VellumPdf.Layout save reports each, under a PDF/A-2 claim, as +/// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document +/// built on this loader and VellumPdf.Kernel alone has no such report. Do not pass +/// such a file to a PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks +/// the report from the loaders. /// public static class JpxImageLoader { @@ -75,6 +81,7 @@ public static class JpxImageLoader private const uint BoxTypeFtyp = 0x66747970; // "ftyp" private const uint BoxTypeIhdr = 0x69686472; // "ihdr" private const uint BoxTypeColr = 0x636F6C72; // "colr" + private const uint BoxTypeBpcc = 0x62706363; // "bpcc" private const uint BoxTypeJp2c = 0x6A703263; // "jp2c" (contiguous codestream) // JPEG 2000 SOC marker (start of codestream). @@ -318,7 +325,13 @@ private static PdfImageXObject LoadJp2(byte[] data) jp2 = BuildMinimalJp2(width, height, nc, bpc, colrEnum ?? EnumCsForComponents(nc), jp2cBox); } - return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc); + // What the loader passes through but PDF/A-2 6.2.8.3 does not allow is recorded for the Layout + // package, which reports it under a PDF/A claim; the Kernel writes the image either way. + return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) + { + Jp2ChannelCount = nc, + Jp2DepthsDiffer = colr.DepthsDiffer, + }; } // ── Box reading ─────────────────────────────────────────────────────────── @@ -450,6 +463,13 @@ private static void ParseJp2Header( case BoxTypeColr: TryParseColr(data, subPayloadOffset, subPayloadLength, ref colrEnum, colr); break; + + case BoxTypeBpcc: + // One byte per channel: the depth less one, and the sign in the top bit. + for (var i = 1; i < subPayloadLength; i++) + if (data[subPayloadOffset + i] != data[subPayloadOffset]) + colr.DepthsDiffer = true; + break; } pos += (int)subTotal; @@ -499,6 +519,7 @@ private sealed class ColrSurvey { public List Enumerated { get; } = []; public bool HasIccProfile { get; set; } + public bool DepthsDiffer { get; set; } } // ── SIZ marker parsing ──────────────────────────────────────────────────── diff --git a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs index 894c7ccef..3012bea64 100644 --- a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs +++ b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs @@ -61,6 +61,15 @@ internal PdfImageXObject( _passthrough = !filter.Equals(PdfName.FlateDecode); } + /// + /// The channel count of the ihdr box of a JP2 file read by , or 0 + /// for any other image. Read by the Layout package to report what PDF/A-2 6.2.8.3 does not allow. + /// + internal int Jp2ChannelCount { get; init; } + + /// Whether the bpcc box of a JP2 file gives its channels different bit depths. + internal bool Jp2DepthsDiffer { get; init; } + /// The soft-mask (alpha channel) stream, or when the image is opaque. public PdfStream? SMask => _sMask; diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 6d3645d88..a4a258268 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -313,7 +313,10 @@ public LayoutImage(PdfImageXObject image) /// whose channel count is not 1, 3 or 4, and a JP2 file whose only colour specification is /// CIEJab (). A JP2 file with an ICC profile or an /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; - /// it is written with no /ColorSpace, so the colour specification in the file decides. + /// it is written with no /ColorSpace, so the colour specification in the file decides. + /// A JP2 file whose channel count is not 1, 3 or 4, or whose channels have different bit depths, + /// is not refused either; the save reports it as + /// under a PDF/A-2 claim. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 /// and Group 4 data carries no header and needs its width, height and coding parameters. Load diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 0e9e8a543..b0557e393 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -312,6 +312,25 @@ public enum LayoutDiagnosticCode /// BandTruncated = 401, + /// + /// A JPEG 2000 image of a JP2 file was drawn in a document whose conformance is PDF/A-2b, + /// PDF/A-2u or PDF/A-2a, and the file has a channel count other than 1, 3 or 4, or channels of + /// different bit depths. Each distinct element and finding is one item, and the message names + /// the image by its alternative text, when it has one, and its size in pixels. + /// + /// + /// Strict mode refuses it. ISO 19005-2:2011, 6.2.8.3, the item's + /// , allows a JPEG 2000 image only one, three or four + /// colour channels, with one bit depth for all of them. ISO 32000-2, 7.4.9, allows both, so the + /// image is written as it is and the file is a valid PDF that PDF/A validation fails. Without a + /// PDF/A claim, and under PDF/UA-1, nothing is reported. The channel count is the one in the + /// file's ihdr box and the depths are those of its bpcc box. Do not pass such + /// a file to a PDF/A document: alone passes it + /// through unreported, 3.0 will refuse it where the image is created, and #474 tracks the + /// loaders' own report. An image that a custom renderer registers itself is not reported. + /// + JpxImageNotAllowedByPdfA = 501, + /// /// An element wrote a font selection for a named Standard 14 font while /// is not diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index eadfdd3cb..41f92dc6f 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -256,3 +256,4 @@ VellumPdf.Layout.Core.LayoutContext.DrawNestedListLevels.get -> bool VellumPdf.Layout.Core.LayoutContext.DrawNestedListLevels.init -> void VellumPdf.Layout.Document.DrawNestedListLevels.get -> bool VellumPdf.Layout.Document.DrawNestedListLevels.set -> void +VellumPdf.Layout.LayoutDiagnosticCode.JpxImageNotAllowedByPdfA = 501 -> VellumPdf.Layout.LayoutDiagnosticCode diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs index dc6c4cdc5..b8c66f8d6 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs @@ -211,6 +211,7 @@ void Place(int zone, double width) if (zones[z].Image is { } logo) { var resName = ctx.RendererContext.RegisterImageXObject(logo.Image); + ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, logo.Image, null); canvas .SaveState() .Concat(band.LogoWidth(z), 0, 0, regionHeight, x[z], ctx.ToPdfY(regionTop + regionHeight)) diff --git a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs new file mode 100644 index 000000000..82e39b2ca --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs @@ -0,0 +1,44 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using VellumPdf.Images; + +namespace VellumPdf.Layout.Rendering; + +/// +/// Reports what a drawn image breaks under a PDF/A claim that the loader writes anyway. +/// +internal static class ImageDiagnostics +{ + /// + /// Reports a JP2 file whose channel count is not 1, 3 or 4, or whose channels have different bit + /// depths, when the sink's claim is PDF/A-2. ISO 32000-2, 7.4.9, allows both; ISO 19005-2, 6.2.8.3, + /// does not. + /// + internal static void ReportJpxUnderPdfA(LayoutDiagnosticSink? sink, PdfImageXObject image, string? altText) + { + if (sink is null || image.Jp2ChannelCount == 0) return; + var clause = LayoutDiagnosticSink.ClauseFor(LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, sink.Conformance); + if (clause is null) return; + + var name = string.IsNullOrEmpty(altText) + ? string.Create(CultureInfo.InvariantCulture, $"The JPEG 2000 image of {image.Width} by {image.Height} pixels") + : string.Create(CultureInfo.InvariantCulture, $"The JPEG 2000 image \"{altText}\" of {image.Width} by {image.Height} pixels"); + if (image.Jp2ChannelCount is not (1 or 3 or 4)) + sink.Report( + LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, + 0, + string.Create(CultureInfo.InvariantCulture, + $"{name} has {image.Jp2ChannelCount} channels; PDF/A-2 allows one, three or four. The image is written as it is."), + perElement: true, + clause: clause); + if (image.Jp2DepthsDiffer) + sink.Report( + LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, + 1, + $"{name} has channels of different bit depths; PDF/A-2 allows one depth for all channels. The image is written as it is.", + perElement: true, + clause: clause); + } +} diff --git a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs index fa25307bd..9deda2459 100644 --- a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs +++ b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs @@ -243,6 +243,8 @@ internal void AddDropped(int count) (LayoutDiagnosticCode.UnembeddedFont, PdfConformance.None) => null, (LayoutDiagnosticCode.UnembeddedFont, PdfConformance.PdfUA1) => "ISO 14289-1:2014, 7.21.4.1", (LayoutDiagnosticCode.UnembeddedFont, _) => "ISO 19005-2:2011, 6.2.11.4.1", + (LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, PdfConformance.PdfA2b or PdfConformance.PdfA2u + or PdfConformance.PdfA2a) => "ISO 19005-2:2011, 6.2.8.3", (LayoutDiagnosticCode.ToUnicodeValueSubstituted, PdfConformance.PdfUA1) => "ISO 14289-1:2014, 7.21.7", (LayoutDiagnosticCode.ToUnicodeValueSubstituted, PdfConformance.PdfA2u or PdfConformance.PdfA2a) => "ISO 19005-2:2011, 6.2.11.7.2", diff --git a/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs b/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs index 478fd26ed..fd9a03462 100644 --- a/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs @@ -224,6 +224,7 @@ public void Draw(DrawContext ctx) // Register the XObject via the per-page RendererContext carried on DrawContext. var resName = ctx.RendererContext.RegisterImageXObject(_img.Image); + ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, _img.Image, _img.AltText); var (areaX, y, _, _) = ctx.ToPdfRect(area); var (boxX, _, _, _) = ctx.ToPdfRect(_occupied); diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 84111f33e..65e0faff3 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -9,6 +9,10 @@ using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; using static VellumPdf.Kernel.Tests.ConformanceAuditG2Support; using static VellumPdf.Kernel.Tests.ConformanceAuditG4Support; +using LayoutDiagnosticCode = VellumPdf.Layout.LayoutDiagnosticCode; +using LayoutDiagnosticSeverity = VellumPdf.Layout.LayoutDiagnosticSeverity; +using LayoutDocumentType = VellumPdf.Layout.Document; +using LayoutElementKind = VellumPdf.Layout.LayoutElementKind; namespace VellumPdf.Kernel.Tests; @@ -891,13 +895,100 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndF Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - [Fact(Skip = "Gap #763, held for a ruling: a JP2 file of two channels is passed through with /ColorSpace /DeviceGray, and veraPDF " + - "fails the PDF/A-2b file on 6.2.8.3-1. ISO 32000-1 and -2, 7.4.9: the number of channels shall match the " + - "colour space. The test accepts a refusal or a file veraPDF passes, as #763 asks.")] - public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure() + /// A JP2 file of two channels beside a greyscale colr box. + private static Kind TwoChannelKind() => new("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 16, 16, "DeviceGray", 8, + "JPXDecode"); + + private static LayoutDocumentType DocumentWith(PdfConformance claim, Kind kind, string? alt = "scan") + { + var doc = NewDocument(claim); + doc.Add(new LayoutImage(Load(kind)) { Width = 40, Height = 20, AltText = alt }); + return doc; + } + + public static TheoryData PdfAImagesNotAllowed() => new() + { + { "two", "has 2 channels" }, + { "depths", "channels of different bit depths" }, + }; + + private static Kind PdfAImage(string which) => which == "two" ? TwoChannelKind() : DifferentDepthsKind(); + + [Theory] + [MemberData(nameof(PdfAImagesNotAllowed))] + public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure(string which, string text) + { + // ISO 32000-2, 7.4.9, allows both inputs, so the Kernel loader keeps them and the Layout save reports them under + // a PDF/A claim: the clause is 19005-2, 6.2.8.3, and the code is an error, so strict mode refuses the save. + foreach (var claim in new[] { PdfConformance.PdfA2b, PdfConformance.PdfA2u, PdfConformance.PdfA2a }) + { + using var doc = DocumentWith(claim, PdfAImage(which)); + var file = Save(doc); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal("ISO 19005-2:2011, 6.2.8.3", item.Clause); + Assert.Equal(LayoutElementKind.Image, item.ElementKind); + Assert.Equal(1, item.Count); + Assert.Contains(text, item.Message); + Assert.Contains("\"scan\"", item.Message); + Assert.Contains("16 by 16 pixels", item.Message); + + // The file is written as the loader writes it, so the report is what stands between it and PDF/A. + Assert.Equal("JPXDecode", Written(file).Name("Filter")); + } + + using var strict = DocumentWith(PdfConformance.PdfA2b, PdfAImage(which)); + strict.StrictDiagnostics = true; + var e = Assert.Throws(() => strict.Save(new MemoryStream())); + Assert.Contains("JpxImageNotAllowedByPdfA", e.Message); + Assert.Contains("ISO 19005-2", e.Message + string.Join("", strict.Diagnostics.Select(d => d.Clause))); + } + + [Theory] + [MemberData(nameof(PdfAImagesNotAllowed))] + public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsNotReportedWithoutAPdfAClaim(string which, string text) + { + Assert.NotEmpty(text); + foreach (var claim in new[] { PdfConformance.None, PdfConformance.PdfUA1 }) + { + using var doc = DocumentWith(claim, PdfAImage(which)); + doc.StrictDiagnostics = true; + Assert.NotEmpty(Save(doc)); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + } + + [Fact] + public void Iso19005_2_6_2_8_3_AJp2FileOfOneThreeOrFourChannelsOfOneDepthIsNotReported() + { + foreach (var (channels, space) in new[] { (1, 17), (3, 16), (4, 12) }) + { + var kind = new Kind("jp2-ok", Jp2File(JpxCodestream(16, 16, channels), channels, space), 16, 16, "DeviceRGB", 8, + "JPXDecode"); + using var doc = DocumentWith(PdfConformance.PdfA2b, kind); + Assert.NotEmpty(Save(doc)); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + // A bpcc box whose channels all have one depth is not a difference. + var same = new Kind("jp2-same", Jp2File(JpxCodestream(16, 16, 3, 7, 0, [8, 8, 8]), 3, 16, [7, 7, 7]), 16, 16, + "DeviceRGB", 8, "JPXDecode"); + using var sameDoc = DocumentWith(PdfConformance.PdfA2b, same); + Assert.NotEmpty(Save(sameDoc)); + Assert.DoesNotContain(sameDoc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AJp2FileWithBothFindingsGivesOneItemForEach() { - AssertRefusedOrAcceptedByVeraPdf(new Kind("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 16, 16, "DeviceGray", - 8, "JPXDecode")); + var kind = new Kind("jp2-both", Jp2File(JpxCodestream(16, 16, 2, 7, 0, [8, 4]), 2, 17, [7, 3]), 16, 16, "DeviceGray", + 8, "JPXDecode"); + using var doc = DocumentWith(PdfConformance.PdfA2b, kind, alt: null); + Save(doc); + var items = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).ToArray(); + Assert.Equal(2, items.Length); + Assert.Contains("The JPEG 2000 image of 16 by 16 pixels has 2 channels", items[0].Message); + Assert.Contains("different bit depths", items[1].Message); } [Fact] @@ -910,13 +1001,6 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsP Assert.Equal(["6.2.8.3-5"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - [Fact(Skip = "Gap #763, held for a ruling: a JP2 file whose channels have depths of 8, 8 and 4 bits (ihdr 0xFF and a bpcc box) is passed " + - "through as /DeviceRGB with /BitsPerComponent 8, and veraPDF fails the PDF/A-2b file on 6.2.8.3-5. ISO 19005-2, " + - "6.2.8.3: every channel has the same bit depth. The test accepts a refusal or a file veraPDF passes, as #763 asks.")] - public void Iso19005_2_6_2_8_3_AJp2FileWithChannelsOfDifferentDepthsIsRefusedOrWrittenWithoutAVeraPdfFailure() - { - AssertRefusedOrAcceptedByVeraPdf(DifferentDepthsKind()); - } /// A JP2 file of three channels whose depths are 8, 8 and 4 bits, given by a bpcc box. private static Kind DifferentDepthsKind() => new("jp2-depths", Jp2File(JpxCodestream(16, 16, 3, 7, 0, [8, 8, 4]), 3, 16, From 5877cd8375bdeb13cdca086216d1d594b8199f86 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 29 Nov 2026 23:13:54 +0100 Subject: [PATCH 06/22] docs(layout): name the JP2 PDF/A diagnostic in the diagnostics list The documentation test requires every LayoutDiagnosticCode to appear in the Document.Diagnostics remarks; the new code was missing. --- src/VellumPdf.Layout/Document.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 512ca928a..02b2f5668 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -125,6 +125,8 @@ public Document() { } /// (a character an embedded font has no glyph /// for, written as glyph 0), (an element that /// selects a Standard 14 font under a conformance claim), + /// (a JP2 image of a channel count + /// other than 1, 3 or 4, or of channels of different bit depths, under a PDF/A-2 claim), /// (a link in the style of a table cell or a /// running band that a PDF/UA-1 claim left unwritten), /// (a character whose ToUnicode From 36f4ab4f8563f22fef7ad383b88aaa2d5cf39104 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 09:29:51 +0100 Subject: [PATCH 07/22] fix(images): write a JP2 device name only for a channel count it fits Review of the #763 loader change found three gaps. A JP2 file with two or more colr boxes and none a device space lost its ColorSpace and then failed PDF/A-2b in veraPDF, where it had passed with the name; only a file with exactly one such box is now written without one. A jp2h file whose ihdr channel count the device name does not fit (one channel beside sRGB, five with no colr box) is refused, as the same data with no jp2h already was, because 7.4.9 matches the colour channels to the components; one channel beyond the space is read as an opacity channel, a CMYK colr box names DeviceCMYK where only that fits, and a pclr or cmap box keeps the name. The PDF/A-2 report for JP2 files no longer quotes the image's alternative text, so the Layout diagnostics still retain no caller text, and a bpcc box that differs only in sign is named as such. The doc sentences that called the kept files valid now say what the code does. A test covers the band logo report, and the conformance rows for #763, #764, #768 and #770 follow in the next commit. --- CHANGELOG.md | 42 ++-- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 133 ++++++++---- .../Images/PdfImageXObject.cs | 2 +- .../Images/TiffImageLoader.cs | 6 +- src/VellumPdf.Layout/Document.cs | 2 +- src/VellumPdf.Layout/Elements/LayoutImage.cs | 17 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 28 ++- .../Rendering/DocumentRenderer.Zones.cs | 2 +- .../Rendering/ImageDiagnostics.cs | 17 +- .../Rendering/LayoutImageRenderer.cs | 2 +- .../ConformanceAuditG4Tests.Images.cs | 48 ++--- .../ConformanceAuditG4Tests.JpxChannels.cs | 197 ++++++++++++++++++ 12 files changed, 383 insertions(+), 113 deletions(-) create mode 100644 tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c646c3ac..94886f0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -855,25 +855,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). specification is no longer overridden by a device name (#763).** `JpegImageLoader` chose `/DeviceRGB` for every component count other than 1 and 4 and accepted every frame type and precision, and `JpxImageLoader` wrote a device name from the channel count whatever the `colr` - box said. ISO 32000-2, 7.4.8, gives DCTDecode data one, three or four components of a byte - each, and 7.4.9 says a `ColorSpace` that is present replaces the colour specification in the - JPEG 2000 data and that the colour channels shall match its components. `Load` now throws + box or the count said. ISO 32000-2, 7.4.8, gives DCTDecode data one, three or four components of + a byte each, and 7.4.9 says a `ColorSpace` that is present replaces the colour specification in + the JPEG 2000 data and that the colour channels shall match its components. `Load` now throws `InvalidDataException` for a JPEG frame with a component count other than 1, 3 or 4, a precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` - box, of a channel count other than 1, 3 or 4, and for a JP2 file whose only colour - specification is enumerated colour space 19 (CIEJab), which 7.4.9 excludes. A JP2 file whose - colour specifications include no sRGB, greyscale or CMYK space (an ICC profile, sYCC, or - another enumerated space) is written with no `ColorSpace`, so the file's own specification - decides, which includes a JP2 file with only an ICC profile. A JP2 file of two channels, or - with channels of different depths (a `bpcc` box), is valid under ISO 32000-2 and fails ISO - 19005-2, 6.2.8.3, so the loader still passes it through, and a Layout save under a PDF/A-2 - claim reports it as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error - that `StrictDiagnostics` refuses, naming the image and the clause; without a claim nothing - changes. **Deliberate output changes and new refusals:** those inputs, and the new diagnostic - under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every - JP2 file with an sRGB, greyscale or CMYK `colr` box or no readable one writes the same bytes - as before. + box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it throws when + the device name it would write does not fit the `ihdr` channel count, which is the name's own + component count or one more for an opacity channel: one channel beside sRGB, three beside + greyscale, two with no `colr` box, five with no `colr` box, and so on. Where a `colr` box + names CMYK and the count fits that and no other name, the file is written as `/DeviceCMYK` + (five channels beside CMYK). A file with a `pclr` or `cmap` box keeps the name, because a palette + changes what the channels are. A JP2 file whose only colour specification is enumerated colour + space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box + that names no sRGB, greyscale or CMYK space (an ICC profile, sYCC, or another enumerated space) is + written with no `ColorSpace`, so the file's own specification decides. A file with two or more + `colr` boxes and none of them a device space keeps the device name it had, because veraPDF + 1.30.4 fails such a file under PDF/A-2b without it. A JP2 file whose `bpcc` box gives channels + different depths or signs, or whose channel count is one above its device space (two beside + greyscale), is still written as it was: ISO 32000-2, 7.4.9, lets colour components differ in + bits per sample and matches only the ordinary colour channels to the colour space, and ISO + 19005-2, 6.2.8.3, allows neither. A Layout save under a PDF/A-2 claim reports it as the new + `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error that `StrictDiagnostics` + refuses, naming the image by its size and the clause and quoting no alternative text; without + a claim nothing changes. **Deliberate output changes and new refusals:** those inputs, and the + new diagnostic under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 + components) and every JP2 file that has a device `colr` box or none and a fitting channel + count, two or more `colr` boxes with no device space and a fitting count, or a palette writes + the same bytes as before. - **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 73d20847d..0b1995240 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -51,23 +51,37 @@ namespace VellumPdf.Images; /// DeviceRGB. /// A JP2 file with no colr box the loader can readthe /// channel count chooses, as above. -/// A JP2 file with only other colour specifications: an ICC profile, or an -/// enumerated space such as sYCC (18)ColorSpace is left out, so the +/// A JP2 file with exactly one colr box, naming no device space: an ICC profile, +/// or an enumerated space such as sYCC (18)ColorSpace is left out, so the /// colour specification in the file decides. +/// A JP2 file with two or more colr boxes, none naming a device +/// spacethe channel count chooses, as above. Without the name, veraPDF 1.30.4 +/// fails these files under PDF/A-2b, which it passes with it. /// A JP2 file whose only colour specifications are enumerated colour space 19 /// (CIEJab)refused, because ISO 32000-2, 7.4.9, excludes CIEJab and there is /// nothing else to use. /// +/// A device name is written only for a channel count that fits it. The ihdr box +/// of a JP2 file with a jp2h box gives the channel count, and ISO 32000-2, 7.4.9, says the +/// ordinary colour channels shall match the components of the colour space. A device name fits a +/// count equal to its components (1, 3 or 4) or one more, which the loader takes as one opacity +/// channel; the cdef box is not read. Where the name chosen above does not fit and a +/// colr box names CMYK, DeviceCMYK is written if the count fits that. Any other file is +/// refused with , because the dictionary would describe samples +/// the data does not have. A file with a pclr or cmap box keeps the name, because a +/// palette changes what the channels are and those boxes are not read. /// An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile is /// not read or checked. Indexed colour spaces are not handled. -/// A JP2 file with a channel count other than 1, 3 or 4, or with channels of different bit -/// depths (a bpcc box), is passed through. ISO 32000-2, 7.4.9, allows both, and -/// ISO 19005-2, 6.2.8.3, allows neither. This loader neither refuses nor reports them. A -/// VellumPdf.Layout save reports each, under a PDF/A-2 claim, as -/// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document -/// built on this loader and VellumPdf.Kernel alone has no such report. Do not pass -/// such a file to a PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks -/// the report from the loaders. +/// A JP2 file whose bpcc box gives channels of different bit depths or signs, or +/// whose channel count is one above its device colour space (2 beside a greyscale colr box, 5 +/// beside CMYK), is passed through. ISO 32000-2, 7.4.9, lets the colour components differ in +/// bits per sample and counts only the ordinary colour channels against the colour space, and ISO +/// 19005-2, 6.2.8.3, allows neither. This loader neither refuses nor reports them. A +/// VellumPdf.Layout save reports each file whose channel count is not 1, 3 or 4, or whose +/// bpcc entries differ, under a PDF/A-2 claim as LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and +/// strict mode refuses it. A document built on this loader and VellumPdf.Kernel alone has no +/// such report. Do not pass such a file to a PDF/A document: 3.0 will refuse it where the +/// image is created, and #474 tracks the report from the loaders. /// public static class JpxImageLoader { @@ -82,15 +96,18 @@ public static class JpxImageLoader private const uint BoxTypeIhdr = 0x69686472; // "ihdr" private const uint BoxTypeColr = 0x636F6C72; // "colr" private const uint BoxTypeBpcc = 0x62706363; // "bpcc" + private const uint BoxTypePclr = 0x70636C72; // "pclr" (palette) + private const uint BoxTypeCmap = 0x636D6170; // "cmap" (component mapping) private const uint BoxTypeJp2c = 0x6A703263; // "jp2c" (contiguous codestream) // JPEG 2000 SOC marker (start of codestream). private const ushort MarkerSOC = 0xFF4F; // JPEG 2000 SIZ marker (image and tile size). private const ushort MarkerSIZ = 0xFF51; - // Bit 15 of the SIZ marker's Rsiz field, the bit that marks a codestream using capabilities - // beyond JPEG 2000 Part 1. ISO/IEC 15444 is not held in this repository, so this bit is the - // only part of Rsiz the loader reads; the other Rsiz values are not examined. + // Bit 15 of the SIZ marker's Rsiz field. That it marks a codestream using capabilities beyond + // JPEG 2000 Part 1 is a reading of ISO/IEC 15444, which is not held in this repository, so the + // meaning is not checked against the text. This bit is the only part of Rsiz the loader reads; + // the other Rsiz values are not examined. private const int RsizPart2Bit = 0x8000; // colr enumColourspace values (ISO 15444-1 Table I.11). @@ -111,21 +128,25 @@ public static class JpxImageLoader /// Thrown when the data is malformed, truncated, or its dimensions exceed /// , or when the codestream's Rsiz has the Part 2 /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h - /// box, with a channel count other than 1, 3 or 4, and for a JP2 file whose only colour - /// specifications are enumerated colour space 19 (CIEJab). + /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose + /// channel count no device colour space fits (see the class summary), and for a JP2 file whose + /// only colour specifications are enumerated colour space 19 (CIEJab). /// /// /// A channel count that no device colour space has is refused for a bare codestream /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a /// colr box it writes, and ISO 32000-2, 7.4.9, says the colour channels shall match the - /// components of the colour space. A JP2 file whose only colour specification is CIEJab is + /// components of the colour space. A channel count that the device name does not fit is + /// refused for a JP2 file with a jp2h box too, as the class summary says. A JP2 file whose only colour specification is CIEJab is /// refused: neither a device name nor an absent ColorSpace would be valid for it. One /// that also has an ICC profile, or another enumerated space, is written with no /// ColorSpace. The class summary lists what is written for each colour specification. /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws /// naming the Rsiz value when bit 15 of the SIZ marker's /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the - /// JPX baseline set of features. The bit is read + /// JPX baseline set of features, and bit 15 marks capabilities + /// beyond JPEG 2000 Part 1. That meaning comes from ISO/IEC 15444, which is not held here, so it is not + /// checked against the text. The bit is read /// from a bare codestream and from the jp2c box of a JP2 file whose codestream starts with /// SOC and SIZ. This loader checks only that bit: the text that defines the baseline set is /// ISO/IEC 15444, which is not checked here, so a codestream that sets no Part 2 bit but still uses @@ -152,8 +173,9 @@ public static PdfImageXObject Load(byte[] jpx) /// Thrown when the data is malformed, truncated, or its dimensions exceed /// , or when the codestream's Rsiz has the Part 2 /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h - /// box, with a channel count other than 1, 3 or 4, and for a JP2 file whose only colour - /// specifications are enumerated colour space 19 (CIEJab). + /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose + /// channel count no device colour space fits (see the class summary), and for a JP2 file whose + /// only colour specifications are enumerated colour space 19 (CIEJab). /// /// /// Thrown when requests . @@ -470,6 +492,13 @@ private static void ParseJp2Header( if (data[subPayloadOffset + i] != data[subPayloadOffset]) colr.DepthsDiffer = true; break; + + case BoxTypePclr: + case BoxTypeCmap: + // A palette turns the stored channels into colour channels, so the ihdr channel count + // no longer says how many colour channels there are. These boxes are not read. + colr.HasPalette = true; + break; } pos += (int)subTotal; @@ -496,6 +525,7 @@ private static void ParseIhdr( // colr payload: METH(1) PREC(1) APPROX(1) [EnumCS(4) if METH=1] [ICCProfile if METH=2]. private static void TryParseColr(byte[] data, int offset, int length, ref int? colrEnum, ColrSurvey colr) { + colr.Boxes++; if (length < 3) return; // malformed but non-fatal for colour space purposes @@ -513,12 +543,15 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c } } - // What the colr boxes of a JP2 file hold: every enumerated colour space in file order, and whether - // any box carries an ICC profile. colrEnum above keeps the last enumerated value, as it always has. + // What the jp2h box of a JP2 file holds: the number of colr boxes, every enumerated colour space in + // file order, whether any box carries an ICC profile, whether there is a palette, and whether the bpcc + // depths differ. colrEnum above keeps the last enumerated value, as it always has. private sealed class ColrSurvey { + public int Boxes { get; set; } public List Enumerated { get; } = []; public bool HasIccProfile { get; set; } + public bool HasPalette { get; set; } public bool DepthsDiffer { get; set; } } @@ -650,28 +683,54 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // ── Colour space inference ──────────────────────────────────────────────── // The /ColorSpace of an image from a JP2 file, or null to leave it out so the colour specification - // in the JPEG 2000 data decides (ISO 32000-2, 7.4.9, Table 87: a ColorSpace that is present - // replaces that specification). - // - A device space among the enumerated ones (12, 16, 17): the name this loader has always - // chosen, from the last enumerated value or the channel count. - // - No device space, and an ICC profile or an enumerated space such as sYCC: left out. A device - // name would make a reader take the samples as device samples. - // - Only CIEJab (19): refused, since neither a name nor the colr box gives a colour space a - // PDF file may use. - // - No usable colr box: the channel count decides, as before. + // in the JPEG 2000 data decides (ISO 32000-2, 7.4.9: a ColorSpace that is present replaces that + // specification, and its component count has to match the ordinary colour channels). + // - A device space among the enumerated ones (12, 16, 17): the name this loader has always chosen, + // from the last enumerated value or the channel count. + // - Only CIEJab (19) and no ICC profile: refused, since neither a name nor the colr box gives a + // colour space a PDF file may use. + // - Exactly one colr box, naming no device space (an ICC profile, or an enumerated space such as + // sYCC): left out. A device name would make a reader take the samples as device samples. + // - Two or more colr boxes and none a device space, or no colr box that can be read: the name this + // loader has always chosen, from the channel count. veraPDF 1.30.4 passes such a file under + // PDF/A-2b with the name and fails it, on 6.2.8.3-2 and 6.2.8.3-3, without it, because none of + // the boxes has an APPROX of 1. + // A name is written only where the channel count fits it; see FitChannels. private static ImageColorSpace? ColorSpaceOf(int components, int? colrEnum, ColrSurvey colr) { if (colr.Enumerated.Exists(e => e is ColrEnumCmyk or ColrEnumSRgb or ColrEnumGreyscale)) - return InferColorSpace(components, colrEnum); - if (colr.HasIccProfile) - return null; - if (colr.Enumerated.Count == 0) - return InferColorSpace(components, colrEnum); - if (colr.Enumerated.TrueForAll(e => e == ColrEnumCieJab)) + return FitChannels(InferColorSpace(components, colrEnum), components, colr, + colr.Enumerated.Contains(ColrEnumCmyk)); + if (colr.Enumerated.Count > 0 && !colr.HasIccProfile && colr.Enumerated.TrueForAll(e => e == ColrEnumCieJab)) throw new InvalidDataException( "JP2 file: its only colour specification is enumerated colour space 19 (CIEJab), which " + "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); - return null; + if (colr.Boxes == 1 && (colr.HasIccProfile || colr.Enumerated.Count == 1)) + return null; + return FitChannels(InferColorSpace(components, colrEnum), components, colr, false); + } + + // The number of ordinary colour channels a device space takes (ISO 32000-2, 7.4.9), plus the one + // opacity channel a file may add. A name that does not fit is replaced by DeviceCMYK where a colr box + // names CMYK and the count fits that; otherwise the file is refused, because the dictionary would + // describe samples the data does not have. A palette (pclr or cmap box) changes what the channels + // are, and those boxes are not read, so a file that has one keeps the name. + private static ImageColorSpace FitChannels(ImageColorSpace named, int components, ColrSurvey colr, bool cmykBox) + { + if (colr.HasPalette || Fits(named, components)) + return named; + if (cmykBox && Fits(ImageColorSpace.DeviceCmyk, components)) + return ImageColorSpace.DeviceCmyk; + throw new InvalidDataException( + $"JP2 file: its ihdr box has {components} channels, which {named} does not take. A device colour " + + "space takes its own component count, or one more for an opacity channel, and the colour channels " + + "shall match the components of the colour space (ISO 32000-2, 7.4.9)."); + } + + private static bool Fits(ImageColorSpace cs, int channels) + { + var own = cs switch { ImageColorSpace.DeviceGray => 1, ImageColorSpace.DeviceCmyk => 4, _ => 3 }; + return channels == own || channels == own + 1; } // A bare codestream, or a JP2 file with no jp2h box, is described to PDF by a colr box this loader diff --git a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs index 3012bea64..23044830d 100644 --- a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs +++ b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs @@ -67,7 +67,7 @@ internal PdfImageXObject( /// internal int Jp2ChannelCount { get; init; } - /// Whether the bpcc box of a JP2 file gives its channels different bit depths. + /// Whether the bpcc box of a JP2 file gives its channels different bit depths or signs. internal bool Jp2DepthsDiffer { get; init; } /// The soft-mask (alpha channel) stream, or when the image is opaque. diff --git a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs index eea7346bf..46224485b 100644 --- a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs @@ -122,7 +122,11 @@ private static byte[] BuildBitReverseLookup() /// samples already multiplied by alpha) writes /Matte [0 0 0] on the soft mask, the /// black matte that formula implies, and leaves the samples as they are. Any other value, or /// none, writes the soft mask with no Matte, as a straight alpha. A 4-sample RGB file - /// whose alpha is 255 everywhere has no soft mask and so no Matte. + /// whose alpha is 255 everywhere has no soft mask and so no Matte. Do not pass a file + /// whose ExtraSamples is 1 and whose colour sample exceeds its alpha, such as 200 beside 100: + /// TIFF 6.0 stores the colour multiplied by alpha, so no colour exceeds it. The loader writes such + /// samples as they are, without clamping them, so the matte formula gives a colour above its range + /// and a reader clamps or not as it chooses; 3.0 will refuse the file. /// A ColorMap the loader cannot use is refused with /// . The tag is read whenever the directory carries it, under /// every compression, so a negative offset on a tag with a nonzero count and an offset that diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 02b2f5668..291dc9996 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -126,7 +126,7 @@ public Document() { } /// for, written as glyph 0), (an element that /// selects a Standard 14 font under a conformance claim), /// (a JP2 image of a channel count - /// other than 1, 3 or 4, or of channels of different bit depths, under a PDF/A-2 claim), + /// other than 1, 3 or 4, or whose channels differ in bit depth or sign, under a PDF/A-2 claim), /// (a link in the style of a table cell or a /// running band that a PDF/UA-1 claim left unwritten), /// (a character whose ToUnicode diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index a4a258268..b564f2825 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -310,13 +310,16 @@ public LayoutImage(PdfImageXObject image) /// a precision other than 8 bits, and a component count other than 1, 3 and 4 /// (). For JPEG 2000 it is a codestream whose /// Rsiz sets the Part 2 bit, a bare codestream or a JP2 file with no jp2h box - /// whose channel count is not 1, 3 or 4, and a JP2 file whose only colour specification is - /// CIEJab (). A JP2 file with an ICC profile or an - /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; - /// it is written with no /ColorSpace, so the colour specification in the file decides. - /// A JP2 file whose channel count is not 1, 3 or 4, or whose channels have different bit depths, - /// is not refused either; the save reports it as - /// under a PDF/A-2 claim. + /// whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose channel count no + /// device colour space fits (the device space's components, or one more), and a JP2 file whose + /// only colour specification is CIEJab ( lists the + /// cases). A JP2 file with exactly one colr box that names an ICC profile or an enumerated + /// colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; it is written + /// with no /ColorSpace, so the colour specification in the file decides. A JP2 file whose + /// bpcc box gives different bit depths or signs, or whose channel count is one above its + /// device colour space, such as 2 channels beside greyscale, is not refused either; the save + /// reports it as under a PDF/A-2 + /// claim. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 /// and Group 4 data carries no header and needs its width, height and coding parameters. Load diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index b0557e393..5ad39b91f 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -314,20 +314,28 @@ public enum LayoutDiagnosticCode /// /// A JPEG 2000 image of a JP2 file was drawn in a document whose conformance is PDF/A-2b, - /// PDF/A-2u or PDF/A-2a, and the file has a channel count other than 1, 3 or 4, or channels of - /// different bit depths. Each distinct element and finding is one item, and the message names - /// the image by its alternative text, when it has one, and its size in pixels. + /// PDF/A-2u or PDF/A-2a, and the file has a channel count other than 1, 3 or 4, or channels whose + /// bpcc entries differ in bit depth or in sign. Each distinct element and finding is one + /// item. The message names the image by its size in pixels and quotes no alternative text; + /// , and + /// say where it is. /// /// /// Strict mode refuses it. ISO 19005-2:2011, 6.2.8.3, the item's /// , allows a JPEG 2000 image only one, three or four - /// colour channels, with one bit depth for all of them. ISO 32000-2, 7.4.9, allows both, so the - /// image is written as it is and the file is a valid PDF that PDF/A validation fails. Without a - /// PDF/A claim, and under PDF/UA-1, nothing is reported. The channel count is the one in the - /// file's ihdr box and the depths are those of its bpcc box. Do not pass such - /// a file to a PDF/A document: alone passes it - /// through unreported, 3.0 will refuse it where the image is created, and #474 tracks the - /// loaders' own report. An image that a custom renderer registers itself is not reported. + /// colour channels, with one bit depth for all of them. ISO 32000-2, 7.4.9, lets the colour + /// components differ in bits per sample and matches only the ordinary colour channels against the + /// colour space, so keeps such a file: a channel + /// count one above the components of the device space it names is read as one opacity channel, + /// and the depths are not touched. The image is written as it is, and PDF/A validation fails it. + /// A JP2 file whose channel count no device space fits is refused by the loader instead and never + /// reaches this report. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. The + /// channel count is the one in the file's ihdr box, and the depths are compared as the + /// bytes of its bpcc box, so one depth with different signs is reported as well. + /// Do not pass such a file to a PDF/A document: + /// alone passes it through unreported, 3.0 will refuse it where the image is created, and #474 + /// tracks the loaders' own report. An image that a custom renderer registers itself is not + /// reported. /// JpxImageNotAllowedByPdfA = 501, diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs index b8c66f8d6..279e4a9bd 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs @@ -211,7 +211,7 @@ void Place(int zone, double width) if (zones[z].Image is { } logo) { var resName = ctx.RendererContext.RegisterImageXObject(logo.Image); - ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, logo.Image, null); + ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, logo.Image); canvas .SaveState() .Concat(band.LogoWidth(z), 0, 0, regionHeight, x[z], ctx.ToPdfY(regionTop + regionHeight)) diff --git a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs index 82e39b2ca..f01b8c020 100644 --- a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs +++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs @@ -12,19 +12,20 @@ namespace VellumPdf.Layout.Rendering; internal static class ImageDiagnostics { /// - /// Reports a JP2 file whose channel count is not 1, 3 or 4, or whose channels have different bit - /// depths, when the sink's claim is PDF/A-2. ISO 32000-2, 7.4.9, allows both; ISO 19005-2, 6.2.8.3, - /// does not. + /// Reports a JP2 file whose channel count is not 1, 3 or 4, or whose bpcc entries differ in depth or + /// sign, when the sink's claim is PDF/A-2. ISO 32000-2, 7.4.9, allows both; ISO 19005-2, 6.2.8.3, + /// does not. The message names the image by its size in pixels and never quotes the alternative text: + /// the item's element kind, element index and page say where it is, and the sink retains no caller + /// text. /// - internal static void ReportJpxUnderPdfA(LayoutDiagnosticSink? sink, PdfImageXObject image, string? altText) + internal static void ReportJpxUnderPdfA(LayoutDiagnosticSink? sink, PdfImageXObject image) { if (sink is null || image.Jp2ChannelCount == 0) return; var clause = LayoutDiagnosticSink.ClauseFor(LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, sink.Conformance); if (clause is null) return; - var name = string.IsNullOrEmpty(altText) - ? string.Create(CultureInfo.InvariantCulture, $"The JPEG 2000 image of {image.Width} by {image.Height} pixels") - : string.Create(CultureInfo.InvariantCulture, $"The JPEG 2000 image \"{altText}\" of {image.Width} by {image.Height} pixels"); + var name = string.Create(CultureInfo.InvariantCulture, + $"The JPEG 2000 image of {image.Width} by {image.Height} pixels"); if (image.Jp2ChannelCount is not (1 or 3 or 4)) sink.Report( LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, @@ -37,7 +38,7 @@ internal static void ReportJpxUnderPdfA(LayoutDiagnosticSink? sink, PdfImageXObj sink.Report( LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, 1, - $"{name} has channels of different bit depths; PDF/A-2 allows one depth for all channels. The image is written as it is.", + $"{name} has channels of different bit depths or signs; PDF/A-2 allows one depth for all channels. The image is written as it is.", perElement: true, clause: clause); } diff --git a/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs b/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs index fd9a03462..d6b293099 100644 --- a/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/LayoutImageRenderer.cs @@ -224,7 +224,7 @@ public void Draw(DrawContext ctx) // Register the XObject via the per-page RendererContext carried on DrawContext. var resName = ctx.RendererContext.RegisterImageXObject(_img.Image); - ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, _img.Image, _img.AltText); + ImageDiagnostics.ReportJpxUnderPdfA(ctx.Diagnostics, _img.Image); var (areaX, y, _, _) = ctx.ToPdfRect(area); var (boxX, _, _, _) = ctx.ToPdfRect(_occupied); diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 65e0faff3..644c90749 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -748,7 +748,8 @@ public void Tiff6_0_8_TheOrientationTagTurnsTheImageSoItsRowZeroIsOnTheSideTheTa /// A JP2 file of whose colr box is METH 1 with the enumerated space. private static byte[] Jp2File(byte[] codestream, int channels, int? enumeratedColourSpace, byte[]? bpcc = null, - bool icc = false, int? extraEnumerated = null, bool noJp2h = false) + bool icc = false, int? extraEnumerated = null, bool noJp2h = false, (int Method, int Value)[]? boxes = null, + bool palette = false) { static byte[] BoxOf(string type, byte[] payload) { @@ -781,6 +782,12 @@ static byte[] Enumerated(int value) .. enumeratedColourSpace is { } e ? Enumerated(e) : [], .. extraEnumerated is { } x ? Enumerated(x) : [], .. icc ? BoxOf("colr", [2, 0, 0, .. new byte[16]]) : [], + // Any colour specifications in file order: METH 1 with the value as the enumerated space, METH 2 and 3 an + // ICC profile of zeros, METH 4 a vendor colour. + .. (boxes ?? []).SelectMany(b => b.Method == 1 ? Enumerated(b.Value) + : BoxOf("colr", [(byte)b.Method, 0, 0, .. new byte[16]])), + // A palette box and a component mapping box; their content is not read, only that they exist. + .. palette ? (byte[])[.. BoxOf("pclr", new byte[8]), .. BoxOf("cmap", new byte[4])] : [], ]; byte[] depths = bpcc is null ? [] : BoxOf("bpcc", bpcc); byte[] header = noJp2h ? [] : BoxOf("jp2h", [.. BoxOf("ihdr", ihdr), .. depths, .. colours]); @@ -853,7 +860,7 @@ public void Iso32000_2_7_4_9_AJp2WithAnEnumeratedDeviceSpaceAmongItsColourSpecif [InlineData(2)] [InlineData(5)] [InlineData(16)] - public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure(int channels) + public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused(int channels) { // The loader describes a bare codestream to PDF by a colr box it writes, and no device space has two, five // or sixteen channels, so it refuses. ISO 32000-2, 7.4.9: the colour channels shall match the components of @@ -865,27 +872,6 @@ public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoChannelsIsRefusedOrWrittenWit null, noJp2h: true))); } - /// - /// What the clause needs of an input that cannot be written validly under PDF/A-2b: the load or the save is - /// refused, or the file written has a ColorSpace that is not a device name for another channel count and veraPDF - /// accepts it. - /// - private static void AssertRefusedOrAcceptedByVeraPdf(Kind kind) - { - byte[] file; - try - { - file = ImageFile(PdfConformance.PdfA2b, kind); - } - catch (InvalidDataException) - { - return; - } - - Assert.Null(Written(file).Dict.Get(N("ColorSpace"))); - Assert.Empty(VeraFailures("2b", file)); - } - [Fact] public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndFailsVeraPdf() { @@ -916,7 +902,7 @@ private static LayoutDocumentType DocumentWith(PdfConformance claim, Kind kind, [Theory] [MemberData(nameof(PdfAImagesNotAllowed))] - public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure(string which, string text) + public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsWrittenAndReportedUnderAPdfAClaim(string which, string text) { // ISO 32000-2, 7.4.9, allows both inputs, so the Kernel loader keeps them and the Layout save reports them under // a PDF/A claim: the clause is 19005-2, 6.2.8.3, and the code is an error, so strict mode refuses the save. @@ -930,7 +916,7 @@ public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVe Assert.Equal(LayoutElementKind.Image, item.ElementKind); Assert.Equal(1, item.Count); Assert.Contains(text, item.Message); - Assert.Contains("\"scan\"", item.Message); + Assert.DoesNotContain("scan", item.Message); Assert.Contains("16 by 16 pixels", item.Message); // The file is written as the loader writes it, so the report is what stands between it and PDF/A. @@ -1007,7 +993,7 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsP [7, 7, 3]), 16, 16, "DeviceRGB", 8, "JPXDecode"); [Fact] - public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefusedOrBackedByAnIccProfile() + public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused() { // Enumerated colour space 19 is CIEJab, which 7.4.9 of ISO 32000-2 excludes. With neither an ICC profile nor // another specification the loader refuses; neither /DeviceRGB nor an absent ColorSpace would be valid. @@ -1020,12 +1006,14 @@ public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefus } [Fact] - public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndHasNoColorSpace() + public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName() { + // Two colour boxes and none a device space: the name stays, because without it veraPDF finds no box with an + // APPROX of 1 and fails the file under PDF/A-2b. var kind = new Kind("jp2-cielab-icc", Jp2File(JpxCodestream(16, 16, 3), 3, 19, icc: true), 16, 16, "DeviceRGB", 8, "JPXDecode"); var image = Written(ImageFile(PdfConformance.None, kind)); - Assert.Null(image.Dict.Get(N("ColorSpace"))); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); var colours = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Where(b => b.Type == "colr") .Select(b => (int)b.Payload[0]).ToArray(); Assert.Equal([1, 2], colours); @@ -1034,10 +1022,10 @@ public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBox [Fact] public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused() { - // sYCC beside CIEJab is a usable specification, so the file is not CIEJab only. + // sYCC beside CIEJab is a second specification, so the file is not CIEJab only; two boxes keep the name. var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-cielab-sycc", Jp2File(JpxCodestream(16, 16, 3), 3, 19, extraEnumerated: 18), 16, 16, "DeviceRGB", 8, "JPXDecode"))); - Assert.Null(image.Dict.Get(N("ColorSpace"))); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); } [Fact] diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs new file mode 100644 index 000000000..001807fe4 --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -0,0 +1,197 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Images; +using VellumPdf.Layout.Elements; +using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG4Support; +using LayoutDiagnosticCode = VellumPdf.Layout.LayoutDiagnosticCode; +using LayoutElementKind = VellumPdf.Layout.LayoutElementKind; + +namespace VellumPdf.Kernel.Tests; + +/// +/// JPEG 2000 files with a jp2h box: which device name is written for which channel count, and which colour +/// specifications keep the name. ISO 32000-2, 7.4.9, is the clause; ISO/IEC 15444 is not held. +/// +public sealed partial class ConformanceAuditG4Tests +{ + private static byte[] Jp2Of(int channels, int? enumerated, bool palette = false, (int, int)[]? boxes = null) => + Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, boxes: boxes, palette: palette); + + private static string? ColourSpaceWritten(byte[] jp2, PdfConformance claim = PdfConformance.None) + { + var kind = new Kind("jp2", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"); + return Written(ImageFile(claim, kind)).Name("ColorSpace"); + } + + // ── Two or more colr boxes and none a device space keep the device name (M1) ─────────────── + + public static TheoryData TwoColourBoxesWithNoDeviceSpace() => new() + { + { 3, 2, 0, 1, 18 }, // ICC profile, then sYCC + { 3, 4, 0, 1, 18 }, // vendor colour, then sYCC + { 3, 1, 19, 2, 0 }, // CIEJab, then an ICC profile + { 3, 1, 19, 1, 18 }, // CIEJab, then sYCC + { 1, 2, 0, 1, 18 }, + { 1, 4, 0, 1, 18 }, + { 1, 1, 19, 2, 0 }, + { 1, 1, 19, 1, 18 }, + }; + + [Theory] + [MemberData(nameof(TwoColourBoxesWithNoDeviceSpace))] + public void Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf(int channels, + int method1, int value1, int method2, int value2) + { + // veraPDF 1.30.4 accepts an image with a ColorSpace and fails one without it when no colr box has APPROX 1, + // so the name stays where the file has more than one colr box. + var jp2 = Jp2Of(channels, null, boxes: [(method1, value1), (method2, value2)]); + var expected = channels == 1 ? "DeviceGray" : "DeviceRGB"; + Assert.Equal(expected, ColourSpaceWritten(jp2)); + var file = ImageFile(PdfConformance.PdfA2b, new Kind("jp2-two-colr", jp2, 16, 16, expected, 8, "JPXDecode")); + Assert.Equal(expected, Written(file).Name("ColorSpace")); + Assert.Empty(VeraFailures("2b", file)); + } + + [Theory] + [InlineData(1, 2, 0)] + [InlineData(3, 2, 0)] + [InlineData(1, 1, 18)] + [InlineData(3, 1, 18)] + [InlineData(3, 1, 99)] + public void Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf(int channels, + int method, int value) + { + var jp2 = Jp2Of(channels, null, boxes: [(method, value)]); + var file = ImageFile(PdfConformance.PdfA2b, new Kind("jp2-one-colr", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode")); + Assert.Null(Written(file).Dict.Get(N("ColorSpace"))); + Assert.Empty(VeraFailures("2b", file)); + } + + // ── The channel count must fit the device name (M2) ─────────────────────────────────────── + + [Theory] + [InlineData(1, 16)] // one channel cannot match the three components of DeviceRGB + [InlineData(3, 17)] // three channels beside DeviceGray + [InlineData(2, null)] // no colr box: the count chooses DeviceRGB + [InlineData(5, null)] + [InlineData(2, 16)] + [InlineData(4, 17)] + [InlineData(6, 12)] // CMYK takes four channels, or five with an opacity channel + [InlineData(2, 12)] + public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountNoDeviceSpaceFitsIsRefused(int channels, int? enumerated) + { + // The same data with no jp2h box is refused too, so the file with the box is no more valid than that one. + var jp2 = Jp2Of(channels, enumerated); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"{channels} channels", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + Assert.Throws(() => ImageFile(PdfConformance.None, + new Kind("jp2", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))); + } + + [Fact] + public void Iso32000_2_7_4_9_AJp2FileWithTwoColourBoxesAndTwoChannelsIsRefused() + { + // Two colour boxes and no device space: the count chooses DeviceRGB, which two channels do not fit. + var jp2 = Jp2Of(2, null, boxes: [(2, 0), (1, 18)]); + Assert.Throws(() => JpxImageLoader.Load(jp2)); + } + + [Theory] + [InlineData(2, 17, "DeviceGray")] // one opacity channel beyond the greyscale space: the ruled case + [InlineData(4, 16, "DeviceRGB")] + [InlineData(5, 12, "DeviceCMYK")] // a CMYK colr box names the space where the count fits no other + [InlineData(4, 12, "DeviceCMYK")] + [InlineData(1, 12, "DeviceGray")] // the name a 2.3.3 save wrote fits, so it stays + [InlineData(3, 12, "DeviceRGB")] + [InlineData(4, null, "DeviceCMYK")] + public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountFitsTheDeviceNameIsWritten(int channels, int? enumerated, string name) + { + Assert.Equal(name, ColourSpaceWritten(Jp2Of(channels, enumerated))); + } + + [Fact] + public void Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount() + { + // The pclr and cmap boxes turn one stored channel into the colour channels of the palette's colour space; + // the loader does not read them, so the ihdr count says nothing about the colour channels. + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2Of(1, 16, palette: true))); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AJp2FileOfFiveChannelsBesideCmykIsWrittenAndReportedUnderAPdfAClaim() + { + // Five channels is one opacity channel beyond CMYK: written as DeviceCMYK, reported as a count of five. + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-5", Jp2Of(5, 12), 16, 16, "DeviceCMYK", 8, "JPXDecode")); + var file = Save(doc); + Assert.Equal("DeviceCMYK", Written(file).Name("ColorSpace")); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Contains("has 5 channels", item.Message); + } + + // ── The report quotes no caller text (M4) and covers a band logo (L1) ──────────────────── + + [Fact] + public void Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText() + { + var alt = "line one\nline two " + new string('x', 300); + using var doc = DocumentWith(PdfConformance.PdfA2b, TwoChannelKind(), alt); + Save(doc); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.DoesNotContain("line one", item.Message); + Assert.DoesNotContain("xxxx", item.Message); + Assert.DoesNotContain('\n', item.Message); + Assert.Equal("The JPEG 2000 image of 16 by 16 pixels has 2 channels; PDF/A-2 allows one, three or four. " + + "The image is written as it is.", item.Message); + Assert.Equal(LayoutElementKind.Image, item.ElementKind); + Assert.Equal(0, item.ElementIndex); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage() + { + using var doc = NewDocument(PdfConformance.PdfA2b); + doc.Header = new RunningBand(BandZone.Logo(new LayoutImage(Load(TwoChannelKind())) { AltText = "logo text" }), + BandZone.Empty, BandZone.Empty); + for (var i = 0; i < 3; i++) + doc.Add(new LayoutImage(Load(new Kind("jpeg", Jpeg(4, 2, 3), 4, 2, "DeviceRGB", 8, "DCTDecode"))) { BreakBefore = VellumPdf.Layout.Core.PageBreakMode.Page }); + Save(doc); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Equal(LayoutElementKind.Header, item.ElementKind); + Assert.Equal(3, item.Count); + Assert.DoesNotContain("logo text", item.Message); + } + + // ── A bpcc box that differs only in sign (L4) ─────────────────────────────────────────── + + [Fact] + public void Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsReportedAsSuch() + { + // 07 87 07: three channels of 8 bits, the second one signed. The whole bpcc byte is compared. + var kind = new Kind("jp2-sign", Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 0x87, 7]), 16, 16, "DeviceRGB", 8, + "JPXDecode"); + using var doc = DocumentWith(PdfConformance.PdfA2b, kind); + var file = Save(doc); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Contains("different bit depths or signs", item.Message); + Assert.Equal(["6.2.8.3-5"], VeraFailures("2b", file)); + } + + // ── A TIFF whose colour exceeds its alpha (L2) ───────────────────────────────────────── + + [Fact] + public void Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs() + { + // TIFF 6.0 says the colour samples are stored multiplied by alpha, so a colour above its alpha is not a file + // the format allows. The loader keeps the samples and writes the Matte; it does not repair the data. + var tiff = Tiff(true, [.. BaseTags(1, 1, 8, 2, 4), Short(338, 1)], [200, 0, 0, 100]); + var image = Written(ImageFile(PdfConformance.None, new Kind("tiff-over", tiff, 1, 1, "DeviceRGB", 8, "FlateDecode"))); + Assert.Equal("C80000", Convert.ToHexString(image.Decoded)); + Assert.Equal("64", Convert.ToHexString(image.SoftMask!.Decoded)); + Assert.IsType(image.SoftMask.Dict.Get(N("Matte"))); + } +} From 4601eef04b136ae71451b115327a8909ee494b6c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 09:29:59 +0100 Subject: [PATCH 08/22] docs(conformance): mark the image gaps #763, #764, #768 and #770 fixed The G4 rows still said gap and cited ten tests that no longer exist under those names, five of them as skipped. Each row now gives the verdict after the fix and names the tests that run, and the PDF/A row says which reading of 6.2.8.3 still needs the standard's text. --- docs/conformance-v2.4.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index a630c1f50..88f9c5989 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -385,9 +385,9 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | Standard and clause | Requirement | Feature | Verdict | Test | |---|---|---|---|---| | ISO 32000-1 8.9.5, Table 89; ISO 32000-2 Table 87 | Subtype is Image; Type, if present, is XObject; Width and Height are integers that count the samples | IMG | compliant | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies`, `Iso32000_1_8_9_5_TheFactoryWritesTheFileTheLoaderWouldHave` | -| ISO 32000-1 8.9.3, Table 89; ISO 32000-2 8.9.3, Table 87 | The number of colour components is inferred from ColorSpace, which is required (JPXDecode excepted), so the colour space is one with the data's component count | IMG | gap #763 for a JPEG whose frame has 2 or 5 components, which is written as DeviceRGB; compliant for the other kinds, whose palettes are expanded to DeviceRGB | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies`, `Iso32000_2_7_4_8_PinsTodayAJpegOfAnotherComponentCountIsWrittenAsDeviceRgb`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused` (skipped) | +| ISO 32000-1 8.9.3, Table 89; ISO 32000-2 8.9.3, Table 87 | The number of colour components is inferred from ColorSpace, which is required (JPXDecode excepted), so the colour space is one with the data's component count | IMG | fixed (#763): a JPEG whose frame has a component count other than 1, 3 or 4 is refused. Compliant for the other kinds, whose palettes are expanded to DeviceRGB | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused` | | ISO 32000-1 8.9.5, Table 89; ISO 32000-2 Table 87 | BitsPerComponent is 1, 2, 4, 8 or 16 and agrees with what the filter delivers: 1 for CCITT and JBIG2, the size of the data for Flate (veraPDF 6.2.8-4) | IMG | compliant: 1, 8 and 16 are written; 1, 2 and 4-bit greys and 1 and 4-bit palettes are written at 8 | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies` | -| ISO 32000-1 Table 89, 7.4.8; ISO 32000-2 Table 87, 7.4.8 | DCTDecode always delivers 8-bit samples, each component value occupying a byte | IMG (JPEG) | gap #763: the frame's sample precision is never read, so a 12-bit JPEG (a SOF1 frame with precision 12) is written as BitsPerComponent 8 DCTDecode (veraPDF passes it) | `Iso32000_1_Table89_PinsTodayAJpegOfTwelveBitPrecisionIsWrittenAsEightBitDct`, `Iso32000_1_Table89_AJpegOfAPrecisionOtherThanEightIsRefused` (skipped) | +| ISO 32000-1 Table 89, 7.4.8; ISO 32000-2 Table 87, 7.4.8 | DCTDecode always delivers 8-bit samples, each component value occupying a byte | IMG (JPEG) | fixed (#763): the frame precision is read and a precision other than 8 is refused, so a 12-bit JPEG is no longer written as BitsPerComponent 8 DCTDecode | `Iso32000_1_Table89_AJpegOfAPrecisionOtherThanEightIsRefused` | | ISO 32000-1 8.9.5, Table 89; ISO 19005-2 6.2.8 | Interpolate, if present, is false; Alternates and OPI are absent (veraPDF 6.2.8-1, 6.2.8-2, 6.2.8-3) | IMG | compliant: none of Interpolate, Alternates, OPI, Intent, ImageMask, Decode, SMaskInData, OC and Metadata is written, searched for in `src` | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies` | | ISO 32000-1 8.9.3; ISO 32000-2 8.9.3 | Each row begins on a byte boundary, components are interleaved, 16-bit samples are high byte first | IMG | compliant | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies` | | ISO 32000-1 8.9.4; ISO 32000-2 8.9.4 | The first row is the top of the image | IMG | compliant: a bottom-up and a top-down BMP give the same picture | `Iso32000_1_8_9_4_ABottomUpAndATopDownBmpAreWrittenTopRowFirst` | @@ -397,16 +397,16 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | JBIG2 data is bitonal, DeviceGray at 1 bit | IMG (JBIG2) | compliant | `Iso32000_1_7_4_7_AJbig2ImageIsBitonalAndHoldsTheSegmentsOfTheSource` | | ISO 32000-2 7.4.7 | The JBIG2 file header, end-of-page segments and the end-of-file segment shall not be present in PDF | IMG (JBIG2) | compliant: the ID string and the segments of type 49 and 51 are dropped; a full Annex D header (ID string, flags, page count) is refused with InvalidDataException | `Iso32000_2_7_4_7_TheJbig2FileHeaderAndTheEndOfPageAndEndOfFileSegmentsAreNotWritten`, `Iso32000_2_7_4_7_AFullAnnexDFileHeaderIsRefusedAndNotDropped` | | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | -| ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | gap #763 for a frame of another component count; compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_PinsTodayAJpegOfAnotherComponentCountIsWrittenAsDeviceRgb` | -| ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | gap #763 for SOF3 (lossless) and SOF9 (arithmetic), which are written as DCTDecode. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_PinsTodayAFrameTypeOtherThanBaselineOrProgressiveIsWrittenAsDctDecode`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` (skipped) | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | gap #763: ColorSpace is always written from the channel count, so a JP2 file whose colr is sYCC is written as DeviceRGB, a bare codestream of two channels as DeviceRGB over an sRGB colr, and a JP2 file of two channels as DeviceGray. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_PinsTodayAJp2WithASyccColourSpecificationIsWrittenAsDeviceRgb`, `Iso32000_2_7_4_9_PinsTodayABareCodestreamOfTwoChannelsGetsAnSrgbColourSpecification`, `Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndFailsVeraPdf`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName` (skipped), `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure` (skipped), `Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsIsRefusedOrWrittenWithoutAVeraPdfFailure` (skipped) | -| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | gap #763: a JP2 file whose only colour specification is CIEJab is written as DeviceRGB, and veraPDF passes it because ColorSpace is present. Neither DeviceRGB nor an absent ColorSpace is valid under 32000-2, so the fix refuses the file or backs it with an ICC profile | `Iso32000_2_7_4_9_PinsTodayAJp2WithACieJabColourSpecificationIsWrittenAsDeviceRgbAndVeraPdfDoesNotLook`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefusedOrBackedByAnIccProfile` (skipped) | -| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | gap #770: the loader reads no Rsiz, so a codestream with the Part 2 bit set is wrapped and written. ISO/IEC 15444-1 and -2, which define the baseline set, are not held; the row checks the Part 2 bit only | `Iso32000_2_7_4_9_PinsTodayAPartTwoCodestreamIsPassedThrough`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` (skipped) | +| ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | +| ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused; a JP2 file with a jp2h whose channel count its device name does not fit is refused, and a CMYK colr box with five channels is written as DeviceCMYK; a JP2 file with exactly one colr box that names no device space is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountNoDeviceSpaceFitsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountFitsTheDeviceNameIsWritten`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | +| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | +| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream with the Part 2 bit set, bare or in a JP2 file. ISO/IEC 15444-1 and -2, which define the baseline set and the meaning of that bit, are not held; the row checks the Part 2 bit only | `Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File`, `Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, one colr box with METH 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | gap #763: a JP2 file of two channels (6.2.8.3-1) and one whose channels have depths of 8, 8 and 4 bits in a bpcc box (6.2.8.3-5) are passed through and fail veraPDF under 2b. Compliant for the fixtures' three channel counts and three depths. The clause was read on 2026-11-29 and confirms the veraPDF checks, including a bpcc box with different depths and two channels; an image that effectively uses DeviceGray, RGB or CMYK, through ColorSpace or the JPX data, also falls under 6.2.4.3 | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsPassedThroughAndFailsVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithChannelsOfDifferentDepthsIsRefusedOrWrittenWithoutAVeraPdfFailure` (skipped) | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, one colr box with METH 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): a JP2 file whose channel count is 2 beside greyscale (6.2.8.3-1) or whose bpcc box gives different depths or signs (6.2.8.3-5) is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The clause was read on 2026-11-29 and confirms the veraPDF checks, including a bpcc box with different depths and two channels; an image that effectively uses DeviceGray, RGB or CMYK, through ColorSpace or the JPX data, also falls under 6.2.4.3. Needs a NEN reading: whether the clause compares the sign bit of a bpcc entry | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsReportedAsSuch` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | -| ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | gap #764: the tag is read and discarded, so associated alpha is written preblended with no Matte | `Iso32000_1_11_6_5_3_PinsTodayAnAssociatedAlphaTiffIsWrittenAsStraightAlphaWithNoMatte`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack` (skipped) | -| ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | gap #768: a tRNS with bits above the bit depth (a valid PNG; decoders mask them) is written outside the range, three inputs measured (grey 8, grey 4, RGB 8). Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_PinsTodayAPngKeyWithBitsAboveTheDepthIsWrittenOutsideTheSampleRange`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` (skipped) | +| ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | +| ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | | ISO 32000-1 8.9.5; ISO 32000-2 8.9.5 | BitsPerComponent of the image and of its soft mask are those of the samples written, 8 when the caller reduces a 16-bit source | IMG (ImageLoadOptions) | compliant | `Iso32000_1_8_9_5_ReducingToEightBitsWritesEightBitSamplesAndAnEightBitSoftMask` | | GIF89a sections 18 and 20 (not an ISO standard) | With `PlaceOnLogicalScreen` the image is the screen's size and transparent outside the frame; without it, the frame at its own size | IMG (GIF, #628) | compliant (the loader documents the default) | `Iso32000_1_11_6_5_3_AGifPlacedOnItsLogicalScreenIsTransparentWhereTheFrameIsNot` | | TIFF 6.0 section 8 (not an ISO standard) | Orientation names the side row 0 is on | IMG (TIFF) | gap #769: the tag is ignored | `Iso32000_1_8_9_4_PinsTodayATiffOrientationOfThreeIsIgnored`, `Tiff6_0_8_TheOrientationTagTurnsTheImageSoItsRowZeroIsOnTheSideTheTagNames` (skipped) | From 1eac2c5324eb9a10e18ad120babcb5629d02de22 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 10:00:37 +0100 Subject: [PATCH 09/22] test(images): give the greyscale colr test a channel count the loader accepts The test built a JP2 file of three channels beside a greyscale colr box and expected DeviceGray, which is the file the loader now refuses because three channels do not fit DeviceGray. Two channels is greyscale plus one opacity channel, and it still shows the colr box deciding over the DeviceRGB that the channel count would give. --- tests/VellumPdf.Kernel.Tests/JpxImageTests.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs index 2a56b57b8..a036e2e28 100644 --- a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs +++ b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs @@ -234,9 +234,11 @@ public void Jp2_Colr_SRgb16_ReportsDeviceRgb() [Fact] public void Jp2_Colr_Greyscale17_ReportsDeviceGray() { - var jp2 = BuildJp2File(width: 4, height: 4, nc: 3, bpc: 8, colrEnum: 17); + // Two channels is greyscale plus one opacity channel (ISO 32000-2, 7.4.9), the shape where the colr box, + // not the channel-count default of DeviceRGB, has to decide. Three channels beside greyscale is refused. + var jp2 = BuildJp2File(width: 4, height: 4, nc: 2, bpc: 8, colrEnum: 17); var img = JpxImageLoader.Load(jp2.File); - // colr greyscale enum overrides the 3-component default of DeviceRGB. + // colr greyscale enum overrides the channel-count default of DeviceRGB. Assert.Contains("/DeviceGray", StreamDictText(img)); } From b1a9d5785d5b80143655dc52bf7b73d8e7a25f35 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 11:16:05 +0100 Subject: [PATCH 10/22] fix(images): count JP2 colour channels as the standards do, report the 6.2.8.3 text A JP2 file with a jp2h box now has its colour channels counted: the type 0 entries of its cdef box, or every channel when it has none (ISO/IEC 15444-1, I.5.3.6). The device name the loader writes must have exactly that many components (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour space) or the file is refused. This replaces the earlier rule that let one channel beyond the name through as an opacity channel, which refused a valid RGB file with two opacity channels declared in a cdef box and kept a greyscale file of two colour channels. A name that already has the right count keeps main's bytes, so a CMYK colr box over five channels is DeviceRGB again and refused (five colour channels). A cmap box without pclr is no longer a palette. A file with no jp2h box is refused before its colour space is chosen, so its message names the missing box, and a jp2h box without ihdr names the codestream as the source of the count. The Layout report (501) follows ISO 19005-2, 6.2.8.3: more than one colour specification without exactly one APPROX of 1, a colr METH other than 1, 2 or 3, and colour channels of different bit depth, depth only and not opacity channels. It no longer reports a channel count or a sign-only bpcc difference. Docs state where veraPDF differs. The class summary, the 501 remarks and the CHANGELOG say what the code does. --- CHANGELOG.md | 51 +-- src/VellumPdf.Kernel/Images/Jp2Findings.cs | 23 ++ src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 235 ++++++++----- .../Images/PdfImageXObject.cs | 9 +- src/VellumPdf.Layout/Document.cs | 4 +- src/VellumPdf.Layout/Elements/LayoutImage.cs | 20 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 28 +- .../Rendering/ImageDiagnostics.cs | 38 +-- .../ConformanceAuditG4Tests.Images.cs | 73 ++-- .../ConformanceAuditG4Tests.JpxChannels.cs | 314 +++++++++++++++--- tests/VellumPdf.Kernel.Tests/JpxImageTests.cs | 16 +- 11 files changed, 587 insertions(+), 224 deletions(-) create mode 100644 src/VellumPdf.Kernel/Images/Jp2Findings.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 94886f0fc..6cf20f11d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -857,33 +857,36 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). precision, and `JpxImageLoader` wrote a device name from the channel count whatever the `colr` box or the count said. ISO 32000-2, 7.4.8, gives DCTDecode data one, three or four components of a byte each, and 7.4.9 says a `ColorSpace` that is present replaces the colour specification in - the JPEG 2000 data and that the colour channels shall match its components. `Load` now throws - `InvalidDataException` for a JPEG frame with a component count other than 1, 3 or 4, a + the JPEG 2000 data and that the ordinary colour channels shall match its components. `Load` now + throws `InvalidDataException` for a JPEG frame with a component count other than 1, 3 or 4, a precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` - box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it throws when - the device name it would write does not fit the `ihdr` channel count, which is the name's own - component count or one more for an opacity channel: one channel beside sRGB, three beside - greyscale, two with no `colr` box, five with no `colr` box, and so on. Where a `colr` box - names CMYK and the count fits that and no other name, the file is written as `/DeviceCMYK` - (five channels beside CMYK). A file with a `pclr` or `cmap` box keeps the name, because a palette - changes what the channels are. A JP2 file whose only colour specification is enumerated colour - space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box - that names no sRGB, greyscale or CMYK space (an ICC profile, sYCC, or another enumerated space) is - written with no `ColorSpace`, so the file's own specification decides. A file with two or more - `colr` boxes and none of them a device space keeps the device name it had, because veraPDF - 1.30.4 fails such a file under PDF/A-2b without it. A JP2 file whose `bpcc` box gives channels - different depths or signs, or whose channel count is one above its device space (two beside - greyscale), is still written as it was: ISO 32000-2, 7.4.9, lets colour components differ in - bits per sample and matches only the ordinary colour channels to the colour space, and ISO - 19005-2, 6.2.8.3, allows neither. A Layout save under a PDF/A-2 claim reports it as the new + box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it counts the + colour channels, which are the type 0 entries of its `cdef` box, or every channel when it has + none (ISO/IEC 15444-1, I.5.3.6), and throws unless the device name it would write has exactly + that many components. So two channels or three beside greyscale, one beside sRGB, and two or + five with no `colr` box and no `cdef` box are refused, while a greyscale file whose `cdef` box + marks one colour and one opacity channel is written as `/DeviceGray`, and so is an RGB file of + five channels whose `cdef` box marks three colour channels. Where a `colr` box names CMYK and + four colour channels fit no other name, the file is written as `/DeviceCMYK`. A file with a + `pclr` box keeps the name, because a palette changes what the channels are; a `cmap` box alone + is not a palette. A JP2 file whose only colour specification is enumerated colour space 19 + (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box that holds + an ICC profile or names an enumerated space other than sRGB, greyscale and CMYK (sYCC, say) is + written with no `ColorSpace`, so the file's own specification decides; a lone vendor box or one + too short to read keeps the name. A file with two or more `colr` boxes and none of them a device + space keeps the device name it had, because veraPDF 1.30.4 fails such a file of one or three + channels under PDF/A-2b without it. A Layout save under a PDF/A-2 claim reports as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error that `StrictDiagnostics` - refuses, naming the image by its size and the clause and quoting no alternative text; without - a claim nothing changes. **Deliberate output changes and new refusals:** those inputs, and the - new diagnostic under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 - components) and every JP2 file that has a device `colr` box or none and a fitting channel - count, two or more `colr` boxes with no device space and a fitting count, or a palette writes - the same bytes as before. + refuses, a JP2 file that ISO 19005-2, 6.2.8.3, does not allow and 7.4.9 does: more than one + colour specification and not exactly one with an APPROX of 1, a colour specification whose METH + is not 1, 2 or 3, or colour channels of different bit depth. The report follows the clause, not + veraPDF, which checks APPROX and METH only without a `ColorSpace` and also fails a sign-only + difference and an opacity channel of another depth. It names the image by its size and the + clause and quotes no alternative text; without a claim nothing changes. **Deliberate output + changes and new refusals:** those inputs, and the new diagnostic under a PDF/A-2 claim; every + other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file whose name has as many + components as it has colour channels, or that has a palette, writes the same bytes as before. - **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and diff --git a/src/VellumPdf.Kernel/Images/Jp2Findings.cs b/src/VellumPdf.Kernel/Images/Jp2Findings.cs new file mode 100644 index 000000000..faccc6cdd --- /dev/null +++ b/src/VellumPdf.Kernel/Images/Jp2Findings.cs @@ -0,0 +1,23 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +namespace VellumPdf.Images; + +/// +/// What a JP2 file's jp2h box holds that ISO 19005-2, 6.2.8.3, does not allow and +/// writes anyway because ISO 32000-2, 7.4.9, allows it. +/// +[Flags] +internal enum Jp2Findings +{ + None = 0, + + /// More than one colour specification, and not exactly one with an APPROX of 1. + ColourSpecificationApprox = 1, + + /// A colour specification whose METH is not 1, 2 or 3. + ColourMethod = 2, + + /// Colour channels of different bit depth, comparing the depth and not the sign. + ColourDepths = 4, +} diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 0b1995240..653bac3a2 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -37,9 +37,10 @@ namespace VellumPdf.Images; /// No JPEG 2000 decode-to-raster is performed in this release — /// throws . /// -/// Colour space (/ColorSpace of the image dictionary). ISO 32000-2, 7.4.9, -/// says a ColorSpace that is present replaces the colour specification in the JPEG 2000 -/// data, so this loader writes one only where it is the same colour space. +/// Colour space (/ColorSpace of the image dictionary). ISO 32000-2, 7.4.9, says a +/// ColorSpace that is present replaces the colour specification in the JPEG 2000 data, and that the +/// number of "ordinary colour channels" in the data shall match the number of components in the colour +/// space. What is written for each kind of file: /// /// A bare codestream, or a JP2 file with no jp2h box1, 3 or /// 4 channels give DeviceGray, DeviceRGB or DeviceCMYK and a colr box @@ -51,37 +52,41 @@ namespace VellumPdf.Images; /// DeviceRGB. /// A JP2 file with no colr box the loader can readthe /// channel count chooses, as above. -/// A JP2 file with exactly one colr box, naming no device space: an ICC profile, -/// or an enumerated space such as sYCC (18)ColorSpace is left out, so the -/// colour specification in the file decides. +/// A JP2 file with exactly one colr box, which holds an ICC profile (method 2 or 3) +/// or an enumerated colour space other than 12, 16 and 17, such as sYCC (18) +/// ColorSpace is left out, so the colour specification in the file decides. A lone vendor colour +/// box (method 4), and a box too short to read, do not count: the channel count chooses. /// A JP2 file with two or more colr boxes, none naming a device -/// spacethe channel count chooses, as above. Without the name, veraPDF 1.30.4 -/// fails these files under PDF/A-2b, which it passes with it. +/// spacethe channel count chooses, as above. veraPDF 1.30.4 passes such a file +/// of one or three channels under PDF/A-2b with the name and fails it without; at four channels it fails +/// the file with the name too, on 6.2.4.3-3. /// A JP2 file whose only colour specifications are enumerated colour space 19 /// (CIEJab)refused, because ISO 32000-2, 7.4.9, excludes CIEJab and there is /// nothing else to use. /// -/// A device name is written only for a channel count that fits it. The ihdr box -/// of a JP2 file with a jp2h box gives the channel count, and ISO 32000-2, 7.4.9, says the -/// ordinary colour channels shall match the components of the colour space. A device name fits a -/// count equal to its components (1, 3 or 4) or one more, which the loader takes as one opacity -/// channel; the cdef box is not read. Where the name chosen above does not fit and a -/// colr box names CMYK, DeviceCMYK is written if the count fits that. Any other file is -/// refused with , because the dictionary would describe samples -/// the data does not have. A file with a pclr or cmap box keeps the name, because a -/// palette changes what the channels are and those boxes are not read. -/// An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile is -/// not read or checked. Indexed colour spaces are not handled. -/// A JP2 file whose bpcc box gives channels of different bit depths or signs, or -/// whose channel count is one above its device colour space (2 beside a greyscale colr box, 5 -/// beside CMYK), is passed through. ISO 32000-2, 7.4.9, lets the colour components differ in -/// bits per sample and counts only the ordinary colour channels against the colour space, and ISO -/// 19005-2, 6.2.8.3, allows neither. This loader neither refuses nor reports them. A -/// VellumPdf.Layout save reports each file whose channel count is not 1, 3 or 4, or whose -/// bpcc entries differ, under a PDF/A-2 claim as LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and -/// strict mode refuses it. A document built on this loader and VellumPdf.Kernel alone has no -/// such report. Do not pass such a file to a PDF/A document: 3.0 will refuse it where the -/// image is created, and #474 tracks the report from the loaders. +/// A name is written only for colour channels it has the components for. ISO 32000-2, 7.4.9, +/// says the number of "ordinary colour channels" shall match the number of components in the colour +/// space. ISO/IEC 15444-1, I.5.3.6, says a codestream that holds only colour channels in colour order has +/// no cdef box and that any other channel (an opacity channel, say) needs one. So the loader counts +/// as colour channels the entries of type 0 of the cdef box (opacity, premultiplied opacity and +/// unspecified entries are not counted), or every channel of the ihdr box when there is no +/// cdef box (of the codestream, when the jp2h box has no ihdr box). The name chosen +/// above must have exactly that many components: DeviceCMYK replaces it where a colr box +/// names CMYK and there are four. If no name fits, the file is invalid under 7.4.9 and is refused with +/// . Only the first cdef box is read, and one too short for its +/// own entry count is ignored. A file with a pclr box keeps the name and is not checked, because a +/// palette changes what the channels are and the box is not read; a cmap box alone is not a +/// palette. An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile +/// is not read or checked. Indexed colour spaces are not handled. +/// A JP2 file that passes those checks may still break ISO 19005-2, 6.2.8.3, and is passed +/// through. The clause requires, when there is more than one colour specification, exactly one with +/// an APPROX of 1; a METH of 1, 2 or 3; and one bit depth for all the colour channels. ISO 32000-2, 7.4.9, +/// requires none of these. This loader neither refuses nor reports such a file. A +/// VellumPdf.Layout save reports it under a PDF/A-2 claim as +/// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on +/// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a +/// PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks the report from the +/// loaders. /// public static class JpxImageLoader { @@ -97,7 +102,7 @@ public static class JpxImageLoader private const uint BoxTypeColr = 0x636F6C72; // "colr" private const uint BoxTypeBpcc = 0x62706363; // "bpcc" private const uint BoxTypePclr = 0x70636C72; // "pclr" (palette) - private const uint BoxTypeCmap = 0x636D6170; // "cmap" (component mapping) + private const uint BoxTypeCdef = 0x63646566; // "cdef" (channel definition) private const uint BoxTypeJp2c = 0x6A703263; // "jp2c" (contiguous codestream) // JPEG 2000 SOC marker (start of codestream). @@ -129,18 +134,21 @@ public static class JpxImageLoader /// , or when the codestream's Rsiz has the Part 2 /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose - /// channel count no device colour space fits (see the class summary), and for a JP2 file whose + /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose /// only colour specifications are enumerated colour space 19 (CIEJab). /// /// /// A channel count that no device colour space has is refused for a bare codestream /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a - /// colr box it writes, and ISO 32000-2, 7.4.9, says the colour channels shall match the - /// components of the colour space. A channel count that the device name does not fit is - /// refused for a JP2 file with a jp2h box too, as the class summary says. A JP2 file whose only colour specification is CIEJab is + /// colr box it writes, and ISO 32000-2, 7.4.9, says the ordinary colour channels shall match + /// the components of the colour space. Colour channels that the device name does not fit are + /// refused for a JP2 file with a jp2h box too, as the class summary says: every channel + /// is a colour channel unless a cdef box says otherwise, and the name must have that many + /// components. A JP2 file whose only colour specification is CIEJab is /// refused: neither a device name nor an absent ColorSpace would be valid for it. One /// that also has an ICC profile, or another enumerated space, is written with no - /// ColorSpace. The class summary lists what is written for each colour specification. + /// ColorSpace only when it has exactly one colr box. The class summary lists what is + /// written for each colour specification. /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws /// naming the Rsiz value when bit 15 of the SIZ marker's /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the @@ -174,7 +182,7 @@ public static PdfImageXObject Load(byte[] jpx) /// , or when the codestream's Rsiz has the Part 2 /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose - /// channel count no device colour space fits (see the class summary), and for a JP2 file whose + /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose /// only colour specifications are enumerated colour space 19 (CIEJab). /// /// @@ -253,6 +261,7 @@ private static PdfImageXObject LoadJp2(byte[] data) // the primary image in the unusual multi-codestream case). int jp2cBoxStart = -1, jp2cBoxTotal = -1, jp2cPayloadOffset = -1, jp2cPayloadLength = -1; int jp2hBoxStart = -1, jp2hBoxTotal = -1; + var channelsFromSiz = false; int ftypBoxStart = -1, ftypBoxTotal = -1; var pos = 0; @@ -318,11 +327,15 @@ private static PdfImageXObject LoadJp2(byte[] data) height = h; nc = c; bpc = b; + channelsFromSiz = true; } ImageLimits.ValidateDimensions("JPEG 2000 (JP2)", width, height); - var cs = ColorSpaceOf(nc, colrEnum, colr); + // With no jp2h box the loader writes the colr box itself, from the channel count alone. + if (jp2hBoxStart < 0) + RefuseUnmatchableChannelCount(nc); + var cs = ColorSpaceOf(nc, channelsFromSiz, colrEnum, colr); var jp2cBox = data[jp2cBoxStart..(jp2cBoxStart + jp2cBoxTotal)]; byte[] jp2; @@ -343,7 +356,6 @@ private static PdfImageXObject LoadJp2(byte[] data) { // jp2h absent (malformed source): synthesise one from the SIZ-derived geometry so the // result is still conformant. Its colr box names a device space, as for a bare codestream. - RefuseUnmatchableChannelCount(nc); jp2 = BuildMinimalJp2(width, height, nc, bpc, colrEnum ?? EnumCsForComponents(nc), jp2cBox); } @@ -351,8 +363,7 @@ private static PdfImageXObject LoadJp2(byte[] data) // package, which reports it under a PDF/A claim; the Kernel writes the image either way. return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) { - Jp2ChannelCount = nc, - Jp2DepthsDiffer = colr.DepthsDiffer, + Jp2Findings = jp2hBoxStart < 0 ? Jp2Findings.None : colr.Findings(), }; } @@ -487,18 +498,20 @@ private static void ParseJp2Header( break; case BoxTypeBpcc: - // One byte per channel: the depth less one, and the sign in the top bit. - for (var i = 1; i < subPayloadLength; i++) - if (data[subPayloadOffset + i] != data[subPayloadOffset]) - colr.DepthsDiffer = true; + // One byte per channel: the depth less one in the low 7 bits, and the sign in the top bit. + colr.Bpcc ??= data[subPayloadOffset..(subPayloadOffset + subPayloadLength)]; break; case BoxTypePclr: - case BoxTypeCmap: // A palette turns the stored channels into colour channels, so the ihdr channel count - // no longer says how many colour channels there are. These boxes are not read. + // no longer says how many colour channels there are. The box is not read. A cmap box + // alone maps channels and is not a palette. colr.HasPalette = true; break; + + case BoxTypeCdef: + TryParseCdef(data, subPayloadOffset, subPayloadLength, colr); + break; } pos += (int)subTotal; @@ -530,6 +543,10 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c return; // malformed but non-fatal for colour space purposes var meth = data[offset]; + if (data[offset + 2] == 1) + colr.Approx1Boxes++; + if (meth is not (1 or 2 or 3)) + colr.OtherMethod = true; if (meth == 1 && length >= 7) { // Enumerated colour space method: 4-byte enum value follows METH/PREC/APPROX. @@ -543,16 +560,69 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c } } - // What the jp2h box of a JP2 file holds: the number of colr boxes, every enumerated colour space in - // file order, whether any box carries an ICC profile, whether there is a palette, and whether the bpcc - // depths differ. colrEnum above keeps the last enumerated value, as it always has. + // cdef payload: N(2), then N entries of Cn(2) Typ(2) Asoc(2). Typ 0 is an ordinary colour channel; opacity, + // premultiplied opacity and unspecified entries are not counted. Only the first cdef box is read, and a box + // too short for its own N is treated as absent, so a file with one is judged by its channel count alone. + private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey colr) + { + if (colr.OrdinaryChannels is not null || length < 2) + return; + var entries = ReadUInt16Be(data, offset); + if (length < 2 + 6 * entries) + return; + var ordinary = new List(); + for (var i = 0; i < entries; i++) + if (ReadUInt16Be(data, offset + 2 + 6 * i + 2) == 0) + ordinary.Add(ReadUInt16Be(data, offset + 2 + 6 * i)); + colr.OrdinaryChannels = ordinary; + } + + // What the jp2h box of a JP2 file holds: the number of colr boxes and how many of them have an APPROX of 1, + // whether any colr box has a method other than 1, 2 or 3, every enumerated colour space in file order, + // whether any box carries an ICC profile, whether there is a palette, the bpcc entries, and the channels the + // first cdef box marks as ordinary colour channels (null when there is none). colrEnum above keeps the + // last enumerated value, as it always has. private sealed class ColrSurvey { public int Boxes { get; set; } + public int Approx1Boxes { get; set; } + public bool OtherMethod { get; set; } public List Enumerated { get; } = []; public bool HasIccProfile { get; set; } public bool HasPalette { get; set; } - public bool DepthsDiffer { get; set; } + public byte[]? Bpcc { get; set; } + public List? OrdinaryChannels { get; set; } + + // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. A palette changes which + // channels are colour channels and its boxes are not read, so the depths of a file with one are not judged. + public Jp2Findings Findings() + { + var found = Jp2Findings.None; + if (Boxes > 1 && Approx1Boxes != 1) + found |= Jp2Findings.ColourSpecificationApprox; + if (OtherMethod) + found |= Jp2Findings.ColourMethod; + if (!HasPalette && Bpcc is { Length: > 1 } bpcc && ColourDepthsDiffer(bpcc)) + found |= Jp2Findings.ColourDepths; + return found; + } + + // The bit depth is the low 7 bits of a bpcc entry (the top bit is the sign). Only colour channels count: with + // a cdef box those it marks as type 0, without one every channel. + private bool ColourDepthsDiffer(byte[] bpcc) + { + int? first = null; + for (var i = 0; i < bpcc.Length; i++) + { + if (OrdinaryChannels is { } colour && !colour.Contains(i)) + continue; + var depth = bpcc[i] & 0x7F; + first ??= depth; + if (depth != first) + return true; + } + return false; + } } // ── SIZ marker parsing ──────────────────────────────────────────────────── @@ -684,22 +754,22 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // The /ColorSpace of an image from a JP2 file, or null to leave it out so the colour specification // in the JPEG 2000 data decides (ISO 32000-2, 7.4.9: a ColorSpace that is present replaces that - // specification, and its component count has to match the ordinary colour channels). + // specification, and the ordinary colour channels have to match its components). // - A device space among the enumerated ones (12, 16, 17): the name this loader has always chosen, // from the last enumerated value or the channel count. // - Only CIEJab (19) and no ICC profile: refused, since neither a name nor the colr box gives a // colour space a PDF file may use. - // - Exactly one colr box, naming no device space (an ICC profile, or an enumerated space such as - // sYCC): left out. A device name would make a reader take the samples as device samples. - // - Two or more colr boxes and none a device space, or no colr box that can be read: the name this - // loader has always chosen, from the channel count. veraPDF 1.30.4 passes such a file under - // PDF/A-2b with the name and fails it, on 6.2.8.3-2 and 6.2.8.3-3, without it, because none of - // the boxes has an APPROX of 1. - // A name is written only where the channel count fits it; see FitChannels. - private static ImageColorSpace? ColorSpaceOf(int components, int? colrEnum, ColrSurvey colr) + // - Exactly one colr box that holds an ICC profile or an enumerated value, and names no device + // space: left out. A device name would make a reader take the samples as device samples. + // - Anything else (two or more colr boxes and none a device space, a single vendor or malformed + // box, or no colr box): the name this loader has always chosen, from the channel count. For two + // or more boxes veraPDF 1.30.4 passes the file under PDF/A-2b at 1 and 3 channels with the name + // and fails it, on 6.2.8.3-2 and 6.2.8.3-3, without it, because none of the boxes has an APPROX of 1. + // A name is written only where the channels fit it; see FitChannels. + private static ImageColorSpace? ColorSpaceOf(int channels, bool channelsFromSiz, int? colrEnum, ColrSurvey colr) { if (colr.Enumerated.Exists(e => e is ColrEnumCmyk or ColrEnumSRgb or ColrEnumGreyscale)) - return FitChannels(InferColorSpace(components, colrEnum), components, colr, + return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, colr.Enumerated.Contains(ColrEnumCmyk)); if (colr.Enumerated.Count > 0 && !colr.HasIccProfile && colr.Enumerated.TrueForAll(e => e == ColrEnumCieJab)) throw new InvalidDataException( @@ -707,31 +777,40 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); if (colr.Boxes == 1 && (colr.HasIccProfile || colr.Enumerated.Count == 1)) return null; - return FitChannels(InferColorSpace(components, colrEnum), components, colr, false); + return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, false); } - // The number of ordinary colour channels a device space takes (ISO 32000-2, 7.4.9), plus the one - // opacity channel a file may add. A name that does not fit is replaced by DeviceCMYK where a colr box - // names CMYK and the count fits that; otherwise the file is refused, because the dictionary would - // describe samples the data does not have. A palette (pclr or cmap box) changes what the channels - // are, and those boxes are not read, so a file that has one keeps the name. - private static ImageColorSpace FitChannels(ImageColorSpace named, int components, ColrSurvey colr, bool cmykBox) + // Checks the name chosen above against the colour channels (ISO 32000-2, 7.4.9: the ordinary colour channels + // shall match the components of the colour space). With a cdef box they are its entries of type 0. Without + // one they are every channel: ISO/IEC 15444-1, I.5.3.6, makes the box mandatory when a codestream holds + // anything but colour channels in colour order. The name must have exactly that many components, and a colr + // box that names CMYK may supply DeviceCMYK for four. Otherwise the file is invalid and refused. A palette + // (a pclr box) changes what the channels are, and the box is not read, so a file that has one keeps the name. + private static ImageColorSpace FitChannels( + ImageColorSpace named, int channels, bool channelsFromSiz, ColrSurvey colr, bool cmykBox) { - if (colr.HasPalette || Fits(named, components)) + if (colr.HasPalette) + return named; + var colour = colr.OrdinaryChannels?.Count ?? channels; + if (ComponentsOf(named) == colour) return named; - if (cmykBox && Fits(ImageColorSpace.DeviceCmyk, components)) + if (cmykBox && colour == 4) return ImageColorSpace.DeviceCmyk; + var why = colr.OrdinaryChannels is null + ? $"its {(channelsFromSiz ? "codestream has" : "ihdr box has")} {channels} channels and no cdef box, so " + + "every one is a colour channel, but " + : $"its cdef box marks {colour} ordinary colour channels, but "; throw new InvalidDataException( - $"JP2 file: its ihdr box has {components} channels, which {named} does not take. A device colour " + - "space takes its own component count, or one more for an opacity channel, and the colour channels " + - "shall match the components of the colour space (ISO 32000-2, 7.4.9)."); + $"JP2 file: {why}{PdfNameOf(named)}, the colour space the loader would write, has {ComponentsOf(named)} " + + "components (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + + "space)."); } - private static bool Fits(ImageColorSpace cs, int channels) - { - var own = cs switch { ImageColorSpace.DeviceGray => 1, ImageColorSpace.DeviceCmyk => 4, _ => 3 }; - return channels == own || channels == own + 1; - } + private static int ComponentsOf(ImageColorSpace cs) => + cs switch { ImageColorSpace.DeviceGray => 1, ImageColorSpace.DeviceCmyk => 4, _ => 3 }; + + private static string PdfNameOf(ImageColorSpace cs) => + cs switch { ImageColorSpace.DeviceGray => "DeviceGray", ImageColorSpace.DeviceCmyk => "DeviceCMYK", _ => "DeviceRGB" }; // A bare codestream, or a JP2 file with no jp2h box, is described to PDF by a colr box this loader // writes, which names sRGB, greyscale or CMYK from the channel count. Two channels, or five or @@ -740,7 +819,7 @@ private static void RefuseUnmatchableChannelCount(int components) { if (components is not (1 or 3 or 4)) throw new InvalidDataException( - $"JPEG 2000 data has {components} channels and no colour specification of its own: " + + $"JPEG 2000 data with no jp2h box has {components} channels and so no colour specification of its own: " + "only 1 (greyscale), 3 (sRGB) or 4 (CMYK) channels can be described as a PDF colour " + "space (ISO 32000-2, 7.4.9)."); } diff --git a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs index 23044830d..a04bce650 100644 --- a/src/VellumPdf.Kernel/Images/PdfImageXObject.cs +++ b/src/VellumPdf.Kernel/Images/PdfImageXObject.cs @@ -62,13 +62,10 @@ internal PdfImageXObject( } /// - /// The channel count of the ihdr box of a JP2 file read by , or 0 - /// for any other image. Read by the Layout package to report what PDF/A-2 6.2.8.3 does not allow. + /// What found in the jp2h box of a JP2 file that ISO 19005-2, 6.2.8.3, + /// does not allow and the loader writes anyway. Read by the Layout package to report it under a PDF/A claim. /// - internal int Jp2ChannelCount { get; init; } - - /// Whether the bpcc box of a JP2 file gives its channels different bit depths or signs. - internal bool Jp2DepthsDiffer { get; init; } + internal Jp2Findings Jp2Findings { get; init; } /// The soft-mask (alpha channel) stream, or when the image is opaque. public PdfStream? SMask => _sMask; diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 291dc9996..b0d61373d 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -125,8 +125,8 @@ public Document() { } /// (a character an embedded font has no glyph /// for, written as glyph 0), (an element that /// selects a Standard 14 font under a conformance claim), - /// (a JP2 image of a channel count - /// other than 1, 3 or 4, or whose channels differ in bit depth or sign, under a PDF/A-2 claim), + /// (a JP2 image whose colour + /// specifications, colour method or colour-channel bit depths PDF/A-2 does not allow), /// (a link in the style of a table cell or a /// running band that a PDF/UA-1 claim left unwritten), /// (a character whose ToUnicode diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index b564f2825..13d9ef182 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -310,16 +310,16 @@ public LayoutImage(PdfImageXObject image) /// a precision other than 8 bits, and a component count other than 1, 3 and 4 /// (). For JPEG 2000 it is a codestream whose /// Rsiz sets the Part 2 bit, a bare codestream or a JP2 file with no jp2h box - /// whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose channel count no - /// device colour space fits (the device space's components, or one more), and a JP2 file whose - /// only colour specification is CIEJab ( lists the - /// cases). A JP2 file with exactly one colr box that names an ICC profile or an enumerated - /// colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; it is written - /// with no /ColorSpace, so the colour specification in the file decides. A JP2 file whose - /// bpcc box gives different bit depths or signs, or whose channel count is one above its - /// device colour space, such as 2 channels beside greyscale, is not refused either; the save - /// reports it as under a PDF/A-2 - /// claim. + /// whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose colour channels + /// (the cdef entries of type 0, or every channel when there is no cdef box) are not + /// as many as the components of the device colour space the loader would write, and a JP2 file + /// whose only colour specification is CIEJab ( lists + /// the cases). A JP2 file with exactly one colr box that names an ICC profile or an + /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; it + /// is written with no /ColorSpace, so the colour specification in the file decides. A JP2 + /// file whose colour channels differ in bit depth, or whose colour specifications PDF/A-2 does + /// not allow, is not refused either; the save reports it as + /// under a PDF/A-2 claim. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 /// and Group 4 data carries no header and needs its width, height and coding parameters. Load diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 5ad39b91f..b17fb9b49 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -314,24 +314,26 @@ public enum LayoutDiagnosticCode /// /// A JPEG 2000 image of a JP2 file was drawn in a document whose conformance is PDF/A-2b, - /// PDF/A-2u or PDF/A-2a, and the file has a channel count other than 1, 3 or 4, or channels whose - /// bpcc entries differ in bit depth or in sign. Each distinct element and finding is one - /// item. The message names the image by its size in pixels and quotes no alternative text; + /// PDF/A-2u or PDF/A-2a, and the file has more than one colour specification and not exactly one + /// with an APPROX of 1, or a colour specification whose METH is not 1, 2 or 3, or colour channels + /// of different bit depths. Each distinct element and finding is one item. The message names the + /// image by its size in pixels and quotes no alternative text; /// , and /// say where it is. /// /// /// Strict mode refuses it. ISO 19005-2:2011, 6.2.8.3, the item's - /// , allows a JPEG 2000 image only one, three or four - /// colour channels, with one bit depth for all of them. ISO 32000-2, 7.4.9, lets the colour - /// components differ in bits per sample and matches only the ordinary colour channels against the - /// colour space, so keeps such a file: a channel - /// count one above the components of the device space it names is read as one opacity channel, - /// and the depths are not touched. The image is written as it is, and PDF/A validation fails it. - /// A JP2 file whose channel count no device space fits is refused by the loader instead and never - /// reaches this report. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. The - /// channel count is the one in the file's ihdr box, and the depths are compared as the - /// bytes of its bpcc box, so one depth with different signs is reported as well. + /// , requires exactly one colour specification with an APPROX + /// of 1 when there are several, a METH of 1, 2 or 3, and one bit depth for all the colour + /// channels. ISO 32000-2, 7.4.9, requires none of it, so + /// writes such a file and the save reports it. The + /// report follows the text of 6.2.8.3, which does not depend on the image dictionary having a + /// ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules only where the + /// dictionary has no ColorSpace, and it also fails channels that differ only in sign or + /// that are counted with an opacity channel, which the text does not. The depths compared are + /// those of the colour channels, the entries of type 0 of the cdef box or every channel + /// when there is none, and a file with a palette is not compared because its colour channels are + /// not read. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. /// Do not pass such a file to a PDF/A document: /// alone passes it through unreported, 3.0 will refuse it where the image is created, and #474 /// tracks the loaders' own report. An image that a custom renderer registers itself is not diff --git a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs index f01b8c020..10367545b 100644 --- a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs +++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs @@ -12,34 +12,30 @@ namespace VellumPdf.Layout.Rendering; internal static class ImageDiagnostics { /// - /// Reports a JP2 file whose channel count is not 1, 3 or 4, or whose bpcc entries differ in depth or - /// sign, when the sink's claim is PDF/A-2. ISO 32000-2, 7.4.9, allows both; ISO 19005-2, 6.2.8.3, - /// does not. The message names the image by its size in pixels and never quotes the alternative text: - /// the item's element kind, element index and page say where it is, and the sink retains no caller - /// text. + /// Reports what records for a JP2 file when the sink's claim is PDF/A-2. ISO + /// 32000-2, 7.4.9, allows each; ISO 19005-2, 6.2.8.3, does not. The text applies whether or not the image + /// dictionary has a ColorSpace. The message names the image by its size in pixels and never quotes the + /// alternative text: the item's element kind, element index and page say where it is, and the sink retains no + /// caller text. /// internal static void ReportJpxUnderPdfA(LayoutDiagnosticSink? sink, PdfImageXObject image) { - if (sink is null || image.Jp2ChannelCount == 0) return; + if (sink is null || image.Jp2Findings == Jp2Findings.None) return; var clause = LayoutDiagnosticSink.ClauseFor(LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, sink.Conformance); if (clause is null) return; var name = string.Create(CultureInfo.InvariantCulture, $"The JPEG 2000 image of {image.Width} by {image.Height} pixels"); - if (image.Jp2ChannelCount is not (1 or 3 or 4)) - sink.Report( - LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, - 0, - string.Create(CultureInfo.InvariantCulture, - $"{name} has {image.Jp2ChannelCount} channels; PDF/A-2 allows one, three or four. The image is written as it is."), - perElement: true, - clause: clause); - if (image.Jp2DepthsDiffer) - sink.Report( - LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, - 1, - $"{name} has channels of different bit depths or signs; PDF/A-2 allows one depth for all channels. The image is written as it is.", - perElement: true, - clause: clause); + void Report(int key, string what) => sink.Report( + LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, key, $"{name} {what} The image is written as it is.", + perElement: true, clause: clause); + + if (image.Jp2Findings.HasFlag(Jp2Findings.ColourSpecificationApprox)) + Report(0, "has more than one colour specification and not exactly one of them has an APPROX of 1; " + + "PDF/A-2 requires exactly one."); + if (image.Jp2Findings.HasFlag(Jp2Findings.ColourMethod)) + Report(1, "has a colour specification whose method is not 1, 2 or 3; PDF/A-2 allows only those."); + if (image.Jp2Findings.HasFlag(Jp2Findings.ColourDepths)) + Report(2, "has colour channels of different bit depths; PDF/A-2 allows one depth for all colour channels."); } } diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 644c90749..d3fd5c01c 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -749,7 +749,8 @@ public void Tiff6_0_8_TheOrientationTagTurnsTheImageSoItsRowZeroIsOnTheSideTheTa /// A JP2 file of whose colr box is METH 1 with the enumerated space. private static byte[] Jp2File(byte[] codestream, int channels, int? enumeratedColourSpace, byte[]? bpcc = null, bool icc = false, int? extraEnumerated = null, bool noJp2h = false, (int Method, int Value)[]? boxes = null, - bool palette = false) + bool palette = false, (int Cn, int Typ, int Asoc)[]? cdef = null, bool cmapOnly = false, bool pclrOnly = false, + byte[][]? rawColr = null, bool noIhdr = false) { static byte[] BoxOf(string type, byte[] payload) { @@ -788,9 +789,17 @@ static byte[] Enumerated(int value) : BoxOf("colr", [(byte)b.Method, 0, 0, .. new byte[16]])), // A palette box and a component mapping box; their content is not read, only that they exist. .. palette ? (byte[])[.. BoxOf("pclr", new byte[8]), .. BoxOf("cmap", new byte[4])] : [], + .. pclrOnly ? BoxOf("pclr", new byte[8]) : [], + .. cmapOnly ? BoxOf("cmap", new byte[4]) : [], + // colr boxes with the payload as given, for the ones too short or of a method the loader does not read. + .. (rawColr ?? []).SelectMany(payload => BoxOf("colr", payload)), + // A channel definition: N(2), then Cn(2) Typ(2) Asoc(2) for each entry. + .. cdef is null ? [] : BoxOf("cdef", [(byte)(cdef.Length >> 8), (byte)cdef.Length, + .. cdef.SelectMany(e => (byte[])[(byte)(e.Cn >> 8), (byte)e.Cn, (byte)(e.Typ >> 8), (byte)e.Typ, + (byte)(e.Asoc >> 8), (byte)e.Asoc])]), ]; byte[] depths = bpcc is null ? [] : BoxOf("bpcc", bpcc); - byte[] header = noJp2h ? [] : BoxOf("jp2h", [.. BoxOf("ihdr", ihdr), .. depths, .. colours]); + byte[] header = noJp2h ? [] : BoxOf("jp2h", [.. noIhdr ? [] : BoxOf("ihdr", ihdr), .. depths, .. colours]); return [ 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A, @@ -863,8 +872,8 @@ public void Iso32000_2_7_4_9_AJp2WithAnEnumeratedDeviceSpaceAmongItsColourSpecif public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused(int channels) { // The loader describes a bare codestream to PDF by a colr box it writes, and no device space has two, five - // or sixteen channels, so it refuses. ISO 32000-2, 7.4.9: the colour channels shall match the components of - // the colour space. + // or sixteen channels, so it refuses. ISO 32000-2, 7.4.9: the ordinary colour channels shall match the + // components of the colour space. var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, channels))); Assert.Contains($"{channels} channels", e.Message); Assert.Throws(() => LayoutImage.FromBytes(JpxCodestream(16, 16, channels))); @@ -873,17 +882,25 @@ public void Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefuse } [Fact] - public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndFailsVeraPdf() - { - // A JP2 file (not a bare codestream) whose ihdr says two channels and whose colr says greyscale. - var kind = new Kind("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 16, 16, "DeviceGray", 8, "JPXDecode"); + public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsBesideGreyscaleIsRefusedAndOneWithAGreyAndAnOpacityChannelIsWritten() + { + // Two channels and no cdef box are two colour channels, which DeviceGray does not take. A cdef box that marks + // one of them as opacity makes the file valid: written as DeviceGray, and not reported (one colour channel). + var bare = Jp2File(JpxCodestream(16, 16, 2), 2, 17); + Assert.Throws(() => ImageFile(PdfConformance.None, + new Kind("jp2-2", bare, 16, 16, "DeviceGray", 8, "JPXDecode"))); + var kind = new Kind("jp2-2op", Jp2File(JpxCodestream(16, 16, 2), 2, 17, cdef: [(0, 0, 1), (1, 1, 1)]), 16, 16, + "DeviceGray", 8, "JPXDecode"); Assert.Equal("DeviceGray", Written(ImageFile(PdfConformance.None, kind)).Name("ColorSpace")); - Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - /// A JP2 file of two channels beside a greyscale colr box. - private static Kind TwoChannelKind() => new("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 16, 16, "DeviceGray", 8, - "JPXDecode"); + /// A JP2 file of three channels beside two colr boxes of which none has an APPROX of 1. + private static Kind ApproxKind() => new("jp2-approx", Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(2, 0), (1, 18)]), + 16, 16, "DeviceRGB", 8, "JPXDecode"); + + /// A JP2 file of three channels with one colr box whose method is 7. + private static Kind MethodKind() => new("jp2-meth", Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(7, 0)]), 16, 16, + "DeviceRGB", 8, "JPXDecode"); private static LayoutDocumentType DocumentWith(PdfConformance claim, Kind kind, string? alt = "scan") { @@ -894,15 +911,21 @@ private static LayoutDocumentType DocumentWith(PdfConformance claim, Kind kind, public static TheoryData PdfAImagesNotAllowed() => new() { - { "two", "has 2 channels" }, - { "depths", "channels of different bit depths" }, + { "approx", "more than one colour specification and not exactly one of them has an APPROX of 1" }, + { "method", "colour specification whose method is not 1, 2 or 3" }, + { "depths", "colour channels of different bit depths" }, }; - private static Kind PdfAImage(string which) => which == "two" ? TwoChannelKind() : DifferentDepthsKind(); + private static Kind PdfAImage(string which) => which switch + { + "approx" => ApproxKind(), + "method" => MethodKind(), + _ => DifferentDepthsKind(), + }; [Theory] [MemberData(nameof(PdfAImagesNotAllowed))] - public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsWrittenAndReportedUnderAPdfAClaim(string which, string text) + public void Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim(string which, string text) { // ISO 32000-2, 7.4.9, allows both inputs, so the Kernel loader keeps them and the Layout save reports them under // a PDF/A claim: the clause is 19005-2, 6.2.8.3, and the code is an error, so strict mode refuses the save. @@ -932,7 +955,7 @@ public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsWrittenAn [Theory] [MemberData(nameof(PdfAImagesNotAllowed))] - public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsNotReportedWithoutAPdfAClaim(string which, string text) + public void Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsNotReportedWithoutAPdfAClaim(string which, string text) { Assert.NotEmpty(text); foreach (var claim in new[] { PdfConformance.None, PdfConformance.PdfUA1 }) @@ -965,20 +988,21 @@ public void Iso19005_2_6_2_8_3_AJp2FileOfOneThreeOrFourChannelsOfOneDepthIsNotRe } [Fact] - public void Iso19005_2_6_2_8_3_AJp2FileWithBothFindingsGivesOneItemForEach() + public void Iso19005_2_6_2_8_3_AJp2FileWithAllThreeFindingsGivesOneItemForEach() { - var kind = new Kind("jp2-both", Jp2File(JpxCodestream(16, 16, 2, 7, 0, [8, 4]), 2, 17, [7, 3]), 16, 16, "DeviceGray", - 8, "JPXDecode"); + var kind = new Kind("jp2-all", Jp2File(JpxCodestream(16, 16, 3, 7, 0, [8, 8, 4]), 3, null, [7, 7, 3], + rawColr: [[7, 0, 0], [1, 0, 0, 0, 0, 0, 16]]), 16, 16, "DeviceRGB", 8, "JPXDecode"); using var doc = DocumentWith(PdfConformance.PdfA2b, kind, alt: null); Save(doc); var items = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).ToArray(); - Assert.Equal(2, items.Length); - Assert.Contains("The JPEG 2000 image of 16 by 16 pixels has 2 channels", items[0].Message); - Assert.Contains("different bit depths", items[1].Message); + Assert.Equal(3, items.Length); + Assert.Contains("The JPEG 2000 image of 16 by 16 pixels has more than one colour specification", items[0].Message); + Assert.Contains("method is not 1, 2 or 3", items[1].Message); + Assert.Contains("different bit depths", items[2].Message); } [Fact] - public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsPassedThroughAndFailsVeraPdf() + public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithColourChannelsOfDifferentDepthsIsPassedThroughAndFailsVeraPdf() { // The ihdr bit depth is 0xFF, which says the depths are in a bpcc box, one byte per channel: 8, 8 and 4 bits. var kind = DifferentDepthsKind(); @@ -987,7 +1011,6 @@ public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsP Assert.Equal(["6.2.8.3-5"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); } - /// A JP2 file of three channels whose depths are 8, 8 and 4 bits, given by a bpcc box. private static Kind DifferentDepthsKind() => new("jp2-depths", Jp2File(JpxCodestream(16, 16, 3, 7, 0, [8, 8, 4]), 3, 16, [7, 7, 3]), 16, 16, "DeviceRGB", 8, "JPXDecode"); diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index 001807fe4..305210859 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -18,8 +18,34 @@ namespace VellumPdf.Kernel.Tests; /// public sealed partial class ConformanceAuditG4Tests { - private static byte[] Jp2Of(int channels, int? enumerated, bool palette = false, (int, int)[]? boxes = null) => - Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, boxes: boxes, palette: palette); + private static byte[] Jp2Of(int channels, int? enumerated, bool palette = false, (int, int)[]? boxes = null, + bool cmapOnly = false, bool pclrOnly = false) => + Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, boxes: boxes, palette: palette, cmapOnly: cmapOnly, + pclrOnly: pclrOnly); + + // The file with the ihdr channel count rewritten, to build a count the codestream does not have. + private static byte[] Jp2FileWithIhdrChannels(byte[] jp2, int channels) + { + var copy = (byte[])jp2.Clone(); + var at = copy.AsSpan().IndexOf("ihdr"u8); + copy[at + 4 + 8] = (byte)(channels >> 8); + copy[at + 4 + 9] = (byte)channels; + return copy; + } + + // The file with one more box appended inside its jp2h box, and the length of jp2h adjusted. + private static byte[] Jp2FileWithRawJp2hBox(byte[] jp2, string type, byte[] payload) + { + var at = jp2.AsSpan().IndexOf("jp2h"u8) - 4; + var length = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(jp2.AsSpan(at)); + var box = new byte[8 + payload.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(box, box.Length); + System.Text.Encoding.ASCII.GetBytes(type).CopyTo(box, 4); + payload.CopyTo(box, 8); + byte[] bytes = [.. jp2.AsSpan(0, at + length), .. box, .. jp2.AsSpan(at + length)]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(at), length + box.Length); + return bytes; + } private static string? ColourSpaceWritten(byte[] jp2, PdfConformance claim = PdfConformance.None) { @@ -71,23 +97,33 @@ public void Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasN Assert.Empty(VeraFailures("2b", file)); } - // ── The channel count must fit the device name (M2) ─────────────────────────────────────── + // ── The colour channels must fit the device name ────────────────────────────────────────── + // ISO/IEC 15444-1, I.5.3.6: a codestream that holds only colour channels in colour order has no cdef box, and any + // other channel needs one. So with no cdef box every channel is a colour channel. [Theory] - [InlineData(1, 16)] // one channel cannot match the three components of DeviceRGB - [InlineData(3, 17)] // three channels beside DeviceGray + [InlineData(1, 16)] // one channel cannot hold the three components of DeviceRGB [InlineData(2, null)] // no colr box: the count chooses DeviceRGB - [InlineData(5, null)] [InlineData(2, 16)] + [InlineData(2, 12)] // a CMYK colr box, but two channels: the name is DeviceRGB, the count chooses + [InlineData(2, 17)] // greyscale takes one colour channel; the second one would need a cdef box + [InlineData(3, 17)] [InlineData(4, 17)] - [InlineData(6, 12)] // CMYK takes four channels, or five with an opacity channel - [InlineData(2, 12)] - public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountNoDeviceSpaceFitsIsRefused(int channels, int? enumerated) + [InlineData(4, 16)] + [InlineData(5, 16)] + [InlineData(5, null)] + [InlineData(5, 12)] // five channels beside a CMYK colr box: no name takes five colour channels + [InlineData(6, 12)] + [InlineData(0, 16)] // an ihdr box that gives no channels at all + [InlineData(0, 17)] + public void Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused(int channels, + int? enumerated) { - // The same data with no jp2h box is refused too, so the file with the box is no more valid than that one. - var jp2 = Jp2Of(channels, enumerated); + var jp2 = Jp2File(JpxCodestream(16, 16, Math.Max(channels, 1)), Math.Max(channels, 1), enumerated); + if (channels == 0) + jp2 = Jp2FileWithIhdrChannels(jp2, 0); var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); - Assert.Contains($"{channels} channels", e.Message); + Assert.Contains($"its ihdr box has {channels} channels and no cdef box, so every one is a colour channel", e.Message); Assert.Throws(() => LayoutImage.FromBytes(jp2)); Assert.Throws(() => ImageFile(PdfConformance.None, new Kind("jp2", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))); @@ -96,41 +132,182 @@ public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountNoDeviceSpaceFitsIsRefused [Fact] public void Iso32000_2_7_4_9_AJp2FileWithTwoColourBoxesAndTwoChannelsIsRefused() { - // Two colour boxes and no device space: the count chooses DeviceRGB, which two channels do not fit. + // Two colour boxes and no device space: the count chooses DeviceRGB, which two channels do not reach. var jp2 = Jp2Of(2, null, boxes: [(2, 0), (1, 18)]); Assert.Throws(() => JpxImageLoader.Load(jp2)); } [Theory] - [InlineData(2, 17, "DeviceGray")] // one opacity channel beyond the greyscale space: the ruled case - [InlineData(4, 16, "DeviceRGB")] - [InlineData(5, 12, "DeviceCMYK")] // a CMYK colr box names the space where the count fits no other + [InlineData(1, 17, "DeviceGray")] + [InlineData(3, 16, "DeviceRGB")] [InlineData(4, 12, "DeviceCMYK")] - [InlineData(1, 12, "DeviceGray")] // the name a 2.3.3 save wrote fits, so it stays - [InlineData(3, 12, "DeviceRGB")] [InlineData(4, null, "DeviceCMYK")] - public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountFitsTheDeviceNameIsWritten(int channels, int? enumerated, string name) + [InlineData(1, 12, "DeviceGray")] // the name a 2.3.3 save wrote already has one component, so it stays + [InlineData(3, 12, "DeviceRGB")] + [InlineData(1, null, "DeviceGray")] + public void Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName(int channels, + int? enumerated, string name) { Assert.Equal(name, ColourSpaceWritten(Jp2Of(channels, enumerated))); } + [Fact] + public void Iso32000_2_7_4_9_TheMessageForAJp2FileWithNoIhdrBoxNamesTheCodestreamNotTheIhdrBox() + { + // A jp2h box with no ihdr box: the count comes from the codestream, so the message cannot say "ihdr box". + var jp2 = Jp2File(JpxCodestream(16, 16, 2), 2, 16, noIhdr: true); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains("its codestream has 2 channels and no cdef box", e.Message); + Assert.DoesNotContain("ihdr", e.Message); + Assert.DoesNotContain("DeviceRgb", e.Message); + Assert.Contains("DeviceRGB", e.Message); + } + + [Theory] + [InlineData(2)] + [InlineData(5)] + [InlineData(6)] + public void Iso32000_2_7_4_9_TheMessageForAJp2FileWithNoJp2hBoxSaysSo(int channels) + { + // The loader writes the colr box itself, so a count with no device space is refused. Five channels would + // pass a check of the name alone, so only this refusal stops them. + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, noJp2h: true); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"no jp2h box has {channels} channels", e.Message); + } + + // ── A cdef box says which channels are ordinary colour channels ─────────────────────────── + + private static (int, int, int)[] Channels(int colour, params int[] otherTypes) + { + var l = new List<(int, int, int)>(); + for (var i = 0; i < colour; i++) + l.Add((i, 0, i + 1)); + for (var i = 0; i < otherTypes.Length; i++) + l.Add((colour + i, otherTypes[i], 1 + i % Math.Max(colour, 1))); + return [.. l]; + } + + [Theory] + [InlineData(5, 16, 3, new[] { 1, 1 }, "DeviceRGB")] // two opacity channels on an RGB image (7.4.9's own example) + [InlineData(6, 16, 3, new[] { 1, 1, 1 }, "DeviceRGB")] + [InlineData(5, 16, 3, new[] { 2, 1 }, "DeviceRGB")] // one premultiplied and one plain opacity channel + [InlineData(4, 16, 3, new[] { 0xFFFF }, "DeviceRGB")] // an unspecified channel is not a colour channel + [InlineData(2, 17, 1, new[] { 1 }, "DeviceGray")] + [InlineData(3, 17, 1, new[] { 1, 2 }, "DeviceGray")] + [InlineData(6, 12, 4, new[] { 1, 1 }, "DeviceCMYK")] // a CMYK colr box and four colour channels: the name follows + [InlineData(5, 12, 4, new[] { 1 }, "DeviceCMYK")] + [InlineData(4, 12, 4, new int[0], "DeviceCMYK")] + [InlineData(5, null, 3, new[] { 1, 1 }, "DeviceRGB")] + public void Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten(int channels, + int? enumerated, int colour, int[] others, string name) + { + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: Channels(colour, others)); + Assert.Equal(name, ColourSpaceWritten(jp2)); + } + + [Fact] + public void Iso32000_2_7_4_9_ACmykBoxAmongSeveralLetsFourColourChannelsHaveDeviceCmyk() + { + // The last enumerated value is sRGB, which has three components; the CMYK box and four colour channels give + // the name that fits. + var jp2 = Jp2File(JpxCodestream(16, 16, 4), 4, 12, extraEnumerated: 16, cdef: Channels(4)); + Assert.Equal("DeviceCMYK", ColourSpaceWritten(jp2)); + } + + [Theory] + [InlineData(2, 17, 2, new int[0])] // greyscale with two colour channels: 7.4.9 allows one + [InlineData(3, 16, 1, new[] { 1, 1 })] // an RGB name over one colour channel + [InlineData(3, 16, 2, new[] { 1 })] + [InlineData(5, 16, 4, new[] { 1 })] // four colour channels, and no CMYK box to name them + [InlineData(5, null, 4, new[] { 1 })] + [InlineData(4, 17, 4, new int[0])] + [InlineData(3, 16, 0, new[] { 1, 1, 1 })] // no colour channel at all + [InlineData(3, 16, 0, new[] { 0xFFFF, 0xFFFF, 0xFFFF })] // unspecified entries do not count + public void Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused(int channels, int? enumerated, + int colour, int[] others) + { + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: Channels(colour, others)); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"its cdef box marks {colour} ordinary colour channels", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + } + + [Fact] + public void Iso32000_2_7_4_9_OnlyTheFirstCdefBoxIsReadAndAShortOneIsIgnored() + { + // A box whose payload cannot hold its own entry count is treated as absent, so the file is judged as one with + // no cdef box: five channels are five colour channels, which DeviceRGB does not take. With two boxes the + // first decides. + var codestream = JpxCodestream(16, 16, 5); + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2File(codestream, 5, 16, cdef: Channels(3, 1, 1)))); + var shortCount = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16), "cdef", [0, 9, 0, 0, 0, 0, 0, 1]); + Assert.Contains("and no cdef box", Assert.Throws(() => JpxImageLoader.Load(shortCount)).Message); + var onlyTheCount = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16), "cdef", [0]); + Assert.Contains("and no cdef box", Assert.Throws(() => JpxImageLoader.Load(onlyTheCount)).Message); + // The first box marks one colour channel, the appended one three: the first decides, so the file is refused. + var twice = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16, cdef: Channels(1, 1, 1, 1, 1)), "cdef", + [0, 3, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 2, 0, 0, 0, 3]); + Assert.Throws(() => JpxImageLoader.Load(twice)); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AJp2FileWithOpacityChannelsBeyondItsColourChannelsIsNotReported() + { + // Five channels, three of them colour: 6.2.8.3 counts the colour channels, so nothing is reported under a PDF/A + // claim. veraPDF 1.30.4 counts the ihdr channels and fails the file; the text does not. + var jp2 = Jp2File(JpxCodestream(16, 16, 5), 5, 16, cdef: Channels(3, 1, 1)); + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-cdef", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode")); + var file = Save(doc); + Assert.Equal("DeviceRGB", Written(file).Name("ColorSpace")); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", file)); + } + + // ── A palette ──────────────────────────────────────────────────────────────────────────── + [Fact] public void Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount() { - // The pclr and cmap boxes turn one stored channel into the colour channels of the palette's colour space; - // the loader does not read them, so the ihdr count says nothing about the colour channels. + // The pclr box turns one stored channel into the colour channels of the palette's colour space; the loader + // does not read it, so the ihdr count says nothing about the colour channels. Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2Of(1, 16, palette: true))); + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2Of(1, 16, pclrOnly: true))); + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, 1), 1, 16, palette: true, + cdef: Channels(3)))); } [Fact] - public void Iso19005_2_6_2_8_3_AJp2FileOfFiveChannelsBesideCmykIsWrittenAndReportedUnderAPdfAClaim() + public void Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxIsNotAPalette() { - // Five channels is one opacity channel beyond CMYK: written as DeviceCMYK, reported as a count of five. - using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-5", Jp2Of(5, 12), 16, 16, "DeviceCMYK", 8, "JPXDecode")); - var file = Save(doc); - Assert.Equal("DeviceCMYK", Written(file).Name("ColorSpace")); - var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); - Assert.Contains("has 5 channels", item.Message); + // cmap maps channels to palette columns; with no palette there is nothing to map to, so the file is judged + // by its channel count. One or two channels beside sRGB lack a colour channel; three are fine. + Assert.Throws(() => JpxImageLoader.Load(Jp2Of(2, 16, cmapOnly: true))); + Assert.Throws(() => JpxImageLoader.Load(Jp2Of(1, 16, cmapOnly: true))); + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2Of(3, 16, cmapOnly: true))); + } + + // ── Which lone colr boxes lose the name ────────────────────────────────────────────────── + + [Theory] + [InlineData(1, 4, 0)] // a lone vendor colour box (method 4) + [InlineData(3, 4, 0)] + [InlineData(3, 7, 0)] // a method the loader does not read + public void Iso32000_2_7_4_9_ALoneColourBoxThatIsNotAnIccProfileOrAnEnumeratedSpaceKeepsTheName(int channels, int method, + int value) + { + var jp2 = Jp2Of(channels, null, boxes: [(method, value)]); + Assert.Equal(channels == 1 ? "DeviceGray" : "DeviceRGB", ColourSpaceWritten(jp2)); + } + + [Theory] + [InlineData(new byte[] { 1, 0 })] // under 3 bytes + [InlineData(new byte[] { 1, 0, 0, 0, 0 })] // method 1 with an enumerated value cut short + [InlineData(new byte[] { 9, 0, 0 })] // a method the loader does not read + public void Iso32000_2_7_4_9_AMalformedLoneColourBoxKeepsTheName(byte[] payload) + { + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: [payload]); + Assert.Equal("DeviceRGB", ColourSpaceWritten(jp2)); } // ── The report quotes no caller text (M4) and covers a band logo (L1) ──────────────────── @@ -139,14 +316,14 @@ public void Iso19005_2_6_2_8_3_AJp2FileOfFiveChannelsBesideCmykIsWrittenAndRepor public void Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText() { var alt = "line one\nline two " + new string('x', 300); - using var doc = DocumentWith(PdfConformance.PdfA2b, TwoChannelKind(), alt); + using var doc = DocumentWith(PdfConformance.PdfA2b, ApproxKind(), alt); Save(doc); var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); Assert.DoesNotContain("line one", item.Message); Assert.DoesNotContain("xxxx", item.Message); Assert.DoesNotContain('\n', item.Message); - Assert.Equal("The JPEG 2000 image of 16 by 16 pixels has 2 channels; PDF/A-2 allows one, three or four. " + - "The image is written as it is.", item.Message); + Assert.Equal("The JPEG 2000 image of 16 by 16 pixels has more than one colour specification and not exactly " + + "one of them has an APPROX of 1; PDF/A-2 requires exactly one. The image is written as it is.", item.Message); Assert.Equal(LayoutElementKind.Image, item.ElementKind); Assert.Equal(0, item.ElementIndex); } @@ -155,7 +332,7 @@ public void Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText() public void Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage() { using var doc = NewDocument(PdfConformance.PdfA2b); - doc.Header = new RunningBand(BandZone.Logo(new LayoutImage(Load(TwoChannelKind())) { AltText = "logo text" }), + doc.Header = new RunningBand(BandZone.Logo(new LayoutImage(Load(ApproxKind())) { AltText = "logo text" }), BandZone.Empty, BandZone.Empty); for (var i = 0; i < 3; i++) doc.Add(new LayoutImage(Load(new Kind("jpeg", Jpeg(4, 2, 3), 4, 2, "DeviceRGB", 8, "DCTDecode"))) { BreakBefore = VellumPdf.Layout.Core.PageBreakMode.Page }); @@ -166,21 +343,84 @@ public void Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnE Assert.DoesNotContain("logo text", item.Message); } - // ── A bpcc box that differs only in sign (L4) ─────────────────────────────────────────── + // ── Colour channels only, and depth only ───────────────────────────────────────────────── [Fact] - public void Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsReportedAsSuch() + public void Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported() { - // 07 87 07: three channels of 8 bits, the second one signed. The whole bpcc byte is compared. + // 07 87 07: three channels of 8 bits, the second one signed. The sign is not part of the bit depth (ISO/IEC + // 15444-1, Table A.11), and 6.2.8.3 compares the bit depth. veraPDF 1.30.4 fails the file on 6.2.8.3-5. var kind = new Kind("jp2-sign", Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 0x87, 7]), 16, 16, "DeviceRGB", 8, "JPXDecode"); using var doc = DocumentWith(PdfConformance.PdfA2b, kind); var file = Save(doc); - var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); - Assert.Contains("different bit depths or signs", item.Message); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); Assert.Equal(["6.2.8.3-5"], VeraFailures("2b", file)); } + [Fact] + public void Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs() + { + // Four channels, bpcc 8, 8, 8 and 4 bits. The cdef box makes the fourth an opacity channel, which 6.2.8.3 does + // not cover; with no cdef box it is a colour channel (a CMYK file) and the depths differ. + var withOpacity = new Kind("jp2-op", Jp2File(JpxCodestream(16, 16, 4), 4, 16, [7, 7, 7, 3], cdef: Channels(3, 1)), + 16, 16, "DeviceRGB", 8, "JPXDecode"); + using var a = DocumentWith(PdfConformance.PdfA2b, withOpacity); + Save(a); + Assert.DoesNotContain(a.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + + var colour = new Kind("jp2-cmyk", Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 7, 3]), 16, 16, "DeviceCMYK", 8, + "JPXDecode"); + using var b = DocumentWith(PdfConformance.PdfA2b, colour); + Save(b); + Assert.Contains("colour channels of different bit depths", + Assert.Single(b.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).Message); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AFileWithAPaletteHasNoDepthsComparedBecauseItsColourChannelsAreNotRead() + { + var kind = new Kind("jp2-pal", Jp2File(JpxCodestream(16, 16, 1), 1, 16, [7, 3], palette: true), 16, 16, "DeviceRGB", 8, + "JPXDecode"); + using var doc = DocumentWith(PdfConformance.PdfA2b, kind); + Save(doc); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + [Fact] + public void Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre() + { + // colr payloads: METH, PREC, APPROX, then the enumerated value (METH 1) or a profile (METH 2). + byte[] approxOne = [1, 0, 1, 0, 0, 0, 16]; + byte[] approxZero = [1, 0, 0, 0, 0, 0, 18]; + byte[] icc = [2, 0, 1, .. new byte[16]]; + foreach (var (boxes, reported) in new[] + { + (new[] { approxOne, approxZero }, false), (new[] { approxZero, approxOne }, false), + (new[] { approxOne, approxOne }, true), (new[] { approxZero, approxZero }, true), + (new[] { approxOne, icc }, true), (new[] { approxOne }, false), + }) + { + var kind = new Kind("jp2-approx", Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: boxes), 16, 16, "DeviceRGB", + 8, "JPXDecode"); + using var doc = DocumentWith(PdfConformance.PdfA2b, kind); + Save(doc); + Assert.Equal(reported, doc.Diagnostics.Any(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA)); + } + } + + [Fact] + public void Iso19005_2_6_2_8_3_ATwoColourBoxFileIsReportedWhetherOrNotColorSpaceIsWrittenAndPassesVeraPdfWithIt() + { + // The clause is not conditioned on the dictionary lacking ColorSpace. veraPDF 1.30.4 checks APPROX only + // without one, so it passes this file, which writes DeviceRGB. + using var doc = DocumentWith(PdfConformance.PdfA2b, ApproxKind()); + var file = Save(doc); + Assert.Equal("DeviceRGB", Written(file).Name("ColorSpace")); + Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + Assert.Empty(VeraFailures("2b", file)); + } + // ── A TIFF whose colour exceeds its alpha (L2) ───────────────────────────────────────── [Fact] diff --git a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs index a036e2e28..1e78fb962 100644 --- a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs +++ b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs @@ -232,14 +232,14 @@ public void Jp2_Colr_SRgb16_ReportsDeviceRgb() } [Fact] - public void Jp2_Colr_Greyscale17_ReportsDeviceGray() - { - // Two channels is greyscale plus one opacity channel (ISO 32000-2, 7.4.9), the shape where the colr box, - // not the channel-count default of DeviceRGB, has to decide. Three channels beside greyscale is refused. - var jp2 = BuildJp2File(width: 4, height: 4, nc: 2, bpc: 8, colrEnum: 17); - var img = JpxImageLoader.Load(jp2.File); - // colr greyscale enum overrides the channel-count default of DeviceRGB. - Assert.Contains("/DeviceGray", StreamDictText(img)); + public void Jp2_Colr_Greyscale17_WithThreeChannelsAndNoCdefBoxIsRefused() + { + // The colr box says greyscale, which takes one colour channel, and with no cdef box all three channels are + // colour channels (ISO 32000-2, 7.4.9, and ISO/IEC 15444-1, I.5.3.6), so the file is invalid. A greyscale + // file with a cdef box that gives it a colour and an opacity channel is written as DeviceGray in + // ConformanceAuditG4Tests.JpxChannels. + var jp2 = BuildJp2File(width: 4, height: 4, nc: 3, bpc: 8, colrEnum: 17); + Assert.Throws(() => JpxImageLoader.Load(jp2.File)); } // ── DecodeToRaster: not supported ───────────────────────────────────────── From c7653ce38611fdb02726312fb125a171701e4e8f Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 11:16:11 +0100 Subject: [PATCH 11/22] docs(conformance): state the JP2 colour-channel rule and the 6.2.8.3 report The ISO 32000-2 7.4.9 row now says the colour channels are counted from the cdef box, or every channel without one, and the name must have that many components. The ISO 19005-2 6.2.8.3 row lists the three findings the Layout report follows and says where veraPDF differs, and drops the sign-bit open point, which the clause text settles. --- docs/conformance-v2.4.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 88f9c5989..85dbc703e 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -399,11 +399,11 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused; a JP2 file with a jp2h whose channel count its device name does not fit is refused, and a CMYK colr box with five channels is written as DeviceCMYK; a JP2 file with exactly one colr box that names no device space is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountNoDeviceSpaceFitsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountFitsTheDeviceNameIsWritten`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the type 0 entries of a cdef box, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its device name has that many components; a CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | | ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream with the Part 2 bit set, bare or in a JP2 file. ISO/IEC 15444-1 and -2, which define the baseline set and the meaning of that bit, are not held; the row checks the Part 2 bit only | `Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File`, `Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, one colr box with METH 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): a JP2 file whose channel count is 2 beside greyscale (6.2.8.3-1) or whose bpcc box gives different depths or signs (6.2.8.3-5) is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The clause was read on 2026-11-29 and confirms the veraPDF checks, including a bpcc box with different depths and two channels; an image that effectively uses DeviceGray, RGB or CMYK, through ColorSpace or the JPX data, also falls under 6.2.4.3. Needs a NEN reading: whether the clause compares the sign bit of a bpcc entry | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsOrDifferentDepthsIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsReportedAsSuch` | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette, whose colour channels are not read. A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, or colour channels of different bit depth is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | | ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | | ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | From d21cd906dd492cf993c16058c29fadf3d4e593a0 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 11:18:40 +0100 Subject: [PATCH 12/22] docs(images): say what the NEN reading of 6.2.8.3 and Rsiz settles The conformance doc paragraph on 6.2.8.3 claimed the clause follows from 6.2.4.3. The reading of 2026-11-30 shows APPROX and METH apply whether or not ColorSpace is written, the channel limit counts colour channels, and the depth rule leaves the sign out. The Rsiz comments, the loader docs and the CHANGELOG cite ISO/IEC 15444-1 Table A.10 for bit 15, and say bit 14 is not examined. --- CHANGELOG.md | 7 ++++--- docs/conformance-v2.4.md | 11 +++++++---- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 17 ++++++++--------- .../ConformanceAuditG4Tests.Images.cs | 4 ++-- .../ConformanceAuditG4Tests.JpxChannels.cs | 2 +- 5 files changed, 22 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cf20f11d..61f1413a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -892,9 +892,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so a codestream with bit 15 set was wrapped and written. `Load` now throws `InvalidDataException` naming `Rsiz` for such a - codestream, bare or inside a JP2 file. ISO/IEC 15444, which defines the baseline set, is not - held here, so only that one bit is checked and a codestream that uses another feature outside the - set still passes through. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 15 set; + codestream, bare or inside a JP2 file. ISO/IEC 15444-1, Table A.10, gives that bit its + meaning. The baseline set is defined in ISO/IEC 15444-2, which is not read here, so only that + one bit is checked: a codestream that uses another feature outside the set, or sets bit 14 + (extended capabilities through a CAP marker), still passes through. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 15 set; every other codestream writes the same bytes as before. - **A TIFF with associated alpha is written with a black Matte on its soft mask (#764).** TIFF diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 85dbc703e..39df1cab0 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -401,7 +401,7 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | | ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the type 0 entries of a cdef box, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its device name has that many components; a CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | -| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream with the Part 2 bit set, bare or in a JP2 file. ISO/IEC 15444-1 and -2, which define the baseline set and the meaning of that bit, are not held; the row checks the Part 2 bit only | `Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File`, `Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | +| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream with the Part 2 bit set, bare or in a JP2 file. ISO/IEC 15444-1 Table A.10, read on NEN on 2026-11-30, gives bit 15 the meaning Part 2 capabilities; bit 14 (extended capabilities through a CAP marker) is not checked, and the baseline set of ISO/IEC 15444-2 is not read. The row checks the Part 2 bit only | `Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File`, `Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | | ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette, whose colour channels are not read. A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, or colour channels of different bit depth is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | @@ -463,9 +463,12 @@ Not done in this audit: ISO 19005-2 rows read in the standard on 2026-11-29: 6.2.4.3 is a shall (DeviceRGB needs a DefaultRGB or an RGB output intent, DeviceCMYK a DefaultCMYK or a CMYK output intent, DeviceGray a DefaultGray or any PDF/A output intent), which settles the use of `DefaultRGB` and confirms the #474 rows. 6.2.8.1 is a shall (no Alternates or OPI in an image -dictionary, Interpolate false if present, an inline image's I false). 6.2.8.3 is a shall for baseline JPX only with the -channel, colr, CIEJab and bit depth limits the row states, so what a loader may write when `ColorSpace` is absent -follows from 6.2.4.3, as #763 proposes, and the #763 and #770 rows keep their verdict. Still unread: 6.2.3 (the profile +dictionary, Interpolate false if present, an inline image's I false). 6.2.8.3 was read on NEN on 2026-11-30 (a paraphrase, +in the clause 6 notes). It is a shall for baseline JPX only, a count of 1, 3 or 4 colour channels, and one bit depth for +all the colour channels, with the sign kept apart from the depth. Where there are several colour specifications, exactly +one has an APPROX of 1, and the colr METH is 1, 2 or 3. Those last two sentences apply whether or not the image +dictionary has a `ColorSpace`, so what a loader may write is not settled by 6.2.4.3 alone. The #763 and #770 rows say +what the text says. Still unread: 6.2.3 (the profile rules beyond veraPDF's 6.2.3-1 to 6.2.3-3), 6.2.4.1 (the Default colour space alternative for each device space), 6.2.7 and 6.2.8.2 (the notes hold no content for either; the fixtures write no `i` operator and no image mask), 6.2.9 (the list of forbidden form keys) and 6.2.10 (what counts as a page that contains transparency, which the notes put in diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 653bac3a2..a165d2356 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -109,10 +109,9 @@ public static class JpxImageLoader private const ushort MarkerSOC = 0xFF4F; // JPEG 2000 SIZ marker (image and tile size). private const ushort MarkerSIZ = 0xFF51; - // Bit 15 of the SIZ marker's Rsiz field. That it marks a codestream using capabilities beyond - // JPEG 2000 Part 1 is a reading of ISO/IEC 15444, which is not held in this repository, so the - // meaning is not checked against the text. This bit is the only part of Rsiz the loader reads; - // the other Rsiz values are not examined. + // Bit 15 of the SIZ marker's Rsiz field: ISO/IEC 15444-1, Table A.10, gives it the meaning of + // capabilities from Part 2. This bit is the only part of Rsiz the loader reads; bit 14, which + // marks extended capabilities through a CAP marker, and the other values are not examined. private const int RsizPart2Bit = 0x8000; // colr enumColourspace values (ISO 15444-1 Table I.11). @@ -153,12 +152,12 @@ public static class JpxImageLoader /// naming the Rsiz value when bit 15 of the SIZ marker's /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the /// JPX baseline set of features, and bit 15 marks capabilities - /// beyond JPEG 2000 Part 1. That meaning comes from ISO/IEC 15444, which is not held here, so it is not - /// checked against the text. The bit is read + /// beyond JPEG 2000 Part 1 (ISO/IEC 15444-1, Table A.10). The bit is read /// from a bare codestream and from the jp2c box of a JP2 file whose codestream starts with - /// SOC and SIZ. This loader checks only that bit: the text that defines the baseline set is - /// ISO/IEC 15444, which is not checked here, so a codestream that sets no Part 2 bit but still uses - /// a feature outside the baseline set passes through. Do not pass a codestream you have not + /// SOC and SIZ. This loader checks only that bit: the baseline set is defined in + /// ISO/IEC 15444-2, which is not checked here, and a codestream with bit 14 set (extended capabilities + /// through a CAP marker) is not examined either, so a codestream that sets no Part 2 bit but still + /// uses a feature outside the baseline set passes through. Do not pass a codestream you have not /// checked against the baseline set; this loader does not decode it. /// public static PdfImageXObject Load(byte[] jpx) diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index d3fd5c01c..2d15d8bdf 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -1054,8 +1054,8 @@ public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRef [Fact] public void Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused() { - // Rsiz with the Part 2 bit (0x8000). Whether that bit puts a codestream outside the baseline set is defined in - // ISO/IEC 15444, which is not held, so the loader refuses on the bit and on nothing else. + // Rsiz with the Part 2 bit (0x8000). ISO/IEC 15444-1, Table A.10, gives it the meaning of Part 2 capabilities, and + // the loader refuses on the bit and on nothing else (bit 14 is not examined). var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000))); Assert.Contains("0x8000", e.Message); } diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index 305210859..63b172250 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -14,7 +14,7 @@ namespace VellumPdf.Kernel.Tests; /// /// JPEG 2000 files with a jp2h box: which device name is written for which channel count, and which colour -/// specifications keep the name. ISO 32000-2, 7.4.9, is the clause; ISO/IEC 15444 is not held. +/// specifications keep the name. ISO 32000-2, 7.4.9, and ISO/IEC 15444-1, I.5.3.6, are the clauses. /// public sealed partial class ConformanceAuditG4Tests { From 9583ec68c6ea1da79719276d06970d6f01a925a3 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 30 Nov 2026 12:05:07 +0100 Subject: [PATCH 13/22] fix(images): refuse only the Part 2 capabilities the JPX baseline excludes Refusing every codestream with Rsiz bit 15 set also refused baseline files that 2.3.3 wrote validly. ISO/IEC 15444-2:2004, M.9.2.3, defines the JPX baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, and Table A.2 says which Rsiz bits are required to decode. With bit 15 set the loader now refuses only when bit 0, 1, 4, 5, 6, 7, 10 or 11 is set. Bit 15 alone, the useful bits 2, 3 and 9, and the multiple component transformation bit 8 pass; the MCC and MCO limits that the baseline puts on bit 8 are not checked. Bit 14 (extended capabilities through a CAP marker, such as the HT block coder) is refused. The reach is unchanged: a bare codestream, and the jp2c of a JP2 file whose codestream starts SOC then SIZ. The loader, LayoutImage.FromBytes and the CHANGELOG entry state the new rule, and the tests pin each required bit refused, each passing bit kept byte for byte, and bit 14 refused. --- CHANGELOG.md | 22 +++--- docs/conformance-v2.4.md | 2 +- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 69 +++++++++++++------ src/VellumPdf.Layout/Elements/LayoutImage.cs | 5 +- .../ConformanceAuditG4Tests.Images.cs | 56 ++++++++++++--- 5 files changed, 110 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61f1413a5..797cd3082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -888,15 +888,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file whose name has as many components as it has colour channels, or that has a palette, writes the same bytes as before. -- **A JPEG 2000 codestream that sets the Part 2 bit of Rsiz is refused (#770).** ISO 32000-2, - 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and - `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so a codestream with bit 15 set - was wrapped and written. `Load` now throws `InvalidDataException` naming `Rsiz` for such a - codestream, bare or inside a JP2 file. ISO/IEC 15444-1, Table A.10, gives that bit its - meaning. The baseline set is defined in ISO/IEC 15444-2, which is not read here, so only that - one bit is checked: a codestream that uses another feature outside the set, or sets bit 14 - (extended capabilities through a CAP marker), still passes through. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 15 set; - every other codestream writes the same bytes as before. +- **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused + (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of + features, and `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so such a codestream + was wrapped and written. ISO/IEC 15444-2:2004, M.9.2.3, defines that set as Part 1 plus only the + irreversible decorrelation and non-linearity extensions. `Load` now throws `InvalidDataException` + naming `Rsiz`, for a codestream bare or inside a JP2 file, when bit 15 (Part 2 capabilities) is + set together with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities that Table A.2 of that + part says are required to decode, and when bit 14 is set (extended capabilities through a CAP + marker, such as the HT block coder; ISO/IEC 15444-1, Table A.10). Bit 15 alone, the "useful" bits + 2, 3 and 9, and bit 8 (multiple component transformation) pass: the baseline allows the + irreversible decorrelation, and its limits on the MCC and MCO marker segments are not checked. + **Deliberate new refusal:** a codestream whose `Rsiz` has bit 14 set, or bit 15 together with one + of the listed required bits; every other codestream writes the same bytes as before. - **A TIFF with associated alpha is written with a black Matte on its soft mask (#764).** TIFF 6.0 says `ExtraSamples` 1 holds colour samples already multiplied by alpha, which is the diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 39df1cab0..755534df9 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -401,7 +401,7 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | | ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the type 0 entries of a cdef box, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its device name has that many components; a CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | -| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream with the Part 2 bit set, bare or in a JP2 file. ISO/IEC 15444-1 Table A.10, read on NEN on 2026-11-30, gives bit 15 the meaning Part 2 capabilities; bit 14 (extended capabilities through a CAP marker) is not checked, and the baseline set of ISO/IEC 15444-2 is not read. The row checks the Part 2 bit only | `Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File`, `Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | +| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream, bare or in a JP2 file, when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined | `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | | ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette, whose colour channels are not read. A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, or colour channels of different bit depth is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index a165d2356..493566ec4 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -109,10 +109,21 @@ public static class JpxImageLoader private const ushort MarkerSOC = 0xFF4F; // JPEG 2000 SIZ marker (image and tile size). private const ushort MarkerSIZ = 0xFF51; - // Bit 15 of the SIZ marker's Rsiz field: ISO/IEC 15444-1, Table A.10, gives it the meaning of - // capabilities from Part 2. This bit is the only part of Rsiz the loader reads; bit 14, which - // marks extended capabilities through a CAP marker, and the other values are not examined. + // The SIZ marker's Rsiz field. ISO/IEC 15444-1, Table A.10, gives bit 15 the meaning of + // capabilities from Part 2 and bit 14 the meaning of extended capabilities through a CAP marker + // (the HT block coder of Part 15 is one). ISO/IEC 15444-2:2004, Table A.2, names the Part 2 + // capability bits, and M.9.2.3 limits the JPX baseline codestream to Part 1 plus the + // irreversible decorrelation and non-linearity extensions. Bit 8 (multiple component + // transformation) therefore passes: the baseline allows its restricted decorrelation, whose + // limits (the MCC and MCO fields) are not checked here. Bits 2, 3 and 9 are "useful" + // capabilities, which a reader may ignore, so they pass too. private const int RsizPart2Bit = 0x8000; + private const int RsizExtendedBit = 0x4000; + // The Table A.2 "required to decode" bits other than bit 8: 0 variable DC offset, 1 variable + // scalar quantization, 4 single sample overlap, 5 arbitrary decomposition style, 6 arbitrary + // transformation kernel, 7 whole sample symmetric kernel, 10 arbitrary shaped ROI, 11 + // precinct-dependent quantization. + private const int RsizRequiredNonBaselineBits = 0x0CF3; // colr enumColourspace values (ISO 15444-1 Table I.11). private const int ColrEnumSRgb = 16; @@ -130,8 +141,9 @@ public static class JpxImageLoader /// A with /Filter /JPXDecode. /// /// Thrown when the data is malformed, truncated, or its dimensions exceed - /// , or when the codestream's Rsiz has the Part 2 - /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h + /// , or when the codestream's Rsiz requires a Part 2 + /// capability outside the JPX baseline set or has the extended capabilities bit (0x4000) set. + /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose /// only colour specifications are enumerated colour space 19 (CIEJab). @@ -148,17 +160,23 @@ public static class JpxImageLoader /// that also has an ICC profile, or another enumerated space, is written with no /// ColorSpace only when it has exactly one colr box. The class summary lists what is /// written for each colour specification. - /// A codestream that uses JPEG 2000 Part 2 capabilities is refused. The call throws - /// naming the Rsiz value when bit 15 of the SIZ marker's - /// Rsiz field is set, because ISO 32000-2, 7.4.9, limits the data of an image XObject to the - /// JPX baseline set of features, and bit 15 marks capabilities - /// beyond JPEG 2000 Part 1 (ISO/IEC 15444-1, Table A.10). The bit is read - /// from a bare codestream and from the jp2c box of a JP2 file whose codestream starts with - /// SOC and SIZ. This loader checks only that bit: the baseline set is defined in - /// ISO/IEC 15444-2, which is not checked here, and a codestream with bit 14 set (extended capabilities - /// through a CAP marker) is not examined either, so a codestream that sets no Part 2 bit but still - /// uses a feature outside the baseline set passes through. Do not pass a codestream you have not - /// checked against the baseline set; this loader does not decode it. + /// A codestream whose Rsiz requires a Part 2 capability outside the JPX + /// baseline set is refused, and so is one with the extended capabilities bit set. The call + /// throws naming the Rsiz value, because ISO 32000-2, + /// 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and ISO/IEC + /// 15444-2, M.9.2.3, defines that set as Part 1 plus only the irreversible decorrelation and + /// non-linearity extensions. With bit 15 (Part 2 capabilities) set, the call refuses when any + /// of bits 0, 1, 4, 5, 6, 7, 10 or 11 is set, the capabilities that ISO/IEC 15444-2, Table A.2, + /// says are required to decode. It refuses when bit 14 is set, which marks extended + /// capabilities through a CAP marker, such as the HT block coder (ISO/IEC 15444-1, Table A.10). + /// Bit 15 alone, the "useful" bits 2, 3 and 9, and bit 8 (multiple component transformation) + /// pass. Bit 8 passes because the baseline allows the irreversible decorrelation + /// transformation; the limits it puts on the MCC and MCO marker segments are not checked, so + /// do not pass a codestream whose multiple component transformation goes beyond them and + /// expect a refusal. The bits are read from a bare codestream and from the jp2c box of a + /// JP2 file whose codestream starts with SOC and SIZ; any other codestream is not examined. + /// This loader does not decode, so a codestream that uses a feature outside the baseline set + /// without signalling it in Rsiz passes through. /// public static PdfImageXObject Load(byte[] jpx) => Load(jpx, ImageLoadOptions.Default); @@ -178,8 +196,9 @@ public static PdfImageXObject Load(byte[] jpx) /// A with /Filter /JPXDecode. /// /// Thrown when the data is malformed, truncated, or its dimensions exceed - /// , or when the codestream's Rsiz has the Part 2 - /// capabilities bit (0x8000) set. Also for a bare codestream, or a JP2 file with no jp2h + /// , or when the codestream's Rsiz requires a Part 2 + /// capability outside the JPX baseline set or has the extended capabilities bit (0x4000) set. + /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose /// only colour specifications are enumerated colour space 19 (CIEJab). @@ -190,8 +209,9 @@ public static PdfImageXObject Load(byte[] jpx) /// instead. /// /// - /// A codestream whose Rsiz has the Part 2 bit set is refused, as for - /// , which also says what is and is not checked. + /// A codestream whose Rsiz requires a Part 2 capability outside the JPX baseline set, or + /// has bit 14 set, is refused, as for , which also says what is and + /// is not checked. /// public static PdfImageXObject Load(byte[] jpx, ImageLoadOptions options) { @@ -667,9 +687,14 @@ private static (int width, int height, int components, int bpc) private static void RefuseOutsideBaseline(int rsiz) { - if ((rsiz & RsizPart2Bit) != 0) + if ((rsiz & RsizExtendedBit) != 0) throw new InvalidDataException( - $"JPEG 2000 codestream: Rsiz 0x{rsiz:X4} has the Part 2 capabilities bit (0x8000) set. " + + $"JPEG 2000 codestream: Rsiz 0x{rsiz:X4} has the extended capabilities bit (0x4000) set. " + + "A PDF image XObject is limited to the JPX baseline set of features (ISO 32000-2, 7.4.9)."); + if ((rsiz & RsizPart2Bit) != 0 && (rsiz & RsizRequiredNonBaselineBits) != 0) + throw new InvalidDataException( + $"JPEG 2000 codestream: Rsiz 0x{rsiz:X4} requires Part 2 capabilities " + + $"(bits 0x{rsiz & RsizRequiredNonBaselineBits:X4}) outside the JPX baseline set. " + "A PDF image XObject is limited to the JPX baseline set of features (ISO 32000-2, 7.4.9)."); } diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 13d9ef182..8d731c430 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -309,8 +309,9 @@ public LayoutImage(PdfImageXObject image) /// (or a JPEG strip of a TIFF) the refused set is a frame type other than SOF0, SOF1 and SOF2, /// a precision other than 8 bits, and a component count other than 1, 3 and 4 /// (). For JPEG 2000 it is a codestream whose - /// Rsiz sets the Part 2 bit, a bare codestream or a JP2 file with no jp2h box - /// whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose colour channels + /// Rsiz requires a Part 2 capability outside the JPX baseline set or sets bit 14 + /// (extended capabilities through a CAP marker), a bare codestream or a JP2 file with no + /// jp2h box whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose colour channels /// (the cdef entries of type 0, or every channel when there is no cdef box) are not /// as many as the components of the device colour space the loader would write, and a JP2 file /// whose only colour specification is CIEJab ( lists diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 2d15d8bdf..b360a1933 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -1054,31 +1054,67 @@ public void Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRef [Fact] public void Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused() { - // Rsiz with the Part 2 bit (0x8000). ISO/IEC 15444-1, Table A.10, gives it the meaning of Part 2 capabilities, and - // the loader refuses on the bit and on nothing else (bit 14 is not examined). - var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000))); - Assert.Contains("0x8000", e.Message); + // Rsiz 0x8001: Part 2 (bit 15) with the variable DC offset capability (bit 0), which ISO/IEC 15444-2:2004, + // Table A.2, says is required to decode. The JPX baseline (M.9.2.3) does not include it. + var e = Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8001))); + Assert.Contains("0x8001", e.Message); } + // Table A.2 bits that are required to decode, other than bit 8: 0, 1, 4, 5, 6, 7, 10, 11. Each is refused alone and + // beside the bits that pass (bit 8, the useful bits 2, 3 and 9). [Theory] - [InlineData(0x8000)] [InlineData(0x8001)] + [InlineData(0x8002)] + [InlineData(0x8010)] + [InlineData(0x8020)] + [InlineData(0x8040)] + [InlineData(0x8080)] + [InlineData(0x8400)] + [InlineData(0x8800)] + [InlineData(0x8FFF)] + [InlineData(0x8101)] + [InlineData(0x860D)] + public void Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused(int rsiz) + { + var codestream = JpxCodestream(16, 16, 3, 7, rsiz); + var e = Assert.Throws(() => JpxImageLoader.Load(codestream)); + Assert.Contains($"0x{rsiz:X4}", e.Message); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(codestream, 3, 16))); + Assert.Throws(() => LayoutImage.FromBytes(codestream)); + } + + // ISO/IEC 15444-1, Table A.10: bit 14 marks extended capabilities through a CAP marker, such as the HT block coder. + [Theory] + [InlineData(0x4000)] + [InlineData(0x4001)] [InlineData(0xC000)] - public void Iso32000_2_7_4_9_APartTwoBitIsRefusedInABareCodestreamAndInTheCodestreamOfAJp2File(int rsiz) + [InlineData(0x7FFF)] + public void Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused(int rsiz) { var codestream = JpxCodestream(16, 16, 3, 7, rsiz); - Assert.Throws(() => JpxImageLoader.Load(codestream)); + var e = Assert.Throws(() => JpxImageLoader.Load(codestream)); + Assert.Contains("0x4000", e.Message); Assert.Throws(() => JpxImageLoader.Load(Jp2File(codestream, 3, 16))); Assert.Throws(() => LayoutImage.FromBytes(codestream)); } + // Part 1 only, Part 2 with nothing required (0x8000), the useful bits 2, 3 and 9, and the multiple component + // transformation bit 8, which the baseline allows in its restricted decorrelation form. Bits 0 to 11 mean nothing + // without bit 15 (Table A.2 defines them under the prefix 1000), so a value below 0x4000 passes too. [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] - [InlineData(0x4000)] - [InlineData(0x7FFF)] - public void Iso32000_2_7_4_9_ARsizWithoutThePartTwoBitIsPassedThroughByteForByte(int rsiz) + [InlineData(0x0FFF)] + [InlineData(0x3FFF)] + [InlineData(0x8000)] + [InlineData(0x8004)] + [InlineData(0x8008)] + [InlineData(0x8200)] + [InlineData(0x8100)] + [InlineData(0x830C)] + [InlineData(0x8208)] + public void Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte(int rsiz) { var codestream = JpxCodestream(16, 16, 3, 7, rsiz); var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-rsiz", codestream, 16, 16, "DeviceRGB", 8, From 8e5e4b1936372f2100103c8f00d7860395e28d5a Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 13:37:21 +0100 Subject: [PATCH 14/22] fix(images): check a lone colr box against the colour channels, count cdef channels once A JP2 file with exactly one colr box naming no device space is written with no /ColorSpace, and its colour channels were never counted, so a file whose sYCC box sat over two channels or whose ICC profile held three colours over five was passed on and no longer reported. The colour channels (cdef type 0 entries, else every channel) must now have as many components as that box: an enumerated space by the definition in ISO/IEC 15444-2:2004 Table M.25, an ICC profile by the data colour space in its header (ICC.1 Table 19). No fit is InvalidDataException, as for a device name. A space whose components the loader does not know is not compared. A file written with no ColorSpace whose colour channels number other than 1, 3 or 4 is reported under a PDF/A-2 claim. A cdef box that names a channel twice, or one the image does not have, counted its entries, so a CMYK box over a one- or three-component codestream gave DeviceCMYK. Distinct channels below the channel count are counted now, which keeps main's name where it fits and never writes a name whose components differ from that number. A cmap box without a pclr box is forbidden in a JP2 file (15444-1 I.5.3.4) and stays judged by the channel count, with the message saying so. In a JPX file (brand jpx or jpxb) no sentence of 15444-2:2004 M.5.1.2, M.11.5 or M.11.6 ties it to a palette, so such a file keeps main's name unchecked. A jplh box is not written with the file; the refusal for a JPX file that has one says so instead of claiming the channels have no definition. The PDF/A report gains two findings from 6.2.8.3: the colour-channel count and a depth outside 1 to 38 (15444-1 Table I.6). Depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from ihdr, so a bare codestream whose components differ in depth is reported. The Rsiz reach is stated as it is: bare codestream, the jp2c that starts SOC then SIZ, and a JP2 file whose dimensions come from the codestream. The HT block coder claim is dropped; Table A.10 says only "extended capabilities through a CAP marker". A short cdef box is skipped and the first readable one is read, and the message says "the loader can read". Tests pin METH 4 and reserved Rsiz bits 12 and 13. --- CHANGELOG.md | 74 ++-- src/VellumPdf.Kernel/Images/Jp2Findings.cs | 8 + src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 336 ++++++++++++++---- src/VellumPdf.Layout/Document.cs | 2 +- src/VellumPdf.Layout/Elements/LayoutImage.cs | 7 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 13 +- .../Rendering/ImageDiagnostics.cs | 4 + .../ConformanceAuditG4Tests.Images.cs | 34 +- .../ConformanceAuditG4Tests.JpxChannels.cs | 321 ++++++++++++++++- 9 files changed, 666 insertions(+), 133 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 797cd3082..2eef392da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -862,43 +862,55 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it counts the - colour channels, which are the type 0 entries of its `cdef` box, or every channel when it has - none (ISO/IEC 15444-1, I.5.3.6), and throws unless the device name it would write has exactly - that many components. So two channels or three beside greyscale, one beside sRGB, and two or - five with no `colr` box and no `cdef` box are refused, while a greyscale file whose `cdef` box - marks one colour and one opacity channel is written as `/DeviceGray`, and so is an RGB file of - five channels whose `cdef` box marks three colour channels. Where a `colr` box names CMYK and - four colour channels fit no other name, the file is written as `/DeviceCMYK`. A file with a - `pclr` box keeps the name, because a palette changes what the channels are; a `cmap` box alone - is not a palette. A JP2 file whose only colour specification is enumerated colour space 19 - (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box that holds - an ICC profile or names an enumerated space other than sRGB, greyscale and CMYK (sYCC, say) is - written with no `ColorSpace`, so the file's own specification decides; a lone vendor box or one - too short to read keeps the name. A file with two or more `colr` boxes and none of them a device - space keeps the device name it had, because veraPDF 1.30.4 fails such a file of one or three - channels under PDF/A-2b without it. A Layout save under a PDF/A-2 claim reports as the new - `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error that `StrictDiagnostics` - refuses, a JP2 file that ISO 19005-2, 6.2.8.3, does not allow and 7.4.9 does: more than one - colour specification and not exactly one with an APPROX of 1, a colour specification whose METH - is not 1, 2 or 3, or colour channels of different bit depth. The report follows the clause, not - veraPDF, which checks APPROX and METH only without a `ColorSpace` and also fails a sign-only - difference and an opacity channel of another depth. It names the image by its size and the - clause and quotes no alternative text; without a claim nothing changes. **Deliberate output - changes and new refusals:** those inputs, and the new diagnostic under a PDF/A-2 claim; every - other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file whose name has as many - components as it has colour channels, or that has a palette, writes the same bytes as before. + colour channels, which are the distinct channels below the channel count that its `cdef` box + marks as type 0, or every channel when it has none (ISO/IEC 15444-1, I.5.3.6), and throws unless + the colour space has exactly that many components: the device name it would write, or, where it + leaves `ColorSpace` out, its lone `colr` box (an enumerated space by the components of its + definition, an ICC profile by the colour space in its header). So two channels or three beside + greyscale, one beside sRGB, two or five with no `colr` box and no `cdef` box, and one, two, four + or five beside sYCC are refused, while a greyscale file whose `cdef` box marks one colour and one + opacity channel is written as `/DeviceGray`, and so is an RGB file of five channels whose `cdef` + box marks three colour channels. A `cdef` box that names a channel twice, or one the image does + not have, counts each channel once. Where a `colr` box names CMYK and four colour channels fit no + other name, the file is written as `/DeviceCMYK`. A file with a `pclr` box keeps the name, + because a palette changes what the channels are, and so does a JPX file (brand `jpx ` or `jpxb`) + with a `cmap` box and no `pclr` box; in a JP2 file such a `cmap` box is not allowed and the file + is judged by its channel count. A JP2 file whose only colour specification is enumerated colour + space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box + that holds an ICC profile or names an enumerated space other than sRGB, greyscale and CMYK + (sYCC, say) is written with no `ColorSpace` when its channels fit, so the file's own + specification decides; a lone vendor box or one too short to read keeps the name. A file with two + or more `colr` boxes and none of them a device space keeps the device name it had, because + veraPDF 1.30.4 fails such a file of one or three channels under PDF/A-2b without it. A Layout + save under a PDF/A-2 claim reports as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` + (501), an error that `StrictDiagnostics` refuses, a JP2 file that ISO 19005-2, 6.2.8.3, does not + allow and 7.4.9 does: more than one colour specification and not exactly one with an APPROX of + 1, a colour specification whose METH is not 1, 2 or 3, colour channels of different bit depth, + a colour channel deeper than 38 bits, or, for a file written with no `ColorSpace`, a number of + colour channels other than 1, 3 or 4. The depths are read from the `bpcc` box, else from the + codestream where the loader takes the dimensions from it, else from the `ihdr` box. The report + follows the clause, not veraPDF, which checks APPROX and METH only without a `ColorSpace` and + also fails a sign-only difference and an opacity channel of another depth. It names the image by + its size and the clause and quotes no alternative text; without a claim nothing changes. + **Deliberate output changes and new refusals:** those inputs, and the new diagnostic under a + PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file + whose name has as many components as it has colour channels, or that has a palette, writes the + same bytes as before. - **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of features, and `JpxImageLoader` never read the `Rsiz` field of the SIZ marker, so such a codestream was wrapped and written. ISO/IEC 15444-2:2004, M.9.2.3, defines that set as Part 1 plus only the irreversible decorrelation and non-linearity extensions. `Load` now throws `InvalidDataException` - naming `Rsiz`, for a codestream bare or inside a JP2 file, when bit 15 (Part 2 capabilities) is - set together with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities that Table A.2 of that - part says are required to decode, and when bit 14 is set (extended capabilities through a CAP - marker, such as the HT block coder; ISO/IEC 15444-1, Table A.10). Bit 15 alone, the "useful" bits - 2, 3 and 9, and bit 8 (multiple component transformation) pass: the baseline allows the - irreversible decorrelation, and its limits on the MCC and MCO marker segments are not checked. + naming `Rsiz`, when bit 15 (Part 2 capabilities) is set together with any of bits 0, 1, 4, 5, 6, + 7, 10 or 11, the capabilities that Table A.2 of that part says are required to decode, and when + bit 14 is set (extended capabilities through a CAP marker; ISO/IEC 15444-1, Table A.10). Bit 15 + alone, the "useful" bits 2, 3 and 9, and bit 8 (multiple component transformation) pass: the + baseline allows the irreversible decorrelation, and its limits on the MCC and MCO marker segments + are not checked. The field is read in three cases: a bare codestream, the `jp2c` box of a JP2 + file whose codestream starts with SOC and SIZ, and a JP2 file whose dimensions the loader takes + from the codestream because it has no `jp2h` box or no `ihdr` box. A JP2 file with an `ihdr` box + and a codestream that does not start with SOC and SIZ is not examined. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 14 set, or bit 15 together with one of the listed required bits; every other codestream writes the same bytes as before. diff --git a/src/VellumPdf.Kernel/Images/Jp2Findings.cs b/src/VellumPdf.Kernel/Images/Jp2Findings.cs index faccc6cdd..510995a90 100644 --- a/src/VellumPdf.Kernel/Images/Jp2Findings.cs +++ b/src/VellumPdf.Kernel/Images/Jp2Findings.cs @@ -20,4 +20,12 @@ internal enum Jp2Findings /// Colour channels of different bit depth, comparing the depth and not the sign. ColourDepths = 4, + + /// + /// A file written with no /ColorSpace whose colour channels number other than 1, 3 or 4. + /// + ColourChannelCount = 8, + + /// A colour channel whose bit depth is outside 1 to 38. + ColourDepthRange = 16, } diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 493566ec4..dc5f25fa0 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -54,8 +54,9 @@ namespace VellumPdf.Images; /// channel count chooses, as above. /// A JP2 file with exactly one colr box, which holds an ICC profile (method 2 or 3) /// or an enumerated colour space other than 12, 16 and 17, such as sYCC (18) -/// ColorSpace is left out, so the colour specification in the file decides. A lone vendor colour -/// box (method 4), and a box too short to read, do not count: the channel count chooses. +/// ColorSpace is left out, so the colour specification in the file decides, but the colour channels +/// must still have as many components as that space (see below). A lone vendor colour box (method 4), and +/// a box too short to read, do not count: the channel count chooses. /// A JP2 file with two or more colr boxes, none naming a device /// spacethe channel count chooses, as above. veraPDF 1.30.4 passes such a file /// of one or three channels under PDF/A-2b with the name and fails it without; at four channels it fails @@ -64,25 +65,41 @@ namespace VellumPdf.Images; /// (CIEJab)refused, because ISO 32000-2, 7.4.9, excludes CIEJab and there is /// nothing else to use. /// -/// A name is written only for colour channels it has the components for. ISO 32000-2, 7.4.9, +/// A colour space is used only for colour channels it has the components for. ISO 32000-2, 7.4.9, /// says the number of "ordinary colour channels" shall match the number of components in the colour /// space. ISO/IEC 15444-1, I.5.3.6, says a codestream that holds only colour channels in colour order has /// no cdef box and that any other channel (an opacity channel, say) needs one. So the loader counts -/// as colour channels the entries of type 0 of the cdef box (opacity, premultiplied opacity and -/// unspecified entries are not counted), or every channel of the ihdr box when there is no -/// cdef box (of the codestream, when the jp2h box has no ihdr box). The name chosen -/// above must have exactly that many components: DeviceCMYK replaces it where a colr box -/// names CMYK and there are four. If no name fits, the file is invalid under 7.4.9 and is refused with -/// . Only the first cdef box is read, and one too short for its -/// own entry count is ignored. A file with a pclr box keeps the name and is not checked, because a -/// palette changes what the channels are and the box is not read; a cmap box alone is not a -/// palette. An ICC profile is counted by the presence of a colr box of method 2 or 3; the profile -/// is not read or checked. Indexed colour spaces are not handled. +/// as colour channels the distinct channels, below the channel count, that the cdef box marks as type 0 +/// (opacity, premultiplied opacity and unspecified entries are not counted), or every channel of the ihdr +/// box when there is no readable cdef box (of the codestream, when the jp2h box has no ihdr +/// box). A cdef box that names a channel twice, or one the image does not have, is not a conforming JP2 +/// box and is not refused for that; counting distinct channels below the channel count keeps a name that fits. +/// The space has to have exactly that many components. Where a name is written, it is the name chosen above, and +/// DeviceCMYK replaces it where a colr box names CMYK and there are four colour channels. Where +/// ColorSpace is left out, it is the lone colr box: an enumerated space has the components of the +/// colour space that ISO/IEC 15444-2:2004, Table M.25, defines (three for sYCC, e-sRGB, ROMM-RGB, e-sYCC and +/// CIELab, one for bi-level and greyscale, and so on) and an ICC profile the components of the data colour space +/// in its header (ICC.1, Table 19). If no fit exists, the file is invalid under 7.4.9 and is refused with +/// . A space whose components are not known here, such as an enumerated value +/// the table does not list or an ICC profile whose header is cut short, is not compared. A cdef box too short +/// for its own entry count is skipped, and the first one long enough is read. The check looks at the jp2h +/// box only: a JPX file's jplh box, which may define opacity channels, is not read and is not written with +/// the file. A file with a pclr box keeps the name and is not checked, because a palette changes what the +/// channels are and the box is not read. So does a file with a cmap box and no pclr box whose +/// ftyp box names the JPX brand (jpx or jpxb): ISO/IEC 15444-2:2004, M.5.1.2, numbers the +/// channels by the cmap entries and no sentence there ties the box to a palette. In a JP2 file such a +/// cmap box is not allowed (ISO/IEC 15444-1, I.5.3.4), and the file is judged by its channel count. An ICC +/// profile is recognised by a colr box of method 2 or 3; only the colour space of its header is read. +/// Indexed colour spaces are not handled. /// A JP2 file that passes those checks may still break ISO 19005-2, 6.2.8.3, and is passed /// through. The clause requires, when there is more than one colour specification, exactly one with -/// an APPROX of 1; a METH of 1, 2 or 3; and one bit depth for all the colour channels. ISO 32000-2, 7.4.9, -/// requires none of these. This loader neither refuses nor reports such a file. A -/// VellumPdf.Layout save reports it under a PDF/A-2 claim as +/// an APPROX of 1; a METH of 1, 2 or 3; 1, 3 or 4 colour channels; and one bit depth, from 1 to 38, for all the +/// colour channels. A file written with a name that was checked has 1, 3 or 4 colour channels, so the count is +/// reported only for a file written with no ColorSpace. The depths are read from the bpcc box, else +/// from the codestream's SIZ marker when the loader had to take the dimensions from it (a bare codestream, a +/// JP2 file with no jp2h box or no ihdr box), else from the ihdr box, and a file with a palette +/// or a JPX cmap box is not compared. ISO 32000-2, 7.4.9, requires none of these. This loader neither +/// refuses nor reports such a file. A VellumPdf.Layout save reports it under a PDF/A-2 claim as /// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on /// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a /// PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks the report from the @@ -103,6 +120,10 @@ public static class JpxImageLoader private const uint BoxTypeBpcc = 0x62706363; // "bpcc" private const uint BoxTypePclr = 0x70636C72; // "pclr" (palette) private const uint BoxTypeCdef = 0x63646566; // "cdef" (channel definition) + private const uint BoxTypeCmap = 0x636D6170; // "cmap" (component mapping) + private const uint BoxTypeJplh = 0x6A706C68; // "jplh" (compositing layer header, JPX only) + private const uint BrandJpx = 0x6A707820; // "jpx " + private const uint BrandJpxBaseline = 0x6A707862; // "jpxb" private const uint BoxTypeJp2c = 0x6A703263; // "jp2c" (contiguous codestream) // JPEG 2000 SOC marker (start of codestream). @@ -110,8 +131,8 @@ public static class JpxImageLoader // JPEG 2000 SIZ marker (image and tile size). private const ushort MarkerSIZ = 0xFF51; // The SIZ marker's Rsiz field. ISO/IEC 15444-1, Table A.10, gives bit 15 the meaning of - // capabilities from Part 2 and bit 14 the meaning of extended capabilities through a CAP marker - // (the HT block coder of Part 15 is one). ISO/IEC 15444-2:2004, Table A.2, names the Part 2 + // capabilities from Part 2 and bit 14 the meaning of extended capabilities through a CAP marker. + // ISO/IEC 15444-2:2004, Table A.2, names the Part 2 // capability bits, and M.9.2.3 limits the JPX baseline codestream to Part 1 plus the // irreversible decorrelation and non-linearity extensions. Bit 8 (multiple component // transformation) therefore passes: the baseline allows its restricted decorrelation, whose @@ -145,16 +166,18 @@ public static class JpxImageLoader /// capability outside the JPX baseline set or has the extended capabilities bit (0x4000) set. /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose - /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose - /// only colour specifications are enumerated colour space 19 (CIEJab). + /// colour channels the colour space does not fit, whether a device name or the lone colr box (see + /// the class summary), and for a JP2 file whose only colour specification is enumerated colour space 19 + /// (CIEJab). /// /// /// A channel count that no device colour space has is refused for a bare codestream /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a /// colr box it writes, and ISO 32000-2, 7.4.9, says the ordinary colour channels shall match - /// the components of the colour space. Colour channels that the device name does not fit are + /// the components of the colour space. Colour channels that the colour space does not fit are /// refused for a JP2 file with a jp2h box too, as the class summary says: every channel - /// is a colour channel unless a cdef box says otherwise, and the name must have that many + /// is a colour channel unless a cdef box says otherwise, and the device name written, or the + /// lone colr box where ColorSpace is left out, must have that many /// components. A JP2 file whose only colour specification is CIEJab is /// refused: neither a device name nor an absent ColorSpace would be valid for it. One /// that also has an ICC profile, or another enumerated space, is written with no @@ -168,13 +191,17 @@ public static class JpxImageLoader /// non-linearity extensions. With bit 15 (Part 2 capabilities) set, the call refuses when any /// of bits 0, 1, 4, 5, 6, 7, 10 or 11 is set, the capabilities that ISO/IEC 15444-2, Table A.2, /// says are required to decode. It refuses when bit 14 is set, which marks extended - /// capabilities through a CAP marker, such as the HT block coder (ISO/IEC 15444-1, Table A.10). + /// capabilities through a CAP marker (ISO/IEC 15444-1, Table A.10). /// Bit 15 alone, the "useful" bits 2, 3 and 9, and bit 8 (multiple component transformation) /// pass. Bit 8 passes because the baseline allows the irreversible decorrelation /// transformation; the limits it puts on the MCC and MCO marker segments are not checked, so /// do not pass a codestream whose multiple component transformation goes beyond them and - /// expect a refusal. The bits are read from a bare codestream and from the jp2c box of a - /// JP2 file whose codestream starts with SOC and SIZ; any other codestream is not examined. + /// expect a refusal. The bits are read in three cases: from a bare codestream, whose + /// marker segments are scanned until SIZ; from the jp2c box of a JP2 file whose codestream starts + /// with SOC and then SIZ, whatever the jp2h box holds; and from the SIZ found by the same scan in + /// a JP2 file whose dimensions the loader takes from the codestream, because it has no jp2h box or + /// its jp2h box has no ihdr box. A JP2 file with a usable ihdr box whose + /// codestream does not start with SOC and SIZ is not examined. /// This loader does not decode, so a codestream that uses a feature outside the baseline set /// without signalling it in Rsiz passes through. /// @@ -200,8 +227,9 @@ public static PdfImageXObject Load(byte[] jpx) /// capability outside the JPX baseline set or has the extended capabilities bit (0x4000) set. /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose - /// channels the device colour space does not fit (see the class summary), and for a JP2 file whose - /// only colour specifications are enumerated colour space 19 (CIEJab). + /// colour channels the colour space does not fit, whether a device name or the lone colr box (see + /// the class summary), and for a JP2 file whose only colour specification is enumerated colour space 19 + /// (CIEJab). /// /// /// Thrown when requests . @@ -252,7 +280,7 @@ private static PdfImageXObject LoadRawCodestream(byte[] data) throw new InvalidDataException( "Not a JPEG 2000 file: missing SOC marker (FF4F) and not a JP2 box file."); - var (width, height, components, bpc) = ParseSizFromCodestream(data, offset: 0); + var (width, height, components, bpc, depths) = ParseSizFromCodestream(data, offset: 0); ImageLimits.ValidateDimensions("JPEG 2000", width, height); RefuseUnmatchableChannelCount(components); @@ -265,7 +293,10 @@ private static PdfImageXObject LoadRawCodestream(byte[] data) // would see 0/0. Wrap the codestream verbatim in a minimal JP2 so the image is // conformant. The codestream bytes are unchanged: lossless passthrough. var jp2 = BuildMinimalJp2(width, height, components, bpc, enumCs, MakeBox(BoxTypeJp2c, data)); - return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc); + return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) + { + Jp2Findings = new ColrSurvey { CodestreamDepths = depths }.Findings(components), + }; } // ── JP2 box file path ───────────────────────────────────────────────────── @@ -299,9 +330,16 @@ private static PdfImageXObject LoadJp2(byte[] data) { ftypBoxStart = pos; ftypBoxTotal = boxTotalLength; + colr.JpxBranded = HasJpxBrand(data, boxPayloadOffset, boxPayloadLength); } break; + case BoxTypeJplh: + // JPX only: the compositing layer header may hold an opacity or channel definition box. It is + // not carried into the file written, so only its presence is noted, for the refusal message. + colr.HasCompositingLayerHeader = true; + break; + case BoxTypeJp2h: if (jp2hBoxStart < 0) { @@ -341,12 +379,13 @@ private static PdfImageXObject LoadJp2(byte[] data) if (jp2cPayloadLength < 2 || data[jp2cPayloadOffset] != 0xFF || data[jp2cPayloadOffset + 1] != 0x4F) throw new InvalidDataException( "jp2c codestream is missing the SOC marker (FF4F)."); - var (w, h, c, b) = ParseSizFromCodestream(data, jp2cPayloadOffset); + var (w, h, c, b, d) = ParseSizFromCodestream(data, jp2cPayloadOffset); width = w; height = h; nc = c; bpc = b; channelsFromSiz = true; + colr.CodestreamDepths = d; } ImageLimits.ValidateDimensions("JPEG 2000 (JP2)", width, height); @@ -382,7 +421,7 @@ private static PdfImageXObject LoadJp2(byte[] data) // package, which reports it under a PDF/A claim; the Kernel writes the image either way. return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) { - Jp2Findings = jp2hBoxStart < 0 ? Jp2Findings.None : colr.Findings(), + Jp2Findings = colr.Findings(nc), }; } @@ -510,6 +549,7 @@ private static void ParseJp2Header( case BoxTypeIhdr: ParseIhdr(data, subPayloadOffset, subPayloadLength, ref height, ref width, ref nc, ref bpc); + colr.IhdrBpc = data[subPayloadOffset + 10]; break; case BoxTypeColr: @@ -523,11 +563,14 @@ private static void ParseJp2Header( case BoxTypePclr: // A palette turns the stored channels into colour channels, so the ihdr channel count - // no longer says how many colour channels there are. The box is not read. A cmap box - // alone maps channels and is not a palette. + // no longer says how many colour channels there are. The box is not read. colr.HasPalette = true; break; + case BoxTypeCmap: + colr.HasCmap = true; + break; + case BoxTypeCdef: TryParseCdef(data, subPayloadOffset, subPayloadLength, colr); break; @@ -574,21 +617,62 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c } else if (meth is 2 or 3) { - // METH 2 and 3 carry an ICC profile. The profile is not read or checked, only its presence. + // METH 2 and 3 carry an ICC profile. Only its presence and the data colour space of its header are + // read (ICC.1, 7.2.6: bytes 16 to 19 of the profile, which starts after METH, PREC and APPROX). colr.HasIccProfile = true; + colr.IccComponents = length >= 3 + 20 ? IccComponentsOf(ReadUInt32Be(data, offset + 3 + 16)) : null; } } + // The number of components of an ICC data colour space (ICC.1, Table 19), or null for a signature that table does + // not list. + private static int? IccComponentsOf(uint signature) => signature switch + { + 0x47524159 => 1, // GRAY + 0x58595A20 or 0x4C616220 or 0x4C757620 or 0x59436272 or 0x59787920 // XYZ, Lab, Luv, YCbr, Yxy + or 0x52474220 or 0x48535620 or 0x484C5320 or 0x434D5920 // RGB, HSV, HLS, CMY + or 0x33434C52 => 3, // 3CLR + 0x434D594B or 0x34434C52 => 4, // CMYK, 4CLR + 0x32434C52 => 2, // 2CLR + _ => NColourComponents(signature), // 5CLR to 9CLR, ACLR to FCLR + }; + + private static int? NColourComponents(uint signature) + { + if ((signature & 0x00FFFFFF) != 0x434C52) + return null; + var digit = (int)(signature >> 24); + return digit is >= '5' and <= '9' ? digit - '0' : digit is >= 'A' and <= 'F' ? digit - 'A' + 10 : null; + } + + // The number of components of an enumerated colour space, or null for a value this loader has no count for. The + // counts follow from the definitions in ISO/IEC 15444-2:2004, Table M.25: CIELab "three components", CMY and + // CMYK as inks (CMYK adds black), YCCK as CMYK recombined with the K sample, bi-level one bit per sample, and the + // colour models YCbCr, PhotoYCC, sYCC, e-sRGB, ROMM-RGB, YPbPr and e-sYCC three channels each. 16 (sRGB) and + // 17 (greyscale) are in ISO/IEC 15444-1, which is not held, so those two are the maintainer's ruling and the + // device spaces the loader has always chosen. 19 (CIEJab) has no count here: a file whose only colour + // specification it is is refused before this is asked. + private static int? EnumeratedComponentsOf(int value) => value switch + { + 0 or 15 or ColrEnumGreyscale => 1, + 1 or 3 or 4 or 9 or 11 or 14 or ColrEnumSRgb or 18 or 20 or 21 or 22 or 23 or 24 => 3, + ColrEnumCmyk or 13 => 4, + _ => null, + }; + // cdef payload: N(2), then N entries of Cn(2) Typ(2) Asoc(2). Typ 0 is an ordinary colour channel; opacity, - // premultiplied opacity and unspecified entries are not counted. Only the first cdef box is read, and a box - // too short for its own N is treated as absent, so a file with one is judged by its channel count alone. + // premultiplied opacity and unspecified entries are not counted. A box too short for its own N is skipped, so + // the first box long enough is the one read and a file with none is judged by its channel count alone. private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey colr) { - if (colr.OrdinaryChannels is not null || length < 2) + if (colr.OrdinaryChannels is not null) return; - var entries = ReadUInt16Be(data, offset); - if (length < 2 + 6 * entries) + if (length < 2 || length < 2 + 6 * ReadUInt16Be(data, offset)) + { + colr.HasUnreadableCdef = true; return; + } + var entries = ReadUInt16Be(data, offset); var ordinary = new List(); for (var i = 0; i < entries; i++) if (ReadUInt16Be(data, offset + 2 + 6 * i + 2) == 0) @@ -596,11 +680,24 @@ private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey colr.OrdinaryChannels = ordinary; } + // ftyp payload: BR(4) MinV(4) then the compatibility list CL(4) each. A file is a JPX file, not only a JP2 file, + // when its brand or any compatible brand is "jpx " or "jpxb" (ISO/IEC 15444-2:2004, M.9.2). + private static bool HasJpxBrand(byte[] data, int offset, int length) + { + for (var at = 0; at + 4 <= length; at += at == 0 ? 8 : 4) + { + var brand = ReadUInt32Be(data, offset + at); + if (brand is BrandJpx or BrandJpxBaseline) + return true; + } + return false; + } + // What the jp2h box of a JP2 file holds: the number of colr boxes and how many of them have an APPROX of 1, // whether any colr box has a method other than 1, 2 or 3, every enumerated colour space in file order, - // whether any box carries an ICC profile, whether there is a palette, the bpcc entries, and the channels the - // first cdef box marks as ordinary colour channels (null when there is none). colrEnum above keeps the - // last enumerated value, as it always has. + // whether any box carries an ICC profile and its components, whether there is a palette or a cmap box, the bpcc + // entries, the ihdr bit depth byte, and the channels the first readable cdef box marks as ordinary colour + // channels (null when there is none). colrEnum above keeps the last enumerated value, as it always has. private sealed class ColrSurvey { public int Boxes { get; set; } @@ -608,39 +705,76 @@ private sealed class ColrSurvey public bool OtherMethod { get; set; } public List Enumerated { get; } = []; public bool HasIccProfile { get; set; } + public int? IccComponents { get; set; } public bool HasPalette { get; set; } + public bool HasCmap { get; set; } + public bool JpxBranded { get; set; } + public bool HasCompositingLayerHeader { get; set; } + public bool HasUnreadableCdef { get; set; } public byte[]? Bpcc { get; set; } + public int? IhdrBpc { get; set; } + public int[]? CodestreamDepths { get; set; } public List? OrdinaryChannels { get; set; } - - // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. A palette changes which - // channels are colour channels and its boxes are not read, so the depths of a file with one are not judged. - public Jp2Findings Findings() + public int? UnnamedColourChannels { get; set; } + + // A pclr box, or in a JPX file a cmap box alone (ISO/IEC 15444-2:2004, M.5.1.2 numbers the channels by the + // cmap entries and no sentence ties the box to a pclr box there), changes which stored components the + // channels are. Neither box is read, so the ihdr and bpcc entries say nothing about the colour channels. + // In a JP2 file a cmap box without a pclr box is not allowed (ISO/IEC 15444-1, I.5.3.4) and is judged by the + // channel count like any other. + public bool ChannelsRemapped => HasPalette || (HasCmap && JpxBranded); + + // The colour channels are the distinct channels below the channel count that a cdef box marks as type 0, or + // every channel when no readable cdef box says otherwise. A cdef box that names one channel twice, or one the + // image does not have, is not a conforming JP2 box (ISO/IEC 15444-1, I.5.3.6) but such a file has been + // written before; counting distinct channels keeps a name that already fits its components. + public int ColourChannels(int channels) => + OrdinaryChannels is null ? channels : OrdinaryChannels.Where(c => c < channels).Distinct().Count(); + + private bool IsColourChannel(int channel) => OrdinaryChannels is null || OrdinaryChannels.Contains(channel); + + // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. The depths of a file whose + // channels are remapped are not judged, because its colour channels are not read. + public Jp2Findings Findings(int channels) { var found = Jp2Findings.None; if (Boxes > 1 && Approx1Boxes != 1) found |= Jp2Findings.ColourSpecificationApprox; if (OtherMethod) found |= Jp2Findings.ColourMethod; - if (!HasPalette && Bpcc is { Length: > 1 } bpcc && ColourDepthsDiffer(bpcc)) - found |= Jp2Findings.ColourDepths; - return found; + if (UnnamedColourChannels is not (null or 1 or 3 or 4)) + found |= Jp2Findings.ColourChannelCount; + return ChannelsRemapped ? found : found | DepthFindings(channels); } - // The bit depth is the low 7 bits of a bpcc entry (the top bit is the sign). Only colour channels count: with - // a cdef box those it marks as type 0, without one every channel. - private bool ColourDepthsDiffer(byte[] bpcc) + // The bit depth is the low 7 bits of a bpcc entry or an Ssiz byte, plus one (the top bit is the sign). Only + // colour channels count: with a cdef box those it marks as type 0, without one every channel. The depths come + // from the bpcc box, else from the codestream when the loader had to read the dimensions from it, else from + // the ihdr box, which holds one depth for all channels. A depth the file gives only in the codestream while + // its ihdr box says otherwise is not compared. + private Jp2Findings DepthFindings(int channels) { + const int MaxDepth = 38; + var found = Jp2Findings.None; + int[]? perChannel = Bpcc is { } bpcc ? [.. bpcc.Select(b => (b & 0x7F) + 1)] : CodestreamDepths; + if (perChannel is null) + { + if (IhdrBpc is { } raw and not 0xFF && (raw & 0x7F) + 1 > MaxDepth && ColourChannels(channels) > 0) + found |= Jp2Findings.ColourDepthRange; + return found; + } int? first = null; - for (var i = 0; i < bpcc.Length; i++) + for (var i = 0; i < perChannel.Length; i++) { - if (OrdinaryChannels is { } colour && !colour.Contains(i)) + if (!IsColourChannel(i)) continue; - var depth = bpcc[i] & 0x7F; - first ??= depth; - if (depth != first) - return true; + if (perChannel[i] > MaxDepth) + found |= Jp2Findings.ColourDepthRange; + first ??= perChannel[i]; + if (perChannel[i] != first) + found |= Jp2Findings.ColourDepths; } - return false; + return found; } } @@ -648,9 +782,10 @@ private bool ColourDepthsDiffer(byte[] bpcc) /// /// Scans forward from (which must point at an SOC marker FF4F) - /// to find the SIZ marker (FF51) and parses width, height, component count, and bit depth. + /// to find the SIZ marker (FF51) and parses width, height, component count, and the bit depth of + /// every component. /// - private static (int width, int height, int components, int bpc) + private static (int width, int height, int components, int bpc, int[] depths) ParseSizFromCodestream(byte[] data, int offset) { // SIZ must immediately follow SOC in a valid JPEG 2000 main header. @@ -715,7 +850,7 @@ private static bool TryReadRsiz(byte[] data, int offset, int length, out int rsi /// Parses the SIZ marker segment payload at /// (i.e. points to the 2-byte Lsiz length field). /// - private static (int width, int height, int components, int bpc) ParseSiz(byte[] data, int pos) + private static (int width, int height, int components, int bpc, int[] depths) ParseSiz(byte[] data, int pos) { // SIZ payload layout (ISO 15444-1 §A.5.1): // Lsiz(2) Rsiz(2) Xsiz(4) Ysiz(4) XOsiz(4) YOsiz(4) XTsiz(4) YTsiz(4) @@ -771,7 +906,12 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // Ssiz high bit = 1 indicates signed component; bit depth = (Ssiz & 0x7F) + 1. var bpc = (ssiz0 & 0x7F) + 1; - return (width, height, csiz, bpc); + // Every component's depth, as far as the segment reaches, for the PDF/A report (ISO/IEC 15444-1, Table A.11). + var depths = new List(csiz); + for (var c = 0; c < csiz && ssizOffset + 3 * c < pos + lsiz; c++) + depths.Add((data[ssizOffset + 3 * c] & 0x7F) + 1); + + return (width, height, csiz, bpc, [.. depths]); } // ── Colour space inference ──────────────────────────────────────────────── @@ -784,7 +924,8 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] // - Only CIEJab (19) and no ICC profile: refused, since neither a name nor the colr box gives a // colour space a PDF file may use. // - Exactly one colr box that holds an ICC profile or an enumerated value, and names no device - // space: left out. A device name would make a reader take the samples as device samples. + // space: left out. A device name would make a reader take the samples as device samples. The colour + // channels must still have as many components as that space (CheckLoneSpace). // - Anything else (two or more colr boxes and none a device space, a single vendor or malformed // box, or no colr box): the name this loader has always chosen, from the channel count. For two // or more boxes veraPDF 1.30.4 passes the file under PDF/A-2b at 1 and 3 channels with the name @@ -800,34 +941,73 @@ private static (int width, int height, int components, int bpc) ParseSiz(byte[] "JP2 file: its only colour specification is enumerated colour space 19 (CIEJab), which " + "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); if (colr.Boxes == 1 && (colr.HasIccProfile || colr.Enumerated.Count == 1)) + { + CheckLoneSpace(channels, channelsFromSiz, colr); return null; + } return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, false); } + // With no ColorSpace written, the colour specification of the file is the one a reader uses, and 7.4.9 still + // requires the ordinary colour channels to match its components. The colour channels are counted as in + // FitChannels. A space whose components are not known here (an ICC profile whose header cannot be read or names + // no listed space, an enumerated value without a count) is not compared. The count is kept for the PDF/A report, + // which allows only 1, 3 or 4 colour channels. + private static void CheckLoneSpace(int channels, bool channelsFromSiz, ColrSurvey colr) + { + if (colr.ChannelsRemapped) + return; + var colour = colr.ColourChannels(channels); + colr.UnnamedColourChannels = colour; + var components = colr.HasIccProfile ? colr.IccComponents : EnumeratedComponentsOf(colr.Enumerated[0]); + if (components is null || components == colour) + return; + var space = colr.HasIccProfile + ? $"an ICC profile of {components} components" + : $"enumerated colour space {colr.Enumerated[0]}, which has {components} components"; + throw new InvalidDataException( + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr, colour)}, but its only colour specification is " + + $"{space} (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + + "space)."); + } + // Checks the name chosen above against the colour channels (ISO 32000-2, 7.4.9: the ordinary colour channels - // shall match the components of the colour space). With a cdef box they are its entries of type 0. Without - // one they are every channel: ISO/IEC 15444-1, I.5.3.6, makes the box mandatory when a codestream holds - // anything but colour channels in colour order. The name must have exactly that many components, and a colr - // box that names CMYK may supply DeviceCMYK for four. Otherwise the file is invalid and refused. A palette - // (a pclr box) changes what the channels are, and the box is not read, so a file that has one keeps the name. + // shall match the components of the colour space). With a cdef box they are the distinct channels it marks + // as type 0. Without one they are every channel: ISO/IEC 15444-1, I.5.3.6, makes the box mandatory when a + // codestream holds anything but colour channels in colour order. The name must have exactly that many + // components, and a colr box that names CMYK may supply DeviceCMYK for four. Otherwise the file is invalid and + // refused. A file whose channels are remapped (ChannelsRemapped) keeps the name unchecked. private static ImageColorSpace FitChannels( ImageColorSpace named, int channels, bool channelsFromSiz, ColrSurvey colr, bool cmykBox) { - if (colr.HasPalette) + if (colr.ChannelsRemapped) return named; - var colour = colr.OrdinaryChannels?.Count ?? channels; + var colour = colr.ColourChannels(channels); if (ComponentsOf(named) == colour) return named; if (cmykBox && colour == 4) return ImageColorSpace.DeviceCmyk; - var why = colr.OrdinaryChannels is null - ? $"its {(channelsFromSiz ? "codestream has" : "ihdr box has")} {channels} channels and no cdef box, so " + - "every one is a colour channel, but " - : $"its cdef box marks {colour} ordinary colour channels, but "; + var cmapHint = colr.HasCmap && !colr.HasPalette + ? " The file has a cmap box and no pclr box, which a JP2 file may not have (ISO/IEC 15444-1, I.5.3.4)." + : ""; throw new InvalidDataException( - $"JP2 file: {why}{PdfNameOf(named)}, the colour space the loader would write, has {ComponentsOf(named)} " + - "components (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + - "space)."); + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr, colour)}, but {PdfNameOf(named)}, the colour " + + $"space the loader would write, has {ComponentsOf(named)} components (ISO 32000-2, 7.4.9: the ordinary " + + $"colour channels shall match the components of the colour space).{cmapHint}"); + } + + // What the refusal says about the colour channels, true about the input: where the count came from, and what + // the loader could not see. + private static string WhyChannels(int channels, bool channelsFromSiz, ColrSurvey colr, int colour) + { + if (colr.OrdinaryChannels is not null) + return $"its cdef box marks {colour} ordinary colour channels"; + var source = channelsFromSiz ? "codestream has" : "ihdr box has"; + if (colr.HasCompositingLayerHeader) + return $"its {source} {channels} channels and no cdef box in its jp2h box, and the jplh box, which may " + + "define them, is not written with the file, so every one is a colour channel in the file written"; + var unreadable = colr.HasUnreadableCdef ? " the loader can read" : ""; + return $"its {source} {channels} channels and no cdef box{unreadable}, so every one is a colour channel"; } private static int ComponentsOf(ImageColorSpace cs) => diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index b0d61373d..902abfee7 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -126,7 +126,7 @@ public Document() { } /// for, written as glyph 0), (an element that /// selects a Standard 14 font under a conformance claim), /// (a JP2 image whose colour - /// specifications, colour method or colour-channel bit depths PDF/A-2 does not allow), + /// specifications, colour method, colour-channel count or colour-channel bit depths PDF/A-2 does not allow), /// (a link in the style of a table cell or a /// running band that a PDF/UA-1 claim left unwritten), /// (a character whose ToUnicode diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 8d731c430..29a0e6811 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -316,10 +316,11 @@ public LayoutImage(PdfImageXObject image) /// as many as the components of the device colour space the loader would write, and a JP2 file /// whose only colour specification is CIEJab ( lists /// the cases). A JP2 file with exactly one colr box that names an ICC profile or an - /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is not refused; it - /// is written with no /ColorSpace, so the colour specification in the file decides. A JP2 + /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is written with + /// no /ColorSpace, so the colour specification in the file decides, and is refused when + /// its colour channels are not as many as the components of that space. A JP2 /// file whose colour channels differ in bit depth, or whose colour specifications PDF/A-2 does - /// not allow, is not refused either; the save reports it as + /// not allow, is not refused; the save reports it as /// under a PDF/A-2 claim. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index b17fb9b49..868311eb9 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -316,7 +316,9 @@ public enum LayoutDiagnosticCode /// A JPEG 2000 image of a JP2 file was drawn in a document whose conformance is PDF/A-2b, /// PDF/A-2u or PDF/A-2a, and the file has more than one colour specification and not exactly one /// with an APPROX of 1, or a colour specification whose METH is not 1, 2 or 3, or colour channels - /// of different bit depths. Each distinct element and finding is one item. The message names the + /// of different bit depths, or a colour channel whose bit depth is outside 1 to 38, or, for a file + /// written with no ColorSpace, a number of colour channels other than 1, 3 or 4. Each distinct + /// element and finding is one item. The message names the /// image by its size in pixels and quotes no alternative text; /// , and /// say where it is. @@ -324,8 +326,8 @@ public enum LayoutDiagnosticCode /// /// Strict mode refuses it. ISO 19005-2:2011, 6.2.8.3, the item's /// , requires exactly one colour specification with an APPROX - /// of 1 when there are several, a METH of 1, 2 or 3, and one bit depth for all the colour - /// channels. ISO 32000-2, 7.4.9, requires none of it, so + /// of 1 when there are several, a METH of 1, 2 or 3, 1, 3 or 4 colour channels, and one bit depth, + /// from 1 to 38, for all the colour channels. ISO 32000-2, 7.4.9, requires none of it, so /// writes such a file and the save reports it. The /// report follows the text of 6.2.8.3, which does not depend on the image dictionary having a /// ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules only where the @@ -333,7 +335,10 @@ public enum LayoutDiagnosticCode /// that are counted with an opacity channel, which the text does not. The depths compared are /// those of the colour channels, the entries of type 0 of the cdef box or every channel /// when there is none, and a file with a palette is not compared because its colour channels are - /// not read. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. + /// not read. A file written with a device name has 1, 3 or 4 colour channels already, so the count + /// is reported only for a file written with no ColorSpace. The depths come from the + /// bpcc box, else from the codestream when the loader took the dimensions from it, else from + /// the ihdr box. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. /// Do not pass such a file to a PDF/A document: /// alone passes it through unreported, 3.0 will refuse it where the image is created, and #474 /// tracks the loaders' own report. An image that a custom renderer registers itself is not diff --git a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs index 10367545b..e94aa312b 100644 --- a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs +++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs @@ -37,5 +37,9 @@ void Report(int key, string what) => sink.Report( Report(1, "has a colour specification whose method is not 1, 2 or 3; PDF/A-2 allows only those."); if (image.Jp2Findings.HasFlag(Jp2Findings.ColourDepths)) Report(2, "has colour channels of different bit depths; PDF/A-2 allows one depth for all colour channels."); + if (image.Jp2Findings.HasFlag(Jp2Findings.ColourChannelCount)) + Report(3, "has a number of colour channels other than 1, 3 or 4; PDF/A-2 allows only those."); + if (image.Jp2Findings.HasFlag(Jp2Findings.ColourDepthRange)) + Report(4, "has a colour channel whose bit depth is outside 1 to 38; PDF/A-2 allows only that range."); } } diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index b360a1933..41a0a3667 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -1083,7 +1083,7 @@ public void Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineI Assert.Throws(() => LayoutImage.FromBytes(codestream)); } - // ISO/IEC 15444-1, Table A.10: bit 14 marks extended capabilities through a CAP marker, such as the HT block coder. + // ISO/IEC 15444-1, Table A.10: bit 14 marks extended capabilities through a CAP marker. [Theory] [InlineData(0x4000)] [InlineData(0x4001)] @@ -1099,8 +1099,10 @@ public void Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused(int rs } // Part 1 only, Part 2 with nothing required (0x8000), the useful bits 2, 3 and 9, and the multiple component - // transformation bit 8, which the baseline allows in its restricted decorrelation form. Bits 0 to 11 mean nothing - // without bit 15 (Table A.2 defines them under the prefix 1000), so a value below 0x4000 passes too. + // transformation bit 8, which the baseline allows in its restricted decorrelation form. A value below 0x4000 has + // the top two bits 00, which ISO/IEC 15444-1, Table A.10, gives to the Part 1 profiles, and Table A.2 of Part 2 + // defines the capability bits only under the prefix 10, so 0x0FFF and 0x3FFF are not Part 2 capabilities. Bits + // 12 and 13 are reserved in Table A.2 and are not examined, with or without bit 15: 0x9000, 0xA000, 0xB000. [Theory] [InlineData(0)] [InlineData(1)] @@ -1114,6 +1116,10 @@ public void Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused(int rs [InlineData(0x8100)] [InlineData(0x830C)] [InlineData(0x8208)] + [InlineData(0x9000)] + [InlineData(0xA000)] + [InlineData(0xB000)] + [InlineData(0x9100)] public void Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte(int rsiz) { var codestream = JpxCodestream(16, 16, 3, 7, rsiz); @@ -1125,6 +1131,28 @@ public void Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThr Assert.Equal(codestream, Jp2Boxes(jp2.Raw).Single(b => b.Type == "jp2c").Payload); } + // SOC, a COM segment, then SIZ: the SIZ marker segment does not follow SOC at once. + private static byte[] ComBeforeSiz(byte[] codestream) => [0xFF, 0x4F, 0xFF, 0x64, 0, 4, 0, 1, .. codestream[2..]]; + + [Theory] + [InlineData(0x8001)] + [InlineData(0x4000)] + public void Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt(int rsiz) + { + // The Rsiz check has three reaches: a bare codestream, the jp2c of a JP2 file whose codestream starts SOC then + // SIZ, and a JP2 file whose dimensions come from the codestream because it has no jp2h box or no ihdr box, + // where SIZ is found by scanning past the COM segment. Here SIZ follows a COM segment. + var codestream = ComBeforeSiz(JpxCodestream(16, 16, 3, 7, rsiz)); + Assert.Throws(() => JpxImageLoader.Load(codestream)); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(codestream, 3, 16, noJp2h: true))); + Assert.Throws(() => JpxImageLoader.Load(Jp2File(codestream, 3, 16, noIhdr: true))); + // A JP2 file with a usable ihdr box and a codestream that does not start SOC then SIZ is not examined: the + // bytes are the ones a 2.3.3 save wrote. + var kept = Written(ImageFile(PdfConformance.None, new Kind("jp2-com", Jp2File(codestream, 3, 16), 16, 16, "DeviceRGB", 8, + "JPXDecode"))); + Assert.Equal(codestream, Jp2Boxes(kept.Raw).Single(b => b.Type == "jp2c").Payload); + } + // ── PNG tRNS: only the low bits of a colour key count when the depth is below 16 ───────────── public static TheoryData StrayBitKeyNames() => new() { "grey8", "grey4", "rgb8" }; diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index 63b172250..7c281fb8a 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -83,9 +83,8 @@ public void Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsIt } [Theory] - [InlineData(1, 2, 0)] + [InlineData(1, 2, 0)] // the 16 profile bytes are no header: the components are not known, so not compared [InlineData(3, 2, 0)] - [InlineData(1, 1, 18)] [InlineData(3, 1, 18)] [InlineData(3, 1, 99)] public void Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf(int channels, @@ -234,17 +233,24 @@ public void Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesI } [Fact] - public void Iso32000_2_7_4_9_OnlyTheFirstCdefBoxIsReadAndAShortOneIsIgnored() + public void Iso32000_2_7_4_9_AShortCdefBoxIsSkippedAndTheFirstOneLongEnoughIsRead() { - // A box whose payload cannot hold its own entry count is treated as absent, so the file is judged as one with - // no cdef box: five channels are five colour channels, which DeviceRGB does not take. With two boxes the - // first decides. + // A box whose payload cannot hold its own entry count is skipped, so with no other cdef box the file is judged + // as one with none: five channels are five colour channels, which DeviceRGB does not take, and the message + // says the loader could not read a cdef box, not that there is none. The first box long enough is the one + // read, and with two of those the first decides. var codestream = JpxCodestream(16, 16, 5); Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2File(codestream, 5, 16, cdef: Channels(3, 1, 1)))); var shortCount = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16), "cdef", [0, 9, 0, 0, 0, 0, 0, 1]); - Assert.Contains("and no cdef box", Assert.Throws(() => JpxImageLoader.Load(shortCount)).Message); + Assert.Contains("and no cdef box the loader can read, so every one", + Assert.Throws(() => JpxImageLoader.Load(shortCount)).Message); var onlyTheCount = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16), "cdef", [0]); - Assert.Contains("and no cdef box", Assert.Throws(() => JpxImageLoader.Load(onlyTheCount)).Message); + Assert.Contains("and no cdef box the loader can read, so every one", + Assert.Throws(() => JpxImageLoader.Load(onlyTheCount)).Message); + // A short box first and a valid one after it: the valid one is read (three colour channels, two opacity). + byte[] valid = [0, 5, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 2, 0, 0, 0, 3, 0, 3, 0, 1, 0, 1, 0, 4, 0, 1, 0, 2]; + var shortThenValid = Jp2FileWithRawJp2hBox(shortCount, "cdef", valid); + Assert.Equal("DeviceRGB", ColourSpaceWritten(shortThenValid)); // The first box marks one colour channel, the appended one three: the first decides, so the file is refused. var twice = Jp2FileWithRawJp2hBox(Jp2File(codestream, 5, 16, cdef: Channels(1, 1, 1, 1, 1)), "cdef", [0, 3, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 2, 0, 0, 0, 3]); @@ -278,15 +284,51 @@ public void Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelC } [Fact] - public void Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxIsNotAPalette() + public void Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount() { - // cmap maps channels to palette columns; with no palette there is nothing to map to, so the file is judged - // by its channel count. One or two channels beside sRGB lack a colour channel; three are fine. - Assert.Throws(() => JpxImageLoader.Load(Jp2Of(2, 16, cmapOnly: true))); - Assert.Throws(() => JpxImageLoader.Load(Jp2Of(1, 16, cmapOnly: true))); + // ISO/IEC 15444-1, I.5.3.4, forbids a cmap box without a pclr box in a JP2 file, so such a file is not a + // palette and is judged by its ihdr channel count: one or two channels beside sRGB lack a colour channel, and + // the message says what is wrong with the file; three are fine. + foreach (var channels in new[] { 1, 2 }) + { + var e = Assert.Throws(() => JpxImageLoader.Load(Jp2Of(channels, 16, cmapOnly: true))); + Assert.Contains("a cmap box and no pclr box", e.Message); + } Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2Of(3, 16, cmapOnly: true))); } + // The file with its ftyp brand and compatibility entry replaced (same length), so it names the JPX brand. + private static byte[] Jp2WithBrand(byte[] jp2, string brand, string compatible) + { + var copy = (byte[])jp2.Clone(); + var at = copy.AsSpan().IndexOf("ftyp"u8) + 4; + System.Text.Encoding.ASCII.GetBytes(brand).CopyTo(copy, at); + System.Text.Encoding.ASCII.GetBytes(compatible).CopyTo(copy, at + 8); + return copy; + } + + [Theory] + [InlineData("jpx ", "jpx ")] + [InlineData("jp2 ", "jpx ")] // a JP2 brand that lists JPX as compatible is a JPX file + [InlineData("jp2 ", "jpxb")] // the JPX baseline compatibility brand + [InlineData("jpxb", "jp2 ")] + public void Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared(string brand, + string compatible) + { + // ISO/IEC 15444-2:2004, M.5.1.2, numbers the channels of a JPX file by the cmap entries, and no sentence of + // M.11.5 or M.11.6 ties the box to a palette, so the ihdr count says nothing about the colour channels. The + // four files are the ones a JP2 brand refuses; the name is the one a 2.3.3 save wrote. + foreach (var (channels, enumerated, name) in new[] { (4, 16, "DeviceRGB"), (3, 17, "DeviceGray"), (1, 16, "DeviceRGB") }) + { + var jp2 = Jp2WithBrand(Jp2Of(channels, enumerated, cmapOnly: true), brand, compatible); + Assert.Equal(name, ColourSpaceWritten(jp2)); + } + var depths = Jp2WithBrand(Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 7, 3], cmapOnly: true), brand, compatible); + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jpx-cmap", depths, 16, 16, "DeviceRGB", 8, "JPXDecode")); + Save(doc); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + // ── Which lone colr boxes lose the name ────────────────────────────────────────────────── [Theory] @@ -421,6 +463,259 @@ public void Iso19005_2_6_2_8_3_ATwoColourBoxFileIsReportedWhetherOrNotColorSpace Assert.Empty(VeraFailures("2b", file)); } + // ── A lone colr box that names no device space: the colour channels must have its components ───────── + + // A colr payload of METH 2 whose profile is a 128-byte header with the given data colour space (ICC.1, 7.2.6). + private static byte[] IccColr(string colourSpace) => + [2, 0, 0, .. new byte[16], .. System.Text.Encoding.ASCII.GetBytes(colourSpace), .. new byte[108]]; + + private static byte[] Jp2WithColr(int channels, byte[] colr, (int, int, int)[]? cdef = null) => + Jp2File(JpxCodestream(16, 16, channels), channels, null, rawColr: [colr], cdef: cdef); + + // The enumerated-space counts follow ISO/IEC 15444-2:2004, Table M.25 (see the loader); 18 is sYCC. + [Theory] + [InlineData(3, 18)] + [InlineData(3, 20)] // e-sRGB + [InlineData(3, 21)] // ROMM-RGB + [InlineData(3, 24)] // e-sYCC + [InlineData(3, 14)] // CIELab, "the three components" + [InlineData(1, 0)] // bi-level + [InlineData(4, 13)] // YCCK + public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsHaveHasNoColorSpace(int channels, + int enumerated) + { + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-enum", Jp2File(JpxCodestream(16, 16, channels), channels, + null, boxes: [(1, enumerated)]), 16, 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + } + + [Theory] + [InlineData(1, 18)] // sYCC takes three colour channels + [InlineData(2, 18)] + [InlineData(4, 18)] + [InlineData(5, 18)] + [InlineData(2, 20)] + [InlineData(4, 21)] + [InlineData(1, 14)] + [InlineData(3, 0)] // bi-level takes one + [InlineData(3, 13)] // YCCK takes four + public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackIsRefused(int channels, + int enumerated) + { + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"its ihdr box has {channels} channels and no cdef box, so every one is a colour channel", e.Message); + Assert.Contains($"only colour specification is enumerated colour space {enumerated}", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + } + + [Theory] + [InlineData("RGB ", 3)] + [InlineData("GRAY", 1)] + [InlineData("CMYK", 4)] + [InlineData("Lab ", 3)] + [InlineData("2CLR", 2)] + [InlineData("5CLR", 5)] + [InlineData("ACLR", 10)] + public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsFitHasNoColorSpace(string space, + int channels) + { + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-icc", Jp2WithColr(channels, IccColr(space)), 16, 16, + "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + } + + [Theory] + [InlineData("RGB ", 1)] + [InlineData("RGB ", 2)] + [InlineData("RGB ", 4)] + [InlineData("RGB ", 5)] + [InlineData("GRAY", 2)] + [InlineData("GRAY", 3)] + [InlineData("CMYK", 3)] + [InlineData("2CLR", 3)] + [InlineData("5CLR", 4)] + public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitIsRefused(string space, + int channels) + { + var e = Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(channels, IccColr(space)))); + Assert.Contains("its only colour specification is an ICC profile of", e.Message); + Assert.Contains($"its ihdr box has {channels} channels", e.Message); + } + + [Fact] + public void Iso32000_2_7_4_9_TheColourChannelsOfAFileWithNoColorSpaceAreCountedByTheCdefBox() + { + // Five channels, an RGB profile, three colour and two opacity channels: fits. The same profile over a cdef box + // that marks two colour channels does not, and a grey profile with one colour and one opacity channel fits. + byte[] icc = IccColr("RGB "); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-icc-cdef", Jp2WithColr(5, icc, Channels(3, 1, 1)), 16, 16, + "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-grey-icc-cdef", Jp2WithColr(2, IccColr("GRAY"), + Channels(1, 1)), 16, 16, "DeviceGray", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + var e = Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(4, icc, Channels(2, 1, 1)))); + Assert.Contains("its cdef box marks 2 ordinary colour channels", e.Message); + Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(3, [1, 0, 0, 0, 0, 0, 18], Channels(2, 1)))); + } + + [Fact] + public void Iso32000_2_7_4_9_AColourSpaceWhoseComponentsAreNotKnownIsNotComparedAndAProfileWithNoHeaderEither() + { + // Enumerated value 99 is reserved and has no count, a profile signature outside Table 19 has none, and a + // profile cut short before byte 20 has no header to read. The loader keeps main's bytes for all three. + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-99", Jp2File(JpxCodestream(16, 16, 2), 2, null, + boxes: [(1, 99)]), 16, 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-xxxx", Jp2WithColr(2, IccColr("XXXX")), 16, 16, + "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-short", Jp2WithColr(2, [2, 0, 0, .. new byte[16]]), 16, + 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + } + + [Fact] + public void Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot() + { + // 6.2.8.3 allows 1, 3 or 4 colour channels. A device name already has one of those counts, so only a file + // written with no ColorSpace can have another: a two-channel profile fits its own count and is reported. + foreach (var (space, channels, reported) in new[] { ("2CLR", 2, true), ("5CLR", 5, true), ("RGB ", 3, false), + ("GRAY", 1, false), ("CMYK", 4, false) }) + { + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-count", Jp2WithColr(channels, IccColr(space)), 16, 16, + "DeviceRGB", 8, "JPXDecode")); + Save(doc); + var items = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).ToArray(); + Assert.Equal(reported, items.Length == 1); + if (reported) + Assert.Contains("a number of colour channels other than 1, 3 or 4", items[0].Message); + } + + // The cdef box decides what is counted: three colour channels beside two opacity channels is fine. + using var withOpacity = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-count-cdef", Jp2WithColr(5, IccColr("RGB "), + Channels(3, 1, 1)), 16, 16, "DeviceRGB", 8, "JPXDecode")); + Save(withOpacity); + Assert.DoesNotContain(withOpacity.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + // ── A cdef box that names a channel twice or one the image does not have ────────────────── + + [Theory] + [InlineData(3, 16, new[] { 0, 1, 2, 2 }, "DeviceRGB")] // channel 2 twice + [InlineData(1, 17, new[] { 0, 0 }, "DeviceGray")] + [InlineData(3, 12, new[] { 0, 1, 2, 2 }, "DeviceRGB")] // three distinct, a CMYK box: not four + [InlineData(1, 12, new[] { 0, 1, 2, 3 }, "DeviceGray")] // three channels the image lacks: one distinct, not four + [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks + public void Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsBelowTheChannelCount(int channels, int enumerated, + int[] colourEntries, string name) + { + // ISO/IEC 15444-1, I.5.3.6, does not allow one (Typ, Asoc) pair twice, and says nothing that bounds Cn; the + // loader counts distinct channels below the channel count, so no name is written whose components differ. + var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); + Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); + } + + [Theory] + [InlineData(3, 16, new[] { 0, 1, 9 }, 2)] // channel 9 does not exist + [InlineData(1, 16, new[] { 0, 1, 2 }, 1)] // two of three colour channels do not exist + [InlineData(4, 12, new[] { 0, 1, 2, 2 }, 3)] // channel 2 twice leaves three, not the four CMYK has + [InlineData(3, 18, new[] { 0, 1, 9 }, 2)] // the lone-sYCC path counts the same way + public void Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsBelowTheChannelCountAreTooFewIsRefused(int channels, + int enumerated, int[] colourEntries, int distinct) + { + var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"its cdef box marks {distinct} ordinary colour channels", e.Message); + } + + // ── A jplh box is not carried into the file, so the message says the channels may be defined there ────── + + [Fact] + public void Iso32000_2_7_4_9_TheMessageForAJpxFileWithACompositingLayerHeaderSaysItIsNotWrittenWithTheFile() + { + // Four channels, sRGB, no cdef box in the jp2h box: a jplh box could give the fourth an opacity role (ISO/IEC + // 15444-2:2004, M.11.7), but the loader writes no jplh box, so the file it writes has four colour channels. + var plain = Jp2File(JpxCodestream(16, 16, 4), 4, 16); + var at = plain.AsSpan().IndexOf("jp2c"u8) - 4; + byte[] jplh = [0, 0, 0, 8, .. "jplh"u8]; + var jpx = Jp2WithBrand([.. plain.AsSpan(0, at), .. jplh, .. plain.AsSpan(at)], "jpx ", "jpx "); + var e = Assert.Throws(() => JpxImageLoader.Load(jpx)); + Assert.Contains("and no cdef box in its jp2h box, and the jplh box, which may define them, is not written with the file", + e.Message); + // Without the jplh box the message is the plain one, and it does not mention the box. + var without = Assert.Throws(() => JpxImageLoader.Load(plain)); + Assert.DoesNotContain("jplh", without.Message); + } + + // ── Depths: the range 1 to 38, and the codestream's own depths where the loader reads the dimensions from it ─ + + [Fact] + public void Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported() + { + // ISO 19005-2, 6.2.8.3, allows a bit depth of 1 to 38 (ISO/IEC 15444-1, Table I.6 gives the field 7 bits and + // a value of one less). 38 bits passes; 39 does not, from a bpcc box, an ihdr box, or the codestream. + foreach (var (depths, reported) in new[] { (38, false), (39, true), (49, true) }) + { + var bpcc = Jp2File(JpxCodestream(16, 16, 3), 3, 16, [(byte)(depths - 1), (byte)(depths - 1), (byte)(depths - 1)]); + var ihdr = Jp2File(JpxCodestream(16, 16, 3, depths - 1), 3, 16); + ihdr[ihdr.AsSpan().IndexOf("ihdr"u8) + 4 + 8 + 2] = (byte)(depths - 1); + var bare = JpxCodestream(16, 16, 3, depths - 1); + var noJp2h = Jp2File(JpxCodestream(16, 16, 1, depths - 1), 1, null, noJp2h: true); + foreach (var bytes in new[] { bpcc, ihdr, bare, noJp2h }) + { + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-depth", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode")); + Save(doc); + var items = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).ToArray(); + Assert.Equal(reported, items.Length == 1); + if (reported) + Assert.Contains("a colour channel whose bit depth is outside 1 to 38", items[0].Message); + } + } + } + + [Fact] + public void Iso19005_2_6_2_8_3_AnOpacityChannelOfMoreThanThirtyEightBitsIsNotReported() + { + // bpcc 8, 8, 8 and 49 bits, with a cdef box that makes the fourth an opacity channel: 6.2.8.3 covers colour + // channels only. + var jp2 = Jp2File(JpxCodestream(16, 16, 4), 4, 16, [7, 7, 7, 0x30], cdef: Channels(3, 1)); + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-op49", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode")); + Save(doc); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + [Theory] + [InlineData(false)] // a bare codestream + [InlineData(true)] // a JP2 file with no jp2h box + public void Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported(bool jp2) + { + // The loader synthesises an ihdr box with the first component's depth and no bpcc box (ISO/IEC 15444-1, + // I.5.3.1, wants BPC 255 and a bpcc box when the depths differ), so the embedded JP2 contradicts its + // codestream. The bytes are written as they have been; the Layout save reports the difference. + var codestream = JpxCodestream(16, 16, 3, depths: [8, 8, 16]); + var bytes = jp2 ? Jp2File(codestream, 3, null, noJp2h: true) : codestream; + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jpx-mixed", bytes, 16, 16, "DeviceRGB", null, "JPXDecode")); + Save(doc); + Assert.Contains("colour channels of different bit depths", + Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).Message); + // The same depths with equal Ssiz are not a difference. + var same = JpxCodestream(16, 16, 3, depths: [16, 16, 16]); + using var ok = DocumentWith(PdfConformance.PdfA2b, new Kind("jpx-same", same, 16, 16, "DeviceRGB", 16, "JPXDecode")); + Save(ok); + Assert.DoesNotContain(ok.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA); + } + + // ── A colr method of 4 (a vendor box) with a name is reported (the METH rule has more than one value to cover) ── + + [Theory] + [InlineData(4)] + [InlineData(7)] + public void Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported(int method) + { + // METH 4 is a vendor colour specification, which 6.2.8.3 does not allow; so is any other value outside 1 to 3. + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(method, 0)]); + using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-meth", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode")); + Save(doc); + Assert.Contains("method is not 1, 2 or 3", + Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).Message); + } + // ── A TIFF whose colour exceeds its alpha (L2) ───────────────────────────────────────── [Fact] From 3098e4ece547628a429db26278e2aa6248b02204 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 13:41:31 +0100 Subject: [PATCH 15/22] docs(conformance): state the lone-colr channel check, the JPX cmap rule and the Rsiz reach The 7.4.9 colour-space row now says a lone non-device colr box is checked against the colour channels (enumerated spaces by ISO/IEC 15444-2:2004 Table M.25, ICC profiles by the header colour space), that cdef channels are counted once, and that a JPX file's cmap box without pclr keeps the name. The 770 row names the three cases in which Rsiz is read. The 6.2.8.3 row adds the colour-channel count for a file written with no ColorSpace, the 1 to 38 depth range and where the depths are read from. --- docs/conformance-v2.4.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 755534df9..9f2547bcc 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -399,11 +399,11 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the type 0 entries of a cdef box, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its device name has that many components; a CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace, and one with two or more keeps the name. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the distinct channels below the channel count that a cdef box marks as type 0, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its colour space has that many components: the device name, or, where ColorSpace is left out, the lone colr box (an enumerated space by its definition in ISO/IEC 15444-2:2004 Table M.25, an ICC profile by the data colour space of its header, ICC.1 Table 19). A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when its channels fit, and one with two or more keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), keeps the name unchecked; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. A space whose components the loader does not know is not compared BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitIsRefused`, `Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsBelowTheChannelCount`, `Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsBelowTheChannelCountAreTooFewIsRefused`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | -| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz and refuses a codestream, bare or in a JP2 file, when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined | `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused` | +| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no ihdr box), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with an ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette, whose colour channels are not read. A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, or colour channels of different bit depth is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText` | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, a colour channel deeper than 38 bits, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | | ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | | ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | From 64c49be44444315d66c3d28648a65a4db06171af Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 13:46:37 +0100 Subject: [PATCH 16/22] docs(images): say why the sRGB and greyscale counts are not cited to Table M.25 The two counts are in ISO/IEC 15444-1, which is not held; the comment now says they rest on the device spaces the loader has always chosen. --- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index dc5f25fa0..8129afca6 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -649,8 +649,8 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c // counts follow from the definitions in ISO/IEC 15444-2:2004, Table M.25: CIELab "three components", CMY and // CMYK as inks (CMYK adds black), YCCK as CMYK recombined with the K sample, bi-level one bit per sample, and the // colour models YCbCr, PhotoYCC, sYCC, e-sRGB, ROMM-RGB, YPbPr and e-sYCC three channels each. 16 (sRGB) and - // 17 (greyscale) are in ISO/IEC 15444-1, which is not held, so those two are the maintainer's ruling and the - // device spaces the loader has always chosen. 19 (CIEJab) has no count here: a file whose only colour + // 17 (greyscale) are in ISO/IEC 15444-1, which is not held, so those two rest on being the device spaces + // the loader has always chosen, with three and one components. 19 (CIEJab) has no count here: a file whose only colour // specification it is is refused before this is asked. private static int? EnumeratedComponentsOf(int value) => value switch { From 7e6f6c7285b0c11fcea39d3f60d7b30018151d84 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 16:09:42 +0100 Subject: [PATCH 17/22] fix(images): keep main's name where it fits a lone colr box, refuse non-baseline spaces A JP2 file with one colr box that names no device space was refused whenever the colour channels differed from that box's components. ISO 32000-2, 7.4.9, lets a ColorSpace that is present replace the colour specification of the data and asks only that the ordinary colour channels match its components, and no sentence of ISO/IEC 15444-1:2024 found in a search of its Annex I ties the channel count to the colour count of the space when there is no cdef box. So the file now keeps the name the channel count chooses where that name has as many components as the colour channels, which is the bytes written before, and is refused only where it has not. An enumerated space outside the JPX baseline list of ISO/IEC 15444-2:2004, M.9.2.4, other than CMYK is refused when it is the only colour specification: 7.4.9 allows no other enumerated space, so no ColorSpace makes such a file valid and the file written before was invalid too. The message names the value as an unsigned number, so the top of the 32-bit field reads as written. A cdef entry for a channel the image lacks now counts as the definition of a colour, capped at the channel count. I.5.3.6 asks for one definition per colour and bounds no channel number, and no sentence found makes such a file non-conforming, so the RGB file whose cdef names channels 0, 1 and 9 keeps its name. A colour with no entry is still not counted. Tests pin the ICC header boundary at 20 bytes, every data colour space of ICC.1 Table 19 and the zero-dimension ihdr reach of the Rsiz check. The depth range, the Rsiz reach and the lone-box prose are corrected in the loader summary, the CHANGELOG, the conformance row and the Layout remarks. --- CHANGELOG.md | 70 +++-- docs/conformance-v2.4.md | 8 +- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 196 ++++++++------ src/VellumPdf.Layout/Elements/LayoutImage.cs | 16 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 5 +- .../ConformanceAuditG4Tests.Images.cs | 23 +- .../ConformanceAuditG4Tests.JpxChannels.cs | 243 ++++++++++++++---- 7 files changed, 402 insertions(+), 159 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 516e2d463..637e3abf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -910,40 +910,55 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it counts the - colour channels, which are the distinct channels below the channel count that its `cdef` box - marks as type 0, or every channel when it has none (ISO/IEC 15444-1, I.5.3.6), and throws unless - the colour space has exactly that many components: the device name it would write, or, where it - leaves `ColorSpace` out, its lone `colr` box (an enumerated space by the components of its - definition, an ICC profile by the colour space in its header). So two channels or three beside - greyscale, one beside sRGB, two or five with no `colr` box and no `cdef` box, and one, two, four - or five beside sYCC are refused, while a greyscale file whose `cdef` box marks one colour and one - opacity channel is written as `/DeviceGray`, and so is an RGB file of five channels whose `cdef` - box marks three colour channels. A `cdef` box that names a channel twice, or one the image does - not have, counts each channel once. Where a `colr` box names CMYK and four colour channels fit no - other name, the file is written as `/DeviceCMYK`. A file with a `pclr` box keeps the name, - because a palette changes what the channels are, and so does a JPX file (brand `jpx ` or `jpxb`) - with a `cmap` box and no `pclr` box; in a JP2 file such a `cmap` box is not allowed and the file - is judged by its channel count. A JP2 file whose only colour specification is enumerated colour - space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 file with exactly one `colr` box - that holds an ICC profile or names an enumerated space other than sRGB, greyscale and CMYK - (sYCC, say) is written with no `ColorSpace` when its channels fit, so the file's own - specification decides; a lone vendor box or one too short to read keeps the name. A file with two - or more `colr` boxes and none of them a device space keeps the device name it had, because + colour channels, which are the distinct channels that the type 0 entries of its `cdef` box name, + never more than the image has, or every channel when it has none (ISO/IEC 15444-1, I.5.3.6), and + throws unless the device name it would write has exactly that many components. So two channels or + three beside greyscale, one beside sRGB, and two or five with no `colr` box and no `cdef` box are + refused, while a greyscale file whose `cdef` box marks one colour and one opacity channel is + written as `/DeviceGray`, and so is an RGB file of five channels whose `cdef` box marks three + colour channels. A `cdef` box that names a channel twice counts it once, and an entry for a + channel the image does not have counts like any other, because I.5.3.6 puts no bound on the + channel number of an entry; a colour with no entry is not counted, so an RGB file whose `cdef` + box has two entries is refused. Where a `colr` box names CMYK and four colour channels fit no + other name, the file is written as `/DeviceCMYK`. A file with a `pclr` box is not checked against + its channel count, because a palette changes what the channels are, and neither is a JPX file + (brand `jpx ` or `jpxb`) with a `cmap` box and no `pclr` box; in a JP2 file such a `cmap` box is + not allowed and the file is judged by its channel count. A JP2 file whose only colour + specification is enumerated colour space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 + file with exactly one `colr` box that holds an ICC profile or names an enumerated space other + than sRGB, greyscale and CMYK (sYCC, say) is written with no `ColorSpace` when the colour + channels have as many components as that space (an enumerated space by the colour model it names, + an ICC profile by the colour space in its header), so the file's own specification decides. When + they do not, 7.4.9 still allows a `ColorSpace` with as many components as the colour channels, so + the file keeps the name the channel count chooses where that name fits, as before, and is + refused where it does not, such as an sYCC box beside two or five channels; ISO/IEC 15444-1:2024, + Annex I, ties the channel count to the colours of the colour space only inside the `cdef` box. + An enumerated space outside the JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, other than + CMYK, is refused when it is the only colour specification, with the value in the message: 7.4.9 + limits the data to the baseline spaces other than CIEJab, CMYK and ICC profiles, so no + `ColorSpace` makes the file valid. The refused values are 0 to 11, 13, 15, 22, 23 and every value + above 24, reserved ones included; 14 (CIELab), 18 (sYCC), 20 (e-sRGB), 21 (ROMM-RGB) and 24 + (e-sYCC) are written as above. A lone vendor box or one too short to read keeps the name. A file + with two or more `colr` boxes and none of them a device space keeps the device name it had, because veraPDF 1.30.4 fails such a file of one or three channels under PDF/A-2b without it. A Layout save under a PDF/A-2 claim reports as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error that `StrictDiagnostics` refuses, a JP2 file that ISO 19005-2, 6.2.8.3, does not - allow and 7.4.9 does: more than one colour specification and not exactly one with an APPROX of - 1, a colour specification whose METH is not 1, 2 or 3, colour channels of different bit depth, - a colour channel deeper than 38 bits, or, for a file written with no `ColorSpace`, a number of - colour channels other than 1, 3 or 4. The depths are read from the `bpcc` box, else from the - codestream where the loader takes the dimensions from it, else from the `ihdr` box. The report + allow: more than one colour specification and not exactly one with an APPROX of 1, a colour + specification whose METH is not 1, 2 or 3, colour channels of different bit depth, a number of + colour channels other than 1, 3 or 4 for a file written with no `ColorSpace`, or a colour channel + deeper than 38 bits. 7.4.9 requires none of the first four, and it limits bits per sample to 1 + through 38, so the loader writes a file with a deeper channel as before and the report covers it. + The depths are read from the `bpcc` box, else from the codestream where the loader takes the + dimensions from it, else from the `ihdr` box, which gives none when its BPC is 255 and the file + has no `bpcc` box. The report follows the clause, not veraPDF, which checks APPROX and METH only without a `ColorSpace` and also fails a sign-only difference and an opacity channel of another depth. It names the image by its size and the clause and quotes no alternative text; without a claim nothing changes. **Deliberate output changes and new refusals:** those inputs, and the new diagnostic under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file whose name has as many components as it has colour channels, or that has a palette, writes the - same bytes as before. + same bytes as before, and so does a JP2 file with one `colr` box that is not a device space where + the name the channel count chooses has as many components as the colour channels. - **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of @@ -957,8 +972,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). baseline allows the irreversible decorrelation, and its limits on the MCC and MCO marker segments are not checked. The field is read in three cases: a bare codestream, the `jp2c` box of a JP2 file whose codestream starts with SOC and SIZ, and a JP2 file whose dimensions the loader takes - from the codestream because it has no `jp2h` box or no `ihdr` box. A JP2 file with an `ihdr` box - and a codestream that does not start with SOC and SIZ is not examined. + from the codestream because it has no `jp2h` box or no usable `ihdr` box (absent, or with a height + or width of 0). A JP2 file with a usable `ihdr` box and a codestream that does not start with SOC + and SIZ is not examined. **Deliberate new refusal:** a codestream whose `Rsiz` has bit 14 set, or bit 15 together with one of the listed required bits; every other codestream writes the same bytes as before. diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 9f2547bcc..b4ec833e6 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -399,11 +399,11 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the distinct channels below the channel count that a cdef box marks as type 0, else every channel, per ISO/IEC 15444-1 I.5.3.6) and is refused unless its colour space has that many components: the device name, or, where ColorSpace is left out, the lone colr box (an enumerated space by its definition in ISO/IEC 15444-2:2004 Table M.25, an ICC profile by the data colour space of its header, ICC.1 Table 19). A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when its channels fit, and one with two or more keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), keeps the name unchecked; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. A space whose components the loader does not know is not compared BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitIsRefused`, `Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsBelowTheChannelCount`, `Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsBelowTheChannelCountAreTooFewIsRefused`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | -| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab) (32000-1 allows it) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused | `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | -| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no ihdr box), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with an ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the distinct channels that the type 0 entries of a cdef box name, at most the channel count, else every channel, per ISO/IEC 15444-1 I.5.3.6, which puts no bound on the channel number of an entry and asks for a definition of every colour) and is refused unless the device name has that many components. A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when the colour channels have as many components as that space (an enumerated space by the colour model it names in ISO/IEC 15444-2:2004 Table M.25, which names the models of sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference and states no count; an ICC profile by the data colour space of its header, ICC.1 Table 19); where they do not, it keeps the name the channel count chooses when that name has as many components as the colour channels (the bytes written before; no sentence of 15444-1:2024 Annex I ties the channel count to the colour space where there is no cdef box) and is refused when no such name exists. A lone enumerated space outside M.9.2.4's baseline list other than 12 is refused with its value in the message: the refused values are 0 to 11, 13, 15, 22, 23 and every value above 24, whatever the channels are. One with two or more colr boxes keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), is not checked against its channel count; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. An ICC profile whose header cannot be read, or whose colour space Table 19 does not list, is not compared. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents`, `Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes`, `Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsUpToTheChannelCount`, `Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsAreTooFewIsRefused`, `Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | +| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab); or enumerated colour space 12 (CMYK); or an ICC profile valid in PDF (32000-1 allows CIEJab) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused, and so is one whose only colour specification is an enumerated space outside the baseline list of ISO/IEC 15444-2:2004 M.9.2.4 (14, 16, 17, 18, 19, 20, 21, 24) other than 12, because 7.4.9 allows no other enumerated space and no ColorSpace makes such a file valid. A lone ICC profile is allowed | `Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | +| ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no usable ihdr box: absent, or with a height or width of 0), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with a usable ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_AnIhdrBoxWithAZeroHeightOrWidthIsNoUsableIhdrAndItsCodestreamIsExamined`, `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, a colour channel deeper than 38 bits, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 allows it, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 requires none of these, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A colour channel deeper than 38 bits is written and reported too, but 32000-2 7.4.9 requires bits per sample between 1 and 38, so such a file is invalid under both. The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared, and an ihdr BPC of 255 with no bpcc box gives no depth. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | | ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | | ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 8129afca6..804c96335 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -54,9 +54,12 @@ namespace VellumPdf.Images; /// channel count chooses, as above. /// A JP2 file with exactly one colr box, which holds an ICC profile (method 2 or 3) /// or an enumerated colour space other than 12, 16 and 17, such as sYCC (18) -/// ColorSpace is left out, so the colour specification in the file decides, but the colour channels -/// must still have as many components as that space (see below). A lone vendor colour box (method 4), and -/// a box too short to read, do not count: the channel count chooses. +/// ColorSpace is left out, so the colour specification in the file decides, when the colour channels +/// have as many components as that space (see below). When they do not, the file is written with the name the +/// channel count chooses, as above, if that name has as many components as there are colour channels, and refused +/// otherwise. An enumerated space outside the JPX baseline set, other than CMYK, is refused whatever the channels +/// are (see below). A lone vendor colour box (method 4), and a box too short to read, do not count: the channel +/// count chooses. /// A JP2 file with two or more colr boxes, none naming a device /// spacethe channel count chooses, as above. veraPDF 1.30.4 passes such a file /// of one or three channels under PDF/A-2b with the name and fails it without; at four channels it fails @@ -69,37 +72,55 @@ namespace VellumPdf.Images; /// says the number of "ordinary colour channels" shall match the number of components in the colour /// space. ISO/IEC 15444-1, I.5.3.6, says a codestream that holds only colour channels in colour order has /// no cdef box and that any other channel (an opacity channel, say) needs one. So the loader counts -/// as colour channels the distinct channels, below the channel count, that the cdef box marks as type 0 -/// (opacity, premultiplied opacity and unspecified entries are not counted), or every channel of the ihdr -/// box when there is no readable cdef box (of the codestream, when the jp2h box has no ihdr -/// box). A cdef box that names a channel twice, or one the image does not have, is not a conforming JP2 -/// box and is not refused for that; counting distinct channels below the channel count keeps a name that fits. -/// The space has to have exactly that many components. Where a name is written, it is the name chosen above, and -/// DeviceCMYK replaces it where a colr box names CMYK and there are four colour channels. Where -/// ColorSpace is left out, it is the lone colr box: an enumerated space has the components of the -/// colour space that ISO/IEC 15444-2:2004, Table M.25, defines (three for sYCC, e-sRGB, ROMM-RGB, e-sYCC and -/// CIELab, one for bi-level and greyscale, and so on) and an ICC profile the components of the data colour space -/// in its header (ICC.1, Table 19). If no fit exists, the file is invalid under 7.4.9 and is refused with -/// . A space whose components are not known here, such as an enumerated value -/// the table does not list or an ICC profile whose header is cut short, is not compared. A cdef box too short -/// for its own entry count is skipped, and the first one long enough is read. The check looks at the jp2h -/// box only: a JPX file's jplh box, which may define opacity channels, is not read and is not written with -/// the file. A file with a pclr box keeps the name and is not checked, because a palette changes what the -/// channels are and the box is not read. So does a file with a cmap box and no pclr box whose -/// ftyp box names the JPX brand (jpx or jpxb): ISO/IEC 15444-2:2004, M.5.1.2, numbers the -/// channels by the cmap entries and no sentence there ties the box to a palette. In a JP2 file such a -/// cmap box is not allowed (ISO/IEC 15444-1, I.5.3.4), and the file is judged by its channel count. An ICC -/// profile is recognised by a colr box of method 2 or 3; only the colour space of its header is read. -/// Indexed colour spaces are not handled. +/// as colour channels the distinct channels that the cdef box marks as type 0 (opacity, premultiplied +/// opacity and unspecified entries are not counted), never more than the image has, or every channel of the +/// ihdr box when there is no readable cdef box (of the codestream, when the jp2h box has no +/// usable ihdr box). A type 0 entry for a channel the image does not have counts like any other, because +/// I.5.3.6 puts no bound on the channel number of an entry and asks for a definition of every colour; a channel +/// named twice counts once, and a colour with no entry is not counted. The space has to have exactly that many +/// components. Where a name is written, it is the name chosen above, and DeviceCMYK replaces it where a +/// colr box names CMYK and there are four colour channels. If no fit exists, the file is invalid under +/// 7.4.9 and is refused with . +/// One colr box that is not a device space. Where ColorSpace is left out, it is the lone +/// colr box that the colour channels are compared with: an enumerated space has the components that +/// ISO/IEC 15444-2:2004, Table M.25, gives its colour model, or ISO/IEC 15444-1, Table I.10, for 16, 17 and 18 (three +/// for sYCC, e-sRGB, ROMM-RGB, e-sYCC and CIELab, one for bi-level and greyscale, and so on), and an ICC profile has +/// the components of the data colour space in its header (ICC.1, Table 19). Table M.25 names the colour models of +/// sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference to the documents that define them and does not state a count, so +/// those four counts rest on the models. When the channels do not fit the space, ISO 32000-2, 7.4.9, still allows +/// a name: a present ColorSpace replaces the colour specification in the data, and its components only have to +/// match the ordinary colour channels. So the file is written with the name the channel count chooses when that name +/// has as many components as there are colour channels, the bytes written before, and refused when it has not. +/// ISO/IEC 15444-1, I.5.3.6, ties the channels to the colours of the colour specification only inside its +/// cdef box, so a file with no such box is not refused for a count that differs from its space. A lone +/// enumerated space outside the JPX baseline set is refused with naming the +/// value, whatever the channels are, because ISO 32000-2, 7.4.9, limits the image data to the baseline spaces other +/// than 19 (ISO/IEC 15444-2:2004, M.9.2.4: sRGB 16, sRGB-grey 17, ROMM-RGB 21, sYCC 18, e-sRGB 20, e-sYCC 24, +/// CIELab 14, CIEJab 19), to CMYK (12) and to an ICC profile, so no ColorSpace makes such a file valid. The +/// refused values are 0 to 11, 13, 15, 22, 23 and every value above 24, reserved ones included; CIEJab alone is +/// refused as described above. An ICC profile whose header is cut short, or names a colour space that Table 19 does +/// not list, has no component count here and is not compared. A +/// cdef box too short for its own entry count is skipped, and the first one long enough is read. The check +/// looks at the jp2h box only: a JPX file's jplh box, which may define opacity channels, is not read +/// and is not written with the file. A file with a pclr box is not checked against its channel count, +/// because a palette changes what the channels are and the box is not read: it keeps the name chosen above, or +/// has no ColorSpace where it has one colr box that is not a device space. So does a file with a +/// cmap box and no pclr box whose ftyp box names the JPX brand (jpx or jpxb): ISO/IEC 15444-2:2004, +/// M.5.1.2, numbers the channels by the cmap entries and no sentence there ties the box to a palette. In a +/// JP2 file such a cmap box is not allowed (ISO/IEC 15444-1, I.5.3.4), and the file is judged by its channel +/// count. An ICC profile is recognised by a colr box of method 2 or 3; only the colour space of its header is +/// read. Indexed colour spaces are not handled. /// A JP2 file that passes those checks may still break ISO 19005-2, 6.2.8.3, and is passed /// through. The clause requires, when there is more than one colour specification, exactly one with /// an APPROX of 1; a METH of 1, 2 or 3; 1, 3 or 4 colour channels; and one bit depth, from 1 to 38, for all the /// colour channels. A file written with a name that was checked has 1, 3 or 4 colour channels, so the count is /// reported only for a file written with no ColorSpace. The depths are read from the bpcc box, else /// from the codestream's SIZ marker when the loader had to take the dimensions from it (a bare codestream, a -/// JP2 file with no jp2h box or no ihdr box), else from the ihdr box, and a file with a palette -/// or a JPX cmap box is not compared. ISO 32000-2, 7.4.9, requires none of these. This loader neither -/// refuses nor reports such a file. A VellumPdf.Layout save reports it under a PDF/A-2 claim as +/// JP2 file with no jp2h box or no usable ihdr box), else from the ihdr box, which gives no +/// depth when its BPC field is 255 and there is no bpcc box; a file with a palette or a JPX cmap box +/// is not compared. ISO 32000-2, 7.4.9, requires none of the first four. It does require bits per sample "between +/// 1 to 38 inclusive", so a colour channel deeper than 38 bits is not valid under 7.4.9 either, and the report +/// covers it. This loader neither refuses nor reports such a file. A VellumPdf.Layout save reports it under a PDF/A-2 claim as /// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on /// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a /// PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks the report from the @@ -167,22 +188,24 @@ public static class JpxImageLoader /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// colour channels the colour space does not fit, whether a device name or the lone colr box (see - /// the class summary), and for a JP2 file whose only colour specification is enumerated colour space 19 - /// (CIEJab). + /// the class summary), for a JP2 file whose only colour specification is enumerated colour space 19 + /// (CIEJab), and for a JP2 file whose only colour specification is an enumerated colour space outside the JPX + /// baseline set other than CMYK (the class summary lists the values). /// /// /// A channel count that no device colour space has is refused for a bare codestream /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a /// colr box it writes, and ISO 32000-2, 7.4.9, says the ordinary colour channels shall match - /// the components of the colour space. Colour channels that the colour space does not fit are - /// refused for a JP2 file with a jp2h box too, as the class summary says: every channel - /// is a colour channel unless a cdef box says otherwise, and the device name written, or the - /// lone colr box where ColorSpace is left out, must have that many - /// components. A JP2 file whose only colour specification is CIEJab is - /// refused: neither a device name nor an absent ColorSpace would be valid for it. One - /// that also has an ICC profile, or another enumerated space, is written with no - /// ColorSpace only when it has exactly one colr box. The class summary lists what is - /// written for each colour specification. + /// the components of the colour space. Colour channels that the device name written does not fit are + /// refused for a JP2 file with a jp2h box too, as the class summary says: every channel is a colour + /// channel unless a cdef box says otherwise, and the name must have that many components. Where + /// ColorSpace is left out, because the file has exactly one colr box that is not a device space, + /// the file is refused only when neither that box's space nor the name the channel count chooses has as many + /// components as the colour channels. A JP2 file whose only colour specification is CIEJab is + /// refused, and so is one whose only colour specification is an enumerated space outside the JPX baseline set + /// other than CMYK: neither a device name nor an absent ColorSpace would be valid for them. A file + /// with CIEJab beside an ICC profile or another enumerated space has more than one colr box, so it is + /// written with the name the channel count chooses. The class summary lists what is written for each colour specification. /// A codestream whose Rsiz requires a Part 2 capability outside the JPX /// baseline set is refused, and so is one with the extended capabilities bit set. The call /// throws naming the Rsiz value, because ISO 32000-2, @@ -200,8 +223,8 @@ public static class JpxImageLoader /// marker segments are scanned until SIZ; from the jp2c box of a JP2 file whose codestream starts /// with SOC and then SIZ, whatever the jp2h box holds; and from the SIZ found by the same scan in /// a JP2 file whose dimensions the loader takes from the codestream, because it has no jp2h box or - /// its jp2h box has no ihdr box. A JP2 file with a usable ihdr box whose - /// codestream does not start with SOC and SIZ is not examined. + /// no usable ihdr box (one that is absent, or whose height or width is 0). A JP2 file with a usable + /// ihdr box whose codestream does not start with SOC and SIZ is not examined. /// This loader does not decode, so a codestream that uses a feature outside the baseline set /// without signalling it in Rsiz passes through. /// @@ -228,8 +251,9 @@ public static PdfImageXObject Load(byte[] jpx) /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// colour channels the colour space does not fit, whether a device name or the lone colr box (see - /// the class summary), and for a JP2 file whose only colour specification is enumerated colour space 19 - /// (CIEJab). + /// the class summary), for a JP2 file whose only colour specification is enumerated colour space 19 + /// (CIEJab), and for a JP2 file whose only colour specification is an enumerated colour space outside the JPX + /// baseline set other than CMYK (the class summary lists the values). /// /// /// Thrown when requests . @@ -645,19 +669,15 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c return digit is >= '5' and <= '9' ? digit - '0' : digit is >= 'A' and <= 'F' ? digit - 'A' + 10 : null; } - // The number of components of an enumerated colour space, or null for a value this loader has no count for. The - // counts follow from the definitions in ISO/IEC 15444-2:2004, Table M.25: CIELab "three components", CMY and - // CMYK as inks (CMYK adds black), YCCK as CMYK recombined with the K sample, bi-level one bit per sample, and the - // colour models YCbCr, PhotoYCC, sYCC, e-sRGB, ROMM-RGB, YPbPr and e-sYCC three channels each. 16 (sRGB) and - // 17 (greyscale) are in ISO/IEC 15444-1, which is not held, so those two rest on being the device spaces - // the loader has always chosen, with three and one components. 19 (CIEJab) has no count here: a file whose only colour - // specification it is is refused before this is asked. - private static int? EnumeratedComponentsOf(int value) => value switch + // The number of components of an enumerated colour space that a lone colr box may name, which is a baseline space + // other than the device spaces 12, 16 and 17 and other than CIEJab (see LoneSpace and IsBaselineEnumerated): CIELab + // (14, "the three components" in ISO/IEC 15444-2:2004, Table M.25) and sYCC (18), e-sRGB (20), ROMM-RGB (21) and + // e-sYCC (24), which Table M.25 names by reference to the documents that define them and so gives no count; their + // colour models (a luma and two chroma channels, or red, green and blue) have three. + private static int EnumeratedComponentsOf(int value) => value switch { - 0 or 15 or ColrEnumGreyscale => 1, - 1 or 3 or 4 or 9 or 11 or 14 or ColrEnumSRgb or 18 or 20 or 21 or 22 or 23 or 24 => 3, - ColrEnumCmyk or 13 => 4, - _ => null, + 14 or 18 or 20 or 21 or 24 => 3, + _ => throw new InvalidOperationException($"Enumerated colour space {value} is not a lone baseline space."), }; // cdef payload: N(2), then N entries of Cn(2) Typ(2) Asoc(2). Typ 0 is an ordinary colour channel; opacity, @@ -724,12 +744,14 @@ private sealed class ColrSurvey // channel count like any other. public bool ChannelsRemapped => HasPalette || (HasCmap && JpxBranded); - // The colour channels are the distinct channels below the channel count that a cdef box marks as type 0, or - // every channel when no readable cdef box says otherwise. A cdef box that names one channel twice, or one the - // image does not have, is not a conforming JP2 box (ISO/IEC 15444-1, I.5.3.6) but such a file has been - // written before; counting distinct channels keeps a name that already fits its components. + // The colour channels are the distinct channels that the type 0 entries of a cdef box name, and never more + // than the image has, or every channel when no readable cdef box says otherwise. ISO/IEC 15444-1, I.5.3.6, + // requires a definition for every colour and puts no bound on the channel number of an entry, so an entry for + // a channel the image lacks is counted like any other, as the definition of one colour; the image cannot hold + // more colour channels than it has channels, hence the cap. A box that names one channel twice has it counted + // once, and a colour with no entry is not counted. public int ColourChannels(int channels) => - OrdinaryChannels is null ? channels : OrdinaryChannels.Where(c => c < channels).Distinct().Count(); + OrdinaryChannels is null ? channels : Math.Min(channels, OrdinaryChannels.Distinct().Count()); private bool IsColourChannel(int channel) => OrdinaryChannels is null || OrdinaryChannels.Contains(channel); @@ -941,36 +963,62 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa "JP2 file: its only colour specification is enumerated colour space 19 (CIEJab), which " + "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); if (colr.Boxes == 1 && (colr.HasIccProfile || colr.Enumerated.Count == 1)) - { - CheckLoneSpace(channels, channelsFromSiz, colr); - return null; - } + return LoneSpace(channels, channelsFromSiz, colrEnum, colr); return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, false); } - // With no ColorSpace written, the colour specification of the file is the one a reader uses, and 7.4.9 still - // requires the ordinary colour channels to match its components. The colour channels are counted as in - // FitChannels. A space whose components are not known here (an ICC profile whose header cannot be read or names - // no listed space, an enumerated value without a count) is not compared. The count is kept for the PDF/A report, - // which allows only 1, 3 or 4 colour channels. - private static void CheckLoneSpace(int channels, bool channelsFromSiz, ColrSurvey colr) + // The one colr box of a file names an ICC profile or an enumerated space other than 12, 16 and 17. Three cases: + // - The space is outside what ISO 32000-2, 7.4.9, lets image data use (an enumerated value that is not in the + // JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, and is not 12): refused, whatever the channels are, because + // no ColorSpace makes such a file valid. This holds for a file with a palette too. + // - The colour channels, counted as in FitChannels, have as many components as the space, or the space has no + // count here (an ICC profile whose header cannot be read or names no listed space, an enumerated value + // without a count): ColorSpace is left out so the colour specification of the file decides (7.4.9: with no + // ColorSpace the colour space information in the data is used). The count is kept for the PDF/A report, which + // allows only 1, 3 or 4 colour channels. + // - They do not: the device name this loader has always chosen from the channel count, when that name has as many + // components as there are colour channels (7.4.9: a present ColorSpace replaces the specification in the data, + // and the ordinary colour channels shall match its components, so that file is valid). ISO/IEC 15444-1, + // I.5.3.6, ties the channels to the colours of the colour specification only where a cdef box exists, so a + // file with none is not refused for a count that differs from its space. Otherwise no name fits, the file + // written before was invalid, and it is refused. + // A file whose channels are remapped (ChannelsRemapped) has its colour channels unread and is left out as well. + private static ImageColorSpace? LoneSpace(int channels, bool channelsFromSiz, int? colrEnum, ColrSurvey colr) { + if (!colr.HasIccProfile && !IsBaselineEnumerated(colr.Enumerated[0])) + throw new InvalidDataException( + $"JP2 file: its only colour specification is enumerated colour space {(uint)colr.Enumerated[0]}, " + + "which is not in the JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, and is not CMYK (12), so " + + "image data that uses it is not allowed in a PDF file (ISO 32000-2, 7.4.9)."); if (colr.ChannelsRemapped) - return; + return null; var colour = colr.ColourChannels(channels); - colr.UnnamedColourChannels = colour; var components = colr.HasIccProfile ? colr.IccComponents : EnumeratedComponentsOf(colr.Enumerated[0]); if (components is null || components == colour) - return; + { + colr.UnnamedColourChannels = colour; + return null; + } + var named = InferColorSpace(channels, colrEnum); + if (ComponentsOf(named) == colour) + return named; var space = colr.HasIccProfile ? $"an ICC profile of {components} components" : $"enumerated colour space {colr.Enumerated[0]}, which has {components} components"; throw new InvalidDataException( $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr, colour)}, but its only colour specification is " + - $"{space} (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + + $"{space} and {PdfNameOf(named)}, the colour space the loader would write instead, has {ComponentsOf(named)} " + + "components (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + "space)."); } + // The enumerated colour spaces of the JPX baseline set (ISO/IEC 15444-2:2004, M.9.2.4): sRGB (16), sRGB-grey (17), + // ROMM-RGB (21), sYCC (18), e-sRGB (20), e-sYCC (24), CIELab (14) and CIEJab (19; 7.4.9 excludes it, and a file + // whose only colour specification is 19 is refused before this is asked). CMYK (12) is allowed by 7.4.9 on its + // own and does not reach this check. + private static bool IsBaselineEnumerated(int value) => + value is ColrEnumSRgb or ColrEnumGreyscale or ColrEnumCieJab or 14 or 18 or 20 or 21 or 24; + // Checks the name chosen above against the colour channels (ISO 32000-2, 7.4.9: the ordinary colour channels // shall match the components of the colour space). With a cdef box they are the distinct channels it marks // as type 0. Without one they are every channel: ISO/IEC 15444-1, I.5.3.6, makes the box mandatory when a diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 29a0e6811..5a8986584 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -312,13 +312,15 @@ public LayoutImage(PdfImageXObject image) /// Rsiz requires a Part 2 capability outside the JPX baseline set or sets bit 14 /// (extended capabilities through a CAP marker), a bare codestream or a JP2 file with no /// jp2h box whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose colour channels - /// (the cdef entries of type 0, or every channel when there is no cdef box) are not - /// as many as the components of the device colour space the loader would write, and a JP2 file - /// whose only colour specification is CIEJab ( lists - /// the cases). A JP2 file with exactly one colr box that names an ICC profile or an - /// enumerated colour space that is not sRGB, greyscale or CMYK, such as sYCC, is written with - /// no /ColorSpace, so the colour specification in the file decides, and is refused when - /// its colour channels are not as many as the components of that space. A JP2 + /// (the distinct channels that the type 0 entries of its cdef box name, or every channel when there is no + /// cdef box) are not as many as the components of the device colour space the loader would write, a JP2 + /// file whose only colour specification is CIEJab, and one whose only colour specification is an enumerated + /// colour space outside the JPX baseline set other than CMYK ( lists the + /// cases). A JP2 file with exactly one colr box that names an ICC profile or an enumerated colour space + /// that is not sRGB, greyscale or CMYK, such as sYCC, is written with no /ColorSpace, so the colour + /// specification in the file decides, when its colour channels are as many as the components of that space, and + /// otherwise with the device name the channel count chooses if that name has as many components as the colour + /// channels; with neither it is refused. A JP2 /// file whose colour channels differ in bit depth, or whose colour specifications PDF/A-2 does /// not allow, is not refused; the save reports it as /// under a PDF/A-2 claim. diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index cfc3e86cc..6cf1597ba 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -333,8 +333,9 @@ public enum LayoutDiagnosticCode /// Strict mode refuses it. ISO 19005-2:2011, 6.2.8.3, the item's /// , requires exactly one colour specification with an APPROX /// of 1 when there are several, a METH of 1, 2 or 3, 1, 3 or 4 colour channels, and one bit depth, - /// from 1 to 38, for all the colour channels. ISO 32000-2, 7.4.9, requires none of it, so - /// writes such a file and the save reports it. The + /// from 1 to 38, for all the colour channels. ISO 32000-2, 7.4.9, requires none of the first four, so + /// writes such a file and the save reports it; it does limit bits + /// per sample to 1 through 38, so a file with a deeper colour channel is invalid under both and is reported too. The /// report follows the text of 6.2.8.3, which does not depend on the image dictionary having a /// ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules only where the /// dictionary has no ColorSpace, and it also fails channels that differ only in sign or diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 41a0a3667..40573752c 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -812,7 +812,7 @@ .. BoxOf("jp2c", codestream), [Theory] [InlineData(18)] [InlineData(20)] - [InlineData(22)] + [InlineData(21)] [InlineData(24)] public void Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName(int enumerated) { @@ -1153,6 +1153,27 @@ public void Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoader Assert.Equal(codestream, Jp2Boxes(kept.Raw).Single(b => b.Type == "jp2c").Payload); } + [Theory] + [InlineData(0, 16, 0x8001)] + [InlineData(16, 0, 0x8001)] + [InlineData(0, 16, 0x4000)] + [InlineData(16, 0, 0x4000)] + public void Iso32000_2_7_4_9_AnIhdrBoxWithAZeroHeightOrWidthIsNoUsableIhdrAndItsCodestreamIsExamined(int height, int width, + int rsiz) + { + // The dimensions come from the codestream when the ihdr box gives a zero height or width, so the Rsiz behind a + // COM segment is read, as for a file with no ihdr box. ISO/IEC 15444-1, I.5.3.1, gives both fields 1 or more. + var refused = Jp2FileWithIhdrSize(Jp2File(ComBeforeSiz(JpxCodestream(16, 16, 3, 7, rsiz)), 3, 16), height, width); + Assert.Throws(() => JpxImageLoader.Load(refused)); + // With a baseline Rsiz the same file loads, and its size is the codestream's, not the ihdr box's. + var loaded = JpxImageLoader.Load(Jp2FileWithIhdrSize(Jp2File(ComBeforeSiz(JpxCodestream(16, 16, 3)), 3, 16), height, + width)); + Assert.Equal((16, 16), (loaded.Width, loaded.Height)); + // An ihdr box of 16 by 16 is usable, and its codestream, which does not start with SOC and SIZ, is not examined. + Assert.Equal(16, JpxImageLoader.Load(Jp2FileWithIhdrSize(Jp2File(ComBeforeSiz(JpxCodestream(16, 16, 3, 7, rsiz)), 3, 16), + 16, 16)).Width); + } + // ── PNG tRNS: only the low bits of a colour key count when the depth is below 16 ───────────── public static TheoryData StrayBitKeyNames() => new() { "grey8", "grey4", "rgb8" }; diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index 7c281fb8a..a9c5adc5e 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -33,6 +33,16 @@ private static byte[] Jp2FileWithIhdrChannels(byte[] jp2, int channels) return copy; } + // The file with the ihdr height and width rewritten, to build an ihdr box that gives no usable dimensions. + private static byte[] Jp2FileWithIhdrSize(byte[] jp2, int height, int width) + { + var copy = (byte[])jp2.Clone(); + var at = copy.AsSpan().IndexOf("ihdr"u8) + 4; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(copy.AsSpan(at), height); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(copy.AsSpan(at + 4), width); + return copy; + } + // The file with one more box appended inside its jp2h box, and the length of jp2h adjusted. private static byte[] Jp2FileWithRawJp2hBox(byte[] jp2, string type, byte[] payload) { @@ -86,7 +96,7 @@ public void Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsIt [InlineData(1, 2, 0)] // the 16 profile bytes are no header: the components are not known, so not compared [InlineData(3, 2, 0)] [InlineData(3, 1, 18)] - [InlineData(3, 1, 99)] + [InlineData(3, 1, 21)] public void Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf(int channels, int method, int value) { @@ -466,21 +476,23 @@ public void Iso19005_2_6_2_8_3_ATwoColourBoxFileIsReportedWhetherOrNotColorSpace // ── A lone colr box that names no device space: the colour channels must have its components ───────── // A colr payload of METH 2 whose profile is a 128-byte header with the given data colour space (ICC.1, 7.2.6). - private static byte[] IccColr(string colourSpace) => - [2, 0, 0, .. new byte[16], .. System.Text.Encoding.ASCII.GetBytes(colourSpace), .. new byte[108]]; + private static byte[] IccColr(string colourSpace, int profileLength = 128) + { + byte[] profile = [.. new byte[16], .. System.Text.Encoding.ASCII.GetBytes(colourSpace), .. new byte[Math.Max(0, profileLength - 20)]]; + return [2, 0, 0, .. profile.AsSpan(0, Math.Min(profile.Length, profileLength))]; + } private static byte[] Jp2WithColr(int channels, byte[] colr, (int, int, int)[]? cdef = null) => Jp2File(JpxCodestream(16, 16, channels), channels, null, rawColr: [colr], cdef: cdef); - // The enumerated-space counts follow ISO/IEC 15444-2:2004, Table M.25 (see the loader); 18 is sYCC. + // The baseline enumerated spaces other than the device ones (ISO/IEC 15444-2:2004, M.9.2.4) have three components: + // 14 CIELab, 18 sYCC, 20 e-sRGB, 21 ROMM-RGB, 24 e-sYCC. [Theory] [InlineData(3, 18)] - [InlineData(3, 20)] // e-sRGB - [InlineData(3, 21)] // ROMM-RGB - [InlineData(3, 24)] // e-sYCC - [InlineData(3, 14)] // CIELab, "the three components" - [InlineData(1, 0)] // bi-level - [InlineData(4, 13)] // YCCK + [InlineData(3, 20)] + [InlineData(3, 21)] + [InlineData(3, 24)] + [InlineData(3, 14)] public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsHaveHasNoColorSpace(int channels, int enumerated) { @@ -488,18 +500,33 @@ public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheCo null, boxes: [(1, enumerated)]), 16, 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); } + // ISO 32000-2, 7.4.9: a ColorSpace that is present replaces the colour specification of the data, and 15444-1, + // I.5.3.6, ties channels to colours only where a cdef box exists. A lone box whose space the channels do not fit + // keeps the name the channel count chooses when that name has as many components as there are colour channels. + [Theory] + [InlineData(1, 18, "DeviceGray")] // sYCC takes three colour channels; one channel beside it keeps main's DeviceGray + [InlineData(4, 18, "DeviceCMYK")] + [InlineData(4, 21, "DeviceCMYK")] + [InlineData(1, 14, "DeviceGray")] + [InlineData(1, 20, "DeviceGray")] + [InlineData(4, 24, "DeviceCMYK")] + public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses( + int channels, int enumerated, string name) + { + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); + Assert.Equal(name, ColourSpaceWritten(jp2)); + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(jp2).Jp2Findings); + } + [Theory] - [InlineData(1, 18)] // sYCC takes three colour channels - [InlineData(2, 18)] - [InlineData(4, 18)] + [InlineData(2, 18)] // no device name has two components [InlineData(5, 18)] [InlineData(2, 20)] - [InlineData(4, 21)] - [InlineData(1, 14)] - [InlineData(3, 0)] // bi-level takes one - [InlineData(3, 13)] // YCCK takes four - public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackIsRefused(int channels, - int enumerated) + [InlineData(5, 21)] + [InlineData(2, 14)] + [InlineData(6, 24)] + public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused( + int channels, int enumerated) { var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); @@ -508,6 +535,52 @@ public void Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheCo Assert.Throws(() => LayoutImage.FromBytes(jp2)); } + // ISO 32000-2, 7.4.9, limits the data to the baseline JPX colour spaces other than 19 (ISO/IEC 15444-2:2004, + // M.9.2.4), CMYK (12) and ICC profiles, so a lone enumerated value outside them is refused whatever the channels + // are, with or without a palette. The values are those of Table M.25 outside the baseline, the reserved ones in + // between, and the ends of the 32-bit field (0x80000000 and above are negative as an int). + public static TheoryData NonBaselineEnumeratedValues() => new() + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 22, 23, 25, 26, 99, 255, 65535, + int.MaxValue, int.MinValue, -1, + }; + + [Theory] + [MemberData(nameof(NonBaselineEnumeratedValues))] + public void Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused(int enumerated) + { + var shown = (uint)enumerated; + foreach (var channels in new[] { 1, 2, 3, 4, 5 }) + { + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"only colour specification is enumerated colour space {shown}, which is not in the JPX baseline", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + } + var palette = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, enumerated)], palette: true); + Assert.Contains($"enumerated colour space {shown}", + Assert.Throws(() => JpxImageLoader.Load(palette)).Message); + } + + [Theory] + [InlineData(14)] + [InlineData(18)] + [InlineData(20)] + [InlineData(21)] + [InlineData(24)] + [InlineData(12)] // CMYK, which 7.4.9 allows on its own, takes the device branch + [InlineData(16)] + [InlineData(17)] + public void Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue(int enumerated) + { + var channels = enumerated == 17 ? 1 : enumerated == 12 ? 4 : 3; + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); + Assert.NotNull(JpxImageLoader.Load(jp2)); + // Not a lone box: a non-baseline value beside a baseline one is not refused for it. + var two = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, 1), (1, enumerated is 12 or 17 ? 16 : enumerated)]); + Assert.NotNull(JpxImageLoader.Load(two)); + } + [Theory] [InlineData("RGB ", 3)] [InlineData("GRAY", 1)] @@ -524,23 +597,89 @@ public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChan } [Theory] - [InlineData("RGB ", 1)] - [InlineData("RGB ", 2)] - [InlineData("RGB ", 4)] + [InlineData("RGB ", 1, "DeviceGray")] // the name the count chooses has as many components as there are colour channels + [InlineData("RGB ", 4, "DeviceCMYK")] + [InlineData("GRAY", 3, "DeviceRGB")] + [InlineData("GRAY", 4, "DeviceCMYK")] + [InlineData("CMYK", 3, "DeviceRGB")] + [InlineData("CMYK", 1, "DeviceGray")] + [InlineData("2CLR", 3, "DeviceRGB")] + [InlineData("5CLR", 4, "DeviceCMYK")] + public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses( + string space, int channels, string name) + { + var jp2 = Jp2WithColr(channels, IccColr(space)); + Assert.Equal(name, ColourSpaceWritten(jp2)); + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(jp2).Jp2Findings); + } + + [Theory] + [InlineData("RGB ", 2)] // no device name has two colour channels, and five have none either [InlineData("RGB ", 5)] [InlineData("GRAY", 2)] - [InlineData("GRAY", 3)] - [InlineData("CMYK", 3)] - [InlineData("2CLR", 3)] - [InlineData("5CLR", 4)] - public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitIsRefused(string space, - int channels) + [InlineData("GRAY", 5)] + [InlineData("CMYK", 2)] + [InlineData("5CLR", 2)] + [InlineData("5CLR", 6)] + public void Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused( + string space, int channels) { var e = Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(channels, IccColr(space)))); Assert.Contains("its only colour specification is an ICC profile of", e.Message); Assert.Contains($"its ihdr box has {channels} channels", e.Message); } + // ICC.1:2010, Table 19: the data colour spaces and their numbers of colours. A profile of each, beside the one + // channel count that matches it (no ColorSpace written) and one that does not but whose name fits (the name is + // written), tells a signature with a count from one without. + [Theory] + [InlineData("XYZ ", 3)] + [InlineData("Lab ", 3)] + [InlineData("Luv ", 3)] + [InlineData("YCbr", 3)] + [InlineData("Yxy ", 3)] + [InlineData("RGB ", 3)] + [InlineData("HSV ", 3)] + [InlineData("HLS ", 3)] + [InlineData("CMY ", 3)] + [InlineData("3CLR", 3)] + [InlineData("GRAY", 1)] + [InlineData("CMYK", 4)] + [InlineData("4CLR", 4)] + [InlineData("2CLR", 2)] + [InlineData("5CLR", 5)] + [InlineData("6CLR", 6)] + [InlineData("7CLR", 7)] + [InlineData("8CLR", 8)] + [InlineData("9CLR", 9)] + [InlineData("ACLR", 10)] + [InlineData("BCLR", 11)] + [InlineData("CCLR", 12)] + [InlineData("DCLR", 13)] + [InlineData("ECLR", 14)] + [InlineData("FCLR", 15)] + public void Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents(string space, int components) + { + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-icc-match", Jp2WithColr(components, IccColr(space)), 16, + 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + // One channel, or three where the profile has one component, mismatches it and takes the name of its own count. + var channels = components == 1 ? 3 : 1; + Assert.Equal(channels == 1 ? "DeviceGray" : "DeviceRGB", ColourSpaceWritten(Jp2WithColr(channels, IccColr(space)))); + } + + [Theory] + [InlineData(19, null)] // no header: the components are not known, so not compared, and no name is written + [InlineData(20, "DeviceRGB")] // the signature is the last four of the first 20 bytes: known, GRAY has one component + [InlineData(21, "DeviceRGB")] + [InlineData(128, "DeviceRGB")] + public void Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes(int profileLength, string? name) + { + // A GRAY profile over three channels: with a readable header it has one component against three colour + // channels and the name the count chooses is written; with 19 bytes there is no header and ColorSpace is left out. + var jp2 = Jp2WithColr(3, IccColr("GRAY", profileLength)); + Assert.Equal(name, ColourSpaceWritten(jp2)); + } + [Fact] public void Iso32000_2_7_4_9_TheColourChannelsOfAFileWithNoColorSpaceAreCountedByTheCdefBox() { @@ -554,15 +693,16 @@ public void Iso32000_2_7_4_9_TheColourChannelsOfAFileWithNoColorSpaceAreCountedB var e = Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(4, icc, Channels(2, 1, 1)))); Assert.Contains("its cdef box marks 2 ordinary colour channels", e.Message); Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(3, [1, 0, 0, 0, 0, 0, 18], Channels(2, 1)))); + // Four channels with one colour channel and an RGB profile: neither the profile nor the name the count + // chooses (DeviceCMYK) has one component, so the file is refused. + Assert.Throws(() => JpxImageLoader.Load(Jp2WithColr(4, icc, Channels(1, 1, 1, 1)))); } [Fact] - public void Iso32000_2_7_4_9_AColourSpaceWhoseComponentsAreNotKnownIsNotComparedAndAProfileWithNoHeaderEither() + public void Iso32000_2_7_4_9_AnIccProfileWhoseComponentsAreNotKnownIsNotComparedAndAProfileWithNoHeaderEither() { - // Enumerated value 99 is reserved and has no count, a profile signature outside Table 19 has none, and a - // profile cut short before byte 20 has no header to read. The loader keeps main's bytes for all three. - Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-99", Jp2File(JpxCodestream(16, 16, 2), 2, null, - boxes: [(1, 99)]), 16, 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); + // A profile signature outside Table 19 has no count, and a profile cut short before byte 20 has no header to + // read, so ColorSpace is left out whatever the channel count is. Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-xxxx", Jp2WithColr(2, IccColr("XXXX")), 16, 16, "DeviceRGB", 8, "JPXDecode"))).Dict.Get(N("ColorSpace"))); Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-short", Jp2WithColr(2, [2, 0, 0, .. new byte[16]]), 16, @@ -599,24 +739,30 @@ public void Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourCha [InlineData(3, 16, new[] { 0, 1, 2, 2 }, "DeviceRGB")] // channel 2 twice [InlineData(1, 17, new[] { 0, 0 }, "DeviceGray")] [InlineData(3, 12, new[] { 0, 1, 2, 2 }, "DeviceRGB")] // three distinct, a CMYK box: not four - [InlineData(1, 12, new[] { 0, 1, 2, 3 }, "DeviceGray")] // three channels the image lacks: one distinct, not four - [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks - public void Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsBelowTheChannelCount(int channels, int enumerated, + [InlineData(1, 12, new[] { 0, 1, 2, 3 }, "DeviceGray")] // four entries for a one-channel image: capped at one + [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks: capped at three + [InlineData(3, 16, new[] { 0, 1, 9 }, "DeviceRGB")] // one definition per colour, the last naming a channel the image lacks + [InlineData(3, 16, new[] { 7, 8, 9 }, "DeviceRGB")] // three definitions, none of a channel the image has + [InlineData(1, 17, new[] { 4 }, "DeviceGray")] + public void Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsUpToTheChannelCount(int channels, int enumerated, int[] colourEntries, string name) { - // ISO/IEC 15444-1, I.5.3.6, does not allow one (Typ, Asoc) pair twice, and says nothing that bounds Cn; the - // loader counts distinct channels below the channel count, so no name is written whose components differ. + // ISO/IEC 15444-1, I.5.3.6, does not allow one (Typ, Asoc) pair twice, requires a definition for every colour and + // puts no bound on Cn. The loader counts the distinct channels the type 0 entries name, at most the channel + // count, so an entry for a channel the image lacks still defines its colour (the file is not shown invalid) + // while no name is written whose components differ from that number. var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); } [Theory] - [InlineData(3, 16, new[] { 0, 1, 9 }, 2)] // channel 9 does not exist - [InlineData(1, 16, new[] { 0, 1, 2 }, 1)] // two of three colour channels do not exist - [InlineData(4, 12, new[] { 0, 1, 2, 2 }, 3)] // channel 2 twice leaves three, not the four CMYK has - [InlineData(3, 18, new[] { 0, 1, 9 }, 2)] // the lone-sYCC path counts the same way - public void Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsBelowTheChannelCountAreTooFewIsRefused(int channels, - int enumerated, int[] colourEntries, int distinct) + [InlineData(1, 16, new[] { 0, 1, 2 }, 1)] // one channel cannot hold three colours, whatever the entries say + [InlineData(4, 12, new[] { 0, 1, 2, 2 }, 3)] // channel 2 twice leaves three definitions, not the four CMYK has + [InlineData(3, 16, new[] { 0, 1 }, 2)] // no definition for the third colour + [InlineData(3, 18, new[] { 0, 1 }, 2)] // the lone-sYCC path counts the same way + [InlineData(4, 12, new[] { 0, 1, 9 }, 3)] + public void Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsAreTooFewIsRefused(int channels, int enumerated, + int[] colourEntries, int distinct) { var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef); @@ -624,6 +770,15 @@ public void Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsBelowTheChannelC Assert.Contains($"its cdef box marks {distinct} ordinary colour channels", e.Message); } + [Fact] + public void Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace() + { + // Three definitions, one naming a channel the image lacks: three colour channels, sYCC has three. + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (9, 0, 3)]); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc-cdef", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))) + .Dict.Get(N("ColorSpace"))); + } + // ── A jplh box is not carried into the file, so the message says the channels may be defined there ────── [Fact] From 4144bd252b068206db95e6c6a751b829dd4c0957 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 19:19:06 +0100 Subject: [PATCH 18/22] fix(images): one colour-channel reading, refuse JP2 files PDF cannot hold The colour channels of a JP2 file are the channels the image has that a type 0 entry of a usable cdef box names, or every channel when the box is absent or leaves a channel undescribed. An entry for a channel the image lacks describes nothing. The reading is stated once on JpxImageLoader and every other place points to it. A JP2 file none of whose readable colr boxes is an allowed colour specification (an ICC profile, CMYK, or a baseline enumerated space other than CIEJab) is refused, as is a colour channel deeper than 38 bits, since ISO 32000-2, 7.4.9, allows neither. The depth finding of the PDF/A report goes with it. LayoutImage no longer promises that all unwritable data is refused; it lists what is. --- CHANGELOG.md | 69 ++--- docs/conformance-v2.4.md | 6 +- src/VellumPdf.Kernel/Images/Jp2Findings.cs | 3 - src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 255 +++++++++++------- src/VellumPdf.Layout/Elements/LayoutImage.cs | 33 ++- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 28 +- .../Rendering/ImageDiagnostics.cs | 2 - .../ConformanceAuditG4Tests.Images.cs | 8 +- .../ConformanceAuditG4Tests.JpxChannels.cs | 236 +++++++++++++--- 9 files changed, 419 insertions(+), 221 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a380ac97..b99c5e4e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -982,21 +982,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). precision other than 8, or a frame type other than SOF0, SOF1 and SOF2, which also covers a JPEG strip of a TIFF. It throws for a bare JPEG 2000 codestream, or a JP2 file with no `jp2h` box, of a channel count other than 1, 3 or 4. For a JP2 file with a `jp2h` box it counts the - colour channels, which are the distinct channels that the type 0 entries of its `cdef` box name, - never more than the image has, or every channel when it has none (ISO/IEC 15444-1, I.5.3.6), and - throws unless the device name it would write has exactly that many components. So two channels or - three beside greyscale, one beside sRGB, and two or five with no `colr` box and no `cdef` box are - refused, while a greyscale file whose `cdef` box marks one colour and one opacity channel is - written as `/DeviceGray`, and so is an RGB file of five channels whose `cdef` box marks three - colour channels. A `cdef` box that names a channel twice counts it once, and an entry for a - channel the image does not have counts like any other, because I.5.3.6 puts no bound on the - channel number of an entry; a colour with no entry is not counted, so an RGB file whose `cdef` - box has two entries is refused. Where a `colr` box names CMYK and four colour channels fit no - other name, the file is written as `/DeviceCMYK`. A file with a `pclr` box is not checked against + colour channels as the `JpxImageLoader` documentation defines them (ISO/IEC 15444-1, I.5.3.6), + and throws unless the device name it would write has exactly that many components. So two + channels or three beside greyscale, one beside sRGB, and two or five with no `colr` box and no + `cdef` box are refused, while a greyscale file whose `cdef` box marks one colour and one opacity + channel is written as `/DeviceGray`, and so is an RGB file of five channels whose `cdef` box marks + three colour channels. Where a `colr` box names CMYK and four colour channels fit no other name, + the file is written as `/DeviceCMYK`. A file with a `pclr` box is not checked against its channel count, because a palette changes what the channels are, and neither is a JPX file (brand `jpx ` or `jpxb`) with a `cmap` box and no `pclr` box; in a JP2 file such a `cmap` box is - not allowed and the file is judged by its channel count. A JP2 file whose only colour - specification is enumerated colour space 19 (CIEJab) is refused too, which 7.4.9 excludes. A JP2 + not allowed and the file is judged by its channel count. A JP2 file with exactly one `colr` box that holds an ICC profile or names an enumerated space other than sRGB, greyscale and CMYK (sYCC, say) is written with no `ColorSpace` when the colour channels have as many components as that space (an enumerated space by the colour model it names, @@ -1005,32 +1000,42 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). the file keeps the name the channel count chooses where that name fits, as before, and is refused where it does not, such as an sYCC box beside two or five channels; ISO/IEC 15444-1:2024, Annex I, ties the channel count to the colours of the colour space only inside the `cdef` box. - An enumerated space outside the JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, other than - CMYK, is refused when it is the only colour specification, with the value in the message: 7.4.9 - limits the data to the baseline spaces other than CIEJab, CMYK and ICC profiles, so no - `ColorSpace` makes the file valid. The refused values are 0 to 11, 13, 15, 22, 23 and every value - above 24, reserved ones included; 14 (CIELab), 18 (sYCC), 20 (e-sRGB), 21 (ROMM-RGB) and 24 - (e-sYCC) are written as above. A lone vendor box or one too short to read keeps the name. A file - with two or more `colr` boxes and none of them a device space keeps the device name it had, because - veraPDF 1.30.4 fails such a file of one or three channels under PDF/A-2b without it. A Layout + A JP2 file none of whose readable `colr` boxes is an allowed colour specification is refused, + whatever its channels and `ColorSpace` are, with the boxes named in the message: 7.4.9 limits + the data to the JPX baseline set of features other than enumerated colour space 19 (CIEJab) and + ISO/IEC 15444-2:2004, M.9.2.4, asks of that set a colour specification from its list, so no + `ColorSpace` makes such a file valid. A colour specification is allowed when it is an ICC profile + (method 2 or 3), CMYK (12), or an enumerated space of that list other than CIEJab: sRGB (16), + greyscale (17), CIELab (14), sYCC (18), e-sRGB (20), ROMM-RGB (21) and e-sYCC (24). The refused + enumerated values are 0 to 11, 13, 15, 19, 22, 23 and every value above 24, reserved ones + included, and the refused methods are any other than 1, 2 and 3, so a lone vendor box, two + reserved values, and a vendor box beside CIEJab are refused. One allowed box is enough: a file + with a vendor box beside an ICC profile, or two or more `colr` boxes of which one is allowed and + none a device space, keeps the device name it had, because veraPDF 1.30.4 fails such a file of one + or three channels under PDF/A-2b without it. A box too short to read (under 3 bytes, or method 1 + under 7) is a colour specification of neither kind, so a file with only such boxes is not + refused for them. A JP2 file with no `colr` box is not refused for the absence. A Layout save under a PDF/A-2 claim reports as the new `LayoutDiagnosticCode.JpxImageNotAllowedByPdfA` (501), an error that `StrictDiagnostics` refuses, a JP2 file that ISO 19005-2, 6.2.8.3, does not allow: more than one colour specification and not exactly one with an APPROX of 1, a colour - specification whose METH is not 1, 2 or 3, colour channels of different bit depth, a number of - colour channels other than 1, 3 or 4 for a file written with no `ColorSpace`, or a colour channel - deeper than 38 bits. 7.4.9 requires none of the first four, and it limits bits per sample to 1 - through 38, so the loader writes a file with a deeper channel as before and the report covers it. - The depths are read from the `bpcc` box, else from the codestream where the loader takes the - dimensions from it, else from the `ihdr` box, which gives none when its BPC is 255 and the file - has no `bpcc` box. The report - follows the clause, not veraPDF, which checks APPROX and METH only without a `ColorSpace` and - also fails a sign-only difference and an opacity channel of another depth. It names the image by - its size and the clause and quotes no alternative text; without a claim nothing changes. + specification whose METH is not 1, 2 or 3, colour channels of different bit depth, or a number of + colour channels other than 1, 3 or 4 for a file written with no `ColorSpace`. 7.4.9 requires none + of those four. It does limit bits per sample to 1 through 38, so a JP2 file (or a bare + codestream) with a colour channel deeper than that is refused in every document; a file with a + palette is not read for it. The depths are read from the `bpcc` box, else from the codestream + where the loader takes the dimensions from it, else from the `ihdr` box, which gives none when + its BPC is 255 and the file has no `bpcc` box. The report follows the clause, not veraPDF, which + checks APPROX and METH only without a `ColorSpace` and also fails a sign-only difference and an + opacity channel of another depth. It names the image by its size and the clause and quotes no + alternative text; without a claim nothing changes. **Deliberate output changes and new refusals:** those inputs, and the new diagnostic under a PDF/A-2 claim; every other JPEG (SOF0 to SOF2, 8-bit, 1, 3 or 4 components) and every JP2 file whose name has as many components as it has colour channels, or that has a palette, writes the same bytes as before, and so does a JP2 file with one `colr` box that is not a device space where - the name the channel count chooses has as many components as the colour channels. + the name the channel count chooses has as many components as the colour channels. A `cdef` box + that leaves a channel undescribed is not used, so a file that main wrote with a name of fewer + components than its channels, beside such a box, is refused (an sRGB file of four channels whose + `cdef` box describes channels 0 to 2 is one). - **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index b4ec833e6..c2bfb8dc8 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -399,11 +399,11 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels (the distinct channels that the type 0 entries of a cdef box name, at most the channel count, else every channel, per ISO/IEC 15444-1 I.5.3.6, which puts no bound on the channel number of an entry and asks for a definition of every colour) and is refused unless the device name has that many components. A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when the colour channels have as many components as that space (an enumerated space by the colour model it names in ISO/IEC 15444-2:2004 Table M.25, which names the models of sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference and states no count; an ICC profile by the data colour space of its header, ICC.1 Table 19); where they do not, it keeps the name the channel count chooses when that name has as many components as the colour channels (the bytes written before; no sentence of 15444-1:2024 Annex I ties the channel count to the colour space where there is no cdef box) and is refused when no such name exists. A lone enumerated space outside M.9.2.4's baseline list other than 12 is refused with its value in the message: the refused values are 0 to 11, 13, 15, 22, 23 and every value above 24, whatever the channels are. One with two or more colr boxes keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), is not checked against its channel count; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. An ICC profile whose header cannot be read, or whose colour space Table 19 does not list, is not compared. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents`, `Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes`, `Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsUpToTheChannelCount`, `Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsAreTooFewIsRefused`, `Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | -| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab); or enumerated colour space 12 (CMYK); or an ICC profile valid in PDF (32000-1 allows CIEJab) | IMG (JPX) | fixed (#763): a JP2 file whose only colour specification is CIEJab is refused, and so is one whose only colour specification is an enumerated space outside the baseline list of ISO/IEC 15444-2:2004 M.9.2.4 (14, 16, 17, 18, 19, 20, 21, 24) other than 12, because 7.4.9 allows no other enumerated space and no ColorSpace makes such a file valid. A lone ICC profile is allowed | `Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels as the `JpxImageLoader` class summary defines them (ISO/IEC 15444-1 I.5.3.6; that reading is stated there once) and is refused unless the device name has that many components. A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when the colour channels have as many components as that space (an enumerated space by the colour model it names in ISO/IEC 15444-2:2004 Table M.25, which names the models of sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference and states no count; an ICC profile by the data colour space of its header, ICC.1 Table 19); where they do not, it keeps the name the channel count chooses when that name has as many components as the colour channels (the bytes written before; no sentence of 15444-1:2024 Annex I ties the channel count to the colour space where there is no cdef box) and is refused when no such name exists. A file none of whose readable colr boxes is an allowed colour specification is refused, whatever the channels are (see the next row). One with two or more colr boxes of which one is allowed, and none a device space, keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), is not checked against its channel count; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. An ICC profile whose header cannot be read, or whose colour space Table 19 does not list, is not compared. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents`, `Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes`, `Iso32000_2_7_4_9_ACdefBoxCountsTheDistinctChannelsItNamesAndIgnoresEntriesForChannelsTheImageLacks`, `Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelButMarksTheWrongNumberOfColourChannelsIsRefused`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsNotUsedAndEveryChannelIsAColourChannel`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedCountsEveryChannelAndTheNameMustHaveThatMany`, `Iso32000_2_7_4_9_AnEntryForAChannelTheImageLacksBesideAnOpacityChannelDefinesNoColour`, `Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | +| ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab); or enumerated colour space 12 (CMYK); or an ICC profile valid in PDF (32000-1 allows CIEJab) | IMG (JPX) | fixed (#763): a JP2 file none of whose readable colr boxes is allowed is refused, because 7.4.9 allows only the JPX baseline set of features other than enumerated space 19, M.9.2.4 of ISO/IEC 15444-2:2004 asks of it a colour specification from its list, and no ColorSpace makes such a file valid. Allowed: an ICC profile (method 2 or 3), CMYK (12), and the enumerated spaces of the list other than 19 (14, 16, 17, 18, 20, 21, 24). Refused: a lone CIEJab, a lone enumerated value outside those (0 to 11, 13, 15, 22, 23, and every value above 24, reserved ones included), a vendor or reserved method (any other than 1, 2 and 3) alone or beside only such boxes, and two or more boxes of those kinds. One allowed box beside others is enough. A box under 3 bytes, or method 1 under 7, is a colour specification of neither kind and is not counted; a file with no colr box is not refused for the absence | `Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue`, `Iso32000_2_7_4_9_ALoneVendorOrReservedColourBoxIsRefused`, `Iso32000_2_7_4_9_AReservedMethodBoxOfThreeBytesIsAColourSpecificationAndIsRefused`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadIsNoColourSpecificationOfEitherKindAndKeepsTheName`, `Iso32000_2_7_4_9_AFileWhoseColourBoxesAreNoneOfThemAnAllowedSpaceIsRefusedAtEveryChannelCount`, `Iso32000_2_7_4_9_AFileWithOneAllowedColourBoxBesideOthersIsNotRefusedForTheOthers`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadBesideAVendorBoxStillLeavesNoAllowedSpace`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | | ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no usable ihdr box: absent, or with a height or width of 0), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with a usable ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_AnIhdrBoxWithAZeroHeightOrWidthIsNoUsableIhdrAndItsCodestreamIsExamined`, `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 requires none of these, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A colour channel deeper than 38 bits is written and reported too, but 32000-2 7.4.9 requires bits per sample between 1 and 38, so such a file is invalid under both. The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared, and an ihdr BPC of 255 with no bpcc box gives no depth. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 requires none of these, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A colour channel deeper than 38 bits is refused in every document, because 32000-2 7.4.9 requires bits per sample between 1 and 38 (a file with a palette is not read for it). The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared, and an ihdr BPC of 255 with no bpcc box gives no depth. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso32000_2_7_4_9_AColourChannelOfMoreThanThirtyEightBitsIsRefusedInEveryDocument`, `Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChannelsAndOnFilesWhoseChannelsAreRead`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | | ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | | ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | diff --git a/src/VellumPdf.Kernel/Images/Jp2Findings.cs b/src/VellumPdf.Kernel/Images/Jp2Findings.cs index 510995a90..b36f5695c 100644 --- a/src/VellumPdf.Kernel/Images/Jp2Findings.cs +++ b/src/VellumPdf.Kernel/Images/Jp2Findings.cs @@ -25,7 +25,4 @@ internal enum Jp2Findings /// A file written with no /ColorSpace whose colour channels number other than 1, 3 or 4. /// ColourChannelCount = 8, - - /// A colour channel whose bit depth is outside 1 to 38. - ColourDepthRange = 16, } diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 804c96335..28c9e930a 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -58,29 +58,43 @@ namespace VellumPdf.Images; /// have as many components as that space (see below). When they do not, the file is written with the name the /// channel count chooses, as above, if that name has as many components as there are colour channels, and refused /// otherwise. An enumerated space outside the JPX baseline set, other than CMYK, is refused whatever the channels -/// are (see below). A lone vendor colour box (method 4), and a box too short to read, do not count: the channel -/// count chooses. -/// A JP2 file with two or more colr boxes, none naming a device -/// spacethe channel count chooses, as above. veraPDF 1.30.4 passes such a file -/// of one or three channels under PDF/A-2b with the name and fails it without; at four channels it fails -/// the file with the name too, on 6.2.4.3-3. -/// A JP2 file whose only colour specifications are enumerated colour space 19 -/// (CIEJab)refused, because ISO 32000-2, 7.4.9, excludes CIEJab and there is -/// nothing else to use. +/// are (see below). A box too short to read does not count: the channel count chooses. +/// A JP2 file with two or more colr boxes, none naming a device space and at least one an +/// allowed space (see below)the channel count chooses, as above. veraPDF 1.30.4 passes such +/// a file of one or three channels under PDF/A-2b with the name and fails it without; at four channels it +/// fails the file with the name too, on 6.2.4.3-3. +/// A JP2 file none of whose readable colr boxes is an allowed space (see +/// below)refused. /// /// A colour space is used only for colour channels it has the components for. ISO 32000-2, 7.4.9, /// says the number of "ordinary colour channels" shall match the number of components in the colour /// space. ISO/IEC 15444-1, I.5.3.6, says a codestream that holds only colour channels in colour order has -/// no cdef box and that any other channel (an opacity channel, say) needs one. So the loader counts -/// as colour channels the distinct channels that the cdef box marks as type 0 (opacity, premultiplied -/// opacity and unspecified entries are not counted), never more than the image has, or every channel of the -/// ihdr box when there is no readable cdef box (of the codestream, when the jp2h box has no -/// usable ihdr box). A type 0 entry for a channel the image does not have counts like any other, because -/// I.5.3.6 puts no bound on the channel number of an entry and asks for a definition of every colour; a channel -/// named twice counts once, and a colour with no entry is not counted. The space has to have exactly that many +/// no cdef box and that any other channel (an opacity channel, say) needs one with a complete list. This is +/// how the loader counts the colour channels, here and wherever another text of this library refers to them: +/// they are the channels that the image has and that a type 0 entry of its cdef box names, a channel named +/// twice counting once, and an entry that names no channel the image has describes nothing and is ignored +/// (I.5.3.6 bounds the channel number of an entry by no sentence). Opacity, premultiplied opacity and unspecified +/// entries are not counted. When there is no readable cdef box, or the box does not describe every +/// channel the image has, every channel is a colour channel. A cdef box that leaves a channel undescribed +/// is not a complete list, which I.5.3.6 asks for. That clause does not define "complete", so this is a reading +/// and not a quoted requirement, and the loader does not refuse the file for it: it does not use the box, as it +/// does not use one that is too short to read. The channels come from the ihdr box (from the codestream, +/// when the jp2h box has no usable ihdr box). The space has to have exactly that many /// components. Where a name is written, it is the name chosen above, and DeviceCMYK replaces it where a /// colr box names CMYK and there are four colour channels. If no fit exists, the file is invalid under /// 7.4.9 and is refused with . +/// A file with no allowed colour specification is refused with , +/// whatever the channels and the ColorSpace are. ISO 32000-2, 7.4.9, limits the image data to the JPX +/// baseline set of features except enumerated colour space 19, and ISO/IEC 15444-2:2004, M.9.2.4, asks of that set +/// at least one colour specification from a list. A colour specification is allowed when it is an ICC profile +/// (method 2 or 3) or an enumerated space of the baseline list other than 19 (sRGB 16, sRGB-grey 17, ROMM-RGB 21, +/// sYCC 18, e-sRGB 20, e-sYCC 24, CIELab 14), or CMYK (12), which 7.4.9 adds. The file is refused when it has +/// readable colr boxes and none is allowed: a lone enumerated space outside that set (the values 0 to 11, +/// 13, 15, 22, 23 and every value above 24, reserved ones included, and 19), a vendor or reserved method (any +/// METH other than 1, 2 and 3), or several boxes of those kinds. A box beside an allowed one does not matter. A +/// box too short to read (under 3 bytes, or a METH 1 box under 7) is not a colour specification of either kind, +/// so a file with only such boxes is not refused for them. A file with no colr box is not refused for the +/// absence, and the channel count chooses. /// One colr box that is not a device space. Where ColorSpace is left out, it is the lone /// colr box that the colour channels are compared with: an enumerated space has the components that /// ISO/IEC 15444-2:2004, Table M.25, gives its colour model, or ISO/IEC 15444-1, Table I.10, for 16, 17 and 18 (three @@ -92,15 +106,10 @@ namespace VellumPdf.Images; /// match the ordinary colour channels. So the file is written with the name the channel count chooses when that name /// has as many components as there are colour channels, the bytes written before, and refused when it has not. /// ISO/IEC 15444-1, I.5.3.6, ties the channels to the colours of the colour specification only inside its -/// cdef box, so a file with no such box is not refused for a count that differs from its space. A lone -/// enumerated space outside the JPX baseline set is refused with naming the -/// value, whatever the channels are, because ISO 32000-2, 7.4.9, limits the image data to the baseline spaces other -/// than 19 (ISO/IEC 15444-2:2004, M.9.2.4: sRGB 16, sRGB-grey 17, ROMM-RGB 21, sYCC 18, e-sRGB 20, e-sYCC 24, -/// CIELab 14, CIEJab 19), to CMYK (12) and to an ICC profile, so no ColorSpace makes such a file valid. The -/// refused values are 0 to 11, 13, 15, 22, 23 and every value above 24, reserved ones included; CIEJab alone is -/// refused as described above. An ICC profile whose header is cut short, or names a colour space that Table 19 does -/// not list, has no component count here and is not compared. A -/// cdef box too short for its own entry count is skipped, and the first one long enough is read. The check +/// cdef box, so a file with no such box is not refused for a count that differs from its space. An ICC +/// profile whose header is cut short, or names a colour space that Table 19 does not list, has no component count +/// here and is not compared. A cdef box too short for its own entry count is skipped, and the first one +/// long enough is read. The check /// looks at the jp2h box only: a JPX file's jplh box, which may define opacity channels, is not read /// and is not written with the file. A file with a pclr box is not checked against its channel count, /// because a palette changes what the channels are and the box is not read: it keeps the name chosen above, or @@ -119,8 +128,10 @@ namespace VellumPdf.Images; /// JP2 file with no jp2h box or no usable ihdr box), else from the ihdr box, which gives no /// depth when its BPC field is 255 and there is no bpcc box; a file with a palette or a JPX cmap box /// is not compared. ISO 32000-2, 7.4.9, requires none of the first four. It does require bits per sample "between -/// 1 to 38 inclusive", so a colour channel deeper than 38 bits is not valid under 7.4.9 either, and the report -/// covers it. This loader neither refuses nor reports such a file. A VellumPdf.Layout save reports it under a PDF/A-2 claim as +/// 1 to 38 inclusive", so a colour channel deeper than 38 bits is refused with +/// in every document, and the depths of a file with a palette or a JPX +/// cmap box are not read for that either. This loader neither refuses nor reports the other findings. A +/// VellumPdf.Layout save reports them under a PDF/A-2 claim as /// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on /// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a /// PDF/A document: 3.0 will refuse it where the image is created, and #474 tracks the report from the @@ -188,24 +199,24 @@ public static class JpxImageLoader /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// colour channels the colour space does not fit, whether a device name or the lone colr box (see - /// the class summary), for a JP2 file whose only colour specification is enumerated colour space 19 - /// (CIEJab), and for a JP2 file whose only colour specification is an enumerated colour space outside the JPX - /// baseline set other than CMYK (the class summary lists the values). + /// the class summary), for a JP2 file none of whose readable colr boxes is an allowed colour + /// specification, and for a JP2 file with a colour channel deeper than 38 bits (the class summary says what + /// each is). /// /// /// A channel count that no device colour space has is refused for a bare codestream /// and for a JP2 file with no jp2h box, because the loader describes them to PDF with a /// colr box it writes, and ISO 32000-2, 7.4.9, says the ordinary colour channels shall match /// the components of the colour space. Colour channels that the device name written does not fit are - /// refused for a JP2 file with a jp2h box too, as the class summary says: every channel is a colour - /// channel unless a cdef box says otherwise, and the name must have that many components. Where + /// refused for a JP2 file with a jp2h box too, as the class summary says: the class summary says which + /// channels are colour channels, and the name must have that many components. Where /// ColorSpace is left out, because the file has exactly one colr box that is not a device space, /// the file is refused only when neither that box's space nor the name the channel count chooses has as many - /// components as the colour channels. A JP2 file whose only colour specification is CIEJab is - /// refused, and so is one whose only colour specification is an enumerated space outside the JPX baseline set - /// other than CMYK: neither a device name nor an absent ColorSpace would be valid for them. A file - /// with CIEJab beside an ICC profile or another enumerated space has more than one colr box, so it is - /// written with the name the channel count chooses. The class summary lists what is written for each colour specification. + /// components as the colour channels. A JP2 file none of whose readable colr boxes is an allowed + /// colour specification is refused, as is one with a colour channel deeper than 38 bits: no + /// ColorSpace makes either valid. A file with CIEJab beside an ICC profile or another allowed + /// space is not refused for it, and is written with the name the channel count chooses. The class summary lists + /// what is written for each colour specification and what counts as allowed. /// A codestream whose Rsiz requires a Part 2 capability outside the JPX /// baseline set is refused, and so is one with the extended capabilities bit set. The call /// throws naming the Rsiz value, because ISO 32000-2, @@ -251,9 +262,9 @@ public static PdfImageXObject Load(byte[] jpx) /// Also for a bare codestream, or a JP2 file with no jp2h /// box, with a channel count other than 1, 3 or 4, for a JP2 file with a jp2h box whose /// colour channels the colour space does not fit, whether a device name or the lone colr box (see - /// the class summary), for a JP2 file whose only colour specification is enumerated colour space 19 - /// (CIEJab), and for a JP2 file whose only colour specification is an enumerated colour space outside the JPX - /// baseline set other than CMYK (the class summary lists the values). + /// the class summary), for a JP2 file none of whose readable colr boxes is an allowed colour + /// specification, and for a JP2 file with a colour channel deeper than 38 bits (the class summary says what + /// each is). /// /// /// Thrown when requests . @@ -311,6 +322,8 @@ private static PdfImageXObject LoadRawCodestream(byte[] data) var enumCs = EnumCsForComponents(components); var cs = InferColorSpace(components, enumCs); + var survey = new ColrSurvey { CodestreamDepths = depths }; + survey.RefuseDepthOutsideRange(components); // A bare codestream carries no JP2 boxes, so PDF/A-2 clause 6.2.8.3 — which reads the // colour-channel count and bit depth from the JP2 ihdr/colr boxes, not the SIZ marker — @@ -319,7 +332,7 @@ private static PdfImageXObject LoadRawCodestream(byte[] data) var jp2 = BuildMinimalJp2(width, height, components, bpc, enumCs, MakeBox(BoxTypeJp2c, data)); return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) { - Jp2Findings = new ColrSurvey { CodestreamDepths = depths }.Findings(components), + Jp2Findings = survey.Findings(components), }; } @@ -441,6 +454,8 @@ private static PdfImageXObject LoadJp2(byte[] data) jp2 = BuildMinimalJp2(width, height, nc, bpc, colrEnum ?? EnumCsForComponents(nc), jp2cBox); } + colr.RefuseDepthOutsideRange(nc); + // What the loader passes through but PDF/A-2 6.2.8.3 does not allow is recorded for the Layout // package, which reports it under a PDF/A claim; the Kernel writes the image either way. return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc) @@ -632,17 +647,25 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c if (data[offset + 2] == 1) colr.Approx1Boxes++; if (meth is not (1 or 2 or 3)) + { colr.OtherMethod = true; + colr.NotAllowed.Add($"a vendor or reserved colour specification (method {meth})"); + } if (meth == 1 && length >= 7) { // Enumerated colour space method: 4-byte enum value follows METH/PREC/APPROX. colrEnum = (int)ReadUInt32Be(data, offset + 3); colr.Enumerated.Add(colrEnum.Value); + if (!IsAllowedEnumerated(colrEnum.Value)) + colr.NotAllowed.Add($"enumerated colour space {(uint)colrEnum.Value}"); + else + colr.AllowedBoxes++; } else if (meth is 2 or 3) { // METH 2 and 3 carry an ICC profile. Only its presence and the data colour space of its header are // read (ICC.1, 7.2.6: bytes 16 to 19 of the profile, which starts after METH, PREC and APPROX). + colr.AllowedBoxes++; colr.HasIccProfile = true; colr.IccComponents = length >= 3 + 20 ? IccComponentsOf(ReadUInt32Be(data, offset + 3 + 16)) : null; } @@ -682,7 +705,8 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c // cdef payload: N(2), then N entries of Cn(2) Typ(2) Asoc(2). Typ 0 is an ordinary colour channel; opacity, // premultiplied opacity and unspecified entries are not counted. A box too short for its own N is skipped, so - // the first box long enough is the one read and a file with none is judged by its channel count alone. + // the first box long enough is the one read and a file with none is judged by its channel count alone. Which + // channels the entries cover decides later whether the box is used at all (ColrSurvey.UsableOrdinaryChannels). private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey colr) { if (colr.OrdinaryChannels is not null) @@ -694,10 +718,16 @@ private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey } var entries = ReadUInt16Be(data, offset); var ordinary = new List(); + var described = new HashSet(); for (var i = 0; i < entries; i++) + { + var channel = ReadUInt16Be(data, offset + 2 + 6 * i); + described.Add(channel); if (ReadUInt16Be(data, offset + 2 + 6 * i + 2) == 0) - ordinary.Add(ReadUInt16Be(data, offset + 2 + 6 * i)); + ordinary.Add(channel); + } colr.OrdinaryChannels = ordinary; + colr.DescribedChannels = described; } // ftyp payload: BR(4) MinV(4) then the compatibility list CL(4) each. A file is a JPX file, not only a JP2 file, @@ -722,6 +752,8 @@ private sealed class ColrSurvey { public int Boxes { get; set; } public int Approx1Boxes { get; set; } + public int AllowedBoxes { get; set; } + public List NotAllowed { get; } = []; public bool OtherMethod { get; set; } public List Enumerated { get; } = []; public bool HasIccProfile { get; set; } @@ -735,6 +767,7 @@ private sealed class ColrSurvey public int? IhdrBpc { get; set; } public int[]? CodestreamDepths { get; set; } public List? OrdinaryChannels { get; set; } + public HashSet? DescribedChannels { get; set; } public int? UnnamedColourChannels { get; set; } // A pclr box, or in a JPX file a cmap box alone (ISO/IEC 15444-2:2004, M.5.1.2 numbers the channels by the @@ -744,16 +777,42 @@ private sealed class ColrSurvey // channel count like any other. public bool ChannelsRemapped => HasPalette || (HasCmap && JpxBranded); - // The colour channels are the distinct channels that the type 0 entries of a cdef box name, and never more - // than the image has, or every channel when no readable cdef box says otherwise. ISO/IEC 15444-1, I.5.3.6, - // requires a definition for every colour and puts no bound on the channel number of an entry, so an entry for - // a channel the image lacks is counted like any other, as the definition of one colour; the image cannot hold - // more colour channels than it has channels, hence the cap. A box that names one channel twice has it counted - // once, and a colour with no entry is not counted. - public int ColourChannels(int channels) => - OrdinaryChannels is null ? channels : Math.Min(channels, OrdinaryChannels.Distinct().Count()); + // ISO 32000-2, 7.4.9, limits image data to the JPX baseline set of features except enumerated colour space 19, + // and ISO/IEC 15444-2:2004, M.9.2.4, makes the baseline ask for at least one colour specification from its + // list: an enumerated space of IsAllowedEnumerated or an ICC profile (METH 2 or 3). So a file whose readable + // colr boxes are all outside that list is not valid in a PDF file whatever ColorSpace says, and is refused. + // A box too short to read (under 3 bytes, or METH 1 under 7) is neither: it is not counted either way, so a + // file with only such boxes is not refused here. + public void RefuseNoAllowedColourSpecification() + { + if (AllowedBoxes > 0 || NotAllowed.Count == 0) + return; + var which = NotAllowed.Count == 1 + ? "its only colour specification is " + NotAllowed[0] + : "none of its colour specifications is one that image data may use (" + + string.Join(", ", NotAllowed) + ")"; + throw new InvalidDataException( + $"JP2 file: {which}, and ISO 32000-2, 7.4.9, allows image data in a PDF file only the JPX baseline " + + "set of ISO/IEC 15444-2:2004, M.9.2.4, other than enumerated colour space 19 (CIEJab), CMYK (12) " + + "and an ICC profile, so no ColorSpace makes the file valid."); + } + + // The colour channels, as the class summary of JpxImageLoader states once: the channels that the image has + // and that a type 0 entry of a usable cdef box names, or every channel when there is no usable cdef box. + public List? UsableOrdinaryChannels(int channels) + { + if (OrdinaryChannels is null || DescribedChannels is null) + return null; + for (var channel = 0; channel < channels; channel++) + if (!DescribedChannels.Contains(channel)) + return null; + return OrdinaryChannels; + } - private bool IsColourChannel(int channel) => OrdinaryChannels is null || OrdinaryChannels.Contains(channel); + public int ColourChannels(int channels) => + UsableOrdinaryChannels(channels) is { } ordinary + ? ordinary.Where(c => c < channels).Distinct().Count() + : channels; // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. The depths of a file whose // channels are remapped are not judged, because its colour channels are not read. @@ -766,37 +825,35 @@ public Jp2Findings Findings(int channels) found |= Jp2Findings.ColourMethod; if (UnnamedColourChannels is not (null or 1 or 3 or 4)) found |= Jp2Findings.ColourChannelCount; - return ChannelsRemapped ? found : found | DepthFindings(channels); + if (!ChannelsRemapped && ColourDepthsOf(channels) is { } depths && depths.Distinct().Count() > 1) + found |= Jp2Findings.ColourDepths; + return found; } - // The bit depth is the low 7 bits of a bpcc entry or an Ssiz byte, plus one (the top bit is the sign). Only - // colour channels count: with a cdef box those it marks as type 0, without one every channel. The depths come - // from the bpcc box, else from the codestream when the loader had to read the dimensions from it, else from - // the ihdr box, which holds one depth for all channels. A depth the file gives only in the codestream while - // its ihdr box says otherwise is not compared. - private Jp2Findings DepthFindings(int channels) + // ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive, so a file with a colour channel deeper + // than that is invalid in a PDF file and is refused. + public void RefuseDepthOutsideRange(int channels) { const int MaxDepth = 38; - var found = Jp2Findings.None; + if (!ChannelsRemapped && ColourDepthsOf(channels) is { } depths && depths.Max() > MaxDepth) + throw new InvalidDataException( + $"JP2 file: a colour channel is {depths.Max()} bits deep, and ISO 32000-2, 7.4.9, allows bits " + + "per sample from 1 to 38 inclusive."); + } + + // The bit depth is the low 7 bits of a bpcc entry or an Ssiz byte, plus one (the top bit is the sign). Only + // the colour channels count, as ColourChannels counts them. The depths come from the bpcc box, else from the + // codestream when the loader had to read the dimensions from it, else from the ihdr box, which holds one + // depth for all channels. A depth the file gives only in the codestream while its ihdr box says otherwise is + // not compared. Null when the file gives no depth, or no colour channel. + private int[]? ColourDepthsOf(int channels) + { int[]? perChannel = Bpcc is { } bpcc ? [.. bpcc.Select(b => (b & 0x7F) + 1)] : CodestreamDepths; if (perChannel is null) - { - if (IhdrBpc is { } raw and not 0xFF && (raw & 0x7F) + 1 > MaxDepth && ColourChannels(channels) > 0) - found |= Jp2Findings.ColourDepthRange; - return found; - } - int? first = null; - for (var i = 0; i < perChannel.Length; i++) - { - if (!IsColourChannel(i)) - continue; - if (perChannel[i] > MaxDepth) - found |= Jp2Findings.ColourDepthRange; - first ??= perChannel[i]; - if (perChannel[i] != first) - found |= Jp2Findings.ColourDepths; - } - return found; + return IhdrBpc is { } raw and not 0xFF && ColourChannels(channels) > 0 ? [(raw & 0x7F) + 1] : null; + var ordinary = UsableOrdinaryChannels(channels); + int[] depths = [.. perChannel.Where((_, i) => ordinary is null || ordinary.Contains(i))]; + return depths.Length == 0 ? null : depths; } } @@ -943,8 +1000,8 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa // specification, and the ordinary colour channels have to match its components). // - A device space among the enumerated ones (12, 16, 17): the name this loader has always chosen, // from the last enumerated value or the channel count. - // - Only CIEJab (19) and no ICC profile: refused, since neither a name nor the colr box gives a - // colour space a PDF file may use. + // - No colour specification that a PDF file may use (ColrSurvey.RefuseNoAllowedColourSpecification), CIEJab + // alone among them: refused first, because no ColorSpace makes such a file valid. // - Exactly one colr box that holds an ICC profile or an enumerated value, and names no device // space: left out. A device name would make a reader take the samples as device samples. The colour // channels must still have as many components as that space (CheckLoneSpace). @@ -955,22 +1012,17 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa // A name is written only where the channels fit it; see FitChannels. private static ImageColorSpace? ColorSpaceOf(int channels, bool channelsFromSiz, int? colrEnum, ColrSurvey colr) { + colr.RefuseNoAllowedColourSpecification(); if (colr.Enumerated.Exists(e => e is ColrEnumCmyk or ColrEnumSRgb or ColrEnumGreyscale)) return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, colr.Enumerated.Contains(ColrEnumCmyk)); - if (colr.Enumerated.Count > 0 && !colr.HasIccProfile && colr.Enumerated.TrueForAll(e => e == ColrEnumCieJab)) - throw new InvalidDataException( - "JP2 file: its only colour specification is enumerated colour space 19 (CIEJab), which " + - "a PDF image XObject may not use (ISO 32000-2, 7.4.9), and it has no ICC profile."); if (colr.Boxes == 1 && (colr.HasIccProfile || colr.Enumerated.Count == 1)) return LoneSpace(channels, channelsFromSiz, colrEnum, colr); return FitChannels(InferColorSpace(channels, colrEnum), channels, channelsFromSiz, colr, false); } - // The one colr box of a file names an ICC profile or an enumerated space other than 12, 16 and 17. Three cases: - // - The space is outside what ISO 32000-2, 7.4.9, lets image data use (an enumerated value that is not in the - // JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, and is not 12): refused, whatever the channels are, because - // no ColorSpace makes such a file valid. This holds for a file with a palette too. + // The one colr box of a file names an ICC profile or an enumerated space other than 12, 16 and 17, and is a space + // that image data may use (RefuseNoAllowedColourSpecification has refused the others). Two cases: // - The colour channels, counted as in FitChannels, have as many components as the space, or the space has no // count here (an ICC profile whose header cannot be read or names no listed space, an enumerated value // without a count): ColorSpace is left out so the colour specification of the file decides (7.4.9: with no @@ -985,11 +1037,6 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa // A file whose channels are remapped (ChannelsRemapped) has its colour channels unread and is left out as well. private static ImageColorSpace? LoneSpace(int channels, bool channelsFromSiz, int? colrEnum, ColrSurvey colr) { - if (!colr.HasIccProfile && !IsBaselineEnumerated(colr.Enumerated[0])) - throw new InvalidDataException( - $"JP2 file: its only colour specification is enumerated colour space {(uint)colr.Enumerated[0]}, " + - "which is not in the JPX baseline set of ISO/IEC 15444-2:2004, M.9.2.4, and is not CMYK (12), so " + - "image data that uses it is not allowed in a PDF file (ISO 32000-2, 7.4.9)."); if (colr.ChannelsRemapped) return null; var colour = colr.ColourChannels(channels); @@ -1012,19 +1059,16 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa "space)."); } - // The enumerated colour spaces of the JPX baseline set (ISO/IEC 15444-2:2004, M.9.2.4): sRGB (16), sRGB-grey (17), - // ROMM-RGB (21), sYCC (18), e-sRGB (20), e-sYCC (24), CIELab (14) and CIEJab (19; 7.4.9 excludes it, and a file - // whose only colour specification is 19 is refused before this is asked). CMYK (12) is allowed by 7.4.9 on its - // own and does not reach this check. - private static bool IsBaselineEnumerated(int value) => - value is ColrEnumSRgb or ColrEnumGreyscale or ColrEnumCieJab or 14 or 18 or 20 or 21 or 24; + // The enumerated colour spaces that image data in a PDF file may use: those of the JPX baseline set (ISO/IEC + // 15444-2:2004, M.9.2.4: sRGB 16, sRGB-grey 17, ROMM-RGB 21, sYCC 18, e-sRGB 20, e-sYCC 24, CIELab 14 and CIEJab + // 19) except CIEJab, which ISO 32000-2, 7.4.9, excludes, and CMYK (12), which 7.4.9 adds. + private static bool IsAllowedEnumerated(int value) => + value is ColrEnumCmyk or ColrEnumSRgb or ColrEnumGreyscale or 14 or 18 or 20 or 21 or 24; // Checks the name chosen above against the colour channels (ISO 32000-2, 7.4.9: the ordinary colour channels - // shall match the components of the colour space). With a cdef box they are the distinct channels it marks - // as type 0. Without one they are every channel: ISO/IEC 15444-1, I.5.3.6, makes the box mandatory when a - // codestream holds anything but colour channels in colour order. The name must have exactly that many - // components, and a colr box that names CMYK may supply DeviceCMYK for four. Otherwise the file is invalid and - // refused. A file whose channels are remapped (ChannelsRemapped) keeps the name unchecked. + // shall match the components of the colour space), which the class summary defines. The name must have exactly + // that many components, and a colr box that names CMYK may supply DeviceCMYK for four. Otherwise the file is + // invalid and refused. A file whose channels are remapped (ChannelsRemapped) keeps the name unchecked. private static ImageColorSpace FitChannels( ImageColorSpace named, int channels, bool channelsFromSiz, ColrSurvey colr, bool cmykBox) { @@ -1048,9 +1092,12 @@ private static ImageColorSpace FitChannels( // the loader could not see. private static string WhyChannels(int channels, bool channelsFromSiz, ColrSurvey colr, int colour) { - if (colr.OrdinaryChannels is not null) + if (colr.UsableOrdinaryChannels(channels) is not null) return $"its cdef box marks {colour} ordinary colour channels"; var source = channelsFromSiz ? "codestream has" : "ihdr box has"; + if (colr.OrdinaryChannels is not null) + return $"its {source} {channels} channels and a cdef box that does not describe every one of them, " + + "so the box is not used and every channel is a colour channel"; if (colr.HasCompositingLayerHeader) return $"its {source} {channels} channels and no cdef box in its jp2h box, and the jplh box, which may " + "define them, is not written with the file, so every one is a colour channel in the file written"; diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 5a8986584..982cb358b 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -304,25 +304,24 @@ public LayoutImage(PdfImageXObject image) /// exception type and message, and the loader's documentation is where to read it. A JPEG is /// passed through as /DCTDecode, never decoded or re-encoded. The format is read from /// the data, not from a file name. - /// JPEG and JPEG 2000 data that cannot be written as a valid image is refused with - /// , the exception of the loader that reads it. For a JPEG - /// (or a JPEG strip of a TIFF) the refused set is a frame type other than SOF0, SOF1 and SOF2, - /// a precision other than 8 bits, and a component count other than 1, 3 and 4 - /// (). For JPEG 2000 it is a codestream whose - /// Rsiz requires a Part 2 capability outside the JPX baseline set or sets bit 14 - /// (extended capabilities through a CAP marker), a bare codestream or a JP2 file with no - /// jp2h box whose channel count is not 1, 3 or 4, a JP2 file with a jp2h box whose colour channels - /// (the distinct channels that the type 0 entries of its cdef box name, or every channel when there is no - /// cdef box) are not as many as the components of the device colour space the loader would write, a JP2 - /// file whose only colour specification is CIEJab, and one whose only colour specification is an enumerated - /// colour space outside the JPX baseline set other than CMYK ( lists the - /// cases). A JP2 file with exactly one colr box that names an ICC profile or an enumerated colour space - /// that is not sRGB, greyscale or CMYK, such as sYCC, is written with no /ColorSpace, so the colour + /// These JPEG and JPEG 2000 inputs are refused with , the + /// exception of the loader that reads them. For a JPEG (or a JPEG strip of a TIFF) the refused set is a frame + /// type other than SOF0, SOF1 and SOF2, a precision other than 8 bits, and a component count other than 1, 3 and 4 + /// (). For JPEG 2000 it is a codestream whose Rsiz requires a + /// Part 2 capability outside the JPX baseline set or sets bit 14 (extended capabilities through a CAP marker); a + /// bare codestream or a JP2 file with no jp2h box whose channel count is not 1, 3 or 4; a JP2 file with a + /// jp2h box whose colour channels, as defines them, are not as many as the + /// components of the colour space it would write; a JP2 file none of whose readable colr boxes is an + /// allowed colour specification (an ICC profile, CMYK, or an enumerated space of the JPX baseline list other + /// than CIEJab); and a JP2 file with a colour channel deeper than 38 bits + /// ( lists the cases). Nothing else is promised to be refused. + /// The loaders do not check every requirement of ISO 32000-2, 7.4.9: a JP2 file with no colr box, for + /// one, is written. A JP2 file with exactly one colr box that names an ICC profile or an enumerated colour + /// space that is not sRGB, greyscale or CMYK, such as sYCC, is written with no /ColorSpace, so the colour /// specification in the file decides, when its colour channels are as many as the components of that space, and /// otherwise with the device name the channel count chooses if that name has as many components as the colour - /// channels; with neither it is refused. A JP2 - /// file whose colour channels differ in bit depth, or whose colour specifications PDF/A-2 does - /// not allow, is not refused; the save reports it as + /// channels; with neither it is refused. A JP2 file whose colour channels differ in bit depth, or whose colour + /// specifications PDF/A-2 does not allow, is not refused; the save reports it as /// under a PDF/A-2 claim. /// Two kinds of data have no signature to read and are not loaded here. A JBIG2 stream in /// the embedded form used inside a PDF starts straight at its first segment, and CCITT Group 3 diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 7ce48c5bf..c16024392 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -337,9 +337,8 @@ public enum LayoutDiagnosticCode /// A JPEG 2000 image of a JP2 file was drawn in a document whose conformance is PDF/A-2b, /// PDF/A-2u or PDF/A-2a, and the file has more than one colour specification and not exactly one /// with an APPROX of 1, or a colour specification whose METH is not 1, 2 or 3, or colour channels - /// of different bit depths, or a colour channel whose bit depth is outside 1 to 38, or, for a file - /// written with no ColorSpace, a number of colour channels other than 1, 3 or 4. Each distinct - /// element and finding is one item. The message names the + /// of different bit depths, or, for a file written with no ColorSpace, a number of colour channels + /// other than 1, 3 or 4. Each distinct element and finding is one item. The message names the /// image by its size in pixels and quotes no alternative text; /// , and /// say where it is. @@ -349,18 +348,17 @@ public enum LayoutDiagnosticCode /// , requires exactly one colour specification with an APPROX /// of 1 when there are several, a METH of 1, 2 or 3, 1, 3 or 4 colour channels, and one bit depth, /// from 1 to 38, for all the colour channels. ISO 32000-2, 7.4.9, requires none of the first four, so - /// writes such a file and the save reports it; it does limit bits - /// per sample to 1 through 38, so a file with a deeper colour channel is invalid under both and is reported too. The - /// report follows the text of 6.2.8.3, which does not depend on the image dictionary having a - /// ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules only where the - /// dictionary has no ColorSpace, and it also fails channels that differ only in sign or - /// that are counted with an opacity channel, which the text does not. The depths compared are - /// those of the colour channels, the entries of type 0 of the cdef box or every channel - /// when there is none, and a file with a palette is not compared because its colour channels are - /// not read. A file written with a device name has 1, 3 or 4 colour channels already, so the count - /// is reported only for a file written with no ColorSpace. The depths come from the - /// bpcc box, else from the codestream when the loader took the dimensions from it, else from - /// the ihdr box. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. + /// writes such a file and the save reports it. It does limit + /// bits per sample to 1 through 38, so the loader refuses a file with a deeper colour channel before any + /// save and the save never reports it. The report follows the text of 6.2.8.3, which does not depend on the + /// image dictionary having a ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules + /// only where the dictionary has no ColorSpace, and it also fails channels that differ only in sign + /// or that are counted with an opacity channel, which the text does not. The colour channels are those + /// that defines, and a file with a palette is not compared + /// because its colour channels are not read. A file written with a device name has 1, 3 or 4 colour + /// channels already, so the count is reported only for a file written with no ColorSpace. The depths + /// come from the bpcc box, else from the codestream when the loader took the dimensions from it, else + /// from the ihdr box. Without a PDF/A claim, and under PDF/UA-1, nothing is reported. /// Do not pass such a file to a PDF/A document: /// alone passes it through unreported, 3.0 will refuse it where the image is created, and #474 /// tracks the loaders' own report. An image that a custom renderer registers itself is not diff --git a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs index e94aa312b..74bac78a3 100644 --- a/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs +++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs @@ -39,7 +39,5 @@ void Report(int key, string what) => sink.Report( Report(2, "has colour channels of different bit depths; PDF/A-2 allows one depth for all colour channels."); if (image.Jp2Findings.HasFlag(Jp2Findings.ColourChannelCount)) Report(3, "has a number of colour channels other than 1, 3 or 4; PDF/A-2 allows only those."); - if (image.Jp2Findings.HasFlag(Jp2Findings.ColourDepthRange)) - Report(4, "has a colour channel whose bit depth is outside 1 to 38; PDF/A-2 allows only that range."); } } diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs index 40573752c..70973b528 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -898,8 +898,12 @@ public void Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsBesideGreyscaleIsRefusedAndO private static Kind ApproxKind() => new("jp2-approx", Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(2, 0), (1, 18)]), 16, 16, "DeviceRGB", 8, "JPXDecode"); - /// A JP2 file of three channels with one colr box whose method is 7. - private static Kind MethodKind() => new("jp2-meth", Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(7, 0)]), 16, 16, + /// + /// A JP2 file of three channels with a colr box whose method is 7 and an sRGB box with an APPROX of 1, so that the + /// method is the only finding and the file has an allowed colour specification. + /// + private static Kind MethodKind() => new("jp2-meth", + Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: [[7, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 16]]), 16, 16, "DeviceRGB", 8, "JPXDecode"); private static LayoutDocumentType DocumentWith(PdfConformance claim, Kind kind, string? alt = "scan") diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index a9c5adc5e..d086db6ba 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -341,27 +341,100 @@ public void Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndIts // ── Which lone colr boxes lose the name ────────────────────────────────────────────────── + // ISO 32000-2, 7.4.9, limits image data to the JPX baseline set except enumerated colour space 19, and ISO/IEC + // 15444-2:2004, M.9.2.4, asks of it a colour specification from a list that holds no vendor method. A file whose + // readable colr boxes are none of an ICC profile, an enumerated space of that list other than 19, or CMYK is + // refused, whatever the channel count and the ColorSpace are. [Theory] [InlineData(1, 4, 0)] // a lone vendor colour box (method 4) [InlineData(3, 4, 0)] + [InlineData(4, 4, 0)] [InlineData(3, 7, 0)] // a method the loader does not read - public void Iso32000_2_7_4_9_ALoneColourBoxThatIsNotAnIccProfileOrAnEnumeratedSpaceKeepsTheName(int channels, int method, - int value) + [InlineData(1, 0, 0)] + [InlineData(4, 255, 0)] + public void Iso32000_2_7_4_9_ALoneVendorOrReservedColourBoxIsRefused(int channels, int method, int value) { var jp2 = Jp2Of(channels, null, boxes: [(method, value)]); - Assert.Equal(channels == 1 ? "DeviceGray" : "DeviceRGB", ColourSpaceWritten(jp2)); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"its only colour specification is a vendor or reserved colour specification (method {method})", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + Assert.Throws(() => ImageFile(PdfConformance.None, + new Kind("jp2", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))); + // A palette does not change that: it says nothing about the colour specification. + Assert.Throws(() => JpxImageLoader.Load(Jp2Of(channels, null, palette: true, + boxes: [(method, value)]))); + } + + [Fact] + public void Iso32000_2_7_4_9_AReservedMethodBoxOfThreeBytesIsAColourSpecificationAndIsRefused() + { + // Three bytes are the least a colr box needs to be read (METH, PREC, APPROX); METH 9 is no allowed method. + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: [[9, 0, 0]]); + Assert.Contains("method 9", Assert.Throws(() => JpxImageLoader.Load(jp2)).Message); } [Theory] [InlineData(new byte[] { 1, 0 })] // under 3 bytes [InlineData(new byte[] { 1, 0, 0, 0, 0 })] // method 1 with an enumerated value cut short - [InlineData(new byte[] { 9, 0, 0 })] // a method the loader does not read - public void Iso32000_2_7_4_9_AMalformedLoneColourBoxKeepsTheName(byte[] payload) + public void Iso32000_2_7_4_9_AColourBoxTooShortToReadIsNoColourSpecificationOfEitherKindAndKeepsTheName(byte[] payload) { + // The box cannot be told from an allowed one, so a file with only such boxes is not refused for them. var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: [payload]); Assert.Equal("DeviceRGB", ColourSpaceWritten(jp2)); } + // A colour specification list as "method:value" pairs in file order. + private static (int, int)[] ColourBoxList(string boxes) => [.. boxes.Split(',').Select(b => + (int.Parse(b.Split(':')[0], System.Globalization.CultureInfo.InvariantCulture), + int.Parse(b.Split(':')[1], System.Globalization.CultureInfo.InvariantCulture)))]; + + [Theory] + [InlineData("1:1,1:3")] // two reserved values + [InlineData("1:19,1:19")] // CIEJab twice + [InlineData("1:19,4:0")] // CIEJab and a vendor box + [InlineData("4:0,4:0")] + [InlineData("4:0,1:1")] + [InlineData("1:22,1:23,1:25")] // values beside the baseline list, none on it + [InlineData("1:13,7:0")] // 13 and a reserved method + public void Iso32000_2_7_4_9_AFileWhoseColourBoxesAreNoneOfThemAnAllowedSpaceIsRefusedAtEveryChannelCount(string boxes) + { + var colr = ColourBoxList(boxes); + foreach (var channels in new[] { 1, 3, 4 }) + { + var jp2 = Jp2Of(channels, null, boxes: colr); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains("none of its colour specifications is one that image data may use", e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + Assert.Throws(() => JpxImageLoader.Load(Jp2Of(channels, null, palette: true, boxes: colr))); + } + } + + [Theory] + [InlineData("4:0,2:0", 3)] // a vendor box and an ICC profile + [InlineData("4:0,3:0", 1)] + [InlineData("4:0,1:12", 4)] // CMYK is allowed + [InlineData("1:1,1:16", 3)] + [InlineData("1:19,1:14", 3)] // CIEJab beside CIELab + [InlineData("1:19,2:0", 1)] + [InlineData("1:22,1:24", 3)] // the baseline list ends at 24 + [InlineData("7:0,1:17", 1)] + public void Iso32000_2_7_4_9_AFileWithOneAllowedColourBoxBesideOthersIsNotRefusedForTheOthers(string boxes, int channels) + { + // The channel count is one that the name written has the components for, so only the colour boxes are in question. + Assert.NotNull(JpxImageLoader.Load(Jp2Of(channels, null, boxes: ColourBoxList(boxes)))); + } + + [Fact] + public void Iso32000_2_7_4_9_AColourBoxTooShortToReadBesideAVendorBoxStillLeavesNoAllowedSpace() + { + // The short box is no colour specification, so the vendor box is the only one: refused. + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(4, 0)], rawColr: [[1, 0]]); + Assert.Contains("its only colour specification is a vendor", + Assert.Throws(() => JpxImageLoader.Load(jp2)).Message); + // Beside an allowed box it is nothing at all. + Assert.Equal("DeviceRGB", ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, 3), 3, 16, rawColr: [[1, 0]]))); + } + // ── The report quotes no caller text (M4) and covers a band logo (L1) ──────────────────── [Fact] @@ -554,7 +627,7 @@ public void Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpac { var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, null, boxes: [(1, enumerated)]); var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); - Assert.Contains($"only colour specification is enumerated colour space {shown}, which is not in the JPX baseline", e.Message); + Assert.Contains($"only colour specification is enumerated colour space {shown}, and ISO 32000-2, 7.4.9, allows", e.Message); Assert.Throws(() => LayoutImage.FromBytes(jp2)); } var palette = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, enumerated)], palette: true); @@ -740,40 +813,93 @@ public void Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourCha [InlineData(1, 17, new[] { 0, 0 }, "DeviceGray")] [InlineData(3, 12, new[] { 0, 1, 2, 2 }, "DeviceRGB")] // three distinct, a CMYK box: not four [InlineData(1, 12, new[] { 0, 1, 2, 3 }, "DeviceGray")] // four entries for a one-channel image: capped at one - [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks: capped at three - [InlineData(3, 16, new[] { 0, 1, 9 }, "DeviceRGB")] // one definition per colour, the last naming a channel the image lacks - [InlineData(3, 16, new[] { 7, 8, 9 }, "DeviceRGB")] // three definitions, none of a channel the image has + [InlineData(3, 16, new[] { 0, 0, 1, 2 }, "DeviceRGB")] // channel 0 twice before the last distinct one + [InlineData(3, 16, new[] { 0, 1, 1, 2, 2, 2 }, "DeviceRGB")] + [InlineData(1, 12, new[] { 0, 0, 0 }, "DeviceGray")] + [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks is ignored + [InlineData(3, 16, new[] { 0, 1, 9 }, "DeviceRGB")] // channel 2 undescribed: the box is not used, every channel counts + [InlineData(3, 16, new[] { 7, 8, 9 }, "DeviceRGB")] // no entry describes a channel the image has [InlineData(1, 17, new[] { 4 }, "DeviceGray")] - public void Iso32000_2_7_4_9_ACdefBoxCountsDistinctColourChannelsUpToTheChannelCount(int channels, int enumerated, - int[] colourEntries, string name) + public void Iso32000_2_7_4_9_ACdefBoxCountsTheDistinctChannelsItNamesAndIgnoresEntriesForChannelsTheImageLacks(int channels, + int enumerated, int[] colourEntries, string name) { - // ISO/IEC 15444-1, I.5.3.6, does not allow one (Typ, Asoc) pair twice, requires a definition for every colour and - // puts no bound on Cn. The loader counts the distinct channels the type 0 entries name, at most the channel - // count, so an entry for a channel the image lacks still defines its colour (the file is not shown invalid) - // while no name is written whose components differ from that number. + // The reading is stated once on JpxImageLoader: a type 0 entry counts its channel once, however many entries + // name it, and an entry for a channel the image does not have describes nothing. Rows with a repeated channel + // before the last distinct one tell this count from one that stops at the first as many entries as there are + // channels. var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); } [Theory] [InlineData(1, 16, new[] { 0, 1, 2 }, 1)] // one channel cannot hold three colours, whatever the entries say - [InlineData(4, 12, new[] { 0, 1, 2, 2 }, 3)] // channel 2 twice leaves three definitions, not the four CMYK has - [InlineData(3, 16, new[] { 0, 1 }, 2)] // no definition for the third colour - [InlineData(3, 18, new[] { 0, 1 }, 2)] // the lone-sYCC path counts the same way - [InlineData(4, 12, new[] { 0, 1, 9 }, 3)] - public void Iso32000_2_7_4_9_ACdefBoxWhoseDistinctColourChannelsAreTooFewIsRefused(int channels, int enumerated, - int[] colourEntries, int distinct) + [InlineData(2, 17, new[] { 0, 1, 7 }, 2)] // greyscale over two described colour channels + public void Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelButMarksTheWrongNumberOfColourChannelsIsRefused(int channels, + int enumerated, int[] colourEntries, int colour) { + // Every channel the image has is named by a type 0 entry, so the box is used and its entries decide. var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef); var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); - Assert.Contains($"its cdef box marks {distinct} ordinary colour channels", e.Message); + Assert.Contains($"its cdef box marks {colour} ordinary colour channels", e.Message); + } + + [Theory] + [InlineData(4, 12, new[] { 0, 1, 2, 2 }, "DeviceCMYK")] // channel 3 undescribed: four colour channels, a CMYK box + [InlineData(3, 16, new[] { 0, 1 }, "DeviceRGB")] // channel 2 undescribed: three colour channels + [InlineData(4, 12, new[] { 0, 1, 9 }, "DeviceCMYK")] + [InlineData(3, 12, new[] { 0 }, "DeviceRGB")] + public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsNotUsedAndEveryChannelIsAColourChannel(int channels, + int enumerated, int[] colourEntries, string name) + { + // I.5.3.6 asks for a complete list; the box is not used, as if it were absent, and the file is not refused for it. + var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); + Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); + } + + [Theory] + [InlineData(4, 16, new[] { 0, 1, 2 })] // RGB over four channels, the fourth undescribed: four colour channels, DeviceRGB has three + [InlineData(2, 17, new[] { 0 })] + public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedCountsEveryChannelAndTheNameMustHaveThatMany(int channels, + int enumerated, int[] colourEntries) + { + var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); + var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef); + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains($"its ihdr box has {channels} channels and a cdef box that does not describe every one of them, so " + + "the box is not used and every channel is a colour channel", e.Message); + } + + [Theory] + [InlineData(65535)] + [InlineData(4)] + [InlineData(0)] + public void Iso32000_2_7_4_9_AnEntryForAChannelTheImageLacksBesideAnOpacityChannelDefinesNoColour(int asoc) + { + // Every colour already has an entry in range, so an extra type 0 entry for channel 9 (or 5) is ignored: the + // colour channels are still three (one for grey), and the name written is the one the box names. + byte[] codestream4 = JpxCodestream(16, 16, 4); + var rgba = Jp2File(codestream4, 4, 16, cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 1, 0), (9, 0, asoc)]); + Assert.Equal("DeviceRGB", ColourSpaceWritten(rgba)); + var graya = Jp2File(JpxCodestream(16, 16, 2), 2, 17, cdef: [(0, 0, 1), (1, 1, 0), (5, 0, asoc)]); + Assert.Equal("DeviceGray", ColourSpaceWritten(graya)); + var five = Jp2File(JpxCodestream(16, 16, 5), 5, 16, cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 1, 0), (4, 0xFFFF, 0xFFFF), + (9, 0, asoc), (10, 0, asoc == 0 ? 0xFFFF : 0)]); + Assert.Equal("DeviceRGB", ColourSpaceWritten(five)); + // A lone sYCC box or an ICC profile of three colours beside the same box: no ColorSpace, three colour channels. + var sycc = Jp2File(codestream4, 4, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 1, 0), (9, 0, asoc)]); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc-extra", sycc, 16, 16, "DeviceRGB", 8, "JPXDecode"))) + .Dict.Get(N("ColorSpace"))); + // No colr box: the name the four channels choose has four components, the colour channels are three: refused. + var nocolr = Jp2File(codestream4, 4, null, cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 1, 0), (9, 0, asoc)]); + Assert.Contains("its cdef box marks 3 ordinary colour channels", + Assert.Throws(() => JpxImageLoader.Load(nocolr)).Message); } [Fact] public void Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace() { - // Three definitions, one naming a channel the image lacks: three colour channels, sYCC has three. + // Channel 2 is undescribed, so the box is not used: three channels, three colour channels, and sYCC has three. var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (9, 0, 3)]); Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc-cdef", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))) .Dict.Get(N("ColorSpace"))); @@ -801,27 +927,49 @@ public void Iso32000_2_7_4_9_TheMessageForAJpxFileWithACompositingLayerHeaderSay // ── Depths: the range 1 to 38, and the codestream's own depths where the loader reads the dimensions from it ─ [Fact] - public void Iso19005_2_6_2_8_3_AColourChannelOfMoreThanThirtyEightBitsIsReported() + public void Iso32000_2_7_4_9_AColourChannelOfMoreThanThirtyEightBitsIsRefusedInEveryDocument() { - // ISO 19005-2, 6.2.8.3, allows a bit depth of 1 to 38 (ISO/IEC 15444-1, Table I.6 gives the field 7 bits and - // a value of one less). 38 bits passes; 39 does not, from a bpcc box, an ihdr box, or the codestream. - foreach (var (depths, reported) in new[] { (38, false), (39, true), (49, true) }) - { - var bpcc = Jp2File(JpxCodestream(16, 16, 3), 3, 16, [(byte)(depths - 1), (byte)(depths - 1), (byte)(depths - 1)]); - var ihdr = Jp2File(JpxCodestream(16, 16, 3, depths - 1), 3, 16); - ihdr[ihdr.AsSpan().IndexOf("ihdr"u8) + 4 + 8 + 2] = (byte)(depths - 1); - var bare = JpxCodestream(16, 16, 3, depths - 1); - var noJp2h = Jp2File(JpxCodestream(16, 16, 1, depths - 1), 1, null, noJp2h: true); - foreach (var bytes in new[] { bpcc, ihdr, bare, noJp2h }) + // ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive (ISO/IEC 15444-1, Table I.6 gives the + // field 7 bits and a value of one less). 38 bits passes; 39 does not, from a bpcc box, an ihdr box, or the + // codestream, at one, three and four channels, and the Kernel and Layout loaders both refuse it. + foreach (var channels in new[] { 1, 3, 4 }) + foreach (var depth in new[] { 38, 39, 49, 128 }) { - using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-depth", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode")); - Save(doc); - var items = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).ToArray(); - Assert.Equal(reported, items.Length == 1); - if (reported) - Assert.Contains("a colour channel whose bit depth is outside 1 to 38", items[0].Message); + var enumerated = channels == 1 ? 17 : channels == 4 ? 12 : 16; + var each = (byte)(depth - 1); + var bpcc = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, [.. Enumerable.Repeat(each, channels)]); + var ihdr = Jp2File(JpxCodestream(16, 16, channels, depth - 1), channels, enumerated); + ihdr[ihdr.AsSpan().IndexOf("ihdr"u8) + 4 + 8 + 2] = each; + var bare = JpxCodestream(16, 16, channels, depth - 1); + var noJp2h = Jp2File(JpxCodestream(16, 16, channels, depth - 1), channels, null, noJp2h: true); + var noIhdr = Jp2File(JpxCodestream(16, 16, channels, depth - 1), channels, enumerated, noIhdr: true); + foreach (var bytes in new[] { bpcc, ihdr, bare, noJp2h, noIhdr }) + { + if (depth == 38) + { + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(bytes).Jp2Findings); + continue; + } + var e = Assert.Throws(() => JpxImageLoader.Load(bytes)); + Assert.Contains($"a colour channel is {depth} bits deep, and ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38", + e.Message); + Assert.Throws(() => LayoutImage.FromBytes(bytes)); + } } - } + } + + [Fact] + public void Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChannelsAndOnFilesWhoseChannelsAreRead() + { + // bpcc 8, 8, 8 and 49 bits, with a cdef box that makes the fourth an opacity channel: only colour channels count. + var opacity = Jp2File(JpxCodestream(16, 16, 4), 4, 16, [7, 7, 7, 0x30], cdef: Channels(3, 1)); + Assert.NotNull(JpxImageLoader.Load(opacity)); + // A cdef box that leaves channel 3 undescribed is not used, so every channel is a colour channel. + var undescribed = Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 7, 0x30], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); + Assert.Contains("49 bits deep", Assert.Throws(() => JpxImageLoader.Load(undescribed)).Message); + // A palette changes which stored components are colour channels, and the palette is not read. + var palette = Jp2File(JpxCodestream(16, 16, 1), 1, 16, [0x30], palette: true); + Assert.NotNull(JpxImageLoader.Load(palette)); } [Fact] @@ -863,8 +1011,10 @@ public void Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamS [InlineData(7)] public void Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported(int method) { - // METH 4 is a vendor colour specification, which 6.2.8.3 does not allow; so is any other value outside 1 to 3. - var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(method, 0)]); + // METH 4 is a vendor colour specification, which 6.2.8.3 does not allow; so is any other value outside 1 to 3. A + // file with only such a box is refused (7.4.9), so an sRGB box with an APPROX of 1 stands beside it, and the + // method is the only finding. + var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, rawColr: [[(byte)method, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 16]]); using var doc = DocumentWith(PdfConformance.PdfA2b, new Kind("jp2-meth", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode")); Save(doc); Assert.Contains("method is not 1, 2 or 3", From b606e47b47c5272f7b84f36bd7ac074ffa0b75c8 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 19:54:33 +0100 Subject: [PATCH 19/22] fix(images): an incomplete cdef box keeps a name that fits either colour count A cdef box that leaves a channel undescribed has two defensible counts, the channels its type 0 entries name and every channel, because ISO/IEC 15444-1, I.5.3.6, asks for a complete list and does not define the word. The loader keeps the name when it has as many components as either count and refuses only when it fits neither, so the box creates no refusal. A depth over 38 bits is refused only for a channel the box names. --- CHANGELOG.md | 6 +-- docs/conformance-v2.4.md | 2 +- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 54 ++++++++++++------- .../ConformanceAuditG4Tests.JpxChannels.cs | 49 ++++++++++++----- 4 files changed, 76 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b99c5e4e7..3cf2c277b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1033,9 +1033,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). whose name has as many components as it has colour channels, or that has a palette, writes the same bytes as before, and so does a JP2 file with one `colr` box that is not a device space where the name the channel count chooses has as many components as the colour channels. A `cdef` box - that leaves a channel undescribed is not used, so a file that main wrote with a name of fewer - components than its channels, beside such a box, is refused (an sRGB file of four channels whose - `cdef` box describes channels 0 to 2 is one). + that leaves a channel undescribed has two counts, and the file is refused only when main's name + fits neither (as the `JpxImageLoader` documentation states), so no such file that main wrote + with a name fitting either count changes. - **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index c2bfb8dc8..fef823482 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -399,7 +399,7 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.7 | An image XObject uses page 1 of the JBIG2 stream only | IMG (JBIG2) | gap #621: a page whose segments are associated with page 2 keeps that association | `Iso32000_2_7_4_7_PinsTodayAJbig2PageKeepsTheAssociationItsSourceGaveIt`, `Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne` (skipped) | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | The data has one, three or four colour components (32000-1 also allows two) | IMG (JPEG) | fixed (#763): a frame of another component count is refused. Compliant for 1, 3 and 4, where the loader writes the colour space of that count, passes the bytes through and writes no Decode and no DecodeParms | `Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies`, `Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused`, `Iso32000_2_7_4_8_AJpegOfAnAcceptedFrameWithOneThreeOrFourComponentsIsPassedThroughByteForByte` | | ISO 32000-1 7.4.8; ISO 32000-2 7.4.8 | DCTDecode decodes baseline JPEG and the progressive extension | IMG (JPEG) | fixed (#763): a frame type other than SOF0, SOF1 and SOF2 (SOF3 lossless, SOF9 arithmetic and the others) is refused. The row rests on the clause's description of the filter, which binds readers; no writer "shall" was found. Compliant for baseline and progressive | `Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt`, `Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode` | -| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels as the `JpxImageLoader` class summary defines them (ISO/IEC 15444-1 I.5.3.6; that reading is stated there once) and is refused unless the device name has that many components. A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when the colour channels have as many components as that space (an enumerated space by the colour model it names in ISO/IEC 15444-2:2004 Table M.25, which names the models of sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference and states no count; an ICC profile by the data colour space of its header, ICC.1 Table 19); where they do not, it keeps the name the channel count chooses when that name has as many components as the colour channels (the bytes written before; no sentence of 15444-1:2024 Annex I ties the channel count to the colour space where there is no cdef box) and is refused when no such name exists. A file none of whose readable colr boxes is an allowed colour specification is refused, whatever the channels are (see the next row). One with two or more colr boxes of which one is allowed, and none a device space, keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), is not checked against its channel count; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. An ICC profile whose header cannot be read, or whose colour space Table 19 does not list, is not compared. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents`, `Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes`, `Iso32000_2_7_4_9_ACdefBoxCountsTheDistinctChannelsItNamesAndIgnoresEntriesForChannelsTheImageLacks`, `Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelButMarksTheWrongNumberOfColourChannelsIsRefused`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsNotUsedAndEveryChannelIsAColourChannel`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedCountsEveryChannelAndTheNameMustHaveThatMany`, `Iso32000_2_7_4_9_AnEntryForAChannelTheImageLacksBesideAnOpacityChannelDefinesNoColour`, `Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | +| ISO 32000-1 7.4.9, ColorSpace; ISO 32000-2 7.4.9, Table 87 | The number of ordinary colour channels in the JPEG 2000 data matches the colour space, and the writer ensures the samples are consistent with it; a JPX image may omit ColorSpace and BitsPerComponent | IMG (JPX) | fixed (#763): a bare codestream or a JP2 file with no jp2h of a channel count other than 1, 3 or 4 is refused. A JP2 file with a jp2h counts the colour channels as the `JpxImageLoader` class summary defines them (ISO/IEC 15444-1 I.5.3.6; that reading is stated there once) and is refused unless the device name has that many components. A CMYK colr box with four colour channels is written as DeviceCMYK. A JP2 file with exactly one colr box that holds an ICC profile or names an enumerated space that is not sRGB, greyscale or CMYK is written with no ColorSpace when the colour channels have as many components as that space (an enumerated space by the colour model it names in ISO/IEC 15444-2:2004 Table M.25, which names the models of sYCC, e-sRGB, ROMM-RGB and e-sYCC by reference and states no count; an ICC profile by the data colour space of its header, ICC.1 Table 19); where they do not, it keeps the name the channel count chooses when that name has as many components as the colour channels (the bytes written before; no sentence of 15444-1:2024 Annex I ties the channel count to the colour space where there is no cdef box) and is refused when no such name exists. A file none of whose readable colr boxes is an allowed colour specification is refused, whatever the channels are (see the next row). One with two or more colr boxes of which one is allowed, and none a device space, keeps the name. A pclr box, or a cmap box without pclr in a file whose ftyp names the JPX brand (M.5.1.2 numbers channels by the cmap entries; no sentence of M.11.5 or M.11.6 ties the box to a palette), is not checked against its channel count; in a JP2 file a cmap box without pclr is not allowed (15444-1 I.5.3.4) and the file is judged by its channel count. An ICC profile whose header cannot be read, or whose colour space Table 19 does not list, is not compared. BitsPerComponent is compliant (written for 1, 2, 4, 8, 16, omitted for 12) | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName`, `Iso19005_2_6_2_8_3_ABareCodestreamOfTwoFiveOrSixteenChannelsIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithNoCdefBoxWhoseChannelCountIsNotTheNamesComponentCountIsRefused`, `Iso32000_2_7_4_9_AJp2FileWhoseChannelCountIsTheNamesComponentCountKeepsTheName`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksAsManyColourChannelsAsTheNameHasIsWritten`, `Iso32000_2_7_4_9_AJp2FileWhoseCdefBoxMarksColourChannelsNoNameTakesIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithAPaletteKeepsTheNameWhateverItsChannelCount`, `Iso19005_2_6_2_8_3_AJp2FileWithTwoColourBoxesAndNoDeviceSpaceKeepsItsDeviceNameAndPassesVeraPdf`, `Iso19005_2_6_2_8_3_AJp2FileWithOneColourBoxThatIsNotADeviceSpaceHasNoColorSpaceAndPassesVeraPdf`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneEnumeratedColourBoxWhoseComponentsTheColourChannelsLackAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitKeepsTheNameTheCountChooses`, `Iso32000_2_7_4_9_AFileWithOneIccProfileWhoseColourSpaceTheColourChannelsDoNotFitAndNoNameFitsIsRefused`, `Iso32000_2_7_4_9_EveryIccDataColourSpaceOfTable19HasItsNumberOfComponents`, `Iso32000_2_7_4_9_AnIccProfileHasAHeaderToReadFromTwentyBytes`, `Iso32000_2_7_4_9_ACdefBoxCountsTheDistinctChannelsItNamesAndIgnoresEntriesForChannelsTheImageLacks`, `Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelButMarksTheWrongNumberOfColourChannelsIsRefused`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedKeepsANameThatFitsTheCountOfEveryChannel`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedKeepsANameThatFitsTheChannelsItNames`, `Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsRefusedWhenTheNameFitsNeitherCount`, `Iso32000_2_7_4_9_ALoneSyccBoxIsLeftWithNoColorSpaceWhenEitherCountOfAnIncompleteCdefBoxFitsIt`, `Iso32000_2_7_4_9_AnEntryForAChannelTheImageLacksBesideAnOpacityChannelDefinesNoColour`, `Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJpxFileKeepsTheNameAndItsDepthsAreNotCompared`, `Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount` | | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab); or enumerated colour space 12 (CMYK); or an ICC profile valid in PDF (32000-1 allows CIEJab) | IMG (JPX) | fixed (#763): a JP2 file none of whose readable colr boxes is allowed is refused, because 7.4.9 allows only the JPX baseline set of features other than enumerated space 19, M.9.2.4 of ISO/IEC 15444-2:2004 asks of it a colour specification from its list, and no ColorSpace makes such a file valid. Allowed: an ICC profile (method 2 or 3), CMYK (12), and the enumerated spaces of the list other than 19 (14, 16, 17, 18, 20, 21, 24). Refused: a lone CIEJab, a lone enumerated value outside those (0 to 11, 13, 15, 22, 23, and every value above 24, reserved ones included), a vendor or reserved method (any other than 1, 2 and 3) alone or beside only such boxes, and two or more boxes of those kinds. One allowed box beside others is enough. A box under 3 bytes, or method 1 under 7, is a colour specification of neither kind and is not counted; a file with no colr box is not refused for the absence | `Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue`, `Iso32000_2_7_4_9_ALoneVendorOrReservedColourBoxIsRefused`, `Iso32000_2_7_4_9_AReservedMethodBoxOfThreeBytesIsAColourSpecificationAndIsRefused`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadIsNoColourSpecificationOfEitherKindAndKeepsTheName`, `Iso32000_2_7_4_9_AFileWhoseColourBoxesAreNoneOfThemAnAllowedSpaceIsRefusedAtEveryChannelCount`, `Iso32000_2_7_4_9_AFileWithOneAllowedColourBoxBesideOthersIsNotRefusedForTheOthers`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadBesideAVendorBoxStillLeavesNoAllowedSpace`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | | ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no usable ihdr box: absent, or with a height or width of 0), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with a usable ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_AnIhdrBoxWithAZeroHeightOrWidthIsNoUsableIhdrAndItsCodestreamIsExamined`, `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 28c9e930a..af16487e9 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -74,14 +74,16 @@ namespace VellumPdf.Images; /// they are the channels that the image has and that a type 0 entry of its cdef box names, a channel named /// twice counting once, and an entry that names no channel the image has describes nothing and is ignored /// (I.5.3.6 bounds the channel number of an entry by no sentence). Opacity, premultiplied opacity and unspecified -/// entries are not counted. When there is no readable cdef box, or the box does not describe every -/// channel the image has, every channel is a colour channel. A cdef box that leaves a channel undescribed -/// is not a complete list, which I.5.3.6 asks for. That clause does not define "complete", so this is a reading -/// and not a quoted requirement, and the loader does not refuse the file for it: it does not use the box, as it -/// does not use one that is too short to read. The channels come from the ihdr box (from the codestream, -/// when the jp2h box has no usable ihdr box). The space has to have exactly that many -/// components. Where a name is written, it is the name chosen above, and DeviceCMYK replaces it where a -/// colr box names CMYK and there are four colour channels. If no fit exists, the file is invalid under +/// entries are not counted. When there is no readable cdef box, every channel is a colour channel. A +/// cdef box that leaves a channel undescribed is not a complete list, which I.5.3.6 asks for. That clause +/// does not define "complete", so the loader reads such a box both ways and the file has two defensible counts: +/// the channels that the box names with a type 0 entry, and every channel. This is a reading and not a quoted +/// requirement, and the loader creates no refusal from it: a name that has as many components as either count is +/// kept, and the file is refused only when the name fits neither, because its output is then invalid under both +/// readings. A box that describes every channel has the one count. The channels come from the ihdr box +/// (from the codestream, when the jp2h box has no usable ihdr box). The space has to have exactly +/// that many components. Where a name is written, it is the name chosen above, and DeviceCMYK replaces it +/// where a colr box names CMYK and there are four colour channels. If no fit exists, the file is invalid under /// 7.4.9 and is refused with . /// A file with no allowed colour specification is refused with , /// whatever the channels and the ColorSpace are. ISO 32000-2, 7.4.9, limits the image data to the JPX @@ -814,6 +816,17 @@ public int ColourChannels(int channels) => ? ordinary.Where(c => c < channels).Distinct().Count() : channels; + // The second count of a cdef box that leaves a channel undescribed: the distinct channels the image has that + // a type 0 entry names. Null for a box that describes every channel and for no box (one count only). + public int? NamedColourChannels(int channels) => + OrdinaryChannels is { } named && UsableOrdinaryChannels(channels) is null + ? named.Where(c => c < channels).Distinct().Count() + : null; + + // Whether a space of this many components has as many components as a colour count of the file. + public bool Fits(int components, int channels) => + components == ColourChannels(channels) || components == NamedColourChannels(channels); + // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. The depths of a file whose // channels are remapped are not judged, because its colour channels are not read. public Jp2Findings Findings(int channels) @@ -831,11 +844,12 @@ public Jp2Findings Findings(int channels) } // ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive, so a file with a colour channel deeper - // than that is invalid in a PDF file and is refused. + // than that is invalid in a PDF file and is refused. Where a cdef box has two counts only the channels it names + // are judged, because a deeper channel among them is deeper under both readings. public void RefuseDepthOutsideRange(int channels) { const int MaxDepth = 38; - if (!ChannelsRemapped && ColourDepthsOf(channels) is { } depths && depths.Max() > MaxDepth) + if (!ChannelsRemapped && ColourDepthsOf(channels, narrow: true) is { } depths && depths.Max() > MaxDepth) throw new InvalidDataException( $"JP2 file: a colour channel is {depths.Max()} bits deep, and ISO 32000-2, 7.4.9, allows bits " + "per sample from 1 to 38 inclusive."); @@ -846,12 +860,13 @@ public void RefuseDepthOutsideRange(int channels) // codestream when the loader had to read the dimensions from it, else from the ihdr box, which holds one // depth for all channels. A depth the file gives only in the codestream while its ihdr box says otherwise is // not compared. Null when the file gives no depth, or no colour channel. - private int[]? ColourDepthsOf(int channels) + private int[]? ColourDepthsOf(int channels, bool narrow = false) { int[]? perChannel = Bpcc is { } bpcc ? [.. bpcc.Select(b => (b & 0x7F) + 1)] : CodestreamDepths; + var count = narrow ? NamedColourChannels(channels) ?? ColourChannels(channels) : ColourChannels(channels); if (perChannel is null) - return IhdrBpc is { } raw and not 0xFF && ColourChannels(channels) > 0 ? [(raw & 0x7F) + 1] : null; - var ordinary = UsableOrdinaryChannels(channels); + return IhdrBpc is { } raw and not 0xFF && count > 0 ? [(raw & 0x7F) + 1] : null; + var ordinary = narrow && OrdinaryChannels is { } named ? named : UsableOrdinaryChannels(channels); int[] depths = [.. perChannel.Where((_, i) => ordinary is null || ordinary.Contains(i))]; return depths.Length == 0 ? null : depths; } @@ -1041,13 +1056,13 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa return null; var colour = colr.ColourChannels(channels); var components = colr.HasIccProfile ? colr.IccComponents : EnumeratedComponentsOf(colr.Enumerated[0]); - if (components is null || components == colour) + if (components is null || colr.Fits(components.Value, channels)) { - colr.UnnamedColourChannels = colour; + colr.UnnamedColourChannels = components is { } c && c == colr.NamedColourChannels(channels) ? c : colour; return null; } var named = InferColorSpace(channels, colrEnum); - if (ComponentsOf(named) == colour) + if (colr.Fits(ComponentsOf(named), channels)) return named; var space = colr.HasIccProfile ? $"an ICC profile of {components} components" @@ -1075,9 +1090,9 @@ private static ImageColorSpace FitChannels( if (colr.ChannelsRemapped) return named; var colour = colr.ColourChannels(channels); - if (ComponentsOf(named) == colour) + if (colr.Fits(ComponentsOf(named), channels)) return named; - if (cmykBox && colour == 4) + if (cmykBox && colr.Fits(4, channels)) return ImageColorSpace.DeviceCmyk; var cmapHint = colr.HasCmap && !colr.HasPalette ? " The file has a cmap box and no pclr box, which a JP2 file may not have (ISO/IEC 15444-1, I.5.3.4)." @@ -1097,7 +1112,8 @@ private static string WhyChannels(int channels, bool channelsFromSiz, ColrSurvey var source = channelsFromSiz ? "codestream has" : "ihdr box has"; if (colr.OrdinaryChannels is not null) return $"its {source} {channels} channels and a cdef box that does not describe every one of them, " + - "so the box is not used and every channel is a colour channel"; + $"so it has {colour} colour channels counting every channel and {colr.NamedColourChannels(channels)} " + + "counting those the box names with a type 0 entry"; if (colr.HasCompositingLayerHeader) return $"its {source} {channels} channels and no cdef box in its jp2h box, and the jplh box, which may " + "define them, is not written with the file, so every one is a colour channel in the file written"; diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index d086db6ba..b1adfaa50 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -844,30 +844,52 @@ public void Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelButMarksTheWrongNu Assert.Contains($"its cdef box marks {colour} ordinary colour channels", e.Message); } + // A cdef box that leaves a channel undescribed has two counts: the channels its type 0 entries name, and every + // channel. The name is kept when it fits either, and the file is refused only when it fits neither. [Theory] - [InlineData(4, 12, new[] { 0, 1, 2, 2 }, "DeviceCMYK")] // channel 3 undescribed: four colour channels, a CMYK box - [InlineData(3, 16, new[] { 0, 1 }, "DeviceRGB")] // channel 2 undescribed: three colour channels + [InlineData(4, 12, new[] { 0, 1, 2, 2 }, "DeviceCMYK")] // every channel: four; the box names three + [InlineData(3, 16, new[] { 0, 1 }, "DeviceRGB")] // every channel: three; the box names two [InlineData(4, 12, new[] { 0, 1, 9 }, "DeviceCMYK")] [InlineData(3, 12, new[] { 0 }, "DeviceRGB")] - public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsNotUsedAndEveryChannelIsAColourChannel(int channels, + public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedKeepsANameThatFitsTheCountOfEveryChannel(int channels, int enumerated, int[] colourEntries, string name) { - // I.5.3.6 asks for a complete list; the box is not used, as if it were absent, and the file is not refused for it. var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); } [Theory] - [InlineData(4, 16, new[] { 0, 1, 2 })] // RGB over four channels, the fourth undescribed: four colour channels, DeviceRGB has three - [InlineData(2, 17, new[] { 0 })] - public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedCountsEveryChannelAndTheNameMustHaveThatMany(int channels, - int enumerated, int[] colourEntries) + [InlineData(4, 16, new[] { 0, 1, 2 }, "DeviceRGB")] // the box names three colour channels, which DeviceRGB has + [InlineData(2, 17, new[] { 0 }, "DeviceGray")] // the box names one, which DeviceGray has; every channel would be two + [InlineData(5, 17, new[] { 3 }, "DeviceGray")] + public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedKeepsANameThatFitsTheChannelsItNames(int channels, + int enumerated, int[] colourEntries, string name) + { + var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); + Assert.Equal(name, ColourSpaceWritten(Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef))); + } + + [Theory] + [InlineData(5, 16, new[] { 0, 1, 9 }, 2)] // names two (channel 9 is outside), every channel is five, DeviceRGB has three + [InlineData(2, 17, new[] { 4 }, 0)] // names none, every channel is two, DeviceGray has one + [InlineData(6, 17, new[] { 0, 1 }, 2)] + public void Iso32000_2_7_4_9_ACdefBoxThatLeavesAChannelUndescribedIsRefusedWhenTheNameFitsNeitherCount(int channels, + int enumerated, int[] colourEntries, int named) { var cdef = colourEntries.Select((cn, i) => (cn, 0, i + 1)).ToArray(); var jp2 = Jp2File(JpxCodestream(16, 16, channels), channels, enumerated, cdef: cdef); var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); - Assert.Contains($"its ihdr box has {channels} channels and a cdef box that does not describe every one of them, so " + - "the box is not used and every channel is a colour channel", e.Message); + Assert.Contains($"its ihdr box has {channels} channels and a cdef box that does not describe every one of them, " + + $"so it has {channels} colour channels counting every channel and {named} counting those the box names", e.Message); + } + + [Fact] + public void Iso32000_2_7_4_9_ALoneSyccBoxIsLeftWithNoColorSpaceWhenEitherCountOfAnIncompleteCdefBoxFitsIt() + { + // Every channel is four, the box names three: sYCC has three, so it fits the second count. + var jp2 = Jp2File(JpxCodestream(16, 16, 4), 4, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); + Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc-incomplete", jp2, 16, 16, "DeviceRGB", 8, + "JPXDecode"))).Dict.Get(N("ColorSpace"))); } [Theory] @@ -964,9 +986,12 @@ public void Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChanne // bpcc 8, 8, 8 and 49 bits, with a cdef box that makes the fourth an opacity channel: only colour channels count. var opacity = Jp2File(JpxCodestream(16, 16, 4), 4, 16, [7, 7, 7, 0x30], cdef: Channels(3, 1)); Assert.NotNull(JpxImageLoader.Load(opacity)); - // A cdef box that leaves channel 3 undescribed is not used, so every channel is a colour channel. + // A cdef box that leaves channel 3 undescribed has two counts, and only the channels it names are judged: + // channel 3 is deeper than 38 bits under one reading only, so the file is kept. Channel 2 is named. var undescribed = Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 7, 0x30], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); - Assert.Contains("49 bits deep", Assert.Throws(() => JpxImageLoader.Load(undescribed)).Message); + Assert.NotNull(JpxImageLoader.Load(undescribed)); + var named = Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 0x30, 7], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); + Assert.Contains("49 bits deep", Assert.Throws(() => JpxImageLoader.Load(named)).Message); // A palette changes which stored components are colour channels, and the palette is not read. var palette = Jp2File(JpxCodestream(16, 16, 1), 1, 16, [0x30], palette: true); Assert.NotNull(JpxImageLoader.Load(palette)); From 6b76247633ad9e18c18b6c17f4ce5c14a5e6a7cd Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 21:26:40 +0100 Subject: [PATCH 20/22] fix(images): judge each cdef reading on name and depth together A cdef box that leaves a channel undescribed has two readings of the colour channels. The loader judged the name against the counts of both readings and the depth against the named channels only, so a file whose every reading broke one of the two rules was kept with main's bytes. A reading now keeps the file only if the name written has that reading's colour-channel count and every colour channel of that reading is 1 to 38 bits deep; the file is refused when no reading passes both, with a message that names the failed check of each. The PDF/A report is judged under the reading that is kept. A bpcc box with more entries than the image has channels is not a conforming JP2 file (I.5.3.2): its extra entries are no colour channels, and a deep one is refused with that said instead of as a colour channel. The refusal for a file with no allowed colour specification lists the allowed values. Stale comments, a renamed method in a comment, and the LayoutImage depth item are corrected, and the two mutation survivors of the last round get tests. --- CHANGELOG.md | 14 +- docs/conformance-v2.4.md | 2 +- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 259 ++++++++++++------ src/VellumPdf.Layout/Elements/LayoutImage.cs | 6 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 8 +- .../ConformanceAuditG4Tests.JpxChannels.cs | 139 +++++++++- 6 files changed, 327 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cf2c277b..9318e595d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1021,8 +1021,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). specification whose METH is not 1, 2 or 3, colour channels of different bit depth, or a number of colour channels other than 1, 3 or 4 for a file written with no `ColorSpace`. 7.4.9 requires none of those four. It does limit bits per sample to 1 through 38, so a JP2 file (or a bare - codestream) with a colour channel deeper than that is refused in every document; a file with a - palette is not read for it. The depths are read from the `bpcc` box, else from the codestream + codestream) is refused in every document when every reading of its channels that the name fits has + a colour channel deeper than that (the `JpxImageLoader` documentation states the readings); a file with a palette is not read for it. A `bpcc` box with more entries than the + image has channels is not a conforming JP2 file (ISO/IEC 15444-1, I.5.3.2), its extra entries + are no channels, and the file is refused, with that said, when one of them is deeper than 38 + bits. The depths are read from the `bpcc` box, else from the codestream where the loader takes the dimensions from it, else from the `ihdr` box, which gives none when its BPC is 255 and the file has no `bpcc` box. The report follows the clause, not veraPDF, which checks APPROX and METH only without a `ColorSpace` and also fails a sign-only difference and an @@ -1033,9 +1036,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). whose name has as many components as it has colour channels, or that has a palette, writes the same bytes as before, and so does a JP2 file with one `colr` box that is not a device space where the name the channel count chooses has as many components as the colour channels. A `cdef` box - that leaves a channel undescribed has two counts, and the file is refused only when main's name - fits neither (as the `JpxImageLoader` documentation states), so no such file that main wrote - with a name fitting either count changes. + that leaves a channel undescribed has two readings of its colour channels, and the file keeps + main's bytes only under a reading whose colour-channel count the name has and whose colour + channels are all 1 to 38 bits deep (as the `JpxImageLoader` documentation states); it is refused + when no reading passes both checks, with a message that names the failed check of each. - **A JPEG 2000 codestream whose Rsiz requires a capability outside the JPX baseline is refused (#770).** ISO 32000-2, 7.4.9, limits the data of an image XObject to the JPX baseline set of diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index fef823482..73dd98b2e 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -403,7 +403,7 @@ JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); F | ISO 32000-2 7.4.9 | A JPEG 2000 image in a PDF file has one of the baseline JPX colour spaces excluding enumerated colour space 19 (CIEJab); or enumerated colour space 12 (CMYK); or an ICC profile valid in PDF (32000-1 allows CIEJab) | IMG (JPX) | fixed (#763): a JP2 file none of whose readable colr boxes is allowed is refused, because 7.4.9 allows only the JPX baseline set of features other than enumerated space 19, M.9.2.4 of ISO/IEC 15444-2:2004 asks of it a colour specification from its list, and no ColorSpace makes such a file valid. Allowed: an ICC profile (method 2 or 3), CMYK (12), and the enumerated spaces of the list other than 19 (14, 16, 17, 18, 20, 21, 24). Refused: a lone CIEJab, a lone enumerated value outside those (0 to 11, 13, 15, 22, 23, and every value above 24, reserved ones included), a vendor or reserved method (any other than 1, 2 and 3) alone or beside only such boxes, and two or more boxes of those kinds. One allowed box beside others is enough. A box under 3 bytes, or method 1 under 7, is a colour specification of neither kind and is not counted; a file with no colr box is not refused for the absence | `Iso32000_2_7_4_9_AFileWhoseOnlyColourSpecificationIsAnEnumeratedSpaceOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_AnEnumeratedSpaceOfTheBaselineOrCmykIsNotRefusedForItsValue`, `Iso32000_2_7_4_9_ALoneVendorOrReservedColourBoxIsRefused`, `Iso32000_2_7_4_9_AReservedMethodBoxOfThreeBytesIsAColourSpecificationAndIsRefused`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadIsNoColourSpecificationOfEitherKindAndKeepsTheName`, `Iso32000_2_7_4_9_AFileWhoseColourBoxesAreNoneOfThemAnAllowedSpaceIsRefusedAtEveryChannelCount`, `Iso32000_2_7_4_9_AFileWithOneAllowedColourBoxBesideOthersIsNotRefusedForTheOthers`, `Iso32000_2_7_4_9_AColourBoxTooShortToReadBesideAVendorBoxStillLeavesNoAllowedSpace`, `Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnIccProfileKeepsBothColourBoxesAndTheDeviceName`, `Iso32000_2_7_4_9_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused` | | ISO 32000-1 7.4.9; ISO 32000-2 7.4.9 | Data used in PDF image XObjects is limited to the JPX baseline set of features | IMG (JPX) | fixed (#770): the loader reads Rsiz, in a bare codestream, in the jp2c of a JP2 file whose codestream starts with SOC and SIZ, and in a JP2 file whose dimensions it takes from the codestream (no jp2h box, or no usable ihdr box: absent, or with a height or width of 0), and refuses the codestream when bit 14 is set (extended capabilities through a CAP marker, ISO/IEC 15444-1 Table A.10), or when bit 15 is set with any of bits 0, 1, 4, 5, 6, 7, 10 or 11, the capabilities ISO/IEC 15444-2:2004 Table A.2 says are required to decode. M.9.2.3 of that edition defines the baseline codestream as Part 1 plus only the irreversible decorrelation and non-linearity extensions, so bit 15 alone, the useful bits 2, 3 and 9, and bit 8 (multiple component transformation) pass. Bit 8 passes because the baseline allows the restricted decorrelation; its MCC and MCO limits are not checked. Bits 12 and 13, which Table A.2 leaves reserved, are not examined. A JP2 file with a usable ihdr box whose codestream does not start with SOC and SIZ is not examined | `Iso32000_2_7_4_9_AnIhdrBoxWithAZeroHeightOrWidthIsNoUsableIhdrAndItsCodestreamIsExamined`, `Iso32000_2_7_4_9_ARsizRequiringAPartTwoCapabilityOutsideTheBaselineIsRefused`, `Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused`, `Iso32000_2_7_4_9_ARsizWithOnlyBaselineOrUsefulPartTwoBitsIsPassedThroughByteForByte`, `Iso32000_2_7_4_9_AJpxCodestreamOutsideTheBaselineFeatureSetIsRefused`, `Iso32000_2_7_4_9_TheRsizOfAnUnexaminedCodestreamIsReadWhereTheLoaderTakesTheDimensionsFromIt` | | ISO 32000-2 7.4.9 | The codestream is passed through unchanged | IMG (JPX) | compliant | `Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte` | -| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 requires none of these, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A colour channel deeper than 38 bits is refused in every document, because 32000-2 7.4.9 requires bits per sample between 1 and 38 (a file with a palette is not read for it). The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared, and an ihdr BPC of 255 with no bpcc box gives no depth. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso32000_2_7_4_9_AColourChannelOfMoreThanThirtyEightBitsIsRefusedInEveryDocument`, `Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChannelsAndOnFilesWhoseChannelsAreRead`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | +| ISO 19005-2 6.2.8.3 | A JPX image has 1, 3 or 4 colour channels, exactly one colour specification with APPROX 1 where there are several, a colr METH of 1, 2 or 3, no CIEJab, and one bit depth of 1 to 38 for all colour channels (veraPDF 6.2.8.3-1 to 6.2.8.3-5) | IMG (JPX) | fixed (#763): every JP2 file the loader writes with a name has 1, 3 or 4 colour channels, except one with a palette or a JPX cmap box, whose colour channels are not read. A file written with no ColorSpace has the colour channels its lone colr box has components for, which may be a count other than 1, 3 or 4 (an ICC profile of two colours, say). A JP2 file with more than one colour specification and not exactly one with APPROX 1, a METH other than 1, 2 or 3, colour channels of different bit depth, or a file written with no ColorSpace whose colour channels number other than 1, 3 or 4, is still written, because 32000-2 requires none of these, and a Layout save under a PDF/A-2 claim reports it as JpxImageNotAllowedByPdfA (501); strict mode refuses it. A file is refused in every document when every reading of its channels that the name fits has a colour channel deeper than 38 bits, because 32000-2 7.4.9 requires bits per sample between 1 and 38 (a file with a palette is not read for it). A cdef box that leaves a channel undescribed has two readings, and the file is kept only under one that passes both the name check and the depth check (stated once on `JpxImageLoader`); the report is judged under the reading kept. A bpcc box with more entries than channels is not a conforming JP2 file (15444-1 I.5.3.2, read on NEN), its extra entries are no channels, and it is refused when one is deeper than 38 bits. The depths are read from the bpcc box, else from the codestream where the loader takes the dimensions from it, else from the ihdr box; a depth that only the codestream shows, beside an ihdr box that says otherwise, is not compared, and an ihdr BPC of 255 with no bpcc box gives no depth. A Kernel-only save has no report (#474). The report follows the clause read on NEN on 2026-11-30 and not veraPDF, which checks APPROX and METH only without ColorSpace, fails a sign-only bpcc difference, and counts opacity channels | `Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim`, `Iso19005_2_6_2_8_3_TwoColourBoxesWithExactlyOneApproxOfOneAreNotReportedAndTwoApproxOfOneAre`, `Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported`, `Iso19005_2_6_2_8_3_ADifferentDepthOnAnOpacityChannelIsNotReportedButOnAColourChannelIs`, `Iso19005_2_6_2_8_3_AJpxImageInARunningBandLogoIsReportedInTheBandOnEveryPage`, `Iso19005_2_6_2_8_3_TheReportOfAJpxImageQuotesNoAlternativeText`, `Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourChannelsIsReportedAndOneOfThreeIsNot`, `Iso32000_2_7_4_9_AColourChannelOfMoreThanThirtyEightBitsIsRefusedInEveryDocument`, `Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChannelsAndOnFilesWhoseChannelsAreRead`, `Iso19005_2_6_2_8_3_ColourChannelsOfDifferentDepthsOnlyTheCodestreamShowsAreReported`, `Iso19005_2_6_2_8_3_AColourSpecificationOfMethodFourOrSevenIsReported` | | ISO 32000-1 11.6.5.3, Table 145; ISO 32000-2 Table 143 | A soft-mask image has ColorSpace DeviceGray, BitsPerComponent, no ImageMask, no Mask, no SMask; SMask replaces Mask | IMG (PNG, GIF, TIFF alpha) | compliant: a separate object of the image's own size, at 8 or 16 bits | `Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows`, `Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask` | | ISO 32000-1 11.6.5.3, Table 146; ISO 32000-2 Table 144 | When Matte is absent the image data shall not be preblended; preblended data carries Matte in the soft mask | IMG (TIFF ExtraSamples 1) | fixed (#764): ExtraSamples 1 is written with a black Matte on the soft mask and the samples as they are. A colour above its alpha is not a TIFF 6.0 file and is written as it is, as the loader documents | `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffHasAMatteOfBlack`, `Iso32000_1_11_6_5_3_ASixteenBitAssociatedAlphaTiffHasAMatteOfBlackAtEitherDepth`, `Iso32000_1_11_6_5_3_AnAssociatedAlphaTiffWhoseColourExceedsItsAlphaIsWrittenAsItIs` | | ISO 32000-1 8.9.6.4; ISO 32000-2 8.9.6.4 | A colour key is 2n integers from 0 to 2^BitsPerComponent - 1, with min not above max, in values before decoding | IMG (PNG tRNS) | fixed (#768): a tRNS word with bits above the bit depth is masked to the depth before it is written. Compliant when the unused bits are 0: 8-bit, 4-bit (rescaled to the written sample) and RGB keys | `Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample`, `Iso32000_1_8_9_6_4_APngKeyWithBitsAboveTheDepthIsMaskedBeforeItIsWritten` | diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index af16487e9..6523b96b2 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -76,15 +76,17 @@ namespace VellumPdf.Images; /// (I.5.3.6 bounds the channel number of an entry by no sentence). Opacity, premultiplied opacity and unspecified /// entries are not counted. When there is no readable cdef box, every channel is a colour channel. A /// cdef box that leaves a channel undescribed is not a complete list, which I.5.3.6 asks for. That clause -/// does not define "complete", so the loader reads such a box both ways and the file has two defensible counts: -/// the channels that the box names with a type 0 entry, and every channel. This is a reading and not a quoted -/// requirement, and the loader creates no refusal from it: a name that has as many components as either count is -/// kept, and the file is refused only when the name fits neither, because its output is then invalid under both -/// readings. A box that describes every channel has the one count. The channels come from the ihdr box -/// (from the codestream, when the jp2h box has no usable ihdr box). The space has to have exactly -/// that many components. Where a name is written, it is the name chosen above, and DeviceCMYK replaces it -/// where a colr box names CMYK and there are four colour channels. If no fit exists, the file is invalid under -/// 7.4.9 and is refused with . +/// does not define "complete", so the loader reads such a box both ways and the file has two readings: the channels +/// that the box names with a type 0 entry, and every channel. This is a reading and not a quoted requirement, and +/// the loader creates no refusal from the incompleteness itself. +/// A reading of an incomplete cdef box keeps the file only if the whole file is valid under that same +/// reading: the name written has that reading's colour-channel count, and every colour channel of that reading is 1 +/// to 38 bits deep (ISO 32000-2, 7.4.9). The file is kept when at least one reading passes both checks, and is +/// refused with when none does, the message naming for each reading the check it +/// fails. A box that describes every channel, and a file with no box, have one reading, judged the same way. The +/// channels come from the ihdr box (from the codestream, when the jp2h box has no usable ihdr +/// box). The space has to have exactly that many components. Where a name is written, it is the name chosen above, +/// and DeviceCMYK replaces it where a colr box names CMYK and there are four colour channels. /// A file with no allowed colour specification is refused with , /// whatever the channels and the ColorSpace are. ISO 32000-2, 7.4.9, limits the image data to the JPX /// baseline set of features except enumerated colour space 19, and ISO/IEC 15444-2:2004, M.9.2.4, asks of that set @@ -130,9 +132,12 @@ namespace VellumPdf.Images; /// JP2 file with no jp2h box or no usable ihdr box), else from the ihdr box, which gives no /// depth when its BPC field is 255 and there is no bpcc box; a file with a palette or a JPX cmap box /// is not compared. ISO 32000-2, 7.4.9, requires none of the first four. It does require bits per sample "between -/// 1 to 38 inclusive", so a colour channel deeper than 38 bits is refused with -/// in every document, and the depths of a file with a palette or a JPX -/// cmap box are not read for that either. This loader neither refuses nor reports the other findings. A +/// 1 to 38 inclusive", so a file is refused when every reading that its name fits has a colour channel +/// deeper than 38 bits (the principle above), with , in every document, and the +/// depths of a file with a palette or a JPX cmap box are not read for that either. A bpcc box with +/// more entries than the image has channels is not a conforming JP2 file (ISO/IEC 15444-1, I.5.3.2, wants one entry +/// per channel); its extra entries are not channels and are not judged as such, and the file is refused when one +/// of them is deeper than 38 bits. This loader neither refuses nor reports the other findings. A /// VellumPdf.Layout save reports them under a PDF/A-2 claim as /// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on /// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a @@ -695,7 +700,7 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c } // The number of components of an enumerated colour space that a lone colr box may name, which is a baseline space - // other than the device spaces 12, 16 and 17 and other than CIEJab (see LoneSpace and IsBaselineEnumerated): CIELab + // other than the device spaces 12, 16 and 17 and other than CIEJab (see LoneSpace and IsAllowedEnumerated): CIELab // (14, "the three components" in ISO/IEC 15444-2:2004, Table M.25) and sYCC (18), e-sRGB (20), ROMM-RGB (21) and // e-sYCC (24), which Table M.25 names by reference to the documents that define them and so gives no count; their // colour models (a luma and two chroma channels, or red, green and blue) have three. @@ -708,7 +713,8 @@ private static void TryParseColr(byte[] data, int offset, int length, ref int? c // cdef payload: N(2), then N entries of Cn(2) Typ(2) Asoc(2). Typ 0 is an ordinary colour channel; opacity, // premultiplied opacity and unspecified entries are not counted. A box too short for its own N is skipped, so // the first box long enough is the one read and a file with none is judged by its channel count alone. Which - // channels the entries cover decides later whether the box is used at all (ColrSurvey.UsableOrdinaryChannels). + // channels the entries cover decides later which readings of the colour channels the file has + // (ColrSurvey.Readings). private static void TryParseCdef(byte[] data, int offset, int length, ColrSurvey colr) { if (colr.OrdinaryChannels is not null) @@ -745,6 +751,13 @@ private static bool HasJpxBrand(byte[] data, int offset, int length) return false; } + // One way of reading which channels of the image are colour channels, as the class summary of JpxImageLoader + // states once. Label says which, for a refusal message. + private sealed record ColourReading(string Label, int[] Channels) + { + public int Count => Channels.Length; + } + // What the jp2h box of a JP2 file holds: the number of colr boxes and how many of them have an APPROX of 1, // whether any colr box has a method other than 1, 2 or 3, every enumerated colour space in file order, // whether any box carries an ICC profile and its components, whether there is a palette or a cmap box, the bpcc @@ -752,6 +765,11 @@ private static bool HasJpxBrand(byte[] data, int offset, int length) // channels (null when there is none). colrEnum above keeps the last enumerated value, as it always has. private sealed class ColrSurvey { + // ISO 32000-2, 7.4.9: bits per sample "between 1 to 38 inclusive". + private const int MaxDepth = 38; + + private ColourReading[]? _readings; + public int Boxes { get; set; } public int Approx1Boxes { get; set; } public int AllowedBoxes { get; set; } @@ -770,8 +788,14 @@ private sealed class ColrSurvey public int[]? CodestreamDepths { get; set; } public List? OrdinaryChannels { get; set; } public HashSet? DescribedChannels { get; set; } + + // The colour channel count of a file written with no ColorSpace, for the PDF/A report. public int? UnnamedColourChannels { get; set; } + // The reading under which the file is kept: the first that passes the name check of the path taken and the + // depth check. Null until a path has chosen one; the first reading stands in for it then. + public ColourReading? Kept { get; set; } + // A pclr box, or in a JPX file a cmap box alone (ISO/IEC 15444-2:2004, M.5.1.2 numbers the channels by the // cmap entries and no sentence ties the box to a pclr box there), changes which stored components the // channels are. Neither box is read, so the ihdr and bpcc entries say nothing about the colour channels. @@ -795,40 +819,69 @@ public void RefuseNoAllowedColourSpecification() string.Join(", ", NotAllowed) + ")"; throw new InvalidDataException( $"JP2 file: {which}, and ISO 32000-2, 7.4.9, allows image data in a PDF file only the JPX baseline " + - "set of ISO/IEC 15444-2:2004, M.9.2.4, other than enumerated colour space 19 (CIEJab), CMYK (12) " + - "and an ICC profile, so no ColorSpace makes the file valid."); + "set of ISO/IEC 15444-2:2004, M.9.2.4, other than enumerated colour space 19 (CIEJab), plus CMYK (12), " + + "so a file needs an allowed colour specification: CMYK (12), an ICC profile, or enumerated 14, 16, 17, " + + "18, 20, 21 or 24, and no ColorSpace makes the file valid."); } - // The colour channels, as the class summary of JpxImageLoader states once: the channels that the image has - // and that a type 0 entry of a usable cdef box names, or every channel when there is no usable cdef box. - public List? UsableOrdinaryChannels(int channels) + // Whether the usable cdef box describes every channel the image has (with any type), which is the one case + // in which the box is a complete list in the sense of the class summary. + public bool CdefDescribesEveryChannel(int channels) { if (OrdinaryChannels is null || DescribedChannels is null) - return null; + return false; for (var channel = 0; channel < channels; channel++) if (!DescribedChannels.Contains(channel)) - return null; - return OrdinaryChannels; + return false; + return true; } - public int ColourChannels(int channels) => - UsableOrdinaryChannels(channels) is { } ordinary - ? ordinary.Where(c => c < channels).Distinct().Count() - : channels; - - // The second count of a cdef box that leaves a channel undescribed: the distinct channels the image has that - // a type 0 entry names. Null for a box that describes every channel and for no box (one count only). - public int? NamedColourChannels(int channels) => - OrdinaryChannels is { } named && UsableOrdinaryChannels(channels) is null - ? named.Where(c => c < channels).Distinct().Count() - : null; + // The readings of the colour channels, as the class summary of JpxImageLoader states once. No readable cdef + // box: every channel, one reading. A box that describes every channel: the channels that a type 0 entry + // names (distinct, and only those the image has), one reading. A box that leaves a channel undescribed: both, + // every channel first. The first reading of the list is the one a name is tried against first. + public IReadOnlyList Readings(int channels) + { + if (_readings is not null) + return _readings; + int[] every = [.. Enumerable.Range(0, channels)]; + if (OrdinaryChannels is null) + return _readings = [new ColourReading("counting every channel", every)]; + int[] named = [.. OrdinaryChannels.Where(c => c < channels).Distinct()]; + return _readings = CdefDescribesEveryChannel(channels) + ? [new ColourReading("counting those its cdef box names", named)] + : [new ColourReading("counting every channel", every), + new ColourReading("counting those the box names", named)]; + } - // Whether a space of this many components has as many components as a colour count of the file. - public bool Fits(int components, int channels) => - components == ColourChannels(channels) || components == NamedColourChannels(channels); + // The first reading whose colour-channel count the path accepts (nameFits) and, when the file has more than + // one reading, whose colour channels are all 1 to 38 bits deep. A file with one reading is judged on depth + // afterwards (RefuseDepthOutsideRange), so a name that fits no count is reported before the depth is. + public ColourReading? FirstValid(int channels, Func nameFits) + { + var readings = Readings(channels); + return readings.FirstOrDefault(r => nameFits(r) && (readings.Count == 1 || DepthOutsideRange(r, channels) is null)); + } - // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through. The depths of a file whose - // channels are remapped are not judged, because its colour channels are not read. + // What the refusal says when no reading is valid: for each reading, the checks it fails. nameFailure gives the + // failed name check of a reading, or null when the name fits it. + public string FailuresPerReading(int channels, Func nameFailure) => + string.Join("; ", Readings(channels).Select(r => + { + var failures = new List(); + if (nameFailure(r) is { } name) + failures.Add(name); + if (DepthOutsideRange(r, channels) is { } deep) + failures.Add(DepthSentence(deep)); + return $"{r.Label} ({r.Count} colour channel{(r.Count == 1 ? "" : "s")}), {string.Join(" and ", failures)}"; + })); + + public static string DepthSentence(int deepest) => + $"a colour channel is {deepest} bits deep, and ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive"; + + // What ISO 19005-2, 6.2.8.3, does not allow and this loader passes through, judged under the reading that is + // kept. The depths of a file whose channels are remapped are not judged, because its colour channels are not + // read. public Jp2Findings Findings(int channels) { var found = Jp2Findings.None; @@ -838,36 +891,48 @@ public Jp2Findings Findings(int channels) found |= Jp2Findings.ColourMethod; if (UnnamedColourChannels is not (null or 1 or 3 or 4)) found |= Jp2Findings.ColourChannelCount; - if (!ChannelsRemapped && ColourDepthsOf(channels) is { } depths && depths.Distinct().Count() > 1) + if (DepthsOf(Kept ?? Readings(channels)[0], channels) is { } depths && depths.Distinct().Count() > 1) found |= Jp2Findings.ColourDepths; return found; } - // ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive, so a file with a colour channel deeper - // than that is invalid in a PDF file and is refused. Where a cdef box has two counts only the channels it names - // are judged, because a deeper channel among them is deeper under both readings. + // ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive. A file with one reading is refused when + // a colour channel of it is deeper than that; a file with two readings has been kept only under one whose + // channels are all in range (FirstValid), so there is nothing left to refuse here. A bpcc box with more + // entries than the image has channels is not a conforming JP2 file (ISO/IEC 15444-1, I.5.3.2: one entry per + // channel); the extra entries are no channels, so they are not judged as such, and a deep one refuses the file. public void RefuseDepthOutsideRange(int channels) { - const int MaxDepth = 38; - if (!ChannelsRemapped && ColourDepthsOf(channels, narrow: true) is { } depths && depths.Max() > MaxDepth) + if (ChannelsRemapped) + return; + if (Bpcc is { } bpcc && bpcc.Length > channels && bpcc.Skip(channels).Max(b => (b & 0x7F) + 1) is var extra && + extra > MaxDepth) throw new InvalidDataException( - $"JP2 file: a colour channel is {depths.Max()} bits deep, and ISO 32000-2, 7.4.9, allows bits " + - "per sample from 1 to 38 inclusive."); + $"JP2 file: its bpcc box has {bpcc.Length} entries and the image has {channels} channels, so it is not " + + "a conforming JP2 file (ISO/IEC 15444-1, I.5.3.2: one entry per channel), and an entry past the last " + + $"channel is {extra} bits deep, where ISO 32000-2, 7.4.9, allows bits per sample from 1 to 38 inclusive."); + if (DepthOutsideRange(Kept ?? Readings(channels)[0], channels) is { } deep) + throw new InvalidDataException($"JP2 file: {DepthSentence(deep)}."); } + // The deepest colour channel of a reading when it is deeper than 38 bits, else null. + private int? DepthOutsideRange(ColourReading reading, int channels) => + DepthsOf(reading, channels) is { } depths && depths.Max() > MaxDepth ? depths.Max() : null; + // The bit depth is the low 7 bits of a bpcc entry or an Ssiz byte, plus one (the top bit is the sign). Only - // the colour channels count, as ColourChannels counts them. The depths come from the bpcc box, else from the - // codestream when the loader had to read the dimensions from it, else from the ihdr box, which holds one - // depth for all channels. A depth the file gives only in the codestream while its ihdr box says otherwise is - // not compared. Null when the file gives no depth, or no colour channel. - private int[]? ColourDepthsOf(int channels, bool narrow = false) + // the channels of the reading count, which are channels the image has, so a bpcc entry past the last channel + // is never read here (RefuseDepthOutsideRange judges it for what it is). The depths come from the + // bpcc box, else from the codestream when the loader had to read the dimensions from it, else from the ihdr + // box, which holds one depth for all channels. A depth the file gives only in the codestream while its ihdr + // box says otherwise is not compared. Null when the file gives no depth, or the reading has no channel. + private int[]? DepthsOf(ColourReading reading, int channels) { + if (ChannelsRemapped) + return null; int[]? perChannel = Bpcc is { } bpcc ? [.. bpcc.Select(b => (b & 0x7F) + 1)] : CodestreamDepths; - var count = narrow ? NamedColourChannels(channels) ?? ColourChannels(channels) : ColourChannels(channels); if (perChannel is null) - return IhdrBpc is { } raw and not 0xFF && count > 0 ? [(raw & 0x7F) + 1] : null; - var ordinary = narrow && OrdinaryChannels is { } named ? named : UsableOrdinaryChannels(channels); - int[] depths = [.. perChannel.Where((_, i) => ordinary is null || ordinary.Contains(i))]; + return IhdrBpc is { } raw and not 0xFF && reading.Count > 0 ? [(raw & 0x7F) + 1] : null; + int[] depths = [.. reading.Channels.Where(i => i < perChannel.Length).Select(i => perChannel[i])]; return depths.Length == 0 ? null : depths; } } @@ -1037,39 +1102,50 @@ private static (int width, int height, int components, int bpc, int[] depths) Pa } // The one colr box of a file names an ICC profile or an enumerated space other than 12, 16 and 17, and is a space - // that image data may use (RefuseNoAllowedColourSpecification has refused the others). Two cases: - // - The colour channels, counted as in FitChannels, have as many components as the space, or the space has no + // that image data may use (RefuseNoAllowedColourSpecification has refused the others). Two cases, each tried over + // the readings of the colour channels (ColrSurvey.FirstValid: the principle of the class summary): + // - A reading valid for the file has as many colour channels as the space has components, or the space has no // count here (an ICC profile whose header cannot be read or names no listed space, an enumerated value // without a count): ColorSpace is left out so the colour specification of the file decides (7.4.9: with no - // ColorSpace the colour space information in the data is used). The count is kept for the PDF/A report, which - // allows only 1, 3 or 4 colour channels. - // - They do not: the device name this loader has always chosen from the channel count, when that name has as many - // components as there are colour channels (7.4.9: a present ColorSpace replaces the specification in the data, - // and the ordinary colour channels shall match its components, so that file is valid). ISO/IEC 15444-1, - // I.5.3.6, ties the channels to the colours of the colour specification only where a cdef box exists, so a - // file with none is not refused for a count that differs from its space. Otherwise no name fits, the file - // written before was invalid, and it is refused. + // ColorSpace the colour space information in the data is used). The count of that reading is kept for the + // PDF/A report, which allows only 1, 3 or 4 colour channels. + // - None does: the device name this loader has always chosen from the channel count, when that name has as many + // components as the colour channels of a valid reading (7.4.9: a present ColorSpace replaces the specification + // in the data, and the ordinary colour channels shall match its components, so that file is valid). + // ISO/IEC 15444-1, I.5.3.6, ties the channels to the colours of the colour specification only where a cdef box + // exists, so a file with none is not refused for a count that differs from its space. Otherwise no name fits, + // the file written before was invalid, and it is refused. // A file whose channels are remapped (ChannelsRemapped) has its colour channels unread and is left out as well. private static ImageColorSpace? LoneSpace(int channels, bool channelsFromSiz, int? colrEnum, ColrSurvey colr) { if (colr.ChannelsRemapped) return null; - var colour = colr.ColourChannels(channels); var components = colr.HasIccProfile ? colr.IccComponents : EnumeratedComponentsOf(colr.Enumerated[0]); - if (components is null || colr.Fits(components.Value, channels)) + var named = InferColorSpace(channels, colrEnum); + if (colr.FirstValid(channels, r => components is null || r.Count == components) is { } space) { - colr.UnnamedColourChannels = components is { } c && c == colr.NamedColourChannels(channels) ? c : colour; + colr.Kept = space; + colr.UnnamedColourChannels = space.Count; return null; } - var named = InferColorSpace(channels, colrEnum); - if (colr.Fits(ComponentsOf(named), channels)) + if (colr.FirstValid(channels, r => r.Count == ComponentsOf(named)) is { } name) + { + colr.Kept = name; return named; - var space = colr.HasIccProfile + } + var spaceText = colr.HasIccProfile ? $"an ICC profile of {components} components" : $"enumerated colour space {colr.Enumerated[0]}, which has {components} components"; + if (colr.Readings(channels).Count > 1) + throw new InvalidDataException( + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr)}, and the file is valid under neither reading: " + + colr.FailuresPerReading(channels, r => + $"its only colour specification is {spaceText} and {PdfNameOf(named)}, the colour space the " + + $"loader would write instead, has {ComponentsOf(named)} components") + + " (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour space)."); throw new InvalidDataException( - $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr, colour)}, but its only colour specification is " + - $"{space} and {PdfNameOf(named)}, the colour space the loader would write instead, has {ComponentsOf(named)} " + + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr)}, but its only colour specification is " + + $"{spaceText} and {PdfNameOf(named)}, the colour space the loader would write instead, has {ComponentsOf(named)} " + "components (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour " + "space)."); } @@ -1082,37 +1158,52 @@ private static bool IsAllowedEnumerated(int value) => // Checks the name chosen above against the colour channels (ISO 32000-2, 7.4.9: the ordinary colour channels // shall match the components of the colour space), which the class summary defines. The name must have exactly - // that many components, and a colr box that names CMYK may supply DeviceCMYK for four. Otherwise the file is - // invalid and refused. A file whose channels are remapped (ChannelsRemapped) keeps the name unchecked. + // that many components under a reading that is valid for the whole file (ColrSurvey.FirstValid), and a colr box + // that names CMYK may supply DeviceCMYK for four. Otherwise the file is invalid and refused. A file whose + // channels are remapped (ChannelsRemapped) keeps the name unchecked. private static ImageColorSpace FitChannels( ImageColorSpace named, int channels, bool channelsFromSiz, ColrSurvey colr, bool cmykBox) { if (colr.ChannelsRemapped) return named; - var colour = colr.ColourChannels(channels); - if (colr.Fits(ComponentsOf(named), channels)) + var components = ComponentsOf(named); + if (colr.FirstValid(channels, r => r.Count == components) is { } name) + { + colr.Kept = name; return named; - if (cmykBox && colr.Fits(4, channels)) + } + if (cmykBox && colr.FirstValid(channels, r => r.Count == 4) is { } cmyk) + { + colr.Kept = cmyk; return ImageColorSpace.DeviceCmyk; + } var cmapHint = colr.HasCmap && !colr.HasPalette ? " The file has a cmap box and no pclr box, which a JP2 file may not have (ISO/IEC 15444-1, I.5.3.4)." : ""; + if (colr.Readings(channels).Count > 1) + throw new InvalidDataException( + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr)}, and the file is valid under neither reading: " + + colr.FailuresPerReading(channels, r => r.Count == components || (cmykBox && r.Count == 4) + ? null + : $"{PdfNameOf(named)}, the colour space the loader would write, has {components} components") + + $" (ISO 32000-2, 7.4.9: the ordinary colour channels shall match the components of the colour space).{cmapHint}"); throw new InvalidDataException( - $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr, colour)}, but {PdfNameOf(named)}, the colour " + - $"space the loader would write, has {ComponentsOf(named)} components (ISO 32000-2, 7.4.9: the ordinary " + + $"JP2 file: {WhyChannels(channels, channelsFromSiz, colr)}, but {PdfNameOf(named)}, the colour " + + $"space the loader would write, has {components} components (ISO 32000-2, 7.4.9: the ordinary " + $"colour channels shall match the components of the colour space).{cmapHint}"); } // What the refusal says about the colour channels, true about the input: where the count came from, and what // the loader could not see. - private static string WhyChannels(int channels, bool channelsFromSiz, ColrSurvey colr, int colour) + private static string WhyChannels(int channels, bool channelsFromSiz, ColrSurvey colr) { - if (colr.UsableOrdinaryChannels(channels) is not null) - return $"its cdef box marks {colour} ordinary colour channels"; + var readings = colr.Readings(channels); + if (colr.CdefDescribesEveryChannel(channels)) + return $"its cdef box marks {readings[0].Count} ordinary colour channels"; var source = channelsFromSiz ? "codestream has" : "ihdr box has"; if (colr.OrdinaryChannels is not null) return $"its {source} {channels} channels and a cdef box that does not describe every one of them, " + - $"so it has {colour} colour channels counting every channel and {colr.NamedColourChannels(channels)} " + + $"so it has {readings[0].Count} colour channels counting every channel and {readings[1].Count} " + "counting those the box names with a type 0 entry"; if (colr.HasCompositingLayerHeader) return $"its {source} {channels} channels and no cdef box in its jp2h box, and the jplh box, which may " + diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 982cb358b..2244137a3 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -313,8 +313,10 @@ public LayoutImage(PdfImageXObject image) /// jp2h box whose colour channels, as defines them, are not as many as the /// components of the colour space it would write; a JP2 file none of whose readable colr boxes is an /// allowed colour specification (an ICC profile, CMYK, or an enumerated space of the JPX baseline list other - /// than CIEJab); and a JP2 file with a colour channel deeper than 38 bits - /// ( lists the cases). Nothing else is promised to be refused. + /// than CIEJab); and a JP2 file with a colour channel deeper than 38 bits, as + /// reads the depths, which it does not for a file with a palette, for a depth that + /// only the codestream shows beside a usable ihdr box, or for an ihdr BPC of 255 with no bpcc + /// box ( lists the cases). Nothing else is promised to be refused. /// The loaders do not check every requirement of ISO 32000-2, 7.4.9: a JP2 file with no colr box, for /// one, is written. A JP2 file with exactly one colr box that names an ICC profile or an enumerated colour /// space that is not sRGB, greyscale or CMYK, such as sYCC, is written with no /ColorSpace, so the colour diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index c16024392..679dc052e 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -349,12 +349,14 @@ public enum LayoutDiagnosticCode /// of 1 when there are several, a METH of 1, 2 or 3, 1, 3 or 4 colour channels, and one bit depth, /// from 1 to 38, for all the colour channels. ISO 32000-2, 7.4.9, requires none of the first four, so /// writes such a file and the save reports it. It does limit - /// bits per sample to 1 through 38, so the loader refuses a file with a deeper colour channel before any - /// save and the save never reports it. The report follows the text of 6.2.8.3, which does not depend on the + /// bits per sample to 1 through 38, so the loader refuses a file with a deeper colour channel, read as the + /// documentation states, before any save and the save never + /// reports it. The report follows the text of 6.2.8.3, which does not depend on the /// image dictionary having a ColorSpace. veraPDF 1.30.4 differs: it checks the APPROX and METH rules /// only where the dictionary has no ColorSpace, and it also fails channels that differ only in sign /// or that are counted with an opacity channel, which the text does not. The colour channels are those - /// that defines, and a file with a palette is not compared + /// that defines, under the reading that the file is kept + /// under, and a file with a palette is not compared /// because its colour channels are not read. A file written with a device name has 1, 3 or 4 colour /// channels already, so the count is reported only for a file written with no ColorSpace. The depths /// come from the bpcc box, else from the codestream when the loader took the dimensions from it, else diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index b1adfaa50..d5f0290c2 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -817,7 +817,7 @@ public void Iso19005_2_6_2_8_3_AFileWrittenWithNoColorSpaceAndTwoOrFiveColourCha [InlineData(3, 16, new[] { 0, 1, 1, 2, 2, 2 }, "DeviceRGB")] [InlineData(1, 12, new[] { 0, 0, 0 }, "DeviceGray")] [InlineData(3, 16, new[] { 0, 1, 2, 7 }, "DeviceRGB")] // a fourth entry for a channel the image lacks is ignored - [InlineData(3, 16, new[] { 0, 1, 9 }, "DeviceRGB")] // channel 2 undescribed: the box is not used, every channel counts + [InlineData(3, 16, new[] { 0, 1, 9 }, "DeviceRGB")] // channel 2 undescribed: two readings, and every channel (three) fits DeviceRGB [InlineData(3, 16, new[] { 7, 8, 9 }, "DeviceRGB")] // no entry describes a channel the image has [InlineData(1, 17, new[] { 4 }, "DeviceGray")] public void Iso32000_2_7_4_9_ACdefBoxCountsTheDistinctChannelsItNamesAndIgnoresEntriesForChannelsTheImageLacks(int channels, @@ -921,7 +921,7 @@ public void Iso32000_2_7_4_9_AnEntryForAChannelTheImageLacksBesideAnOpacityChann [Fact] public void Iso32000_2_7_4_9_ALoneSyccBoxWithACdefBoxThatDefinesThreeColoursIsWrittenWithNoColorSpace() { - // Channel 2 is undescribed, so the box is not used: three channels, three colour channels, and sYCC has three. + // Channel 2 is undescribed, so the box has two readings: every channel (three, which sYCC has) and the two it names. var jp2 = Jp2File(JpxCodestream(16, 16, 3), 3, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (9, 0, 3)]); Assert.Null(Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc-cdef", jp2, 16, 16, "DeviceRGB", 8, "JPXDecode"))) .Dict.Get(N("ColorSpace"))); @@ -986,10 +986,6 @@ public void Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChanne // bpcc 8, 8, 8 and 49 bits, with a cdef box that makes the fourth an opacity channel: only colour channels count. var opacity = Jp2File(JpxCodestream(16, 16, 4), 4, 16, [7, 7, 7, 0x30], cdef: Channels(3, 1)); Assert.NotNull(JpxImageLoader.Load(opacity)); - // A cdef box that leaves channel 3 undescribed has two counts, and only the channels it names are judged: - // channel 3 is deeper than 38 bits under one reading only, so the file is kept. Channel 2 is named. - var undescribed = Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 7, 0x30], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); - Assert.NotNull(JpxImageLoader.Load(undescribed)); var named = Jp2File(JpxCodestream(16, 16, 4), 4, 12, [7, 7, 0x30, 7], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); Assert.Contains("49 bits deep", Assert.Throws(() => JpxImageLoader.Load(named)).Message); // A palette changes which stored components are colour channels, and the palette is not read. @@ -997,6 +993,137 @@ public void Iso32000_2_7_4_9_ADepthOverThirtyEightBitsIsOnlyJudgedOnColourChanne Assert.NotNull(JpxImageLoader.Load(palette)); } + // ── A reading of an incomplete cdef box keeps the file only if the whole file is valid under it ────────── + + // The ihdr BPC byte of a JP2 file with no bpcc box: the depth less one. + private static byte[] WithIhdrDepth(byte[] jp2, int depth) + { + byte[] copy = [.. jp2]; + copy[copy.AsSpan().IndexOf("ihdr"u8) + 4 + 8 + 2] = (byte)(depth - 1); + return copy; + } + + public static TheoryData FilesNoReadingOfWhichIsValid() + { + // Each file is invalid under every reading of its cdef box: under one the name has the wrong number of + // components or no colour channel exists, under the other a colour channel is deeper than 38 bits. + const string RgbName = "DeviceRGB, the colour space the loader would write, has 3 components"; + const string Every = "counting every channel ("; + const string Named = "counting those the box names ("; + return new TheoryData + { + // bpcc 8, 8, 49 over sRGB, channels 0 and 1 named: every channel is three (DeviceRGB) and 49 bits deep, + // and the two named have the wrong name + { "depth49-rgb3", Jp2File(JpxCodestream(16, 16, 3, depths: [8, 8, 49]), 3, 16, [7, 7, 0x30], + cdef: [(0, 0, 1), (1, 0, 2)]), + $"{Every}3 colour channels), a colour channel is 49 bits deep", $"{Named}2 colour channels), {RgbName}" }, + { "bpcc39-rgb3", Jp2File(JpxCodestream(16, 16, 3, depths: [8, 8, 39]), 3, 16, [7, 7, 38], + cdef: [(0, 0, 1), (1, 0, 2)]), + $"{Every}3 colour channels), a colour channel is 39 bits deep", $"{Named}2 colour channels), {RgbName}" }, + // CMYK over four channels with the undescribed fourth 39 bits deep: the name fits four, which is every + // channel and not the three that are named + { "bpcc39-cmyk4", Jp2File(JpxCodestream(16, 16, 4, depths: [8, 8, 8, 39]), 4, 12, [7, 7, 7, 38], + cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]), + $"{Every}4 colour channels), a colour channel is 39 bits deep", + $"{Named}3 colour channels), DeviceCMYK, the colour space the loader would write, has 4 components" }, + // A cdef box with no entry names no channel, so the named reading has no colour channel + { "empty-cdef-ihdr39", WithIhdrDepth(Jp2File(JpxCodestream(16, 16, 3), 3, 16, cdef: []), 39), + $"{Every}3 colour channels), a colour channel is 39 bits deep", $"{Named}0 colour channels), {RgbName}" }, + { "entry-for-channel-5-ihdr39", WithIhdrDepth(Jp2File(JpxCodestream(16, 16, 1), 1, 17, cdef: [(5, 0, 1)]), 39), + $"{Every}1 colour channel), a colour channel is 39 bits deep", + $"{Named}0 colour channels), DeviceGray, the colour space the loader would write, has 1 components" }, + // An entry for a channel the image lacks leaves channel 2 undescribed + { "entry-for-channel-9-ihdr39", WithIhdrDepth(Jp2File(JpxCodestream(16, 16, 3), 3, 16, + cdef: [(0, 0, 1), (1, 0, 2), (9, 0, 3)]), 39), + $"{Every}3 colour channels), a colour channel is 39 bits deep", $"{Named}2 colour channels), {RgbName}" }, + }; + } + + [Theory] + [MemberData(nameof(FilesNoReadingOfWhichIsValid))] + public void Iso32000_2_7_4_9_AFileWithAnIncompleteCdefBoxIsRefusedWhenNoReadingOfItIsValidInBothChecks(string label, + byte[] jp2, string everyChannel, string namedChannels) + { + // The principle on JpxImageLoader: a reading keeps the file only if the name written has its count and every + // colour channel of it is 1 to 38 bits deep. Here one of the two checks fails under each reading, though each + // check passes under some reading, and the message names the failed check of each reading. + var e = Assert.Throws(() => JpxImageLoader.Load(jp2)); + Assert.Contains("the file is valid under neither reading", e.Message); + Assert.Contains(everyChannel, e.Message); + Assert.Contains(namedChannels, e.Message); + Assert.Throws(() => LayoutImage.FromBytes(jp2)); + Assert.NotEmpty(label); + } + + [Fact] + public void Iso32000_2_7_4_9_AFileWithAnIncompleteCdefBoxIsKeptUnderTheReadingThatIsValidInBothChecks() + { + // Channel 0 is 39 bits deep and undescribed, channel 1 is named and 8 bits deep, and the name has one component: + // the named reading passes both checks and the every-channel reading passes neither. + var grey = Jp2File(JpxCodestream(16, 16, 2, depths: [39, 8]), 2, 17, [38, 7], cdef: [(1, 0, 1)]); + Assert.Equal("DeviceGray", ColourSpaceWritten(grey)); + // The finding of ISO 19005-2, 6.2.8.3, is judged under that reading too: one colour channel, so one depth. + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(grey).Jp2Findings); + // Where the every-channel reading passes both checks it is the one kept, so its mixed depths are found. + var mixed = Jp2File(JpxCodestream(16, 16, 3, depths: [8, 8, 16]), 3, 16, [7, 7, 15], cdef: [(0, 0, 1), (1, 0, 2)]); + Assert.Equal("DeviceRGB", ColourSpaceWritten(mixed)); + Assert.Equal(Jp2Findings.ColourDepths, JpxImageLoader.Load(mixed).Jp2Findings); + } + + [Fact] + public void Iso32000_2_7_4_9_ALoneBoxWhoseSpaceHasNoCountIsKeptUnderTheReadingWhoseChannelsAreInRange() + { + // An ICC profile of a colour space that Table 19 does not list has no count, so either reading fits it. The + // every-channel reading has a channel of 39 bits, so the reading of the two named channels is the one kept, and + // the file, written with no ColorSpace, has two colour channels, which the Layout save reports. + var jp2 = Jp2File(JpxCodestream(16, 16, 3, depths: [8, 8, 39]), 3, null, [7, 7, 38], rawColr: [IccColr("XXXX")], + cdef: [(0, 0, 1), (1, 0, 2)]); + Assert.Null(ColourSpaceWritten(jp2)); + Assert.Equal(Jp2Findings.ColourChannelCount, JpxImageLoader.Load(jp2).Jp2Findings); + // With every channel 8 bits deep both readings are valid, and the every-channel reading is the one kept: three + // colour channels, which 6.2.8.3 allows, where the named reading would have two. + var shallow = Jp2File(JpxCodestream(16, 16, 3), 3, null, [7, 7, 7], rawColr: [IccColr("XXXX")], + cdef: [(0, 0, 1), (1, 0, 2)]); + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(shallow).Jp2Findings); + } + + [Fact] + public void Iso32000_2_7_4_9_AnIncompleteCdefBoxUnderALoneSpaceThatOnlyTheNamedChannelsFitReportsTheNamedCount() + { + // A lone sYCC box (three components) over five channels, three of them named: the named reading is the one the + // space fits, so the colour count is three and the file is not found to have another number of colour channels. + var jp2 = Jp2File(JpxCodestream(16, 16, 5), 5, null, boxes: [(1, 18)], cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3)]); + Assert.Null(ColourSpaceWritten(jp2)); + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(jp2).Jp2Findings); + } + + [Fact] + public void Iso32000_2_7_4_9_ACmykBoxOverAnIncompleteCdefBoxThatNamesFourOfFiveChannelsIsWrittenAsDeviceCmyk() + { + // Every channel is five and the name the count chooses (DeviceRGB) has three: the four named channels are the + // reading that CMYK fits. + var jp2 = Jp2File(JpxCodestream(16, 16, 5), 5, 12, cdef: [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 0, 4)]); + Assert.Equal("DeviceCMYK", ColourSpaceWritten(jp2)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Iso32000_2_7_4_9_ABpccBoxWithMoreEntriesThanChannelsIsNotAConformingFileAndItsExtraEntriesAreNoChannels(bool cdef) + { + // ISO/IEC 15444-1, I.5.3.2: one entry per channel. An entry past the last channel is no colour channel, so a + // deep one refuses the file for the box and says so, and a shallow one is not judged at all. + (int, int, int)[]? entries = cdef ? [(0, 0, 1), (1, 0, 2), (2, 0, 3), (3, 0, 4)] : null; + var deep = Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 7, 7, 38], cdef: entries); + var e = Assert.Throws(() => JpxImageLoader.Load(deep)); + Assert.Contains("its bpcc box has 4 entries and the image has 3 channels, so it is not a conforming JP2 file", e.Message); + Assert.Contains("I.5.3.2", e.Message); + Assert.DoesNotContain("a colour channel is", e.Message); + var shallow = Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 7, 7, 15], cdef: entries); + Assert.Equal("DeviceRGB", ColourSpaceWritten(shallow)); + Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(shallow).Jp2Findings); + } + [Fact] public void Iso19005_2_6_2_8_3_AnOpacityChannelOfMoreThanThirtyEightBitsIsNotReported() { From 4e18f544231463b4a03d1b6a047a21b3a6dd270a Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 21:28:39 +0100 Subject: [PATCH 21/22] docs(images): say which depths the LayoutImage refusal covers The refused-list item for a colour channel deeper than 38 bits had no qualifier, while the loader does not read the depths of a file with a palette or a JPX cmap box, a depth only the codestream shows beside a usable ihdr box, or an ihdr BPC of 255 with no bpcc box. The item now says so and points to the loader. --- src/VellumPdf.Layout/Elements/LayoutImage.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/VellumPdf.Layout/Elements/LayoutImage.cs b/src/VellumPdf.Layout/Elements/LayoutImage.cs index 2244137a3..971ccc973 100644 --- a/src/VellumPdf.Layout/Elements/LayoutImage.cs +++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs @@ -313,10 +313,10 @@ public LayoutImage(PdfImageXObject image) /// jp2h box whose colour channels, as defines them, are not as many as the /// components of the colour space it would write; a JP2 file none of whose readable colr boxes is an /// allowed colour specification (an ICC profile, CMYK, or an enumerated space of the JPX baseline list other - /// than CIEJab); and a JP2 file with a colour channel deeper than 38 bits, as - /// reads the depths, which it does not for a file with a palette, for a depth that - /// only the codestream shows beside a usable ihdr box, or for an ihdr BPC of 255 with no bpcc - /// box ( lists the cases). Nothing else is promised to be refused. + /// than CIEJab); and a JP2 file with a colour channel deeper than 38 bits, as reads + /// the depths, which it does not for a file with a palette or a JPX cmap box, for a depth that only the + /// codestream shows beside a usable ihdr box, or for an ihdr BPC of 255 with no bpcc box + /// ( lists the cases). Nothing else is promised to be refused. /// The loaders do not check every requirement of ISO 32000-2, 7.4.9: a JP2 file with no colr box, for /// one, is written. A JP2 file with exactly one colr box that names an ICC profile or an enumerated colour /// space that is not sRGB, greyscale or CMYK, such as sYCC, is written with no /ColorSpace, so the colour From 87830995177be0e06ebadc005e51a6d6c9c5c05f Mon Sep 17 00:00:00 2001 From: Tim81 Date: Tue, 1 Dec 2026 21:55:19 +0100 Subject: [PATCH 22/22] test(images): pin the depth check of a cdef box that describes every channel The principle says a complete cdef box has one reading, judged the same way as an incomplete one. A deep colour channel under such a box was covered only through a file with no box, so a test now covers it. The summary also says that the extra bpcc entries refuse only a file whose depths are read. --- src/VellumPdf.Kernel/Images/JpxImageLoader.cs | 4 ++-- .../ConformanceAuditG4Tests.JpxChannels.cs | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs index 6523b96b2..5bb25cb3f 100644 --- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs +++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs @@ -136,8 +136,8 @@ namespace VellumPdf.Images; /// deeper than 38 bits (the principle above), with , in every document, and the /// depths of a file with a palette or a JPX cmap box are not read for that either. A bpcc box with /// more entries than the image has channels is not a conforming JP2 file (ISO/IEC 15444-1, I.5.3.2, wants one entry -/// per channel); its extra entries are not channels and are not judged as such, and the file is refused when one -/// of them is deeper than 38 bits. This loader neither refuses nor reports the other findings. A +/// per channel); its extra entries are not channels and are not judged as such, and a file whose depths are read +/// is refused when one of them is deeper than 38 bits. This loader neither refuses nor reports the other findings. A /// VellumPdf.Layout save reports them under a PDF/A-2 claim as /// LayoutDiagnosticCode.JpxImageNotAllowedByPdfA, and strict mode refuses it. A document built on /// this loader and VellumPdf.Kernel alone has no such report. Do not pass such a file to a diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs index d5f0290c2..da8348f81 100644 --- a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs @@ -1124,6 +1124,16 @@ public void Iso32000_2_7_4_9_ABpccBoxWithMoreEntriesThanChannelsIsNotAConforming Assert.Equal(Jp2Findings.None, JpxImageLoader.Load(shallow).Jp2Findings); } + [Fact] + public void Iso32000_2_7_4_9_ACdefBoxThatDescribesEveryChannelHasOneReadingAndItsColourChannelsAreJudgedForDepth() + { + // Every channel is named, so there is one reading, and its third colour channel is 49 bits deep. + var deep = Jp2File(JpxCodestream(16, 16, 3), 3, 16, [7, 7, 0x30], cdef: Channels(3)); + var e = Assert.Throws(() => JpxImageLoader.Load(deep)); + Assert.Contains("a colour channel is 49 bits deep", e.Message); + Assert.DoesNotContain("valid under neither reading", e.Message); + } + [Fact] public void Iso19005_2_6_2_8_3_AnOpacityChannelOfMoreThanThirtyEightBitsIsNotReported() {