diff --git a/docs/conformance-v2.4.md b/docs/conformance-v2.4.md index 382a99a9..04a3b4e3 100644 --- a/docs/conformance-v2.4.md +++ b/docs/conformance-v2.4.md @@ -359,6 +359,113 @@ for a note block or on the P of a blank paragraph. ## G4 Graphics and images +Tests: `ConformanceAuditG4Tests` in `tests/VellumPdf.Kernel.Tests`, run at origin/main b2791ba. Every image is generated in the +test from its format's own layout, with nothing on disk and nothing downloaded: PNG of each colour type and depth, a JPEG that is a +frame header only, BMP, GIF, TIFF, JBIG2, and JPEG 2000 codestreams and JP2 files. Each goes through `LayoutImage.FromBytes`, is +saved under no claim and under PDF/A-2b, 2u, 2a and PDF/UA-1, and is read back through the Reader. veraPDF 1.30.4 and qpdf 12.4.2 run on +the claimed fixtures, and poppler reads the text of the justified lines. Fonts are DejaVu Sans, plus the Standard 14 faces in the word-spacing +rows under no claim. + +53 rows: 32 compliant, 15 gap, 3 not applicable, 3 human-only. A row that is compliant for most input and has a gap for one construct +is counted as a gap. Five gaps are new: #763 (JPEG and JPEG 2000 data the loaders describe with a colour space or sample size it does not +have), #764 (TIFF associated alpha written without Matte), #768 (a PNG colour key with bits above the bit depth), #769 (TIFF Orientation) and +#770 (a JPEG 2000 codestream outside the baseline feature set). The others cite the issue that already tracks them: #474, +#621, #303 and #583. Each gap has a test that pins today's output. Where the output a fix must produce is known, a skipped test asserts it; +the #474 row has none, because #474 asks for a report through the notify-and-continue channel, which has no member for this report yet. + +veraPDF has no rule for the consistency of an image dictionary with its data, a soft-mask image's restrictions, a colour key's range, the +component count a DCT stream may carry or the word spacing of a composite font, so the tests assert the written keys, operands and +bytes and use the oracles as a second reading. The veraPDF rules for this group were read from the profiles in `cli-1.30.4.jar`: 6.1.7.1, +6.1.7.2, 6.1.13, 6.2.2 to 6.2.6, 6.2.8, 6.2.8.3, 6.2.9, 6.2.10, and for PDF/UA-1 7.1-1 to 7.1-3 and 7.3-1. + +Feature key: IMG is an image loaded by `LayoutImage.FromBytes`, `FromFile` or `FromStream` (#720) through the PNG, JPEG, BMP, GIF, TIFF, +JBIG2 or JPEG 2000 loader (#624 and #628 hardened the BMP, TIFF and GIF ones); FIT is `LayoutImage.FitToPage` (#683); NOTE is a +`NoteBlock` background and border (#721); RULE is a `BandRule` and LOGO a `BandZone.Logo` (#735); JUST is a justified paragraph (#674, #665). + +| 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.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 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` | +| ISO 32000-1 7.4.1, Table 6; ISO 19005-2 6.1.7.2 | The filters written are Table 6 filters other than LZWDecode (veraPDF 6.1.7.2-1) | IMG | compliant: Flate, DCT, CCITT, JBIG2 and JPX | `Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies`, `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf` | +| ISO 19005-2 6.1.7.1 | Length is the number of bytes between the keywords; the stream dictionary has no F, FFilter or FDecodeParms (veraPDF 6.1.7.1-1, 6.1.7.1-2, 6.1.7.1-3) | IMG | compliant | `Iso19005_2_6_1_7_1_TheLengthOfAnImageStreamIsTheNumberOfBytesBetweenItsKeywords` | +| ISO 32000-1 7.4.6, Table 11 | A CCITT stream names Columns and Rows and K; BlackIs1 is absent when the polarity is the default | IMG (TIFF Group 3 and Group 4) | compliant | `Iso32000_1_7_4_6_ACcittImageNamesItsColumnsAndRowsAndKeepsTheDefaultPolarity` | +| 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-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 full text is not held (needs NEN) | `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 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 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) | +| ISO 32000-2 7.5.2; ISO 19005-2 6.1.2 | The header's version is one that has every feature the file uses (veraPDF 6.1.2) | IMG | compliant: PDF 2.0 under no claim, PDF 1.7 under a claim, both at or above 1.5 | `Iso32000_2_7_5_2_TheHeaderNamesAVersionThatHasEveryFeatureTheImagesUse` | +| ISO 19005-2 6.2.4.3; ISO 32000-1 8.6.4 | DeviceRGB needs a matching RGB output intent (or DefaultRGB), DeviceCMYK a CMYK one, DeviceGray any PDF/A output intent (veraPDF 6.2.4.3-2, 6.2.4.3-3, 6.2.4.3-4) | IMG, NOTE, RULE, LOGO | gap #474 where the family does not match (a CMYK image under sRGB; an RGB image, note block or rule under a CMYK intent): the file is saved with its claim and veraPDF fails it. Compliant where it matches (RGB and grey under the default sRGB intent, CMYK and grey under a CMYK intent) | `Iso19005_2_6_2_4_3_TheFileHoldsTheColourSpaceItPaintsAndVeraPdfFailsOnlyWhereTheIntentIsOfAnotherFamily`, `Iso19005_2_6_2_4_3_PinsTodayAFileThatPaintsAColourItsOutputIntentDoesNotCoverIsSavedWithItsClaim` (no skipped test: #474 asks for a report through the notify-and-continue channel, which has no member for this report yet) | +| ISO 19005-2 6.2.3 | The output intent's profile is a prtr or mntr profile of version below 5 (veraPDF 6.2.3-1, 6.2.3-2, 6.2.3-3) | IMG, NOTE | compliant for the sRGB and the generic CMYK profiles | `Iso19005_2_6_2_4_3_TheFileHoldsTheColourSpaceItPaintsAndVeraPdfFailsOnlyWhereTheIntentIsOfAnotherFamily` | +| ISO 19005-2 6.2.4.2, 6.2.4.4 | ICCBased profile versions and overprint; Separation and DeviceN rules (veraPDF 6.2.4.2-1, 6.2.4.2-2, 6.2.4.4-1, 6.2.4.4-2) | IMG, NOTE, RULE | not applicable: no image, note block or band rule writes ICCBased, Separation or DeviceN; the three image colour spaces are device names (`ImageColorSpace` has three members) | none | +| ISO 19005-2 6.2.5, 6.2.6, 6.2.9; ISO 32000-1 8.6.5.8 | No TR, TR2, HTP or halftone, rendering intents are the four defined, no reference or PostScript XObject (veraPDF 6.2.5-1 to 6.2.5-6, 6.2.6-1, 6.2.9-1 to 6.2.9-3) | IMG, NOTE, RULE | not applicable: none of the fixtures has an ExtGState, `gs`, `ri`, a form XObject or a halftone (the tests assert it for the note block and the rule; `src/VellumPdf.Layout` and `src/VellumPdf.Kernel/Images` have no `Intent`, `ri` or form writer) | `Iso32000_1_8_6_4_3_ANoteBlockPaintsItsBackgroundAndBorderWithDeviceRgbOperands` | +| ISO 19005-2 6.2.10; ISO 32000-1 11.4.7, Table 30 | Transparency is allowed; a page that uses it needs a Group with CS only when the file has no PDF/A output intent (veraPDF 6.2.10-1, 6.2.10-2) | IMG (soft mask) | compliant: no Group, ExtGState or blend mode is written, and a PDF/A file always has the sRGB intent; the exact wording of the condition needs NEN | `Iso19005_2_6_2_10_AnImageWithASoftMaskNeedsNoPageGroupWhenAnOutputIntentIsPresent`, `Iso19005_2_6_2_10_TheTransparentImagesOfEveryLoaderPassVeraPdfAndQpdf` | +| ISO 19005-2 6.2.2, 6.2.8 | Only operators of ISO 32000-1; the images are accepted by veraPDF and qpdf (veraPDF 6.2.2-1, 6.2.2-2) | IMG | compliant under 2b, 2u, 2a and UA-1 for the output of every loader except the DeviceCMYK kinds, which fail 6.2.4.3-3 under the sRGB intent (#474); the JPEG frame headers are left out of the qpdf run, which decodes them | `Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf` | +| ISO 32000-1 8.6.4.3; ISO 32000-2 8.6.4.3 | A DeviceRGB component is a number from 0.0 to 1.0, set by `rg` or `RG` | NOTE, RULE | compliant: the `NoteBlock` setters and the `BandRule` constructor refuse a channel outside the range, NaN or infinity (`ColorRgb` itself never throws); 0 and 1 are written, and a value below 5e-6 is written as 0 | `Iso32000_1_8_6_4_3_AChannelOutsideZeroToOneIsRefusedWhenTheColourIsBuilt`, `Iso32000_1_8_6_4_3_AChannelIsWrittenAsItsFiveDecimalFormAndATinyOneAsZero` | +| ISO 32000-1 8.6.4.3, 8.5.3 | The note block fills its background and then four border bars with `rg`, `re` and `f`, inside q and Q | NOTE | compliant: the background covers the box, the bars are BorderWidth thick inside it, one path | `Iso32000_1_8_6_4_3_ANoteBlockPaintsItsBackgroundAndBorderWithDeviceRgbOperands` | +| ISO 32000-1 8.4.3.2; ISO 32000-2 8.4.3.2 | The line width is not negative; a width of 0 is the thinnest line the device draws and should not be used | RULE | compliant: a negative or non-finite width is refused when the rule is built; 0 is written as `0 w` (the clause advises against it, and `BandRule` documents it) | `Iso32000_1_8_4_3_2_ABandRuleIsOneStrokedLineOfItsWidthInItsColour`, `Iso32000_1_8_4_3_2_AZeroWidthRuleIsWrittenAsAZeroLineWidthWhichTheClauseAllows`, `Iso32000_1_8_4_3_2_ANegativeOrNonFiniteRuleWidthIsRefusedWhenTheRuleIsBuilt` | +| ISO 19005-2 6.2.4.3 | A note block and a band rule in a PDF/A file with the default sRGB intent pass veraPDF and qpdf (veraPDF 6.2.4.3-2) | NOTE, RULE | compliant under 2b, 2u and 2a (and under UA-1) | `Iso19005_2_6_2_4_3_ANoteBlockInAFileWithAnSrgbOutputIntentPassesVeraPdfAndQpdf`, `Iso19005_2_6_2_4_3_ABandRuleInAFileWithAnSrgbOutputIntentPassesVeraPdfAndQpdf` | +| ISO 32000-1 8.3.4, 8.9.4; ISO 32000-2 8.3.4, 8.9.4 | An image is placed by one `cm` of the form [w 0 0 h x y] inside q and Q, with positive extents so the matrix is invertible | FIT | compliant on seven page sizes, margins, running bands and alignments | `Iso32000_1_8_9_4_AFittedImageIsAUnitSquareScaledInsideTheContentBoxWithItsProportions` | +| ISO 32000-1 8.9.4 | The image lies inside the content box and the MediaBox, and keeps its proportions | FIT | compliant: a taller image is scaled to the content height, one that fits is not enlarged | `Iso32000_1_8_9_4_AFittedImageIsAUnitSquareScaledInsideTheContentBoxWithItsProportions`, `Iso32000_1_8_9_4_WithoutFitToPageAnImageTallerThanTheContentBoxIsRefusedAndOneThatFitsIsUnchanged` | +| ISO 32000-1 8.3.4 | A non-invertible matrix is avoided | FIT | compliant: a fitted extent that would be written as 0 is refused when the document is saved | `Iso32000_1_8_3_4_AFitThatWouldWriteAnExtentAsZeroIsRefusedAndNeverMakesTheMatrixSingular` | +| ISO 19005-2 6.1.13; ISO 32000-1 7.3.3, 8.4.2 | Reals are within +-3.403e38 and none nonzero is closer to zero than 1.175e-38; numbers are written as plain decimals with no exponent (7.3.3); q and Q are balanced (8.4.2) and nested at most 28 deep (veraPDF 6.1.13-2, 6.1.13-5, 6.1.13-8) | FIT, NOTE, RULE | compliant: operands have at most five decimals and no exponent; the q depth of a fitted image is 1 | `Iso32000_1_8_9_4_AFittedImageIsAUnitSquareScaledInsideTheContentBoxWithItsProportions`, `Iso32000_1_8_4_2_AFittedImageIsDrawnInsideItsOwnGraphicsStateSoNothingAfterItIsScaled` | +| ISO 32000-1 Table 30 (Rotate) | A page's rotation does not change what the matrix means | FIT | not applicable: the Layout document writes no /Rotate (searched `Document.cs` for rotate); the Kernel `PdfPage.Rotate` is a separate member | none | +| ISO 32000-1 9.3.3; ISO 32000-2 9.3.3 | Tw applies to the single-byte code 32 of a simple font | JUST (Standard 14) | compliant: a justified line sets Tw so that the string and its code-32 spaces fill the box exactly, and sets it back to 0 | `Iso32000_1_9_3_3_AJustifiedStandard14LineSpreadsItsSlackOverTheSingleByteSpacesWithTw` | +| ISO 32000-1 9.3.3; ISO 32000-2 9.3.3 | Tw does not apply to a byte 32 inside a multiple-byte code | JUST (embedded Type 0) | compliant: Tw is never set for a justified line in an embedded font; words are positioned with Tm | `Iso32000_1_9_3_3_AJustifiedEmbeddedFontLineSetsNoWordSpacingBecauseItsCodesAreTwoBytes` | +| ISO 32000-1 9.3.3 | The same, on a line that mixes a Standard 14 and an embedded fragment | JUST | compliant: no Tw on the line | `Iso32000_1_9_3_3_AJustifiedLineThatMixesAStandard14AndAnEmbeddedFragmentSetsNoWordSpacing` | +| ISO 32000-1 9.3.3 | A no-break space is not code 32, so Tw does not stretch it | JUST | compliant: the slack is shared by the code-32 spaces only | `Iso32000_1_9_3_3_ANoBreakSpaceIsNotCode32SoTwDoesNotSpreadTheSlackOverIt` | +| ISO 14289-1 7.3; Matterhorn 13-001, 13-004 | A graphic that is real content is tagged Figure, and the Figure has Alt (veraPDF 7.1-3, 7.3-1) | IMG | compliant: a Figure with an MCID and an Alt in tagged files (2a, UA-1); the Alt of an image with no `AltText` is the word Figure (#583) | `Iso14289_1_7_3_ABodyImageIsAFigureWithAltTextWhenTheFileIsTagged`, `Iso14289_1_7_3_VeraPdfAcceptsATaggedFigureAndAnArtifactBackgroundUnderEveryClaim` | +| ISO 14289-1 7.3; Matterhorn 13-004 | The Alt text represents the contents of the figure (veraPDF 7.3-1) | IMG | gap #583: an image with no `AltText` gets the placeholder "Figure", which is present but describes nothing | `Iso14289_1_7_3_ABodyImageIsAFigureWithAltTextWhenTheFileIsTagged` | +| ISO 14289-1 7.3, 7.1; Matterhorn 01-003 to 01-005 | A graphic that is not meaningful content is an artifact, and everything painted is tagged or an artifact (veraPDF 7.1-1, 7.1-2, 7.1-3) | NOTE, RULE, LOGO | compliant: the note block's fill and border, a band rule and a band logo are one Artifact sequence each in a tagged file, outside the structure tree | `Iso14289_1_7_3_ALogoInABandIsAnArtifactAndNotAFigure`, `Iso14289_1_7_1_WhatIsPaintedOutsideTheStructureIsAnArtifactAndNothingIsPaintedOutsideBoth`, `Iso32000_1_8_6_4_3_ANoteBlockPaintsItsBackgroundAndBorderWithDeviceRgbOperands` | +| ISO 14289-1 7.1; Matterhorn 01-001, 01-002 | Real content is not marked as an artifact and decoration is not tagged | NOTE, RULE, LOGO | human-only: Matterhorn 01-001, 01-002 (a note block's colour may carry the meaning "warning", which the structure tree does not state) | none | +| ISO 14289-1 7.1; Matterhorn 04-001 | Information is not conveyed by colour alone | NOTE, RULE | human-only: Matterhorn 04-001 | none | +| ISO 14289-1 7.3; Matterhorn 13-003, 13-005, 13-006, 13-007, 13-008 | A caption is a Caption; ActualText is not used for a Figure; grouped graphics are one Figure; a more accessible form is used | IMG | human-only: Matterhorn 13-003 (no Caption is written: #295), 13-005 to 13-008 | none | +| ISO 19005-2 6.7.3.1 | Rules and backgrounds are Layout artifacts, running heads Pagination artifacts (a should, binding at level A) | NOTE, RULE, LOGO | gap #303: each is a bare /Artifact | `Iso32000_1_8_6_4_3_ANoteBlockPaintsItsBackgroundAndBorderWithDeviceRgbOperands`, `Iso19005_2_6_7_3_1_TheNoteBlockArtifactCarriesATypeInItsPropertyList` (skipped) | + +Oracle checks and product notes outside the count (they hold a property of poppler or of the product, not a requirement of a clause): + +| Check | Test | +|---|---| +| pdftotext in content order reads the words of a justified line, Standard 14 or embedded, separated by one space | `Iso32000_1_9_3_3_PopplerReadsTheWordsOfAJustifiedLineSeparatedByOneSpaceInRawOrder` | +| Reducing a 16-bit PNG to eight bits keeps the high byte of its colour key, which masks every sample with that high byte; the key stays in range, so no clause is broken, and `ImageLoadOptions` does not say it | `Iso32000_1_8_9_6_4_PinsTodayReducingToEightBitsWidensASixteenBitKeyToAllSamplesWithTheSameHighByte` | + +Not done in this audit: + +- The encoders (#491, #494, #495) and the v2.5 work are out of scope. The image encoding is always the loader's: Flate for raster data, a + passthrough for JPEG, CCITT, JBIG2 and JPEG 2000. +- The JPEG, JPEG 2000, JBIG2 and CCITT fixtures are frame headers or short synthetic streams, so none of them decodes to a picture. qpdf + decodes a DCT body and warns about the frame headers, so the qpdf run leaves the JPEG kinds out. The decode of these filters is not measured. +- Pixel output was measured once, by hand: poppler's rendering of the associated-alpha TIFF in #764. No test renders a page. +- An Adobe CMYK JPEG, whose samples are stored inverted, is passed through without a `Decode` array. No clause was found that makes + this a requirement, and it was not measured. +- Barcodes draw with `rg` too (`BarcodePainter`), but the package is unchanged since v2.3.3 and is out of this group. It belongs to the same + class as #474 for a CMYK output intent. +- The colours of text, table cells and the pie chart, and the human-readable text of a barcode, are older than v2.4 and were not run. +- Page `/Rotate` is written by `PdfPage.Rotate` in the Kernel only; Layout writes none, so FitToPage on a rotated page has no fixture. +- Interlaced and multi-frame GIF, planar and LZW TIFF, and Adam7 PNG were not run through the oracles. + +ISO 19005-2 rows that need the maintainer's NEN check before the test is acceptance (the notes record these as paraphrased or read in +part): 6.2.3 (the profile rules beyond veraPDF's 6.2.3-1 to 6.2.3-3, and the use of `DefaultRGB`), 6.2.4.1 and 6.2.4.3 (the wording of the +Default colour space alternative for each device space), 6.2.8.3 (the rules on the effective device colour space of a JPX image, which decide +what a loader may write when `ColorSpace` is absent, as #763 proposes), 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 Annex A). + ## G5 File structure and metadata Audited at origin/main bbf317b, 68 commits after v2.3.3. Fixtures are saved in the test with the fonts in the tree, under no claim and under PDF/A-2b, 2u, 2a and PDF/UA-1, through six paths: the Layout document, the Kernel document, object streams, linearization, the unsigned placeholder of the signing path, and the signed file. `AuditScanner` reads the saved bytes without the library's Reader. veraPDF 1.30.4 and qpdf 12.4.2 run on every claimed fixture, and veraPDF is not run on the unsigned placeholder, because its /ByteRange holds ten nines until the signature patches it. diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Support.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Support.cs new file mode 100644 index 00000000..d9dad87d --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Support.cs @@ -0,0 +1,477 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Canvas; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.TestSupport; +using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; +using LayoutDocument = VellumPdf.Layout.Document; + +namespace VellumPdf.Kernel.Tests; + +/// +/// What the graphics and images audit (G4) builds and reads back: image files of every format the +/// factories read, generated from each format's own layout with no file on disk; the image +/// XObjects of a saved file with the dictionary entries of each; and the colour and placement +/// operators of its content streams. Fixtures use only the fonts in the tree. +/// +internal static class ConformanceAuditG4Support +{ + // ── PNG ───────────────────────────────────────────────────────────────────────────────── + + private static readonly uint[] CrcTable = BuildCrcTable(); + + private static uint[] BuildCrcTable() + { + var table = new uint[256]; + for (uint n = 0; n < 256; n++) + { + var c = n; + for (var k = 0; k < 8; k++) + c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1; + table[n] = c; + } + + return table; + } + + private static uint Crc(byte[] type, byte[] data) + { + var c = 0xFFFFFFFFu; + foreach (var b in type) + c = CrcTable[(c ^ b) & 0xFF] ^ (c >> 8); + foreach (var b in data) + c = CrcTable[(c ^ b) & 0xFF] ^ (c >> 8); + return c ^ 0xFFFFFFFFu; + } + + private static void Chunk(Stream s, string type, byte[] data) + { + var t = Encoding.ASCII.GetBytes(type); + Span be = stackalloc byte[4]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(be, (uint)data.Length); + s.Write(be); + s.Write(t); + s.Write(data); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(be, Crc(t, data)); + s.Write(be); + } + + internal static byte[] Zlib(byte[] raw) + { + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) + z.Write(raw); + return ms.ToArray(); + } + + /// + /// A PNG of , the unfiltered scanlines (each long), + /// with the optional PLTE and tRNS chunks. + /// + internal static byte[] Png(int width, int height, int bitDepth, int colorType, byte[] rows, int rowBytes, + byte[]? plte = null, byte[]? trns = null) + { + using var ms = new MemoryStream(); + ms.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + var ihdr = new byte[13]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(ihdr, width); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), height); + ihdr[8] = (byte)bitDepth; + ihdr[9] = (byte)colorType; + Chunk(ms, "IHDR", ihdr); + if (plte is not null) + Chunk(ms, "PLTE", plte); + if (trns is not null) + Chunk(ms, "tRNS", trns); + var filtered = new byte[height * (rowBytes + 1)]; + for (var y = 0; y < height; y++) + Array.Copy(rows, y * rowBytes, filtered, y * (rowBytes + 1) + 1, rowBytes); + Chunk(ms, "IDAT", Zlib(filtered)); + Chunk(ms, "IEND", []); + return ms.ToArray(); + } + + // ── JPEG, JBIG2 and JPEG 2000: headers the loaders read; the bytes pass through ────────── + + /// A baseline JPEG that holds a frame header only: start of image, SOF0, end of image. + internal static byte[] Jpeg(int width, int height, int components) + { + var sof = new List { 0xFF, 0xC0, 0, (byte)(8 + 3 * components), 8, (byte)(height >> 8), (byte)height, + (byte)(width >> 8), (byte)width, (byte)components }; + for (var c = 1; c <= components; c++) + sof.AddRange([(byte)c, 0x11, 0]); + return [0xFF, 0xD8, .. sof, 0xFF, 0xD9]; + } + + private static void I32(byte[] b, int at, int v) => + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(b.AsSpan(at), v); + + private static byte[] Segment(int number, int type, int page, byte[] data) + { + var header = new byte[11]; + I32(header, 0, number); + header[4] = (byte)type; + header[5] = 0; + header[6] = (byte)page; + I32(header, 7, data.Length); + return [.. header, .. data]; + } + + /// A JBIG2 file the loader reads: the ID string, a page-information segment and one MMR region. + internal static byte[] Jbig2(int width, int height, int page = 1) + { + var pageInfo = new byte[19]; + I32(pageInfo, 0, width); + I32(pageInfo, 4, height); + var region = new byte[20]; + I32(region, 0, width); + I32(region, 4, height); + region[17] = 0x01; + region[18] = 0xFF; + region[19] = 0xFF; + return [0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A, .. Segment(0, 48, page, pageInfo), + .. Segment(1, 39, page, region)]; + } + + /// A bare JPEG 2000 codestream: SOC, a SIZ segment and EOC. + internal static byte[] JpxCodestream(int width, int height, int components, int ssiz = 7, int rsiz = 0, + int[]? depths = null) + { + var buf = new List { 0xFF, 0x4F, 0xFF, 0x51 }; + void Be16(int v) => buf.AddRange([(byte)(v >> 8), (byte)v]); + void Be32(int v) => buf.AddRange([(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v]); + Be16(38 + 3 * components); + Be16(rsiz); + foreach (var v in new[] { width, height, 0, 0, width, height, 0, 0 }) + Be32(v); + Be16(components); + for (var c = 0; c < components; c++) + buf.AddRange([(byte)(depths is null ? ssiz : depths[c] - 1), 1, 1]); + buf.AddRange([0xFF, 0xD9]); + return [.. buf]; + } + + // ── BMP ───────────────────────────────────────────────────────────────────────────────── + + /// + /// A BITMAPINFOHEADER BMP. are the rows as stored (padded to four + /// bytes); a negative stores them top-down. + /// + internal static byte[] Bmp(int width, int height, int bitCount, byte[] pixels, byte[]? paletteBgr0 = null) + { + var paletteBytes = paletteBgr0?.Length ?? 0; + var offset = 14 + 40 + paletteBytes; + using var ms = new MemoryStream(); + using var w = new BinaryWriter(ms); + w.Write((byte)'B'); + w.Write((byte)'M'); + w.Write(offset + pixels.Length); + w.Write(0); + w.Write(offset); + w.Write(40); + w.Write(width); + w.Write(height); + w.Write((short)1); + w.Write((short)bitCount); + w.Write(0); + w.Write(pixels.Length); + w.Write(2835); + w.Write(2835); + w.Write(paletteBytes / 4); + w.Write(0); + if (paletteBgr0 is not null) + w.Write(paletteBgr0); + w.Write(pixels); + return ms.ToArray(); + } + + // ── GIF ───────────────────────────────────────────────────────────────────────────────── + + /// + /// A GIF89a of one frame, 2 by 1, colour indices 0 and 1, from a two-entry global table. With + /// set, a Graphic Control Extension names that index + /// transparent. + /// + internal static byte[] Gif(int? transparentIndex, byte[] table6, int screenWidth = 2, int screenHeight = 1, + int left = 0, int top = 0) + { + using var ms = new MemoryStream(); + ms.Write("GIF89a"u8); + ms.Write([(byte)screenWidth, 0, (byte)screenHeight, 0, 0x80, 0, 0]); + ms.Write(table6); + if (transparentIndex is { } t) + ms.Write([0x21, 0xF9, 0x04, 0x01, 0, 0, (byte)t, 0]); + ms.Write([0x2C, (byte)left, 0, (byte)top, 0, 2, 0, 1, 0, 0]); + // LZW, minimum code size 2: clear (4), index 0, index 1, end of information (5), 3 bits each, + // least significant bit first: 100 000 001 101 -> 0x04 (bits 001 + 000 at 3..5... packed below). + var bits = new List(); + foreach (var code in new[] { 4, 0, 1, 5 }) + for (var i = 0; i < 3; i++) + bits.Add(((code >> i) & 1) != 0); + var data = new List(); + for (var i = 0; i < bits.Count; i += 8) + { + var b = 0; + for (var k = 0; k < 8 && i + k < bits.Count; k++) + if (bits[i + k]) + b |= 1 << k; + data.Add((byte)b); + } + + ms.WriteByte(2); + ms.WriteByte((byte)data.Count); + ms.Write([.. data]); + ms.WriteByte(0); + ms.WriteByte(0x3B); + return ms.ToArray(); + } + + // ── TIFF ──────────────────────────────────────────────────────────────────────────────── + + internal sealed record Tag(ushort Id, ushort Type, uint[] Values); + + /// + /// A TIFF with one strip of (StripOffsets and StripByteCounts are + /// filled in) and, when is set, a second directory after the first. + /// + internal static byte[] Tiff(bool littleEndian, IEnumerable tags, byte[] strip, bool secondImage = false) + { + var list = tags.ToList(); + list.Add(new Tag(273, 4, [0])); + list.Add(new Tag(279, 4, [(uint)strip.Length])); + list = [.. list.OrderBy(t => t.Id)]; + var ifdSize = 2 + list.Count * 12 + 4; + var extra = new MemoryStream(); + var entries = new MemoryStream(); + var extraStart = 8 + ifdSize; + var stripOffsetFieldAt = -1; + + void U16(Stream s, int v) + { + var b = littleEndian ? new[] { (byte)v, (byte)(v >> 8) } : new[] { (byte)(v >> 8), (byte)v }; + s.Write(b); + } + + void U32(Stream s, uint v) + { + var b = littleEndian + ? new[] { (byte)v, (byte)(v >> 8), (byte)(v >> 16), (byte)(v >> 24) } + : new[] { (byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v }; + s.Write(b); + } + + foreach (var t in list) + { + U16(entries, t.Id); + U16(entries, t.Type); + U32(entries, (uint)t.Values.Length); + var size = t.Type == 3 ? 2 : 4; + if (t.Values.Length * size <= 4) + { + var before = entries.Length; + foreach (var v in t.Values) + { + if (t.Type == 3) + U16(entries, (int)v); + else + U32(entries, v); + } + + while (entries.Length - before < 4) + entries.WriteByte(0); + if (t.Id == 273) + stripOffsetFieldAt = (int)before; + } + else + { + U32(entries, (uint)(extraStart + extra.Length)); + foreach (var v in t.Values) + { + if (t.Type == 3) + U16(extra, (int)v); + else + U32(extra, v); + } + } + } + + var dataOffset = (uint)(8 + ifdSize + extra.Length); + var entryBytes = entries.ToArray(); + var patch = new MemoryStream(); + U32(patch, dataOffset); + Array.Copy(patch.ToArray(), 0, entryBytes, stripOffsetFieldAt, 4); + + using var ms = new MemoryStream(); + ms.Write(littleEndian ? "II"u8 : "MM"u8); + U16(ms, 42); + U32(ms, 8); + U16(ms, list.Count); + ms.Write(entryBytes); + var nextAt = 8 + ifdSize + (int)extra.Length + strip.Length; + U32(ms, secondImage ? (uint)nextAt : 0); + ms.Write(extra.ToArray()); + ms.Write(strip); + if (secondImage) + { + // A second page: width, height, and nothing the loader would use. + U16(ms, 2); + foreach (var (id, v) in new[] { (256, 9u), (257, 9u) }) + { + U16(ms, id); + U16(ms, 3); + U32(ms, 1); + U16(ms, (int)v); + U16(ms, 0); + } + + U32(ms, 0); + } + + return ms.ToArray(); + } + + internal static Tag Short(ushort id, params uint[] values) => new(id, 3, values); + + internal static Tag Long(ushort id, params uint[] values) => new(id, 4, values); + + /// The tags every uncompressed TIFF of this audit carries. + internal static List BaseTags(int width, int height, int bitsPerSample, int photometric, + int samplesPerPixel, int compression = 1) + { + var bits = Enumerable.Repeat((uint)bitsPerSample, samplesPerPixel).ToArray(); + return + [ + Short(256, (uint)width), + Short(257, (uint)height), + Short(258, bits), + Short(259, (uint)compression), + Short(262, (uint)photometric), + Short(277, (uint)samplesPerPixel), + Short(278, (uint)height), + ]; + } + + // ── Image XObjects of a saved file ────────────────────────────────────────────────────── + + /// One image XObject: its dictionary, its object number, its raw body and its decoded body. + internal sealed record ImageObject( + string Resource, int ObjectNumber, PdfDictionary Dict, byte[] Raw, byte[] Decoded, ImageObject? SoftMask, + int BodyOffset) + { + internal double Num(string key) => ConformanceAuditG2Support.Num(Dict.Get(new PdfName(key))); + + internal string? Name(string key) => Dict.Get(new PdfName(key)) is PdfName n ? n.Value : null; + } + + /// The image XObjects each page of the file draws, each once, in resource order. + internal static List ImageObjects(Pdf pdf) + { + var result = new List(); + var seen = new HashSet(); + for (var i = 0; i < pdf.Reader.PageCount; i++) + { + var resources = pdf.Dict(pdf.Reader.GetPage(i).Dictionary.Get(N("Resources"))); + if (resources.Get(N("XObject")) is not { } xo) + continue; + foreach (var (key, value) in pdf.Dict(xo).Entries) + { + var reference = Assert.IsType(value); + if (!seen.Add(reference.ObjectNumber)) + continue; + var image = ReadImage(pdf, reference, key.Value); + if (image.Name("Subtype") == "Image") + result.Add(image); + } + } + + return result; + } + + private static ImageObject ReadImage(Pdf pdf, PdfIndirectReference reference, string resource) + { + var stream = pdf.Reader.ResolveStream(reference)!; + ImageObject? soft = null; + if (stream.Dictionary.Get(N("SMask")) is PdfIndirectReference mask) + soft = ReadImage(pdf, mask, resource + "/SMask"); + return new ImageObject(resource, reference.ObjectNumber, stream.Dictionary, stream.RawBody.ToArray(), + ImageBytes(pdf, stream), soft, stream.BodyOffset); + } + + private static byte[] ImageBytes(Pdf pdf, VellumPdf.Reader.ParsedStream stream) + { + // A DCT, JPX, JBIG2 or CCITT body is not decoded by the reader; its filter name is the answer. + var filter = stream.Dictionary.Get(N("Filter")); + return filter is PdfName { Value: "FlateDecode" } ? pdf.Reader.GetDecodedStreamData(stream)! : stream.RawBody.ToArray(); + } + + /// The names of the keys an image dictionary holds. + internal static string[] Keys(PdfDictionary dict) => [.. dict.Entries.Select(e => e.Key.Value).Order()]; + + // ── Content streams ───────────────────────────────────────────────────────────────────── + + internal static double D(string s) => double.Parse(s, CultureInfo.InvariantCulture); + + /// The operands of every cm that is followed by a Do, in order. + internal static List<(double[] Matrix, string Resource)> PlacedImages(string content) + { + var result = new List<(double[], string)>(); + double[]? last = null; + foreach (var op in ConformanceAuditG2Support.Operators(content)) + { + if (op.Name == "cm") + last = [.. op.Operands.Select(D)]; + else if (op.Name == "Do" && last is not null) + result.Add((last, op.Operands[0][1..])); + } + + return result; + } + + // ── Oracles ───────────────────────────────────────────────────────────────────────────── + + /// The rules veraPDF fails for under , gated. + internal static List VeraFailures(string flavour, byte[] pdf) + { + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + if (!ExternalTool.TryRun("verapdf", ["--flavour", flavour, path], out var exit, out var report, + out var stderr, out var timedOut, timeoutMs: 120_000)) + OracleGate.Unavailable("verapdf"); + Assert.False(timedOut, $"veraPDF timed out.\n{stderr}"); + Assert.True(exit is 0 or 1, $"veraPDF exited {exit}: {VeraPdfExitCode.Describe(exit)}\n{report}\n{stderr}"); + Assert.Contains("isCompliant=", report, StringComparison.Ordinal); + return [.. Regex.Matches(report, + " $"{m.Groups[1].Value}-{m.Groups[2].Value}")]; + } + + // ── Documents ─────────────────────────────────────────────────────────────────────────── + + internal static bool PdfA(PdfConformance claim) => + claim is PdfConformance.PdfA2b or PdfConformance.PdfA2u or PdfConformance.PdfA2a; + + /// A Layout document that follows and has A4 pages with 72 pt margins. + internal static LayoutDocument NewDocument(PdfConformance claim, PdfRectangle? page = null, + EdgeInsets? margins = null) + { + var doc = ConformanceAuditG2Support.LayoutDocument(claim); + if (page is { } p) + doc.PageSize = p; + if (margins is { } m) + doc.Margins = m; + return doc; + } + + /// The names of the operators the content holds, in order. + internal static List OperatorNames(string content) => + [.. ConformanceAuditG2Support.Operators(content).Select(o => o.Name)]; +} diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Colour.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Colour.cs new file mode 100644 index 00000000..11ac207a --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Colour.cs @@ -0,0 +1,630 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text.RegularExpressions; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG2Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG4Support; +using LayoutDocument = VellumPdf.Layout.Document; + +namespace VellumPdf.Kernel.Tests; + +// Colour spaces and what a PDF/A claim makes of them (ISO 32000-1 8.6.4, 19005-2 6.2.4 and 6.2.10), +// the colours of a note block and of a band rule (#721, #735), and the tagging of what is painted +// (ISO 14289-1 7.1 and 7.3). +public sealed partial class ConformanceAuditG4Tests +{ + private static readonly ColorRgb Pale = new(0.9, 0.95, 1.0); + + private static readonly ColorRgb Ink = new(0.2, 0.4, 0.6); + + // ── Reading what was painted ───────────────────────────────────────────────────────────────── + + /// The operators of the first q...Q that holds , with the one before and after it. + private static (List Region, Op? Before, Op? After) Region(string content, string paint) + { + var ops = Operators(content); + var at = ops.FindIndex(o => o.Name == paint); + Assert.True(at >= 0, $"the page paints no {paint}"); + var start = ops.FindLastIndex(at, o => o.Name == "q"); + var depth = 0; + var end = start; + for (; end < ops.Count; end++) + { + if (ops[end].Name == "q") + depth++; + else if (ops[end].Name == "Q" && --depth == 0) + break; + } + + return (ops[start..(end + 1)], start > 0 ? ops[start - 1] : null, + end + 1 < ops.Count ? ops[end + 1] : null); + } + + private static double[] Numbers(Op op) => [.. op.Operands.Select(D)]; + + private static void AssertFiveDecimalsAtMost(Op op) + { + foreach (var operand in op.Operands) + Assert.Matches(@"^-?\d+(\.\d{1,5})?$", operand); + } + + private static byte[] NoteFile(PdfConformance claim, Action? configure = null, + LayoutDocument? into = null) + { + var doc = into ?? NewDocument(claim); + var style = Style(doc, DejaVu); + var note = new NoteBlock { Background = Pale, BorderColor = Ink, BorderWidth = 2, Padding = new EdgeInsets(6) }; + note.Add("A note that is set apart from the text.", style); + configure?.Invoke(note); + doc.Add(note); + return Save(doc); + } + + private static byte[] BandFile(PdfConformance claim, BandRule rule, bool header = false) + { + var doc = NewDocument(claim); + var style = Style(doc, DejaVu, 9); + var band = new RunningBand("Page {page} of {pages}", style) { Rule = rule }; + if (header) + doc.Header = band; + else + doc.Footer = band; + doc.Add(new Paragraph("Body text.", Style(doc, DejaVu))); + return Save(doc); + } + + // ── ISO 32000-1 8.6.4.3, 8.4.4 and 8.5.3.3: a note block's background and border ────────────── + + [Theory] + [MemberData(nameof(ClaimData))] + public void Iso32000_1_8_6_4_3_ANoteBlockPaintsItsBackgroundAndBorderWithDeviceRgbOperands(PdfConformance claim) + { + var file = NoteFile(claim); + using var pdf = new Pdf(file); + var (region, before, after) = Region(pdf.Page(0), "rg"); + + // The construct: q, background (rg, re, f), border (rg, four re, f), Q. + Assert.Equal(["q", "rg", "re", "f", "rg", "re", "re", "re", "re", "f", "Q"], region.Select(o => o.Name).ToArray()); + + // 8.6.4.3: each component is a number from 0 to 1, written as the operands of rg. The writer formats to + // five decimals, so the colours below are exact. + Assert.Equal([0.9, 0.95, 1.0], Numbers(region[1])); + Assert.Equal([0.2, 0.4, 0.6], Numbers(region[4])); + AssertFiveDecimalsAtMost(region[1]); + AssertFiveDecimalsAtMost(region[4]); + + // The background fills the content box's width and ends at the top margin; the border is four bars of + // BorderWidth inside the box, filled in one path (8.5.3.3, nonzero winding, so the bars need no join). + var page = new LayoutDocument().PageSize; + var left = new LayoutDocument().Margins.Left; + var width = page.Width - left - new LayoutDocument().Margins.Right; + var box = Numbers(region[2]); + Assert.Equal(left, box[0], 3); + Assert.Equal(width, box[2], 3); + Assert.Equal(page.Height - new LayoutDocument().Margins.Top, box[1] + box[3], 3); + var bars = region.Where(o => o.Name == "re").Skip(1).Select(Numbers).ToArray(); + Assert.Contains(bars, b => Close(b, [box[0], box[1], 2, box[3]])); + Assert.Contains(bars, b => Close(b, [box[0] + box[2] - 2, box[1], 2, box[3]])); + Assert.Contains(bars, b => Close(b, [box[0] + 2, box[1], box[2] - 4, 2])); + Assert.Contains(bars, b => Close(b, [box[0] + 2, box[1] + box[3] - 2, box[2] - 4, 2])); + + // Only DeviceRGB operators colour the box: no cs, sc, g, k or their stroking forms, and the colour is + // set inside q and Q so it does not leak into the text that follows. + Assert.DoesNotContain(region, o => o.Name is "cs" or "CS" or "sc" or "SC" or "scn" or "SCN" or "g" or "G" + or "k" or "K" or "RG" or "B" or "b" or "f*"); + + // 19005-2 6.2.5 and 6.2.10-1: no graphics state dictionary is written, so no TR, HTP, blend mode or + // overprint setting can be in it, and no group is written either. + var resources = pdf.Dict(pdf.Reader.GetPage(0).Dictionary.Get(N("Resources"))); + Assert.Null(resources.Get(N("ExtGState"))); + Assert.Null(pdf.Reader.GetPage(0).Dictionary.Get(N("Group"))); + Assert.DoesNotContain(Operators(pdf.Page(0)), o => o.Name is "gs" or "ri" or "i" or "sh" or "BI"); + + // 14289-1 7.1 and 19005-2 6.7.3.1: in a tagged document neither is content, so both are one artifact; + // otherwise no marked-content operator is written around them. + if (Tagged(claim)) + { + Assert.Equal(("BMC", "/Artifact"), (before!.Name, before.Operands[0])); + Assert.Equal("EMC", after!.Name); + } + else + { + Assert.NotEqual("BMC", before?.Name); + } + } + + private static bool Close(double[] a, double[] b) => + a.Length == b.Length && a.Zip(b).All(p => Math.Abs(p.First - p.Second) < 1e-3); + + [Theory] + [MemberData(nameof(OracleClaimData))] + public void Iso19005_2_6_2_4_3_ANoteBlockInAFileWithAnSrgbOutputIntentPassesVeraPdfAndQpdf(PdfConformance claim) + { + var file = NoteFile(claim); + + // The construct: rg is in the file and the output intent is RGB. + using var pdf = new Pdf(file); + Assert.Contains(" rg", pdf.Page(0)); + Assert.Equal(3, OutputIntentComponents(pdf)); + + Assert.Empty(VeraFailures(ConformanceAuditG2Support.Flavour(claim), file)); + QpdfChecks(file); + } + + [Fact] + public void Iso32000_1_8_6_4_3_AChannelIsWrittenAsItsFiveDecimalFormAndATinyOneAsZero() + { + foreach (var (given, written) in new[] { (0.0, "0"), (1.0, "1"), (1e-9, "0"), (0.123456789, "0.12346"), (0.999999, "1") }) + { + using var pdf = new Pdf(NoteWith(new ColorRgb(given, given, given), new ColorRgb(0, 0, 0))); + var operands = Region(pdf.Page(0), "rg").Region[1].Operands; + Assert.All(operands, o => Assert.Equal(written, o)); + } + } + + private static byte[] NoteWith(ColorRgb background, ColorRgb border) + { + var doc = NewDocument(PdfConformance.None); + var note = new NoteBlock { Background = background, BorderColor = border, BorderWidth = 1 }; + note.Add("Text", Style(doc, DejaVu)); + doc.Add(note); + return Save(doc); + } + + [Theory] + [InlineData(-0.1)] + [InlineData(1.0000001)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void Iso32000_1_8_6_4_3_AChannelOutsideZeroToOneIsRefusedWhenTheColourIsBuilt(double channel) + { + var bad = new ColorRgb(0.5, channel, 0.5); + + // Each of the three colours of a note block and a band rule is checked where it is set, and the message + // cites 8.6.4.3, which says a DeviceRGB component is a number from 0.0 to 1.0. + Assert.Contains("8.6.4.3", Assert.Throws(() => new NoteBlock { Background = bad }).Message); + Assert.Throws(() => new NoteBlock { BorderColor = bad }); + Assert.Throws(() => new BandRule(BandRulePosition.Above, 0.5, bad)); + } + + // ── ISO 32000-1 8.4.3.2 and 8.6.4.3: a band rule ────────────────────────────────────────────── + + [Theory] + [MemberData(nameof(ClaimData))] + public void Iso32000_1_8_4_3_2_ABandRuleIsOneStrokedLineOfItsWidthInItsColour(PdfConformance claim) + { + var rule = new BandRule(BandRulePosition.Above, 1.5, new ColorRgb(0.1, 0.2, 0.3)); + var file = BandFile(claim, rule); + using var pdf = new Pdf(file); + var (region, before, after) = Region(pdf.Page(0), "RG"); + + // The construct: q, RG, w, m, l, S, Q. + Assert.Equal(["q", "RG", "w", "m", "l", "S", "Q"], region.Select(o => o.Name).ToArray()); + + // 19005-2 6.2.5: no graphics state dictionary is written for a rule. + Assert.Null(pdf.Dict(pdf.Reader.GetPage(0).Dictionary.Get(N("Resources"))).Get(N("ExtGState"))); + + // 8.4.3.2: the width is a non-negative number; 8.6.4.3: the stroking colour is three numbers from 0 to 1. + Assert.Equal([0.1, 0.2, 0.3], Numbers(region[1])); + Assert.Equal(1.5, Numbers(region[2])[0]); + + // The line is horizontal, runs from the left margin to the right margin of the page, and lies inside the + // page, 0.75 pt (half the width) inside the band's top edge. + var margins = new LayoutDocument().Margins; + var page = new LayoutDocument().PageSize; + var from = Numbers(region[3]); + var to = Numbers(region[4]); + Assert.Equal(from[1], to[1]); + Assert.Equal(margins.Left, from[0], 3); + Assert.Equal(page.Width - margins.Right, to[0], 3); + Assert.InRange(from[1], 0, page.Height); + + // 14289-1 7.1: a rule is decoration, so it is an artifact in a tagged file, and no operator but RG sets + // the colour. + Assert.DoesNotContain(region, o => o.Name is "rg" or "cs" or "CS" or "SC" or "SCN" or "G" or "K"); + if (Tagged(claim)) + { + // The sequence that opens this rule's own q...Q is the artifact, and the one after it closes. + Assert.Equal(("BMC", "/Artifact"), (before!.Name, before.Operands[0])); + Assert.Equal("EMC", after!.Name); + } + else + { + Assert.NotEqual("BMC", before?.Name); + } + } + + [Fact] + public void Iso32000_1_8_4_3_2_AZeroWidthRuleIsWrittenAsAZeroLineWidthWhichTheClauseAllows() + { + var file = BandFile(PdfConformance.None, new BandRule(BandRulePosition.Below, 0, Ink), header: true); + using var pdf = new Pdf(file); + var (region, _, _) = Region(pdf.Page(0), "RG"); + + // 8.4.3.2: "shall be non-negative" admits 0, the thinnest line the device renders. The clause advises + // against it because the result depends on the device; BandRule documents that. + Assert.Equal("0", region.Single(o => o.Name == "w").Operands[0]); + Assert.Equal(["q", "RG", "w", "m", "l", "S", "Q"], region.Select(o => o.Name).ToArray()); + } + + [Theory] + [InlineData(-0.5)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + public void Iso32000_1_8_4_3_2_ANegativeOrNonFiniteRuleWidthIsRefusedWhenTheRuleIsBuilt(double width) + { + Assert.Throws(() => new BandRule(BandRulePosition.Above, width)); + } + + [Theory] + [MemberData(nameof(OracleClaimData))] + public void Iso19005_2_6_2_4_3_ABandRuleInAFileWithAnSrgbOutputIntentPassesVeraPdfAndQpdf(PdfConformance claim) + { + var file = BandFile(claim, new BandRule(BandRulePosition.Above, 1, Ink)); + using var pdf = new Pdf(file); + Assert.Contains(" RG", pdf.Page(0)); + Assert.Equal(3, OutputIntentComponents(pdf)); + Assert.Empty(VeraFailures(ConformanceAuditG2Support.Flavour(claim), file)); + QpdfChecks(file); + } + + // ── ISO 19005-2 6.2.4.3: device colour needs an output intent of the same family ───────────── + + /// The component count of the first output intent's profile, or null when the file has none. + private static int? OutputIntentComponents(Pdf pdf) + { + if (pdf.Catalog.Get(N("OutputIntents")) is not { } intents) + return null; + var intent = pdf.Dict(Assert.Single(pdf.Array(intents).Items())); + Assert.Equal("GTS_PDFA1", Assert.IsType(intent.Get(N("S"))).Value); + var profile = pdf.Reader.ResolveStream(Assert.IsType(intent.Get(N("DestOutputProfile"))))!; + return (int)Num(profile.Dictionary.Get(N("N"))); + } + + public enum Paint + { + RgbImage, + GreyImage, + CmykImage, + NoteBlock, + BandRule, + } + + private static byte[] PaintFile(Paint paint, PdfConformance claim, bool cmykIntent) + { + var doc = NewDocument(claim); + if (cmykIntent) + doc.UseCmykOutputIntent(); + switch (paint) + { + case Paint.RgbImage: + doc.Add(new LayoutImage(Load(KindTable["png-rgb8"])) { Width = 40, Height = 20 }); + break; + case Paint.GreyImage: + doc.Add(new LayoutImage(Load(KindTable["png-grey8"])) { Width = 40, Height = 20 }); + break; + case Paint.CmykImage: + doc.Add(new LayoutImage(Load(KindTable["jpeg-cmyk"])) { Width = 40, Height = 20 }); + break; + case Paint.NoteBlock: + return NoteFile(claim, null, doc); + default: + doc.Footer = new RunningBand("Page {page}", Style(doc, DejaVu, 9)) { Rule = new BandRule(BandRulePosition.Above, 1, Ink) }; + doc.Add(new Paragraph("Body", Style(doc, DejaVu))); + break; + } + + return Save(doc); + } + + public static TheoryData PaintCases() + { + var data = new TheoryData(); + foreach (var paint in Enum.GetValues()) + foreach (var cmyk in new[] { false, true }) + foreach (var claim in new[] { PdfConformance.PdfA2b, PdfConformance.PdfA2u, PdfConformance.PdfA2a }) + data.Add(paint, cmyk, claim); + return data; + } + + private static string? ExpectedColourRule(Paint paint, bool cmykIntent) => (paint, cmykIntent) switch + { + (Paint.CmykImage, false) => "6.2.4.3-3", + (Paint.RgbImage or Paint.NoteBlock or Paint.BandRule, true) => "6.2.4.3-2", + _ => null, + }; + + [Theory] + [MemberData(nameof(PaintCases))] + public void Iso19005_2_6_2_4_3_TheFileHoldsTheColourSpaceItPaintsAndVeraPdfFailsOnlyWhereTheIntentIsOfAnotherFamily( + Paint paint, bool cmykIntent, PdfConformance claim) + { + var file = PaintFile(paint, claim, cmykIntent); + using var pdf = new Pdf(file); + + // The construct: the colour space of the paint, and the family of the output intent's profile. + var content = pdf.Page(0); + switch (paint) + { + case Paint.RgbImage: + Assert.Equal("DeviceRGB", ImageObjects(pdf).Single().Name("ColorSpace")); + break; + case Paint.GreyImage: + Assert.Equal("DeviceGray", ImageObjects(pdf).Single().Name("ColorSpace")); + break; + case Paint.CmykImage: + Assert.Equal("DeviceCMYK", ImageObjects(pdf).Single().Name("ColorSpace")); + break; + case Paint.NoteBlock: + Assert.Contains(" rg", content); + break; + default: + Assert.Contains(" RG", content); + break; + } + + Assert.Equal(cmykIntent ? 4 : 3, OutputIntentComponents(pdf)); + + // veraPDF 6.2.4.3-2 (DeviceRGB needs an RGB output intent), -3 (DeviceCMYK needs a CMYK one) and -4 + // (DeviceGray needs any PDF/A output intent). The library writes the file in the mismatching cases (#474). + var failedAll = VeraFailures(ConformanceAuditG2Support.Flavour(claim), file); + var failed = failedAll.Where(f => f.StartsWith("6.2.4.3", StringComparison.Ordinal)); + Assert.Equal(ExpectedColourRule(paint, cmykIntent) is { } rule ? [rule] : [], failed.ToArray()); + + // 6.2.3 and 6.2.4.2: the profile of the intent, sRGB or the generic CMYK one, is a valid output profile + // (prtr or mntr, version below 5), and nothing else in these files fails. + Assert.DoesNotContain(failedAll, f => f.StartsWith("6.2.3", StringComparison.Ordinal)); + Assert.Equal(failed.ToArray(), failedAll.ToArray()); + } + + [Theory] + [InlineData(Paint.CmykImage, false)] + [InlineData(Paint.RgbImage, true)] + [InlineData(Paint.NoteBlock, true)] + [InlineData(Paint.BandRule, true)] + public void Iso19005_2_6_2_4_3_PinsTodayAFileThatPaintsAColourItsOutputIntentDoesNotCoverIsSavedWithItsClaim(Paint paint, + bool cmykIntent) + { + // #474 asks the save to report that the claim cannot be met, through the notify-and-continue channel, and to + // write the file. That channel has no member for this report yet (Layout has TextEncodingWarnings and + // BandTruncations only), so there is nothing to assert about the report. What is pinned is the write: the + // save does not throw, the claim is stamped as part 2 conformance B, and veraPDF fails 6.2.4.3. + var file = PaintFile(paint, PdfConformance.PdfA2b, cmykIntent); + var text = System.Text.Encoding.Latin1.GetString(file); + Assert.Matches(@"pdfaid:part[^0-9]{1,8}2", text); + Assert.Matches(@"pdfaid:conformance[^A-Z]{1,8}B", text); + Assert.Contains(VeraFailures("2b", file), f => f.StartsWith("6.2.4.3", StringComparison.Ordinal)); + } + + [Theory(Skip = "Gap #303: the note block's fill and border are a bare /Artifact BMC, and #303 asks for a property " + + "list with /Type, /Subtype and /BBox, written as BDC.")] + [InlineData(PdfConformance.PdfA2a)] + [InlineData(PdfConformance.PdfUA1)] + public void Iso19005_2_6_7_3_1_TheNoteBlockArtifactCarriesATypeInItsPropertyList(PdfConformance claim) + { + using var pdf = new Pdf(NoteFile(claim)); + var (_, before, _) = Region(pdf.Page(0), "rg"); + Assert.Equal("BDC", before!.Name); + Assert.Equal("/Artifact", before.Operands[0]); + Assert.Contains("/Type", before.Operands); + } + + // ── ISO 19005-2 6.2.10, 32000-1 11.4.7: transparency without a page group ───────────────────── + + [Theory] + [MemberData(nameof(AlphaKindNames))] + public void Iso19005_2_6_2_10_AnImageWithASoftMaskNeedsNoPageGroupWhenAnOutputIntentIsPresent(string name) + { + var kind = KindTable[name]; + foreach (var claim in Claims) + { + var file = ImageFile(claim, kind); + using var pdf = new Pdf(file); + + // The construct: the page draws an image that has an SMask. + Assert.NotNull(Assert.Single(ImageObjects(pdf)).SoftMask); + + // 32000-1 Table 30 and 11.4.7: Group is optional, and the library writes none. 19005-2 6.2.10 needs a + // group with CS only when the file has no PDF/A output intent, which a PDF/A file here always has. + var page = pdf.Reader.GetPage(0).Dictionary; + Assert.Null(page.Get(N("Group"))); + var resources = pdf.Dict(page.Get(N("Resources"))); + Assert.Null(resources.Get(N("ExtGState"))); + if (PdfA(claim)) + Assert.Equal(3, OutputIntentComponents(pdf)); + } + } + + [Theory] + [MemberData(nameof(OracleClaimData))] + public void Iso19005_2_6_2_10_TheTransparentImagesOfEveryLoaderPassVeraPdfAndQpdf(PdfConformance claim) + { + var kinds = KindTable.Values.Where(k => k.SMask is not null).ToArray(); + var file = ImageFile(claim, kinds); + using var pdf = new Pdf(file); + Assert.Equal(kinds.Length, ImageObjects(pdf).Count(i => i.SoftMask is not null)); + Assert.Empty(VeraFailures(ConformanceAuditG2Support.Flavour(claim), file)); + QpdfChecks(file); + } + + // ── Every loader's output under each claim ───────────────────────────────────────────────── + + [Theory] + [MemberData(nameof(OracleClaimData))] + public void Iso19005_2_6_2_8_TheOutputOfEveryLoaderThatNeedsNoCmykIntentPassesVeraPdfAndQpdf(PdfConformance claim) + { + var kinds = KindTable.Values.Where(k => k.ColorSpace != "DeviceCMYK").ToArray(); + var file = ImageFile(claim, kinds); + + // The construct: one image XObject for each kind, with a soft mask for each of the alpha kinds. + using var pdf = new Pdf(file); + Assert.Equal(kinds.Length, ImageObjects(pdf).Count(i => !i.Resource.Contains("/SMask"))); + Assert.Equal(kinds.Count(k => k.SMask is not null), ImageObjects(pdf).Count(i => i.SoftMask is not null)); + + Assert.Empty(VeraFailures(ConformanceAuditG2Support.Flavour(claim), file)); + + // qpdf decodes a DCT body to check it, and a frame header alone is not a decodable JPEG, so the check + // covers the file without the JPEG kinds. + QpdfChecks(ImageFile(claim, [.. kinds.Where(k => k.Filter != "DCTDecode")])); + } + + // ── ISO 14289-1 7.3, Matterhorn 13 and 01: a figure is tagged, a decoration is an artifact ─── + + private static List StructElements(Pdf pdf) + { + var found = new List(); + if (pdf.Catalog.Get(N("StructTreeRoot")) is not { } rootObject) + return found; + Walk(pdf.Dict(rootObject).Get(N("K"))); + return found; + + void Walk(PdfObject? node) + { + switch (pdf.Resolve(node)) + { + case PdfArray array: + foreach (var item in array.Items()) + Walk(item); + break; + case PdfDictionary dict: + if (dict.Get(N("S")) is not null) + found.Add(dict); + Walk(dict.Get(N("K"))); + break; + } + } + } + + /// The marked-content tags open at each Do, by image resource name. + private static List<(string Resource, string[] Open, int? Mcid)> DrawnWithTags(string content) + { + var drawn = new List<(string, string[], int?)>(); + var open = new Stack<(string Tag, int? Mcid)>(); + var ops = Operators(content); + for (var i = 0; i < ops.Count; i++) + { + var op = ops[i]; + switch (op.Name) + { + case "BMC": + open.Push((op.Operands[0][1..], null)); + break; + case "BDC": + var mcid = op.Operands.IndexOf("/MCID") is var k and >= 0 ? (int?)int.Parse(op.Operands[k + 1], CultureInfo.InvariantCulture) : null; + open.Push((op.Operands[0][1..], mcid)); + break; + case "EMC": + open.Pop(); + break; + case "Do": + drawn.Add((op.Operands[0][1..], [.. open.Select(o => o.Tag).Reverse()], open.FirstOrDefault().Mcid)); + break; + } + } + + return drawn; + } + + [Theory] + [MemberData(nameof(ClaimData))] + public void Iso14289_1_7_3_ABodyImageIsAFigureWithAltTextWhenTheFileIsTagged(PdfConformance claim) + { + var doc = NewDocument(claim); + doc.Add(new LayoutImage(Load(KindTable["png-rgb8"])) { Width = 40, Height = 20, AltText = "Two coloured squares" }); + doc.Add(new LayoutImage(Load(KindTable["png-grey8"])) { Width = 40, Height = 20 }); + var file = Save(doc); + using var pdf = new Pdf(file); + var drawn = DrawnWithTags(pdf.Page(0)); + + // The construct: two images are drawn. + Assert.Equal(2, drawn.Count); + if (!Tagged(claim)) + { + // Without a claim to tag, or under PDF/A level B and U, an image is drawn outside marked content. + Assert.All(drawn, d => Assert.Empty(d.Open)); + Assert.Empty(StructElements(pdf)); + return; + } + + // Tagged: each image is in a Figure sequence with an MCID, and a Figure structure element carries Alt (7.3, + // Table 323). An image with no AltText gets the word Figure (#583: not a description, which only a person + // can judge: Matterhorn 13-004 machine-checks presence, 13-004's meaning is human-only). + Assert.All(drawn, d => Assert.Equal(["Figure"], d.Open)); + var figures = StructElements(pdf).Where(e => ((PdfName)e.Get(N("S"))!).Value == "Figure").ToArray(); + Assert.Equal(2, figures.Length); + Assert.Equal(["Two coloured squares", "Figure"], figures.Select(f => TextString(f.Get(N("Alt"))!)).ToArray()); + + // 14.7.4.4: content items that are marked-content sequences are found through the page's StructParents key, + // so the image XObject carries none. + Assert.NotNull(pdf.Reader.GetPage(0).Dictionary.Get(N("StructParents"))); + Assert.All(ImageObjects(pdf), i => Assert.Null(i.Dict.Get(N("StructParent")))); + Assert.Equal(drawn.Select(d => d.Mcid), figures.Select(f => (int?)Num(f.Get(N("K"))))); + } + + [Theory] + [MemberData(nameof(OracleClaimData))] + public void Iso14289_1_7_3_VeraPdfAcceptsATaggedFigureAndAnArtifactBackgroundUnderEveryClaim(PdfConformance claim) + { + var doc = NewDocument(claim); + doc.Add(new LayoutImage(Load(KindTable["png-rgba8"])) { Width = 40, Height = 20, AltText = "A red square" }); + var file = NoteFile(claim, null, doc); + Assert.Empty(VeraFailures(ConformanceAuditG2Support.Flavour(claim), file)); + } + + [Theory] + [MemberData(nameof(ClaimData))] + public void Iso14289_1_7_3_ALogoInABandIsAnArtifactAndNotAFigure(PdfConformance claim) + { + var doc = NewDocument(claim); + var logo = new LayoutImage(Load(KindTable["png-rgb8"])); + doc.Header = new RunningBand(BandZone.Logo(logo), BandZone.Empty, BandZone.Empty) { Height = 30 }; + doc.Add(new Paragraph("Body text.", Style(doc, DejaVu))); + var file = Save(doc); + using var pdf = new Pdf(file); + var drawn = DrawnWithTags(pdf.Page(0)); + + // The construct: the logo is drawn once. + var one = Assert.Single(drawn); + if (Tagged(claim)) + { + // Decoration is an artifact (7.3 first exception, and 7.1: artifacts are not in the tree). + Assert.Equal(["Artifact"], one.Open); + Assert.DoesNotContain(StructElements(pdf), e => ((PdfName)e.Get(N("S"))!).Value == "Figure"); + } + else + { + Assert.Empty(one.Open); + } + } + + [Fact] + public void Iso14289_1_7_1_WhatIsPaintedOutsideTheStructureIsAnArtifactAndNothingIsPaintedOutsideBoth() + { + // veraPDF 7.1-3: every painted object is either tagged or inside an Artifact sequence. A note block, a band + // rule, a logo and a body image together leave nothing outside both. + var doc = NewDocument(PdfConformance.PdfUA1); + doc.Footer = new RunningBand("Page {page}", Style(doc, DejaVu, 9)) { Rule = new BandRule(BandRulePosition.Above, 1, Ink) }; + doc.Header = new RunningBand(BandZone.Logo(new LayoutImage(Load(KindTable["png-rgb8"]))), BandZone.Empty, + BandZone.Empty) + { Height = 30 }; + doc.Add(new LayoutImage(Load(KindTable["png-rgba8"])) { Width = 40, Height = 20, AltText = "A red square" }); + var file = NoteFile(PdfConformance.PdfUA1, null, doc); + Assert.Empty(VeraFailures("ua1", file)); + QpdfChecks(file); + + // The construct: the page paints a fill, a stroke and two images. + using var pdf = new Pdf(file); + var names = Operators(pdf.Page(0)).Select(o => o.Name).ToList(); + Assert.Contains("f", names); + Assert.Contains("S", names); + Assert.Equal(2, names.Count(n => n == "Do")); + Assert.Equal(names.Count(n => n is "BMC" or "BDC"), names.Count(n => n == "EMC")); + } +} diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs new file mode 100644 index 00000000..97553484 --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Images.cs @@ -0,0 +1,1054 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Images; +using VellumPdf.Layout.Elements; +using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG2Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG4Support; + +namespace VellumPdf.Kernel.Tests; + +/// +/// The ISO audit of graphics and images (group G4), one test per clause. The clause inventory, the +/// feature matrix and the verdicts are in docs/conformance-v2.4.md. Every fixture is +/// generated here from each format's own layout, with fonts from the tree, and each test first +/// checks that the construct is in the file before it asserts values against the clause. A +/// requirement the code violates has a test that is skipped, with the gap's label in the reason, so +/// the assertion is ready for the fix. +/// +/// +/// ISO 19005-2 is not held in the repository: its clause numbers come from the maintainer's NEN +/// Connect reading, and the test names use them as written there. The other standards are the +/// copies in docs/iso. veraPDF has no rule for several requirements below (the consistency +/// of an image dictionary with its data, a soft-mask image's restrictions, a colour-key range, the +/// word spacing of a composite font), so the tests assert the written keys, operands and bytes +/// directly and use the oracles as a second reading. +/// +public sealed partial class ConformanceAuditG4Tests +{ + // ── The image kinds: one input for each thing a loader reads, and what it must write ───────── + + /// What a loader must write for one input: the dictionary values and the decoded samples. + public sealed record Kind( + string Name, byte[] Bytes, int Width, int Height, string ColorSpace, int? Bpc, string Filter, + string? Samples = null, int SMaskBpc = 0, string? SMask = null, int[]? Mask = null) + { + public override string ToString() => Name; + } + + private static uint[] RedGreenMap() + { + var map = new uint[768]; + map[0] = 0xFF00; // index 0: red + map[256 + 1] = 0xFF00; // index 1: green + return map; + } + + private static readonly Dictionary KindTable = BuildKinds(); + + private static Dictionary BuildKinds() + { + var kinds = new List + { + // PNG: every colour type and depth, the soft mask of an alpha channel, a colour key. + new("png-grey8", Png(2, 2, 8, 0, [0, 0x80, 0xFF, 0x40], 2), 2, 2, "DeviceGray", 8, "FlateDecode", "0080FF40"), + new("png-grey1", Png(8, 1, 1, 0, [0xA5], 1), 8, 1, "DeviceGray", 8, "FlateDecode", "FF00FF0000FF00FF"), + new("png-grey2", Png(4, 1, 2, 0, [0x1B], 1), 4, 1, "DeviceGray", 8, "FlateDecode", "0055AAFF"), + new("png-grey16", Png(2, 1, 16, 0, [0x12, 0x34, 0xAB, 0xCD], 4), 2, 1, "DeviceGray", 16, "FlateDecode", "1234ABCD"), + new("png-rgb8", Png(2, 1, 8, 2, [255, 0, 0, 0, 255, 0], 6), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("png-rgb16", Png(1, 1, 16, 2, [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC], 6), 1, 1, "DeviceRGB", 16, "FlateDecode", "123456789ABC"), + new("png-rgba8", Png(2, 1, 8, 6, [255, 0, 0, 128, 0, 255, 0, 255], 8), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00", 8, "80FF"), + new("png-rgba16", Png(1, 1, 16, 6, [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0x80, 0x00], 8), 1, 1, "DeviceRGB", 16, "FlateDecode", "123456789ABC", 16, "8000"), + new("png-grey-alpha8", Png(2, 1, 8, 4, [10, 128, 200, 255], 4), 2, 1, "DeviceGray", 8, "FlateDecode", "0AC8", 8, "80FF"), + new("png-palette8-alpha", Png(2, 1, 8, 3, [0, 1], 2, [255, 0, 0, 0, 255, 0], [0, 255]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00", 8, "00FF"), + new("png-palette4", Png(2, 1, 4, 3, [0x01], 1, [255, 0, 0, 0, 255, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("png-palette1", Png(8, 1, 1, 3, [0xA5], 1, [0, 0, 0, 255, 255, 255]), 8, 1, "DeviceRGB", 8, "FlateDecode", "FFFFFF000000FFFFFF000000000000FFFFFF000000FFFFFF"), + 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]), + + // JPEG passes through; the frame header decides the colour space. + new("jpeg-grey", Jpeg(4, 2, 1), 4, 2, "DeviceGray", 8, "DCTDecode"), + new("jpeg-rgb", Jpeg(4, 2, 3), 4, 2, "DeviceRGB", 8, "DCTDecode"), + new("jpeg-cmyk", Jpeg(4, 2, 4), 4, 2, "DeviceCMYK", 8, "DCTDecode"), + + // BMP: row order, depth, palette. + new("bmp-24", Bmp(2, 1, 24, [0, 0, 255, 0, 255, 0, 0, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("bmp-24-two-rows", Bmp(2, 2, 24, [0, 0, 255, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0]), 2, 2, "DeviceRGB", 8, "FlateDecode", "0000FF000000FF000000FF00"), + new("bmp-24-top-down", Bmp(2, -2, 24, [0, 0, 255, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0]), 2, 2, "DeviceRGB", 8, "FlateDecode", "FF000000FF000000FF000000"), + new("bmp-32", Bmp(2, 1, 32, [0, 0, 255, 0, 0, 255, 0, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("bmp-8", Bmp(2, 1, 8, [0, 1, 0, 0], [255, 0, 0, 0, 0, 255, 0, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "0000FF00FF00"), + + // GIF: an opaque frame, and a frame whose Graphic Control Extension names a transparent index. + new("gif-opaque", Gif(null, [255, 0, 0, 0, 0, 255]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF00000000FF"), + new("gif-transparent", Gif(1, [255, 0, 0, 0, 0, 255]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF00000000FF", 8, "FF00"), + + // TIFF: photometric, depth, alpha, palette. + new("tiff-grey8", Tiff(true, BaseTags(2, 1, 8, 1, 1), [0x10, 0xF0]), 2, 1, "DeviceGray", 8, "FlateDecode", "10F0"), + new("tiff-white-is-zero", Tiff(true, BaseTags(2, 1, 8, 0, 1), [0x10, 0xF0]), 2, 1, "DeviceGray", 8, "FlateDecode", "EF0F"), + new("tiff-grey16", Tiff(false, BaseTags(2, 1, 16, 1, 1), [0x12, 0x34, 0xAB, 0xCD]), 2, 1, "DeviceGray", 16, "FlateDecode", "1234ABCD"), + new("tiff-rgb8", Tiff(true, BaseTags(2, 1, 8, 2, 3), [255, 0, 0, 0, 255, 0]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("tiff-rgba8", Tiff(true, [.. BaseTags(2, 1, 8, 2, 4), Short(338, 2)], [255, 0, 0, 128, 0, 255, 0, 255]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00", 8, "80FF"), + new("tiff-rgba16", Tiff(false, [.. BaseTags(1, 1, 16, 2, 4), Short(338, 2)], [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0x80, 0x00]), 1, 1, "DeviceRGB", 16, "FlateDecode", "123456789ABC", 16, "8000"), + new("tiff-palette8", Tiff(true, [.. BaseTags(2, 1, 8, 3, 1), Short(320, RedGreenMap())], [0, 1]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"), + new("tiff-first-of-two-pages", Tiff(true, BaseTags(2, 1, 8, 1, 1), [0x10, 0xF0], secondImage: true), 2, 1, "DeviceGray", 8, "FlateDecode", "10F0"), + new("tiff-group4", Tiff(true, BaseTags(8, 8, 1, 0, 1, 4), [0xFF]), 8, 8, "DeviceGray", 1, "CCITTFaxDecode"), + new("tiff-group3", Tiff(true, BaseTags(8, 8, 1, 0, 1, 3), [0xFF]), 8, 8, "DeviceGray", 1, "CCITTFaxDecode"), + + // JBIG2 and JPEG 2000 pass through. + new("jbig2", Jbig2(16, 16), 16, 16, "DeviceGray", 1, "JBIG2Decode"), + new("jpx-3-channels", JpxCodestream(16, 16, 3), 16, 16, "DeviceRGB", 8, "JPXDecode"), + new("jpx-1-channel", JpxCodestream(16, 16, 1), 16, 16, "DeviceGray", 8, "JPXDecode"), + new("jpx-4-channels", JpxCodestream(16, 16, 4), 16, 16, "DeviceCMYK", 8, "JPXDecode"), + new("jpx-16-bit", JpxCodestream(16, 16, 3, 15), 16, 16, "DeviceRGB", 16, "JPXDecode"), + new("jpx-12-bit", JpxCodestream(16, 16, 3, 11), 16, 16, "DeviceRGB", null, "JPXDecode"), + }; + return kinds.ToDictionary(k => k.Name); + } + + public static TheoryData KindNames() + { + var data = new TheoryData(); + foreach (var name in KindTable.Keys) + data.Add(name); + return data; + } + + public static TheoryData AlphaKindNames() + { + var data = new TheoryData(); + foreach (var k in KindTable.Values.Where(k => k.SMask is not null)) + data.Add(k.Name); + return data; + } + + public static TheoryData ColourKeyKindNames() + { + var data = new TheoryData(); + foreach (var k in KindTable.Values.Where(k => k.Mask is not null)) + data.Add(k.Name); + return data; + } + + public static TheoryData ClaimData() + { + var data = new TheoryData(); + foreach (var c in Claims) + data.Add(c); + return data; + } + + public static TheoryData OracleClaimData() + { + var data = new TheoryData(); + foreach (var c in ClaimsWithAnOracle) + data.Add(c); + return data; + } + + /// A document of that holds one image of each of . + private static byte[] ImageFile(PdfConformance claim, params Kind[] kinds) + { + var doc = NewDocument(claim); + foreach (var k in kinds) + doc.Add(new LayoutImage(Load(k)) { Width = 40, Height = 20, AltText = k.Name }); + return Save(doc); + } + + private static PdfImageXObject Load(Kind k) => LayoutImage.FromBytes(k.Bytes).Image; + + private static ImageObject Written(byte[] file, int index = 0) + { + using var pdf = new Pdf(file); + return ImageObjects(pdf)[index]; + } + + // ── ISO 32000-1 8.9.5, Table 89; ISO 32000-2 8.9.5, Table 87 ───────────────────────────── + + [Theory] + [MemberData(nameof(KindNames))] + public void Iso32000_1_8_9_5_EveryImageDictionaryHoldsTable89EntriesWithTheValuesTheDataImplies(string name) + { + var kind = KindTable[name]; + foreach (var claim in Claims) + { + var file = ImageFile(claim, kind); + using var pdf = new Pdf(file); + + // The construct: exactly one image XObject, drawn once. + var image = Assert.Single(ImageObjects(pdf)); + Assert.Equal("Image", image.Name("Subtype")); + Assert.Equal("XObject", image.Name("Type")); + + // Table 89: Width and Height are integers and equal the samples of the source; the colour + // space is a device name chosen for the number of components; BitsPerComponent is one of + // 1, 2, 4, 8, 16 and is absent only for a JPX image. + Assert.Equal(kind.Width, (int)image.Num("Width")); + Assert.Equal(kind.Height, (int)image.Num("Height")); + Assert.Equal(kind.ColorSpace, image.Name("ColorSpace")); + if (kind.Bpc is { } bpc) + { + Assert.Equal(bpc, (int)image.Num("BitsPerComponent")); + Assert.Contains(bpc, new[] { 1, 2, 4, 8, 16 }); + } + else + { + Assert.Null(image.Dict.Get(N("BitsPerComponent"))); + Assert.Equal("JPXDecode", kind.Filter); + } + + // 8.9.5.1 and 19005-2 6.2.8: no key outside the ones a loader sets, so no Interpolate, Alternates, + // OPI, Decode, Intent or ImageMask, and the keys that never appear for a loader's output stay absent. + string[] allowed = + ["BitsPerComponent", "ColorSpace", "DecodeParms", "Filter", "Height", "Length", "Mask", "SMask", + "Subtype", "Type", "Width"]; + Assert.Empty(Keys(image.Dict).Except(allowed)); + foreach (var absent in new[] { "Interpolate", "Alternates", "OPI", "Decode", "Intent", "ImageMask", "SMaskInData", + "OC", "Metadata" }) + Assert.Null(image.Dict.Get(N(absent))); + + // The filter is the one the data needs, and it is a Table 6 filter other than LZWDecode. + Assert.Equal(kind.Filter, image.Name("Filter")); + Assert.Contains(kind.Filter, new[] + { + "FlateDecode", "DCTDecode", "CCITTFaxDecode", "JBIG2Decode", "JPXDecode", + }); + + // 8.9.3: each row starts on a byte boundary, components interleave, so a Flate image holds + // ceil(width * bits * components / 8) * height bytes. + if (kind.Filter == "FlateDecode") + { + var components = kind.ColorSpace switch { "DeviceGray" => 1, "DeviceRGB" => 3, _ => 4 }; + var rowBytes = ((kind.Width * kind.Bpc!.Value * components) + 7) / 8; + Assert.Equal(rowBytes * kind.Height, image.Decoded.Length); + } + + // The samples are the ones the source holds, top row first (8.9.4). + if (kind.Samples is not null) + Assert.Equal(kind.Samples, Convert.ToHexString(image.Decoded)); + } + } + + [Theory] + [MemberData(nameof(KindNames))] + public void Iso19005_2_6_1_7_1_TheLengthOfAnImageStreamIsTheNumberOfBytesBetweenItsKeywords(string name) + { + var kind = KindTable[name]; + var file = ImageFile(PdfConformance.PdfA2b, kind); + using var pdf = new Pdf(file); + var image = Assert.Single(ImageObjects(pdf)); + + // The construct: the stream keyword, then the body, then an end of line and endstream. + var length = (int)image.Num("Length"); + Assert.Equal(length, image.Raw.Length); + var text = Encoding.Latin1.GetString(file); + var after = text.AsSpan(image.BodyOffset + length); + Assert.True(after.StartsWith("\nendstream") || after.StartsWith("\r\nendstream"), + $"the bytes after the body are not an end of line and endstream: {after[..14].ToString()}"); + + // A stream dictionary has no F, FFilter or FDecodeParms. + foreach (var key in new[] { "F", "FFilter", "FDecodeParms" }) + Assert.Null(image.Dict.Get(N(key))); + } + + // ── 7.4.4, 7.4.6, 7.4.7, 7.4.8, 7.4.9: what each filter delivers ─────────────────────────── + + [Fact] + public void Iso32000_1_7_4_6_ACcittImageNamesItsColumnsAndRowsAndKeepsTheDefaultPolarity() + { + foreach (var (name, k) in new[] { ("tiff-group4", -1), ("tiff-group3", 0) }) + { + var kind = KindTable[name]; + var image = Written(ImageFile(PdfConformance.None, kind)); + var parms = Assert.IsType(image.Dict.Get(N("DecodeParms"))); + + // Table 11: K below 0 is Group 4 and K of 0 is Group 3 one-dimensional; Columns is the width, + // Rows the height; BlackIs1 is absent, so false, and 0 bits are black in the sample data. + Assert.Equal(k, (int)Num(parms.Get(N("K")))); + Assert.Equal(kind.Width, (int)Num(parms.Get(N("Columns")))); + Assert.Equal(kind.Height, (int)Num(parms.Get(N("Rows")))); + Assert.Null(parms.Get(N("BlackIs1"))); + + // 8.9.5: a CCITT filter delivers 1-bit samples, so the image is DeviceGray at 1 bit per component. + Assert.Equal("DeviceGray", image.Name("ColorSpace")); + Assert.Equal(1, (int)image.Num("BitsPerComponent")); + Assert.Equal([0xFF], image.Raw); + } + } + + [Fact] + public void Iso32000_1_7_4_7_AJbig2ImageIsBitonalAndHoldsTheSegmentsOfTheSource() + { + var kind = KindTable["jbig2"]; + var image = Written(ImageFile(PdfConformance.PdfA2b, kind)); + + // The construct: the body is the embedded organisation of the source's segments, passed through. + Assert.Equal("JBIG2Decode", image.Name("Filter")); + Assert.Equal(61, image.Raw.Length); + + // 7.4.7: bitonal only. The image is DeviceGray at one bit, with no Decode and no ImageMask, and a + // file with no global segments has no DecodeParms. + Assert.Equal("DeviceGray", image.Name("ColorSpace")); + Assert.Equal(1, (int)image.Num("BitsPerComponent")); + Assert.Null(image.Dict.Get(N("DecodeParms"))); + Assert.Null(image.Dict.Get(N("Decode"))); + } + + [Fact(Skip = "Gap #621: a JBIG2 page whose segments are associated with page 2 is written with that association, " + + "and a PDF image XObject may use page 1 only (ISO 32000-2, 7.4.7).")] + public void Iso32000_2_7_4_7_AJbig2ImageStreamAssociatesItsSegmentsWithPageOne() + { + var image = Written(ImageFile(PdfConformance.PdfA2b, new Kind("jbig2-page-two", Jbig2(16, 16, page: 2), 16, 16, + "DeviceGray", 1, "JBIG2Decode"))); + Assert.DoesNotContain(2, ReadPageAssociations(image.Raw)); + } + + private static byte[] Jbig2Segment(int number, int type, int page, byte[] data) + { + var header = new byte[11]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(header, number); + header[4] = (byte)type; + header[6] = (byte)page; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(7), data.Length); + return [.. header, .. data]; + } + + /// The page association of each segment of an embedded-organisation JBIG2 body (T.88, 7.2). + private static List ReadPageAssociations(byte[] body) + { + var pages = new List(); + var at = 0; + // The embedded form has no file header; the body begins with the first segment header. + if (body.Length > 8 && body[0] == 0x97 && body[1] == 0x4A) + at = 8; + while (at + 11 <= body.Length) + { + var length = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(at + 7)); + pages.Add(body[at + 6]); + at += 11 + length; + } + + return pages; + } + + [Theory] + [InlineData("jpeg-grey", 1)] + [InlineData("jpeg-rgb", 3)] + [InlineData("jpeg-cmyk", 4)] + public void Iso32000_1_7_4_8_AJpegPassesThroughAsDctDecodeWithTheColourSpaceItsFrameHeaderImplies(string name, + int components) + { + var kind = KindTable[name]; + var image = Written(ImageFile(PdfConformance.None, kind)); + + // The construct: the body is the source, byte for byte, behind the DCTDecode name. + Assert.Equal("DCTDecode", image.Name("Filter")); + Assert.Equal(kind.Bytes, image.Raw); + + // 7.4.8 and 8.9.5: DCTDecode delivers 8-bit samples; one, three or four components are Gray, RGB and + // CMYK, and the dictionary has no Decode and no DecodeParms (no ColorTransform). + Assert.Equal(8, (int)image.Num("BitsPerComponent")); + Assert.Equal(components switch { 1 => "DeviceGray", 3 => "DeviceRGB", _ => "DeviceCMYK" }, + image.Name("ColorSpace")); + Assert.Null(image.Dict.Get(N("Decode"))); + 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.")] + [InlineData(2)] + [InlineData(5)] + public void Iso32000_2_7_4_8_ADctImageOfAnotherComponentCountIsRefused(int components) + { + Assert.Throws(() => JpegImageLoader.Load(Jpeg(4, 2, components))); + } + + [Fact] + public void Iso32000_1_Table89_PinsTodayAJpegOfTwelveBitPrecisionIsWrittenAsEightBitDct() + { + // The frame header's precision byte is 12; the loader never reads it. Table 89 says DCTDecode always delivers + // 8-bit samples, and 7.4.8 that each component value occupies a byte. + var bytes = Jpeg(4, 2, 3); + bytes[3] = 0xC1; // SOF1, extended sequential DCT, which allows a precision of 12 + bytes[6] = 12; + var image = Written(ImageFile(PdfConformance.PdfA2b, new Kind("jpeg-12", bytes, 4, 2, "DeviceRGB", 8, "DCTDecode"))); + Assert.Equal(8, (int)image.Num("BitsPerComponent")); + Assert.Equal(bytes, image.Raw); + Assert.Empty(VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, new Kind("jpeg-12", bytes, 4, 2, "DeviceRGB", 8, + "DCTDecode")))); + } + + [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() + { + var bytes = Jpeg(4, 2, 3); + bytes[3] = 0xC1; + bytes[6] = 12; + Assert.Throws(() => JpegImageLoader.Load(bytes)); + } + + [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.")] + [InlineData(0xC3)] + [InlineData(0xC9)] + public void Iso32000_2_7_4_8_AJpegOfAFrameTypeTheFilterDoesNotDecodeIsNotWrittenAsDctDecode(int marker) + { + var bytes = Jpeg(4, 2, 3); + bytes[3] = (byte)marker; + Assert.Throws(() => JpegImageLoader.Load(bytes)); + } + + [Fact] + public void Iso32000_2_7_4_8_AProgressiveJpegIsAcceptedBecauseTheFilterDecodesIt() + { + var bytes = Jpeg(4, 2, 3); + bytes[3] = 0xC2; + var image = Written(ImageFile(PdfConformance.None, new Kind("jpeg-progressive", bytes, 4, 2, "DeviceRGB", 8, + "DCTDecode"))); + Assert.Equal(bytes, image.Raw); + } + + [Theory] + [InlineData("jpx-3-channels", 3, 8, 16)] + [InlineData("jpx-1-channel", 1, 8, 17)] + [InlineData("jpx-4-channels", 4, 8, 12)] + [InlineData("jpx-16-bit", 3, 16, 16)] + [InlineData("jpx-12-bit", 3, 12, 16)] + public void Iso19005_2_6_2_8_3_AJpxImageIsAJp2FileWithOneColourSpecificationOfAnAllowedMethod(string name, + int channels, int depth, int enumeratedColourSpace) + { + var kind = KindTable[name]; + var image = Written(ImageFile(PdfConformance.PdfA2b, kind)); + + // The construct: a JP2 file, which starts with the signature box, then ftyp, jp2h and jp2c. + Assert.Equal("JPXDecode", image.Name("Filter")); + var boxes = Jp2Boxes(image.Raw); + Assert.Equal(["jP ", "ftyp", "jp2h", "jp2c"], boxes.Select(b => b.Type).ToArray()); + + // 6.2.8.3: one, three or four colour channels; one colr box with a METH of 1, 2 or 3 and, for METH 1, an + // enumerated space other than CIEJab (19); a bit depth of 1 to 38 in the ihdr box that is the same for + // every channel. + var header = Jp2Boxes(boxes[2].Payload); + Assert.Equal(["ihdr", "colr"], header.Select(b => b.Type).ToArray()); + var ihdr = header[0].Payload; + Assert.Equal(channels, (ihdr[8] << 8) | ihdr[9]); + Assert.Equal(depth, (ihdr[10] & 0x7F) + 1); + var colr = header[1].Payload; + Assert.Equal(1, colr[0]); + Assert.Equal(enumeratedColourSpace, (colr[3] << 24) | (colr[4] << 16) | (colr[5] << 8) | colr[6]); + Assert.NotEqual(19, enumeratedColourSpace); + + // Table 89: BitsPerComponent is optional for JPXDecode; it is written when it is one of 1, 2, 4, 8, 16 and + // left out otherwise, which is what 19005-2 6.2.8-4 needs for a 12-bit image. + if (depth is 1 or 2 or 4 or 8 or 16) + Assert.Equal(depth, (int)image.Num("BitsPerComponent")); + else + Assert.Null(image.Dict.Get(N("BitsPerComponent"))); + } + + [Fact] + public void Iso32000_2_7_4_9_TheJpxCodestreamIsTheSourceByteForByte() + { + var kind = KindTable["jpx-3-channels"]; + var image = Written(ImageFile(PdfConformance.None, kind)); + var codestream = Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload; + Assert.Equal(kind.Bytes, codestream); + } + + private sealed record Box(string Type, byte[] Payload); + + private static List Jp2Boxes(byte[] data) + { + var boxes = new List(); + var at = 0; + while (at + 8 <= data.Length) + { + var length = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(at)); + Assert.True(length >= 8 && at + length <= data.Length, "a box of a JP2 file has its length inside the file"); + boxes.Add(new Box(Encoding.Latin1.GetString(data, at + 4, 4), data[(at + 8)..(at + length)])); + at += length; + } + + Assert.Equal(data.Length, at); + return boxes; + } + + // ── 8.9.5.1, Table 89 and 11.6.5.3, Table 145: the soft mask of an alpha channel ────────────── + + [Theory] + [MemberData(nameof(AlphaKindNames))] + public void Iso32000_1_11_6_5_3_ASoftMaskIsAnImageOfItsOwnThatTable145Allows(string name) + { + var kind = KindTable[name]; + foreach (var claim in Claims) + { + using var pdf = new Pdf(ImageFile(claim, kind)); + var image = Assert.Single(ImageObjects(pdf)); + + // The construct: an SMask entry that is an indirect reference to a second image XObject. + Assert.IsType(image.Dict.Get(N("SMask"))); + var mask = Assert.IsType(image.SoftMask); + Assert.Equal("Image", mask.Name("Subtype")); + + // Table 145: Type XObject, Subtype Image, ColorSpace DeviceGray, BitsPerComponent given, no + // ImageMask, no Mask, no SMask. Without Matte its size is independent; the loaders write the + // image's own size. The alpha samples are what the source holds. + Assert.Equal("XObject", mask.Name("Type")); + Assert.Equal("DeviceGray", mask.Name("ColorSpace")); + Assert.Equal(kind.SMaskBpc, (int)mask.Num("BitsPerComponent")); + Assert.Contains(kind.SMaskBpc, new[] { 8, 16 }); + Assert.Equal(kind.Width, (int)mask.Num("Width")); + Assert.Equal(kind.Height, (int)mask.Num("Height")); + foreach (var absent in new[] { "ImageMask", "Mask", "SMask", "Matte", "Decode", "Interpolate", "Alternates" }) + Assert.Null(mask.Dict.Get(N(absent))); + Assert.Equal(kind.SMask, Convert.ToHexString(mask.Decoded)); + + // Table 89: SMask overrides Mask, and a loader never writes both. + Assert.Null(image.Dict.Get(N("Mask"))); + Assert.Null(image.Dict.Get(N("SMaskInData"))); + + // The soft mask is its own object and is not drawn. + Assert.NotEqual(image.ObjectNumber, mask.ObjectNumber); + Assert.Single(PlacedImages(pdf.Page(0))); + } + } + + [Fact] + public void Iso32000_1_11_6_5_3_AnImageWithNoNonOpaqueAlphaHasNoSoftMask() + { + // A BMP and a 32-bit BMP carry no alpha, an RGBA TIFF whose alpha is 255 everywhere has none to write. + var opaque = new Kind("tiff-opaque-alpha", Tiff(true, [.. BaseTags(2, 1, 8, 2, 4), Short(338, 2)], + [255, 0, 0, 255, 0, 255, 0, 255]), 2, 1, "DeviceRGB", 8, "FlateDecode", "FF000000FF00"); + var image = Written(ImageFile(PdfConformance.PdfA2b, opaque)); + Assert.Null(image.Dict.Get(N("SMask"))); + Assert.Null(image.SoftMask); + } + + // ── 8.9.6.4: colour key masking ────────────────────────────────────────────────────────────── + + [Theory] + [MemberData(nameof(ColourKeyKindNames))] + public void Iso32000_1_8_9_6_4_AColourKeyIsPairsOfIntegersInsideTheSampleRangeAndNamesAStoredSample(string name) + { + var kind = KindTable[name]; + var image = Written(ImageFile(PdfConformance.PdfA2b, kind)); + + // The construct: a Mask array and no SMask. + var mask = Assert.IsType(image.Dict.Get(N("Mask"))); + Assert.Null(image.Dict.Get(N("SMask"))); + + // 2n integers, n the number of components, each from 0 to 2^BitsPerComponent - 1 and min not above max. + var components = kind.ColorSpace == "DeviceGray" ? 1 : 3; + var values = mask.Items().Select(v => (int)Num(v)).ToArray(); + Assert.Equal(2 * components, values.Length); + Assert.All(values, v => Assert.InRange(v, 0, (1 << kind.Bpc!.Value) - 1)); + for (var c = 0; c < components; c++) + Assert.True(values[2 * c] <= values[(2 * c) + 1]); + Assert.Equal(kind.Mask, values); + + // The range is of values before decoding, so the colour the source marked transparent must be the + // sample a pixel of the written data holds, and the pixel the source kept must not match. + var samples = image.Decoded; + bool Masked(int pixel) => Enumerable.Range(0, components).All(c => + samples[(pixel * components) + c] >= values[2 * c] && samples[(pixel * components) + c] <= values[(2 * c) + 1]); + Assert.Equal([true, false], [Masked(0), Masked(1)]); + } + + // ── 8.9.4 and 8.9.3: samples are written top row first, whatever the source's order ────────── + + [Fact] + public void Iso32000_1_8_9_4_ABottomUpAndATopDownBmpAreWrittenTopRowFirst() + { + // The same two rows stored in the two orders of a BMP give the same picture, top row first. + var bottomUp = Written(ImageFile(PdfConformance.None, KindTable["bmp-24-two-rows"])); + var topDown = Written(ImageFile(PdfConformance.None, KindTable["bmp-24-top-down"])); + var topRow = Convert.FromHexString("0000FF000000"); + var bottomRow = Convert.FromHexString("FF0000" + "00FF00"); + // Stored rows: A = red, green and B = blue, black. A bottom-up file stores the bottom row first. + Assert.Equal([.. topRow, .. bottomRow], bottomUp.Decoded); + Assert.Equal(Convert.FromHexString("FF000000FF00" + "0000FF000000"), topDown.Decoded); + } + + // ── Options the factories pass on: bit depth and the GIF logical screen ────────────────────── + + [Theory] + [InlineData("png-rgba16")] + [InlineData("tiff-rgba16")] + public void Iso32000_1_8_9_5_ReducingToEightBitsWritesEightBitSamplesAndAnEightBitSoftMask(string name) + { + var kind = KindTable[name]; + var image = LayoutImage.FromBytes(kind.Bytes, new ImageLoadOptions { BitDepth = ImageBitDepth.ReduceToEight }); + var doc = NewDocument(PdfConformance.PdfA2b); + doc.Add(new LayoutImage(image.Image) { Width = 40, Height = 20 }); + var written = Written(Save(doc)); + + // The construct: the same source as the 16-bit kind, now at 8 bits for the colour and for the alpha. + Assert.Equal(8, (int)written.Num("BitsPerComponent")); + var mask = Assert.IsType(written.SoftMask); + Assert.Equal(8, (int)mask.Num("BitsPerComponent")); + + // The high byte of each sample is kept. + Assert.Equal("12569A", Convert.ToHexString(written.Decoded)); + Assert.Equal("80", Convert.ToHexString(mask.Decoded)); + } + + [Fact] + public void Iso32000_1_11_6_5_3_AGifPlacedOnItsLogicalScreenIsTransparentWhereTheFrameIsNot() + { + var bytes = Gif(null, [255, 0, 0, 0, 0, 255], screenWidth: 4, screenHeight: 3, left: 1, top: 1); + var placed = LayoutImage.FromBytes(bytes, new GifLoadOptions { PlaceOnLogicalScreen = true }); + var doc = NewDocument(PdfConformance.PdfA2b); + doc.Add(new LayoutImage(placed.Image) { Width = 40, Height = 30 }); + var image = Written(Save(doc)); + + // The construct: the image is as large as the screen and has a soft mask the frame did not need. + Assert.Equal((4, 3), ((int)image.Num("Width"), (int)image.Num("Height"))); + var mask = Assert.IsType(image.SoftMask); + Assert.Equal((4, 3), ((int)mask.Num("Width"), (int)mask.Num("Height"))); + + // Alpha is 255 over the two pixels of the frame, at (1,1) and (2,1), and 0 elsewhere, and the frame's + // colours are at those pixels. + Assert.Equal("00000000" + "00FFFF00" + "00000000", Convert.ToHexString(mask.Decoded)); + Assert.Equal("FF0000" + "0000FF", Convert.ToHexString(image.Decoded[(((1 * 4) + 1) * 3)..(((1 * 4) + 3) * 3)])); + + // Without the option the frame is returned at its own size and the position is not applied (documented). + var own = Written(ImageFile(PdfConformance.PdfA2b, new Kind("gif-own", bytes, 2, 1, "DeviceRGB", 8, "FlateDecode"))); + Assert.Equal((2, 1), ((int)own.Num("Width"), (int)own.Num("Height"))); + Assert.Null(own.SoftMask); + } + + [Fact] + public void Iso32000_2_7_5_2_TheHeaderNamesAVersionThatHasEveryFeatureTheImagesUse() + { + // 16-bit samples and JPX are PDF 1.5, soft masks 1.4, colour key masks 1.3, JBIG2 1.4. A file with no claim + // is written as PDF 2.0 and a file with a claim as PDF 1.7, which is what PDF/A-2 builds on. + var kinds = new[] { "png-rgba16", "jpx-3-channels", "jbig2", "png-grey-key8" }.Select(n => KindTable[n]).ToArray(); + foreach (var claim in ConformanceAuditG2Support.Claims) + { + var file = ImageFile(claim, kinds); + Assert.StartsWith(claim == PdfConformance.None ? "%PDF-2.0" : "%PDF-1.7", Encoding.Latin1.GetString(file)); + } + } + + // ── 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() + { + var image = Written(ImageFile(PdfConformance.None, new Kind("jbig2-page-two", Jbig2(16, 16, page: 2), 16, 16, + "DeviceGray", 1, "JBIG2Decode"))); + Assert.Contains(2, ReadPageAssociations(image.Raw)); + } + + private static byte[] AssociatedAlphaTiff() => Tiff(true, + [.. 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, + "DeviceRGB", 8, "FlateDecode"))); + + // Associated alpha is the preblend formula with a black matte, so the samples stay and Matte is [0 0 0]. + 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)); + } + + [Fact] + public void Iso32000_1_8_9_4_PinsTodayATiffOrientationOfThreeIsIgnored() + { + var image = Written(ImageFile(PdfConformance.None, new Kind("tiff-rotated", Tiff(true, + [.. BaseTags(2, 1, 8, 1, 1), Short(274, 3)], [0x10, 0xF0]), 2, 1, "DeviceGray", 8, "FlateDecode"))); + Assert.Equal("10F0", Convert.ToHexString(image.Decoded)); + } + + [Fact(Skip = "Gap #769: TiffImageLoader ignores the Orientation tag, so a file stored rotated or mirrored is " + + "written in its storage order and shows the wrong way up (TIFF 6.0, section 8, tag 274).")] + public void Tiff6_0_8_TheOrientationTagTurnsTheImageSoItsRowZeroIsOnTheSideTheTagNames() + { + // Orientation 3: row 0 is at the bottom and column 0 on the right, so the stored pixels 10 F0 read F0 10. + var image = Written(ImageFile(PdfConformance.None, new Kind("tiff-rotated", Tiff(true, + [.. BaseTags(2, 1, 8, 1, 1), Short(274, 3)], [0x10, 0xF0]), 2, 1, "DeviceGray", 8, "FlateDecode"))); + Assert.Equal("F010", Convert.ToHexString(image.Decoded)); + } + + // ── 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) + { + static byte[] BoxOf(string type, byte[] payload) + { + var box = new byte[8 + payload.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(box, box.Length); + Encoding.ASCII.GetBytes(type).CopyTo(box, 4); + payload.CopyTo(box, 8); + return box; + } + + var ihdr = new byte[14]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(ihdr, 16); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), 16); + ihdr[8] = (byte)(channels >> 8); + 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); + byte[] depths = bpcc is null ? [] : BoxOf("bpcc", bpcc); + 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)]), + .. BoxOf("jp2c", codestream), + ]; + } + + [Fact] + public void Iso32000_2_7_4_9_PinsTodayAJp2WithASyccColourSpecificationIsWrittenAsDeviceRgb() + { + // Enumerated colour space 18 is sYCC. The dictionary's ColorSpace, when present, replaces the file's colour + // specification (Table 87), so the YCC samples are read as RGB. + var bytes = Jp2File(JpxCodestream(16, 16, 3), 3, 18); + var image = Written(ImageFile(PdfConformance.None, new Kind("jp2-sycc", bytes, 16, 16, "DeviceRGB", 8, "JPXDecode"))); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); + var colr = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Single(b => b.Type == "colr").Payload; + Assert.Equal(18, colr[6]); + } + + [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() + { + 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. + Assert.Null(Written(file).Dict.Get(N("ColorSpace"))); + } + + [Fact] + public void Iso32000_2_7_4_9_PinsTodayABareCodestreamOfTwoChannelsGetsAnSrgbColourSpecification() + { + var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, + "DeviceRGB", 8, "JPXDecode"))); + var header = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload); + Assert.Equal(2, (header[0].Payload[8] << 8) | header[0].Payload[9]); + Assert.Equal(16, header[1].Payload[6]); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); + + // veraPDF's 6.2.8.3-1 fails the file under a PDF/A claim: the image has two colour channels. + var claimed = ImageFile(PdfConformance.PdfA2b, new Kind("jpx-2", JpxCodestream(16, 16, 2), 16, 16, "DeviceRGB", + 8, "JPXDecode")); + Assert.Equal(["6.2.8.3-1"], VeraFailures("2b", claimed)); + } + + [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() + { + AssertRefusedOrAcceptedByVeraPdf(new Kind("jpx-2", JpxCodestream(16, 16, 2), 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. + /// + private static void AssertRefusedOrAcceptedByVeraPdf(Kind kind) + { + byte[] file; + try + { + file = ImageFile(PdfConformance.PdfA2b, kind); + } + catch (InvalidDataException) + { + return; + } + + Assert.Null(Written(file).Dict.Get(N("ColorSpace"))); + Assert.Empty(VeraFailures("2b", file)); + } + + [Fact] + public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileOfTwoChannelsIsPassedThroughAndFailsVeraPdf() + { + // 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))); + } + + [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() + { + AssertRefusedOrAcceptedByVeraPdf(new Kind("jp2-2", Jp2File(JpxCodestream(16, 16, 2), 2, 17), 16, 16, "DeviceGray", + 8, "JPXDecode")); + } + + [Fact] + public void Iso19005_2_6_2_8_3_PinsTodayAJp2FileWithChannelsOfDifferentDepthsIsPassedThroughAndFailsVeraPdf() + { + // 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(); + var image = Written(ImageFile(PdfConformance.None, kind)); + Assert.Contains(Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload), b => b.Type == "bpcc"); + 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() + { + // 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 ||). + var kind = new Kind("jp2-cielab", Jp2File(JpxCodestream(16, 16, 3), 3, 19), 16, 16, "DeviceRGB", 8, "JPXDecode"); + var image = Written(ImageFile(PdfConformance.None, kind)); + Assert.Equal("DeviceRGB", image.Name("ColorSpace")); + var colr = Jp2Boxes(Jp2Boxes(image.Raw).Single(b => b.Type == "jp2h").Payload).Single(b => b.Type == "colr").Payload; + Assert.Equal(19, colr[6]); + Assert.Empty(VeraFailures("2b", ImageFile(PdfConformance.PdfA2b, kind))); + } + + [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() + { + 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]); + } + + [Fact] + public void Iso32000_2_7_4_9_PinsTodayAPartTwoCodestreamIsPassedThrough() + { + // Rsiz with the Part 2 bit (0x8000) says the codestream uses extensions outside the baseline set that 7.4.9 + // limits PDF to. The loader reads no Rsiz, so the codestream is wrapped as it is. Whether the Part 2 bit puts it outside the + // baseline set is defined in ISO/IEC 15444-2, which is not held, so this pins the bytes and nothing more. + var image = Written(ImageFile(PdfConformance.None, new Kind("jpx-part2", JpxCodestream(16, 16, 3, 7, 0x8000), 16, 16, + "DeviceRGB", 8, "JPXDecode"))); + Assert.Equal("JPXDecode", image.Name("Filter")); + var codestream = Jp2Boxes(image.Raw).Single(b => b.Type == "jp2c").Payload; + Assert.Equal([0x80, 0x00], codestream[6..8]); + } + + [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() + { + Assert.Throws(() => JpxImageLoader.Load(JpxCodestream(16, 16, 3, 7, 0x8000))); + } + + // ── 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 + { + // 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]), + }; + + [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 image = Written(ImageFile(PdfConformance.PdfA2b, kind)); + Assert.Equal(needed, Assert.IsType(image.Dict.Get(N("Mask"))).Items().Select(v => (int)Num(v)).ToArray()); + } + + [Fact] + public void Iso32000_1_8_9_6_4_PinsTodayReducingToEightBitsWidensASixteenBitKeyToAllSamplesWithTheSameHighByte() + { + // The key 0x1234 and the samples 0x1234 and 0x1299 become the key 0x12 over the samples 0x12 and 0x12, so both + // pixels are masked. The result is inside the range, so no clause is broken; ImageLoadOptions does not say it. + var png = Png(2, 1, 16, 0, [0x12, 0x34, 0x12, 0x99], 4, null, [0x12, 0x34]); + var image = LayoutImage.FromBytes(png, new ImageLoadOptions { BitDepth = ImageBitDepth.ReduceToEight }); + var doc = NewDocument(PdfConformance.PdfA2b); + doc.Add(new LayoutImage(image.Image) { Width = 40, Height = 20 }); + var written = Written(Save(doc)); + Assert.Equal("1212", Convert.ToHexString(written.Decoded)); + Assert.Equal([0x12, 0x12], Assert.IsType(written.Dict.Get(N("Mask"))).Items().Select(v => (int)Num(v)).ToArray()); + } + + // ── 7.4.7: a JBIG2 stream in a PDF has no file header, end-of-page or end-of-file segment ───── + + [Fact] + public void Iso32000_2_7_4_7_TheJbig2FileHeaderAndTheEndOfPageAndEndOfFileSegmentsAreNotWritten() + { + // The source has the ID string, a page-information segment, a region, an end-of-page segment (type 49) and an + // end-of-file segment (type 51). + var source = new List(Jbig2(16, 16)); + source.AddRange(Jbig2Segment(2, 49, 1, [])); + source.AddRange(Jbig2Segment(3, 51, 0, [])); + Assert.Equal([0x97, 0x4A, 0x42, 0x32], source.Take(4).ToArray()); + var image = Written(ImageFile(PdfConformance.PdfA2b, new Kind("jbig2-framed", [.. source], 16, 16, "DeviceGray", 1, + "JBIG2Decode"))); + + Assert.NotEqual([0x97, 0x4A, 0x42, 0x32], image.Raw.Take(4).ToArray()); + Assert.Equal([48, 39], SegmentTypes(image.Raw)); + } + + [Fact] + public void Iso32000_2_7_4_7_AFullAnnexDFileHeaderIsRefusedAndNotDropped() + { + // ID string, flags (sequential, page count known) and a page count of 1, then the segments: the loader + // reads the ID string only, so the flags and count are read as a segment header and the file is refused. + byte[] source = [0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A, 0x01, 0, 0, 0, 1, .. Jbig2(16, 16)[8..]]; + Assert.Throws(() => LayoutImage.FromBytes(source)); + } + + private static List SegmentTypes(byte[] body) + { + var types = new List(); + var at = 0; + while (at + 11 <= body.Length) + { + types.Add(body[at + 4] & 0x3F); + at += 11 + System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(at + 7)); + } + + return types; + } + + // ── The same source through a loader and through the factory ───────────────────────────────── + + [Theory] + [MemberData(nameof(KindNames))] + public void Iso32000_1_8_9_5_TheFactoryWritesTheFileTheLoaderWouldHave(string name) + { + var kind = KindTable[name]; + PdfImageXObject viaLoader = kind.Filter switch + { + "DCTDecode" => JpegImageLoader.Load(kind.Bytes), + "JBIG2Decode" => Jbig2ImageLoader.Load(kind.Bytes), + "JPXDecode" => JpxImageLoader.Load(kind.Bytes), + _ => name.StartsWith("png", StringComparison.Ordinal) ? PngImageLoader.Load(kind.Bytes) + : name.StartsWith("gif", StringComparison.Ordinal) ? GifImageLoader.Load(kind.Bytes) + : name.StartsWith("bmp", StringComparison.Ordinal) ? BmpImageLoader.Load(kind.Bytes) + : TiffImageLoader.Load(kind.Bytes), + }; + + byte[] Build(PdfImageXObject image) + { + var doc = NewDocument(PdfConformance.None); + doc.Add(new LayoutImage(image) { Width = 40, Height = 20 }); + return Save(doc); + } + + // The construct: both files hold one image of the kind's size. + var viaFactory = LayoutImage.FromBytes(kind.Bytes).Image; + Assert.Equal((kind.Width, kind.Height), (viaLoader.Width, viaLoader.Height)); + Assert.Equal((kind.Width, kind.Height), (viaFactory.Width, viaFactory.Height)); + + // The two files are the same bytes, so the factory adds nothing the loader would not write. + Assert.Equal(Build(viaLoader), Build(viaFactory)); + } +} diff --git a/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Placement.cs b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Placement.cs new file mode 100644 index 00000000..bb1c467d --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/ConformanceAuditG4Tests.Placement.cs @@ -0,0 +1,365 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text.RegularExpressions; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.TestSupport; +using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG2Support; +using static VellumPdf.Kernel.Tests.ConformanceAuditG4Support; +using LayoutDocument = VellumPdf.Layout.Document; + +namespace VellumPdf.Kernel.Tests; + +// FitToPage (#683, #471) against ISO 32000-1 8.3.4 and 8.9.4, and the word spacing of a justified +// line (#674, #665) against 9.3.3. +public sealed partial class ConformanceAuditG4Tests +{ + // ── FitToPage: the cm matrix against the page box ──────────────────────────────────────────── + + public sealed record Page(string Name, double Width, double Height, double Margin, int ImageWidth, int ImageHeight, + HorizontalAlignment Alignment, bool Bands, bool ExceedsWithoutFit) + { + public override string ToString() => Name; + } + + private static readonly Page[] Pages = + [ + new("a4-portrait-square", 595.28, 841.89, 72, 100, 100, HorizontalAlignment.Left, false, false), + new("a4-landscape-square", 841.89, 595.28, 72, 100, 100, HorizontalAlignment.Left, false, true), + new("letter-wide-image", 612, 792, 36, 200, 100, HorizontalAlignment.Left, false, false), + new("small-landscape-square", 300, 200, 20, 100, 100, HorizontalAlignment.Center, false, true), + new("tall-narrow-tall-image", 200, 1000, 10, 100, 1000, HorizontalAlignment.Right, false, true), + new("square-page-no-margin", 400, 400, 0, 50, 300, HorizontalAlignment.Center, false, true), + new("short-page-with-bands", 500, 160, 10, 100, 100, HorizontalAlignment.Left, true, true), + ]; + + public static TheoryData PageNames() + { + var data = new TheoryData(); + foreach (var p in Pages) + data.Add(p.Name); + return data; + } + + private static (LayoutDocument Doc, double ContentTop, double ContentBottom) FitDocument(Page page, bool fit) + { + var doc = NewDocument(PdfConformance.None, new PdfRectangle(0, 0, page.Width, page.Height), + new EdgeInsets(page.Margin)); + var top = page.Height - page.Margin; + var bottom = page.Margin; + if (page.Bands) + { + var style = Style(doc, DejaVu, 9); + var header = new RunningBand("Header", style); + var footer = new RunningBand("Footer {page}", style); + doc.Header = header; + doc.Footer = footer; + top -= header.EffectiveHeight; + bottom += footer.EffectiveHeight; + } + + var png = Png(page.ImageWidth, page.ImageHeight, 8, 0, new byte[page.ImageWidth * page.ImageHeight], + page.ImageWidth); + doc.Add(new LayoutImage(LayoutImage.FromBytes(png).Image) + { + FitToPage = fit, + Alignment = page.Alignment, + }); + return (doc, top, bottom); + } + + [Theory] + [MemberData(nameof(PageNames))] + public void Iso32000_1_8_9_4_AFittedImageIsAUnitSquareScaledInsideTheContentBoxWithItsProportions(string name) + { + var page = Pages.Single(p => p.Name == name); + var (doc, top, bottom) = FitDocument(page, fit: true); + var file = Save(doc); + using var pdf = new Pdf(file); + + // 19005-2 6.1.13: every number of the content is a plain decimal with no exponent, within the real limits. + Assert.All(Operators(pdf.Page(0)).SelectMany(o => o.Operands).Where(o => o.Length > 0 && (char.IsDigit(o[0]) || o[0] == '-')), + o => Assert.Matches(@"^-?\d+(\.\d{1,5})?$", o)); + + // The construct: q, cm, Do, Q, one image on one page. + Assert.Equal(1, pdf.Reader.PageCount); + var content = pdf.Page(0); + var ops = Operators(content); + var doAt = ops.FindIndex(o => o.Name == "Do"); + Assert.Equal(["q", "cm", "Do", "Q"], ops.Skip(doAt - 2).Take(4).Select(o => o.Name).ToArray()); + var (matrix, _) = Assert.Single(PlacedImages(content)); + Assert.Equal(6, matrix.Length); + + // 8.3.4 and 8.9.4: [w 0 0 h x y] maps the unit square to the rectangle of the image with no rotation or + // skew, with positive extents, so the matrix is invertible and the image is not mirrored. + var (w, h, x, y) = (matrix[0], matrix[3], matrix[4], matrix[5]); + Assert.Equal([0, 0], [matrix[1], matrix[2]]); + Assert.True(w > 0 && h > 0); + + // The proportions of the source are kept (to the five decimals the writer prints). + Assert.Equal((double)page.ImageWidth / page.ImageHeight, w / h, 3); + + // The rectangle lies inside the content box, which lies inside the MediaBox. + var mediaBox = pdf.Array(pdf.Reader.GetPage(0).Dictionary.Get(N("MediaBox"))).Items().Select(Num).ToArray(); + Assert.Equal([0, 0, page.Width, page.Height], mediaBox); + const double eps = 1e-3; + Assert.InRange(x, page.Margin - eps, page.Width - page.Margin + eps); + Assert.InRange(x + w, page.Margin - eps, page.Width - page.Margin + eps); + Assert.InRange(y, bottom - eps, top + eps); + Assert.InRange(y + h, bottom - eps, top + eps); + + // Alignment moves it inside its row: left at the left margin, centred, or against the right margin. + var inner = page.Width - (2 * page.Margin); + Assert.Equal(page.Alignment switch + { + HorizontalAlignment.Center => page.Margin + ((inner - w) / 2), + HorizontalAlignment.Right => page.Margin + inner - w, + _ => page.Margin, + }, x, 3); + + // An image taller than the content box is scaled to exactly its height; one that fits is not enlarged. + var contentHeight = top - bottom; + if (page.ExceedsWithoutFit) + Assert.Equal(contentHeight, h, 3); + else + Assert.True(h <= contentHeight + eps); + } + + [Theory] + [MemberData(nameof(PageNames))] + public void Iso32000_1_8_9_4_WithoutFitToPageAnImageTallerThanTheContentBoxIsRefusedAndOneThatFitsIsUnchanged( + string name) + { + var page = Pages.Single(p => p.Name == name); + if (page.ExceedsWithoutFit) + { + var (doc, _, _) = FitDocument(page, fit: false); + var e = Assert.Throws(() => Save(doc)); + Assert.Contains("FitToPage", e.Message); + return; + } + + // The image that fits has the same matrix with and without the member. + var plain = FitDocument(page, fit: false).Doc; + var fitted = FitDocument(page, fit: true).Doc; + using var a = new Pdf(Save(plain)); + using var b = new Pdf(Save(fitted)); + Assert.Equal(Assert.Single(PlacedImages(a.Page(0))).Matrix, Assert.Single(PlacedImages(b.Page(0))).Matrix); + } + + [Fact] + public void Iso32000_1_8_3_4_AFitThatWouldWriteAnExtentAsZeroIsRefusedAndNeverMakesTheMatrixSingular() + { + // An explicit height of 1e9 pt fitted to a 700 pt box is a factor of 7e-7, and a width of 1e-5 pt becomes + // 7e-12 pt, which the five-decimal writer would print as 0 and so make the matrix non-invertible (8.3.4). + var doc = NewDocument(PdfConformance.None); + doc.Add(new LayoutImage(Load(KindTable["png-grey8"])) { Width = 1e-5, Height = 1e9, FitToPage = true }); + var e = Assert.Throws(() => Save(doc)); + Assert.Contains("width of 0", e.Message); + } + + [Fact] + public void Iso32000_1_8_4_2_AFittedImageIsDrawnInsideItsOwnGraphicsStateSoNothingAfterItIsScaled() + { + var page = Pages[1]; + var doc = FitDocument(page, fit: true).Doc; + doc.Add(new Paragraph("After the image.", Style(doc, DejaVu))); + using var pdf = new Pdf(Save(doc)); + + // The construct: the fitted image fills the page, so the paragraph is on the next page, drawn after a scaled + // matrix was set on the first. + Assert.Equal(2, pdf.Reader.PageCount); + Assert.Equal(["q", "cm", "Do", "Q"], OperatorNames(pdf.Page(0)).ToArray()); + var names = OperatorNames(pdf.Page(1)); + Assert.True(names.Contains("Tj") || names.Contains("TJ")); + + // q and Q balance on each page and the nesting never exceeds 28 (19005-2 6.1.13), so the scaled matrix + // is undone by the Q that follows the Do. + var max = 0; + foreach (var index in new[] { 0, 1 }) + { + var depth = 0; + foreach (var n in OperatorNames(pdf.Page(index))) + { + if (n == "q") + max = Math.Max(max, ++depth); + else if (n == "Q") + depth--; + Assert.True(depth >= 0); + } + + Assert.Equal(0, depth); + } + + Assert.InRange(max, 1, 28); + } + + // ── ISO 32000-1 9.3.3: word spacing ─────────────────────────────────────────────────────────── + + private const string Words = "aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt uu vv ww xx yy zz"; + + private static LayoutDocument JustifiedDocument(Func style) + { + var doc = NewDocument(PdfConformance.None, new PdfRectangle(0, 0, 300, 400), new EdgeInsets(50)); + doc.Add(new Paragraph(Words, style(doc)) { Alignment = HorizontalAlignment.Justify }); + return doc; + } + + /// The state in force at each shown string: the font's subtype, the Tw, the bytes shown. + private static List<(string Subtype, double WordSpacing, byte[] Bytes)> ShownWithSpacing(Pdf pdf) + { + var fonts = new Dictionary(); + var resources = pdf.Dict(pdf.Reader.GetPage(0).Dictionary.Get(N("Resources"))); + foreach (var (key, value) in pdf.Dict(resources.Get(N("Font"))).Entries) + fonts[key.Value] = Assert.IsType(pdf.Dict(value).Get(PdfName.Subtype)).Value; + + var result = new List<(string, double, byte[])>(); + var font = ""; + var tw = 0.0; + foreach (var op in Operators(pdf.Page(0))) + { + switch (op.Name) + { + case "Tf": + font = op.Operands[0][1..]; + break; + case "Tw": + tw = D(op.Operands[0]); + break; + case "Tj": + result.Add((fonts[font], tw, StringBytes(op.Operands[0]))); + break; + case "TJ": + foreach (var piece in op.Operands.Where(o => o.StartsWith('(') || o.StartsWith('<'))) + result.Add((fonts[font], tw, StringBytes(piece))); + break; + } + } + + return result; + } + + [Fact] + public void Iso32000_1_9_3_3_AJustifiedStandard14LineSpreadsItsSlackOverTheSingleByteSpacesWithTw() + { + var helvetica = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 12 }; + using var pdf = new Pdf(Save(JustifiedDocument(_ => helvetica))); + var shown = ShownWithSpacing(pdf); + + // The construct: a simple (Type1) font shown with a positive Tw on the justified lines. + var spaced = shown.Where(s => s.WordSpacing != 0).ToList(); + Assert.NotEmpty(spaced); + Assert.All(spaced, s => Assert.Equal("Type1", s.Subtype)); + + // 9.3.3: Tw acts on the single-byte code 32 of a simple font, so a justified string has some, and the + // width of the string plus Tw for each of them is the width of the content box (200 pt). + foreach (var (_, tw, bytes) in spaced) + { + var spaces = bytes.Count(b => b == 32); + Assert.True(spaces > 0); + var text = System.Text.Encoding.Latin1.GetString(bytes); + Assert.Equal(200.0, helvetica.MeasureString(text) + (spaces * tw), 3); + } + + // Tw is a state parameter, so it is put back to 0 and the last line, which is not justified, has none. + var ops = OperatorNames(pdf.Page(0)); + Assert.Equal(ops.Count(n => n == "Tw") / 2, spaced.Count); + Assert.Equal(0.0, shown[^1].WordSpacing); + Assert.All(Regex.Matches(pdf.Page(0), @"(\S+) Tw").Select(m => m.Groups[1].Value), + v => Assert.Matches(@"^-?\d+(\.\d{1,5})?$", v)); + } + + [Fact] + public void Iso32000_1_9_3_3_ANoBreakSpaceIsNotCode32SoTwDoesNotSpreadTheSlackOverIt() + { + var helvetica = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 12 }; + var doc = NewDocument(PdfConformance.None, new PdfRectangle(0, 0, 300, 400), new EdgeInsets(50)); + doc.Add(new Paragraph("aa\u00A0bb cc dd\u00A0ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt uu vv", helvetica) + { + Alignment = HorizontalAlignment.Justify, + }); + using var pdf = new Pdf(Save(doc)); + var spaced = ShownWithSpacing(pdf).Where(s => s.WordSpacing != 0).ToList(); + + // The construct: a justified string shows byte A0 (WinAnsi no-break space) as well as byte 32. + Assert.Contains(spaced, s => s.Bytes.Contains((byte)0xA0)); + + // Tw acts on code 32 alone, so the line is as wide as the box when the slack is shared by those spaces only. + foreach (var (_, tw, bytes) in spaced) + { + var text = System.Text.Encoding.Latin1.GetString(bytes); + Assert.Equal(200.0, helvetica.MeasureString(text) + (bytes.Count(b => b == 32) * tw), 3); + } + } + + [Fact] + public void Iso32000_1_9_3_3_AJustifiedEmbeddedFontLineSetsNoWordSpacingBecauseItsCodesAreTwoBytes() + { + using var pdf = new Pdf(Save(JustifiedDocument(doc => Style(doc, DejaVu, 12)))); + var shown = ShownWithSpacing(pdf); + + // The construct: strings are shown through a Type 0 font, and there are enough of them to justify. + Assert.True(shown.Count > 10); + Assert.All(shown, s => Assert.Equal("Type0", s.Subtype)); + + // 9.3.3 applies Tw to a single-byte code 32 only, so a Type 0 font with Identity-H codes is never + // spaced with it: Tw is never set, and the gaps are made by positioning the words. + Assert.All(shown, s => Assert.Equal(0.0, s.WordSpacing)); + Assert.DoesNotMatch(@"[1-9\-.]\S* Tw", pdf.Page(0)); + Assert.True(Operators(pdf.Page(0)).Count(o => o.Name == "Tm") >= shown.Count); + } + + [Fact] + public void Iso32000_1_9_3_3_AJustifiedLineThatMixesAStandard14AndAnEmbeddedFragmentSetsNoWordSpacing() + { + var doc = NewDocument(PdfConformance.None, new PdfRectangle(0, 0, 300, 400), new EdgeInsets(50)); + var helvetica = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 12 }; + var paragraph = new Paragraph([new TextRun(Words[..30] + " ", helvetica), new TextRun(Words[30..], Style(doc, DejaVu, 12))]) + { + Alignment = HorizontalAlignment.Justify, + }; + doc.Add(paragraph); + using var pdf = new Pdf(Save(doc)); + var shown = ShownWithSpacing(pdf); + + // The construct: both a Type1 and a Type0 string are shown. + Assert.Contains(shown, s => s.Subtype == "Type1"); + Assert.Contains(shown, s => s.Subtype == "Type0"); + + // A line that holds an embedded fragment is positioned as a whole, so Tw never applies to the codes of + // the Type 0 string and the standard-14 fragment is spaced by position as well. + Assert.All(shown, s => Assert.Equal(0.0, s.WordSpacing)); + } + + [Fact] + public void Iso32000_1_9_3_3_PopplerReadsTheWordsOfAJustifiedLineSeparatedByOneSpaceInRawOrder() + { + foreach (var embedded in new[] { false, true }) + { + var helvetica = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 12 }; + var file = Save(JustifiedDocument(doc => embedded ? Style(doc, DejaVu, 12) : helvetica)); + + // The same words come out whether the gap is made by Tw or by position. + Assert.Equal(Words, RawText(file)); + } + } + + /// The text in content order (pdftotext -raw), with white space inside a line kept as it is. + private static string RawText(byte[] pdf) + { + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + if (!ExternalTool.TryRun("pdftotext", ["-raw", path, "-"], out var exit, out var text, out var stderr, out var timedOut)) + OracleGate.Unavailable("pdftotext"); + Assert.True(exit == 0 && !timedOut, $"pdftotext -raw exit {exit}, stderr: {stderr}"); + // A line end between two words is the space between them; every other space is kept as poppler gives it. + return Regex.Replace(text.Trim(), "[\r\n]+", " "); + } +}