diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe8d32f1..9318e595 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -971,6 +971,115 @@ 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 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 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 counts the
+ 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 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.
+ 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, 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) 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
+ 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. A `cdef` box
+ 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
+ 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`, 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 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.
+
+- **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
+ 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 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/docs/conformance-v2.4.md b/docs/conformance-v2.4.md
index a630c1f5..73dd98b2 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 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` |
-| 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, 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) | 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) |
@@ -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/Jp2Findings.cs b/src/VellumPdf.Kernel/Images/Jp2Findings.cs
new file mode 100644
index 00000000..b36f5695
--- /dev/null
+++ b/src/VellumPdf.Kernel/Images/Jp2Findings.cs
@@ -0,0 +1,28 @@
+// 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,
+
+ ///
+ /// A file written with no /ColorSpace whose colour channels number other than 1, 3 or 4.
+ ///
+ ColourChannelCount = 8,
+}
diff --git a/src/VellumPdf.Kernel/Images/JpegImageLoader.cs b/src/VellumPdf.Kernel/Images/JpegImageLoader.cs
index 70d520a4..91f6a9f7 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 3725b82c..5bb25cb3 100644
--- a/src/VellumPdf.Kernel/Images/JpxImageLoader.cs
+++ b/src/VellumPdf.Kernel/Images/JpxImageLoader.cs
@@ -37,14 +37,112 @@ 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, 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:
///
-/// - 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 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, 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 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.
///
-/// ICC and indexed colour spaces from JP2 colr boxes are not yet handled;
-/// component-count inference is used as a fallback.
+/// 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 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, 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 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
+/// 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
+/// 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. 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 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 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 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
+/// 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
{
@@ -58,16 +156,40 @@ 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 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).
private const ushort MarkerSOC = 0xFF4F;
// 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.
+ // 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;
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).
@@ -79,8 +201,51 @@ 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 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
+ /// 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 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: 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 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,
+ /// 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 (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 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
+ /// 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.
+ ///
public static PdfImageXObject Load(byte[] jpx)
=> Load(jpx, ImageLoadOptions.Default);
@@ -99,13 +264,25 @@ 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 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
+ /// 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 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 .
/// Full JPEG 2000 decode (DWT + EBCOT + MQ arithmetic) is not yet supported; use
/// instead.
///
+ ///
+ /// 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)
{
ArgumentNullException.ThrowIfNull(jpx);
@@ -145,19 +322,25 @@ 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);
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 —
// 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 = survey.Findings(components),
+ };
}
// ── JP2 box file path ─────────────────────────────────────────────────────
@@ -166,11 +349,13 @@ 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).
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;
@@ -189,16 +374,23 @@ 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)
{
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;
@@ -219,22 +411,33 @@ 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)
{
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);
- var cs = InferColorSpace(nc, colrEnum);
+ // 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;
@@ -254,11 +457,18 @@ 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.
jp2 = BuildMinimalJp2(width, height, nc, bpc, colrEnum ?? EnumCsForComponents(nc), jp2cBox);
}
- return new PdfImageXObject(width, height, jp2, PdfName.JPXDecode, cs, bpc);
+ 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)
+ {
+ Jp2Findings = colr.Findings(nc),
+ };
}
// ── Box reading ───────────────────────────────────────────────────────────
@@ -335,7 +545,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;
@@ -385,10 +595,30 @@ 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:
- TryParseColr(data, subPayloadOffset, subPayloadLength, ref colrEnum);
+ TryParseColr(data, subPayloadOffset, subPayloadLength, ref colrEnum, colr);
+ break;
+
+ case BoxTypeBpcc:
+ // 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:
+ // 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.
+ colr.HasPalette = true;
+ break;
+
+ case BoxTypeCmap:
+ colr.HasCmap = true;
+ break;
+
+ case BoxTypeCdef:
+ TryParseCdef(data, subPayloadOffset, subPayloadLength, colr);
break;
}
@@ -414,28 +644,307 @@ 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)
{
+ colr.Boxes++;
if (length < 3)
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;
+ 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;
+ }
+ }
+
+ // 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 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 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.
+ private static int EnumeratedComponentsOf(int value) => value switch
+ {
+ 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,
+ // 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 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)
+ return;
+ if (length < 2 || length < 2 + 6 * ReadUInt16Be(data, offset))
+ {
+ colr.HasUnreadableCdef = true;
+ return;
+ }
+ 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(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,
+ // 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;
+ }
+
+ // 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
+ // 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
+ {
+ // 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; }
+ public List NotAllowed { get; } = [];
+ 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; }
+ 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.
+ // 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);
+
+ // 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), 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.");
+ }
+
+ // 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 false;
+ for (var channel = 0; channel < channels; channel++)
+ if (!DescribedChannels.Contains(channel))
+ return false;
+ return true;
+ }
+
+ // 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)];
+ }
+
+ // 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 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;
+ if (Boxes > 1 && Approx1Boxes != 1)
+ found |= Jp2Findings.ColourSpecificationApprox;
+ if (OtherMethod)
+ found |= Jp2Findings.ColourMethod;
+ if (UnnamedColourChannels is not (null or 1 or 3 or 4))
+ found |= Jp2Findings.ColourChannelCount;
+ 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. 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)
+ {
+ 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: 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 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;
+ if (perChannel is null)
+ 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;
}
- // 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.
}
// ── SIZ marker parsing ────────────────────────────────────────────────────
///
/// 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.
@@ -470,11 +979,37 @@ 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 & RsizExtendedBit) != 0)
+ throw new InvalidDataException(
+ $"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).");
+ }
+
+ // 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).
///
- 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)
@@ -499,6 +1034,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);
@@ -528,11 +1065,171 @@ 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 ────────────────────────────────────────────────
+ // 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 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.
+ // - 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).
+ // - 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)
+ {
+ 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.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, and is a space
+ // 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 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 components = colr.HasIccProfile ? colr.IccComponents : EnumeratedComponentsOf(colr.Enumerated[0]);
+ var named = InferColorSpace(channels, colrEnum);
+ if (colr.FirstValid(channels, r => components is null || r.Count == components) is { } space)
+ {
+ colr.Kept = space;
+ colr.UnnamedColourChannels = space.Count;
+ return null;
+ }
+ if (colr.FirstValid(channels, r => r.Count == ComponentsOf(named)) is { } name)
+ {
+ colr.Kept = name;
+ return named;
+ }
+ 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)}, 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).");
+ }
+
+ // 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), which the class summary defines. The name must have exactly
+ // 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 components = ComponentsOf(named);
+ if (colr.FirstValid(channels, r => r.Count == components) is { } name)
+ {
+ colr.Kept = name;
+ return named;
+ }
+ 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)}, 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)
+ {
+ 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 {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 " +
+ "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) =>
+ 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
+ // 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 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).");
+ }
+
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 b406a9bb..a04bce65 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)
{
@@ -59,6 +61,12 @@ internal PdfImageXObject(
_passthrough = !filter.Equals(PdfName.FlateDecode);
}
+ ///
+ /// 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 Jp2Findings Jp2Findings { get; init; }
+
/// The soft-mask (alpha channel) stream, or when the image is opaque.
public PdfStream? SMask => _sMask;
@@ -135,8 +143,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 +173,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/PngImageLoader.cs b/src/VellumPdf.Kernel/Images/PngImageLoader.cs
index f3e51b89..fc26e996 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/src/VellumPdf.Kernel/Images/TiffImageLoader.cs b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs
index 475f6214..46224485 100644
--- a/src/VellumPdf.Kernel/Images/TiffImageLoader.cs
+++ b/src/VellumPdf.Kernel/Images/TiffImageLoader.cs
@@ -116,10 +116,17 @@ 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. 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
@@ -142,6 +149,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
@@ -604,7 +614,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 +848,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 +895,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 +904,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 +925,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/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs
index 13ccd03d..23d66fa9 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 whose colour
+ /// 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 a7a0b34d..971ccc97 100644
--- a/src/VellumPdf.Layout/Elements/LayoutImage.cs
+++ b/src/VellumPdf.Layout/Elements/LayoutImage.cs
@@ -304,6 +304,27 @@ 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.
+ /// 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, 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
+ /// 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.
/// 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 +460,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 +580,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/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs
index b0b120b1..679dc052 100644
--- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs
+++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs
@@ -333,6 +333,41 @@ 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 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, 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.
+ ///
+ ///
+ /// 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 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, 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, 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
+ /// 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
+ /// 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 ff11440e..9b0caa18 100644
--- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt
+++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt
@@ -260,6 +260,7 @@ 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
VellumPdf.Layout.Elements.PageLabelRange.Header.get -> VellumPdf.Layout.Elements.RunningBand?
VellumPdf.Layout.Elements.PageLabelRange.Header.init -> void
VellumPdf.Layout.Elements.PageLabelRange.Footer.get -> VellumPdf.Layout.Elements.RunningBand?
diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs
index b43679cc..dfb7b6a0 100644
--- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs
+++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.Zones.cs
@@ -212,6 +212,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);
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 00000000..74bac78a
--- /dev/null
+++ b/src/VellumPdf.Layout/Rendering/ImageDiagnostics.cs
@@ -0,0 +1,43 @@
+// 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 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.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");
+ 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.");
+ 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.");
+ }
+}
diff --git a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs
index 3674f228..61330137 100644
--- a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs
+++ b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs
@@ -277,6 +277,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 478fd26e..d6b29309 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);
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 de9e7717..70973b52 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;
@@ -70,6 +74,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"),
@@ -358,51 +366,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)));
+ 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]
- 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"))));
- }
-
- [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]
@@ -639,29 +669,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()
{
@@ -675,21 +682,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,
@@ -699,6 +691,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]
@@ -722,7 +747,10 @@ 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, (int Method, int Value)[]? boxes = null,
+ 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)
{
@@ -740,117 +768,245 @@ 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]]) : [],
+ // 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])] : [],
+ .. 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", [.. noIhdr ? [] : 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()
+ [Theory]
+ [InlineData(18)]
+ [InlineData(20)]
+ [InlineData(21)]
+ [InlineData(24)]
+ public void Iso32000_2_7_4_9_AJp2ColourSpecificationThatIsNotADeviceSpaceIsNotOverriddenByADeviceName(int enumerated)
{
- // 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"));
+ // 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]);
+ 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]
+ public void Iso32000_2_7_4_9_AJp2WithAnEnumeratedDeviceSpaceAmongItsColourSpecificationsKeepsTheDeviceName()
+ {
+ // 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"));
+ }
- // 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));
+ [Theory]
+ [InlineData(2)]
+ [InlineData(5)]
+ [InlineData(16)]
+ 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 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)));
+ Assert.Throws(() => JpxImageLoader.Load(Jp2File(JpxCodestream(16, 16, channels), channels,
+ null, noJp2h: true)));
}
- [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 Iso19005_2_6_2_8_3_AJp2FileOfTwoChannelsBesideGreyscaleIsRefusedAndOneWithAGreyAndAnOpacityChannelIsWritten()
{
- AssertRefusedOrAcceptedByVeraPdf(new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, "DeviceRGB", 8, "JPXDecode"));
+ // 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"));
}
+ /// 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");
+
///
- /// 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.
+ /// 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 void AssertRefusedOrAcceptedByVeraPdf(Kind kind)
+ 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")
+ {
+ var doc = NewDocument(claim);
+ doc.Add(new LayoutImage(Load(kind)) { Width = 40, Height = 20, AltText = alt });
+ return doc;
+ }
+
+ public static TheoryData PdfAImagesNotAllowed() => new()
+ {
+ { "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 switch
+ {
+ "approx" => ApproxKind(),
+ "method" => MethodKind(),
+ _ => DifferentDepthsKind(),
+ };
+
+ [Theory]
+ [MemberData(nameof(PdfAImagesNotAllowed))]
+ public void Iso19005_2_6_2_8_3_AJp2FileThatBreaksTheClauseIsWrittenAndReportedUnderAPdfAClaim(string which, string text)
{
- byte[] file;
- try
+ // 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 })
{
- file = ImageFile(PdfConformance.PdfA2b, kind);
+ 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.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.
+ Assert.Equal("JPXDecode", Written(file).Name("Filter"));
}
- catch (InvalidDataException)
+
+ 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_AJp2FileThatBreaksTheClauseIsNotReportedWithoutAPdfAClaim(string which, string text)
+ {
+ Assert.NotEmpty(text);
+ foreach (var claim in new[] { PdfConformance.None, PdfConformance.PdfUA1 })
{
- return;
+ using var doc = DocumentWith(claim, PdfAImage(which));
+ doc.StrictDiagnostics = true;
+ Assert.NotEmpty(Save(doc));
+ Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA);
}
-
- Assert.Null(Written(file).Dict.Get(N("ColorSpace")));
- Assert.Empty(VeraFailures("2b", file));
}
[Fact]
- public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndFailsVeraPdf()
+ public void Iso19005_2_6_2_8_3_AJp2FileOfOneThreeOrFourChannelsOfOneDepthIsNotReported()
{
- // 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");
- Assert.Equal("DeviceGray", Written(ImageFile(PdfConformance.None, kind)).Name("ColorSpace"));
- Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind)));
+ 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(Skip = "Gap #763: 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()
+ [Fact]
+ public void Iso19005_2_6_2_8_3_AJp2FileWithAllThreeFindingsGivesOneItemForEach()
{
- AssertRefusedOrAcceptedByVeraPdf(new Kind("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 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(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();
@@ -859,109 +1015,190 @@ 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 " +
- "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,
[7, 7, 3]), 16, 16, "DeviceRGB", 8, "JPXDecode");
[Fact]
- public void Iso32000_2_7_4_9_PinsTodayAJp2WithACieJabColourSpecificationIsWrittenAsDeviceRgbAndVeraPdfDoesNotLook()
+ public void Iso32000_2_7_4_9_AJp2FileWhoseOnlyColourSpecificationIsCieJabIsRefused()
{
- // 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 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]
+ 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.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 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);
}
- [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_AJp2FileWithCieJabAndAnotherEnumeratedSpaceIsNotRefused()
{
- 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 image = Written(file);
- 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]);
+ // 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.Equal("DeviceRGB", image.Name("ColorSpace"));
}
[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,
+ // 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(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.
+ [Theory]
+ [InlineData(0x4000)]
+ [InlineData(0x4001)]
+ [InlineData(0xC000)]
+ [InlineData(0x7FFF)]
+ public void Iso32000_2_7_4_9_ARsizWithTheExtendedCapabilitiesBitIsRefused(int rsiz)
+ {
+ var codestream = JpxCodestream(16, 16, 3, 7, rsiz);
+ 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. 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)]
+ [InlineData(2)]
+ [InlineData(0x0FFF)]
+ [InlineData(0x3FFF)]
+ [InlineData(0x8000)]
+ [InlineData(0x8004)]
+ [InlineData(0x8008)]
+ [InlineData(0x8200)]
+ [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);
+ 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("JPXDecode", image.Name("Filter"));
- var codestream = Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload;
- Assert.Equal([0x80, 0x00], codestream[6..8]);
+ Assert.Equal(codestream, Jp2Boxes(jp2.Raw).Single(b => b.Type == "jp2c").Payload);
}
- [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()
+ // 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);
+ }
+
+ [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)
{
- Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000)));
+ // 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" };
- 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]
diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs
new file mode 100644
index 00000000..da8348f8
--- /dev/null
+++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.JpxChannels.cs
@@ -0,0 +1,1199 @@
+// 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, and ISO/IEC 15444-1, I.5.3.6, are the clauses.
+///
+public sealed partial class ConformanceAuditG4Tests
+{
+ 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 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)
+ {
+ 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)
+ {
+ 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)] // 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, 21)]
+ 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 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 hold the three components of DeviceRGB
+ [InlineData(2, null)] // no colr box: the count chooses DeviceRGB
+ [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(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)
+ {
+ 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($"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")));
+ }
+
+ [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 reach.
+ var jp2 = Jp2Of(2, null, boxes: [(2, 0), (1, 18)]);
+ Assert.Throws(() => JpxImageLoader.Load(jp2));
+ }
+
+ [Theory]
+ [InlineData(1, 17, "DeviceGray")]
+ [InlineData(3, 16, "DeviceRGB")]
+ [InlineData(4, 12, "DeviceCMYK")]
+ [InlineData(4, null, "DeviceCMYK")]
+ [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_AShortCdefBoxIsSkippedAndTheFirstOneLongEnoughIsRead()
+ {
+ // 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 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 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]);
+ 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 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 Iso32000_2_7_4_9_ACmapBoxWithoutAPclrBoxInAJp2FileIsNotAPaletteAndIsJudgedByItsChannelCount()
+ {
+ // 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 ──────────────────────────────────────────────────
+
+ // 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
+ [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)]);
+ 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
+ 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]
+ 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, 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 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);
+ }
+
+ [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(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 });
+ 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);
+ }
+
+ // ── Colour channels only, and depth only ─────────────────────────────────────────────────
+
+ [Fact]
+ public void Iso19005_2_6_2_8_3_ABpccBoxOfOneDepthAndDifferentSignsIsNotReported()
+ {
+ // 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);
+ 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 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, 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 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)]
+ [InlineData(3, 21)]
+ [InlineData(3, 24)]
+ [InlineData(3, 14)]
+ 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")));
+ }
+
+ // 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(2, 18)] // no device name has two components
+ [InlineData(5, 18)]
+ [InlineData(2, 20)]
+ [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));
+ 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));
+ }
+
+ // 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}, 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);
+ 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)]
+ [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, "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", 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()
+ {
+ // 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))));
+ // 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_AnIccProfileWhoseComponentsAreNotKnownIsNotComparedAndAProfileWithNoHeaderEither()
+ {
+ // 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,
+ 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")] // four entries for a one-channel image: capped at one
+ [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: 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,
+ int enumerated, int[] colourEntries, string name)
+ {
+ // 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(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 {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")] // 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_ACdefBoxThatLeavesAChannelUndescribedKeepsANameThatFitsTheCountOfEveryChannel(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(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 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]
+ [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()
+ {
+ // 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")));
+ }
+
+ // ── 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 Iso32000_2_7_4_9_AColourChannelOfMoreThanThirtyEightBitsIsRefusedInEveryDocument()
+ {
+ // 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 })
+ {
+ 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));
+ 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));
+ }
+
+ // ── 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 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()
+ {
+ // 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. 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",
+ Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.JpxImageNotAllowedByPdfA).Message);
+ }
+
+ // ── 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")));
+ }
+}
diff --git a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs
index 2a56b57b..1e78fb96 100644
--- a/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs
+++ b/tests/VellumPdf.Kernel.Tests/JpxImageTests.cs
@@ -232,12 +232,14 @@ public void Jp2_Colr_SRgb16_ReportsDeviceRgb()
}
[Fact]
- public void Jp2_Colr_Greyscale17_ReportsDeviceGray()
+ 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);
- var img = JpxImageLoader.Load(jp2.File);
- // colr greyscale enum overrides the 3-component default of DeviceRGB.
- Assert.Contains("/DeviceGray", StreamDictText(img));
+ Assert.Throws(() => JpxImageLoader.Load(jp2.File));
}
// ── DecodeToRaster: not supported ─────────────────────────────────────────